3 # Copyright (C) 2013 Chad Hanna, Kipp Cannon
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 ### A program to plot the likelihood distributions in noise of a gstlal inspiral analysis
24 # =============================================================================
28 # =============================================================================
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,
46 from matplotlib
import figure
47 from matplotlib.backends.backend_agg
import FigureCanvasAgg as FigureCanvas
49 from optparse
import OptionParser
54 from ligo.lw
import dbtables
55 from ligo.lw
import lsctables
56 from glue.text_progress_bar
import ProgressBar
57 from lal.utils
import CacheEntry
58 from lalinspiral
import thinca
59 from ligo.segments
import utils as segmentsUtils
62 from gstlal
import far
63 from gstlal
import dagparts
64 from gstlal.plots
import far as plotfar
67 class SnrChiColourNorm(matplotlib.colors.Normalize):
68 def __call__(
self, value, clip = None):
69 value, is_scalar = self.process_value(value)
70 numpy.clip(value, 1e-200, 1e+200, value)
72 self.autoscale_None(value)
74 vmin = math.log(self.vmin)
75 vmax = math.log(self.vmax)
76 xbar = (vmax + vmin) / 2.
77 delta = (vmax - vmin) / 2.
80 value = (numpy.arctan((numpy.log(value) - xbar) * pi_2 / delta) + pi_2) / math.pi
81 return value[0] if is_scalar else value
83 def inverse(self, value):
84 vmin = math.log(self.vmin)
85 vmax = math.log(self.vmax)
86 xbar = (vmax + vmin) / 2.
87 delta = (vmax - vmin) / 2.
90 value = numpy.exp(numpy.tan(value * math.pi - pi_2) * delta / pi_2 + xbar)
91 numpy.clip(value, 1e-200, 1e+200, value)
94 def _autoscale(self, vmin, vmax):
97 xbar = (vmax + vmin) / 2.
98 delta = (vmax - vmin) / 2.
99 xbar += 2. * delta / 3.
101 vmin = math.exp(xbar - delta)
102 vmax = math.exp(xbar + delta)
105 def autoscale(self, A):
106 self.vmin, self.vmax = self._autoscale(numpy.ma.min(A), numpy.ma.max(A))
108 def autoscale_None(self, A):
109 vmin, vmax = self._autoscale(numpy.ma.min(A), numpy.ma.max(A))
110 if self.vmin is None:
112 if self.vmax is None:
117 # =============================================================================
121 # =============================================================================
125 def parse_command_line():
126 parser = OptionParser()
127 parser.add_option(
"-d",
"--database", metavar =
"filename", action =
"append", help =
"Retrieve search results from this database (optional). Can be given multiple times.")
128 parser.add_option(
"-c",
"--database-cache", metavar =
"filename", help =
"Retrieve search results from all databases in this LAL cache (optional). See lalapps_path2cache.")
129 parser.add_option(
"--max-snr", metavar =
"SNR", default = 200., type =
"float", help =
"Plot SNR PDFs up to this value of SNR (default = 200).")
130 parser.add_option(
"--max-log-lambda", metavar =
"value", default = 40., type =
"float", help =
"Plot ranking statistic CCDFs, etc., up to this value of the natural logarithm of the likelihood ratio (default = 40).")
131 parser.add_option(
"--min-log-lambda", metavar =
"value", default = -5., type =
"float", help =
"Plot ranking statistic CCDFs, etc., down to this value of the natural logarithm of the likelihood ratio (default = -5).")
132 parser.add_option(
"--scatter-log-lambdas", metavar =
"[low]:[high][,[low]:[high]...]", help =
"Overlay scatter plots of candidate parameter co-ordinates on various PDF plots, limiting the candidates to those whose log likelihood ratios are in the given range (default = don't overlay scatter plot). Use a range of \":\" to plot all candidates.")
133 parser.add_option(
"--output-dir", metavar =
"output-dir", default =
".", help =
"Write output to this directory (default = \".\").")
134 parser.add_option(
"--output-format", metavar =
"extension", default =
".png", help =
"Select output format by setting the filename extension (default = \".png\").")
135 parser.add_option(
"-t",
"--tmp-space", metavar =
"path", help =
"Path to a directory suitable for use as a work area while manipulating the database file. The database file will be worked on in this directory, and then moved to the final location when complete. This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
136 parser.add_option(
"--add-zerolag-to-background", action =
"store_true", help =
"Add zerolag events to background before populating coincident parameter PDF histograms.")
137 parser.add_option(
"--user-tag", metavar =
"user-tag", default =
"ALL", help =
"Set the adjustable component of the description fields in the output filenames (default = \"ALL\").")
138 parser.add_option(
"--plot-snr-snr-pdfs", action =
"store_true", help =
"Plot the full cache of snr-snr-pdfs.")
139 parser.add_option(
"--event-snr", metavar =
"ifo:snr", action =
"append", help =
"SNR to plot on snr chisq plots. Pass as ifo:snr, e.g. H1:3.2. Can be passed multiple times, though only once for each ifo. Must also pass --event-chisq for ifo.")
140 parser.add_option(
"--event-chisq", metavar =
"ifo:chisq", action =
"append", help =
"chisq to plot on snr chisq plots. Pass as ifo:chisq, e.g. H1:1.1. Can be passed multiple times, though only once for each ifo. Must also pass --event-snr for ifo.")
141 parser.add_option(
"-v",
"--verbose", action =
"store_true", help =
"Be verbose.")
142 options, filenames = parser.parse_args()
144 if options.database_cache is not None:
145 if options.database is None:
146 options.database = []
147 options.database += [CacheEntry(line).path for line in open(options.database_cache)]
149 valid_formats = (
".png",
".pdf",
".svg")
150 if options.output_format not in valid_formats:
151 raise ValueError(
"invalid --output-format \"%s\", allowed are %s" % (options.output_format,
", ".join(
"\"%s\"" % fmt for fmt in valid_formats)))
153 if options.scatter_log_lambdas is not None:
154 options.scatter_log_lambdas = segmentsUtils.from_range_strings(options.scatter_log_lambdas.split(
","), boundtype = float).coalesce()
156 options.user_tag = options.user_tag.upper()
158 options.event_snr_dict = {}
159 options.event_chisq_dict = {}
160 if options.event_snr or options.event_chisq:
161 for ifo_snr_str in options.event_snr:
162 ifo, snr = ifo_snr_str.split(
':')
163 options.event_snr_dict[ifo] = float(snr)
164 for ifo_chisq_str in options.event_chisq:
165 if ifo_chisq_str.split(':')[0] != ifo:
167 options.event_chisq_dict[ifo] =
float(ifo_chisq_str.split(':')[1])
169 for ifo in options.event_snr_dict.keys():
170 if ifo not in options.event_chisq_dict.keys():
172 raise ValueError("Each ifo provided to --event-snr or --event-chisq must be provided to both options")
174 return options, filenames
178 # =============================================================================
182 # =============================================================================
186 def load_distributions(filenames, verbose = False):
187 # RankingStat objects go into a dictionary indexed by the template
188 # bank ID set they are for, with RankinStat objects for the same
189 # templates being summed. RankingStatPDF objects are summed (and
190 # therefore are required to be fore the same templates). these
191 # organizational choices reflect the current use cases for this
194 rankingstatpdf = None
195 for n, filename in enumerate(filenames, 1):
197 print(
"%d/%d:" % (n, len(filenames)), file=sys.stderr)
198 this_rankingstat, this_rankingstatpdf = far.parse_likelihood_control_doc(far.ligolw_utils.load_filename(filename, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
199 if this_rankingstat is not None:
200 template_ids = this_rankingstat.template_ids
201 if template_ids in rankingstats:
202 rankingstats[template_ids] += this_rankingstat
204 rankingstats[template_ids] = this_rankingstat
205 if this_rankingstatpdf is not None:
206 if rankingstatpdf is None:
207 rankingstatpdf = this_rankingstatpdf
209 rankingstatpdf += this_rankingstatpdf
210 progress = ProgressBar(text =
"Density estimation", max = len(rankingstats)) if verbose and rankingstats else None
211 for rankingstat in rankingstats.values():
212 if progress is not None:
214 if options.add_zerolag_to_background:
215 rankingstat.denominator.lnzerolagdensity = rankingstat.zerolag
218 # the segment is only used to construct T050017-style filenames, so
219 # just fake one if there
's no livetime information
221 if rankingstatpdf is not None:
222 seg = rankingstatpdf.segments.extent()
224 rankingstat = list(rankingstats.values())[0]
226 seg = rankingstat.segmentlists.extent_all()
229 return rankingstats, rankingstatpdf, seg
232 def load_search_results(filenames, tmp_path = None, verbose = False):
238 for n, filename in enumerate(filenames, 1):
240 print("%d/%d: %s" % (n, len(filenames), filename), file=sys.stderr)
241 with dbtables.workingcopy(filename, tmp_path = tmp_path, discard = True, verbose = verbose) as working_filename:
242 connection = sqlite3.connect(str(working_filename))
244 xmldoc = dbtables.get_xml(connection)
245 definer_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
247 cursor = connection.cursor()
249 # subclass to allow it to carry extra attributes
250 class snglsdict(dict):
251 __slots__ = ("ln_likelihood_ratio", "fap")
253 for coinc_event_id, rows in itertools.groupby(cursor.execute("""
255 coinc_event_map.coinc_event_id,
256 coinc_event.likelihood,
257 coinc_inspiral.false_alarm_rate,
264 time_slide.time_slide_id == coinc_event.time_slide_id
265 AND time_slide.offset != 0
272 JOIN coinc_event_map ON (
273 coinc_event_map.table_name == 'sngl_inspiral
'
274 AND coinc_event_map.event_id == sngl_inspiral.event_id
276 JOIN coinc_event ON (
277 coinc_event.coinc_event_id == coinc_event_map.coinc_event_id
279 JOIN coinc_inspiral ON (
280 coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
283 coinc_event.coinc_def_id == ?
285 coinc_event_map.coinc_event_id
286 """, (definer_id,)), lambda row: row[0]):
288 is_timeslide = rows[0][3]
289 # {instrument: (snr, chisq)} dictionary
290 sngls = snglsdict((row[4], (row[5], row[6])) for row in rows)
291 sngls.ln_likelihood_ratio = rows[0][1]
292 sngls.fap = rows[0][2]
294 timeslide_sngls.append(sngls)
296 zerolag_sngls.append(sngls)
301 timeslide_ln_lr = sorted((sngls.ln_likelihood_ratio, sngls.fap) for sngls in timeslide_sngls)
302 zerolag_ln_lr = sorted((sngls.ln_likelihood_ratio, sngls.fap) for sngls in zerolag_sngls)
304 return timeslide_ln_lr, zerolag_ln_lr, timeslide_sngls, zerolag_sngls
308 # =============================================================================
312 # =============================================================================
321 options, filenames = parse_command_line()
329 rankingstats, rankingstatpdf, seg = load_distributions(filenames, verbose = options.verbose)
333 timeslide_ln_lr, zerolag_ln_lr, timeslide_sngls, zerolag_sngls = load_search_results(options.database, tmp_path = options.tmp_space, verbose = options.verbose)
334 if options.scatter_log_lambdas is not None:
335 sngls = [sngl for sngl in timeslide_sngls + zerolag_sngls if sngl.ln_likelihood_ratio in options.scatter_log_lambdas]
339 timeslide_ln_lr, zerolag_ln_lr, sngls = None, None, None
347 for bin_index, rankingstat in enumerate(sorted(rankingstats.values(), key = lambda rankingstat: sorted(rankingstat.template_ids))):
349 for instrument in rankingstat.instruments:
350 for snr_chi_type in ("background_pdf", "injection_pdf", "zero_lag_pdf", "LR"):
351 if instrument in options.event_snr_dict.keys():
352 fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, snr_chi_type, options.max_snr, sngls = sngls, event_snr = options.event_snr_dict[instrument], event_chisq = options.event_chisq_dict[instrument])
354 fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, snr_chi_type, options.max_snr, sngls = sngls)
357 plotname = dagparts.T050017_filename(instrument, "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%04d_%s_SNRCHI2" % (options.user_tag, bin_index, snr_chi_type.upper()), seg, options.output_format, path = options.output_dir)
359 print("writing %s" % plotname, file=sys.stderr)
360 fig.savefig(plotname)
363 fig = plotfar.plot_rates(rankingstat)
364 plotname = dagparts.T050017_filename("H1L1V1", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%04d_RATES" % (options.user_tag, bin_index), seg, options.output_format, path = options.output_dir)
366 print("writing %s" % plotname, file=sys.stderr)
367 fig.savefig(plotname)
371 if options.plot_snr_snr_pdfs:
372 # assume PDFs are identical for all template bank bins, and pick
374 rankingstat = list(rankingstats.values())[0]
375 for (instruments, horizon_distances) in sorted(rankingstat.numerator.SNRPDF.snr_joint_pdf_cache.keys(), key = lambda x: sorted(x[1])):
376 # they're stored as a frozen set of quantized key/value
377 # pairs, need to unquantize them and get a dictionary back
378 horizon_distances = rankingstat.numerator.SNRPDF.quantized_horizon_distances(horizon_distances)
379 fig = plotfar.plot_snr_joint_pdf(rankingstat.numerator.SNRPDF, instruments, horizon_distances, rankingstat.min_instruments, options.max_snr, sngls = sngls)
381 plotname = dagparts.T050017_filename(instruments,
"GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_SNR_PDF_%s" % (options.user_tag,
"_".join([
"%s_%s" % (k, horizon_distances[k]) for k in sorted(horizon_distances)]) ), seg, options.output_format, path = options.output_dir)
383 print(
"writing %s" % plotname, file=sys.stderr)
384 fig.savefig(plotname)
387 # ranking statistic PDFs and CCDFs
388 if rankingstatpdf is not None:
389 for Title, which, NAME in ((
"Noise",
"noise",
"NOISE"), (
"Signal",
"signal",
"SIGNAL")):
390 fig = plotfar.plot_likelihood_ratio_pdf(rankingstatpdf, (options.min_log_lambda, options.max_log_lambda), Title, which = which)
391 plotname = dagparts.T050017_filename(
"COMBINED",
"GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%s_LIKELIHOOD_RATIO_PDF" % (options.user_tag, NAME), seg, options.output_format, path = options.output_dir)
393 print(
"writing %s" % plotname, file=sys.stderr)
394 fig.savefig(plotname)
396 if rankingstatpdf is not None and rankingstatpdf.zero_lag_lr_lnpdf.array.any():
397 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
398 if zerolag_ln_lr is not None:
399 xhi = max(zerolag_ln_lr + timeslide_ln_lr)[0]
400 xhi = 5. * math.ceil(xhi / 5.)
401 xhi = max(xhi, options.max_log_lambda)
403 xhi = options.max_log_lambda
404 fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (options.min_log_lambda, xhi), observed_ln_likelihood_ratios = zerolag_ln_lr, is_open_box = True)
405 plotname = dagparts.T050017_filename(
"COMBINED",
"GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_NOISE_LIKELIHOOD_RATIO_CCDF_openbox" % options.user_tag, seg, options.output_format, path = options.output_dir)
407 print(
"writing %s" % plotname, file=sys.stderr)
408 fig.savefig(plotname)
410 fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (options.min_log_lambda, xhi), observed_ln_likelihood_ratios = timeslide_ln_lr, is_open_box = False)
411 plotname = dagparts.T050017_filename(
"COMBINED",
"GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_NOISE_LIKELIHOOD_RATIO_CCDF_closedbox" % options.user_tag, seg, options.output_format, path = options.output_dir)
413 print(
"writing %s" % plotname, file=sys.stderr)
414 fig.savefig(plotname)