gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_dlrs_diag
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2017,2019 Kipp Cannon
4 #
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.
9 #
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.
14 #
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.
18 
19 
20 #
21 # =============================================================================
22 #
23 # Preamble
24 #
25 # =============================================================================
26 #
27 
28 
29 try:
30  from fpconst import NegInf
31 except ImportError:
32  NegInf = float("-inf")
33 import itertools
34 import matplotlib
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": 600,
43  "savefig.dpi": 600,
44  "text.usetex": True
45 })
46 from matplotlib import figure
47 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
48 from optparse import OptionParser
49 import sqlite3
50 import sys
51 
52 
53 from glue.text_progress_bar import ProgressBar
54 from ligo.lw import dbtables
55 from ligo.lw import lsctables
56 from ligo.lw import utils as ligolw_utils
57 from ligo.lw.utils import coincs as ligolw_coincs
58 from gstlal import far
59 from gstlal import plotutil
60 from lal import rate
61 from lal.utils import CacheEntry
62 from lalinspiral.thinca import InspiralCoincDef
63 
64 
65 #
66 # =============================================================================
67 #
68 # Command Line
69 #
70 # =============================================================================
71 #
72 
73 
74 def parse_command_line():
75  parser = OptionParser()
76  parser.add_option("--candidates", metavar = "filename", help = "Set the name of the SQLite database from which to pull candidates (required).")
77  parser.add_option("--ranking-stat-cache", metavar = "filename", help = "Load all ranking statistic files from this cache (required).")
78  parser.add_option("--output-format", metavar = "extension", default = ".png", help = "Select output format by setting the filename extension (default = \".png\").")
79  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
80  options, filenames = parser.parse_args()
81 
82  required_options = ["candidates", "ranking_stat_cache"]
83  missing_options = [option for option in required_options if getattr(options, option) is None]
84  if missing_options:
85  raise ValueError("%s is(arg) required" % ", ".join("--%s" % option.subst("_", "-") for option in missing_options))
86 
87  valid_formats = (".png", ".pdf", ".svg")
88  if options.output_format not in valid_formats:
89  raise ValueError("invalid --output-format \"%s\", allowed are %s" % (options.output_format, ", ".join("\"%s\"" % fmt for fmt in valid_formats)))
90 
91  if filenames:
92  raise ValueError("unexpected arguments %s" % " ".join(filenames))
93 
94  return options, filenames
95 
96 
97 #
98 # =============================================================================
99 #
100 # Main
101 #
102 # =============================================================================
103 #
104 
105 
106 #
107 # command line
108 #
109 
110 
111 options, filenames = parse_command_line()
112 
113 
114 #
115 # load ranking statistic data. disable the fast-path code
116 #
117 
118 
119 if True:
120  rankingstat_index = {}
121  for n, line in enumerate(open(options.ranking_stat_cache), 1):
122  rankingstat = far.RankingStat.from_xml(ligolw_utils.load_url(CacheEntry(line).url, contenthandler = far.RankingStat.LIGOLWContentHandler, verbose = options.verbose), u"gstlal_inspiral_likelihood")
123  rankingstat.finish()
124  rankingstat.fast_path_stat_threshold = NegInf
125  rankingstat_index.update((template_id, rankingstat) for template_id in rankingstat.template_ids)
126  # FIXME: remove this
127  break
128 
129 
130 #
131 # collect metadata
132 #
133 
134 
135 connection = sqlite3.connect(options.candidates)
136 xmldoc = dbtables.get_xml(connection)
137 coinc_def_id = ligolw_coincs.get_coinc_def_id(xmldoc, InspiralCoincDef.search, InspiralCoincDef.search_coinc_type, create_new = False)
138 sngl_inspiral_row = lsctables.SnglInspiralTable.get_table(xmldoc).row_from_cols
139 offset_vectors = dict((time_slide_id, offset_vector) for time_slide_id, offset_vector in lsctables.TimeSlideTable.get_table(xmldoc).as_dict().items())
140 
141 
142 #
143 # iterate over candidates, generate (ranking stat, fast-path stat) samples
144 #
145 
146 cursor_outer = connection.cursor()
147 cursor_inner = connection.cursor()
148 
149 if options.verbose:
150  (n_samples,), = cursor_outer.execute("SELECT COUNT(*) FROM coinc_event WHERE coinc_def_id == ? AND time_slide_id NOT IN (SELECT DISTINCT(time_slide_id) FROM time_slide WHERE offset != 0);", (coinc_def_id,)).fetchall()
151  progress = ProgressBar(text = "Sampling", max = n_samples)
152  progress.show()
153 else:
154  progress = None
155 
156 x = []
157 y = []
158 
159 # FIXME: remove this
160 template_id = rankingstat_index.keys()[0]
161 
162 with open("dump.txt", "w") as out:
163  # iterate over zero-lag coincs
164  for ln_lr, coinc_event_id, time_slide_id in cursor_outer.execute("SELECT coinc_event.likelihood, coinc_event.coinc_event_id, coinc_event.time_slide_id FROM coinc_event WHERE coinc_def_id == ? AND time_slide_id NOT IN (SELECT DISTINCT(time_slide_id) FROM time_slide WHERE offset != 0);", (coinc_def_id,)):
165  # retrieve triggers
166  events = map(sngl_inspiral_row, cursor_inner.execute("SELECT sngl_inspiral.* FROM sngl_inspiral JOIN coinc_event_map ON (coinc_event_map.table_name == 'sngl_inspiral' AND coinc_event_map.event_id == sngl_inspiral.event_id) WHERE coinc_event_map.coinc_event_id == ?", (coinc_event_id,)))
167  # FIXME: remove this
168  for event in events:
169  event.template_id = template_id
170  # compute ranking statistic arguments
171  rankingstat = rankingstat_index[events[0].template_id]
172  fast_path_stat = rankingstat.fast_path_stat
173  kwargs = rankingstat.kwargs_from_triggers(events, offset_vectors[time_slide_id])
174  # evaluate full ranking stat and fast-path ranking stat and save
175  x.append(ln_lr)
176  y.append(fast_path_stat(**kwargs))
177  # update output
178  print >>out, "%.16g %.16g %d" % (x[-1], y[-1], coinc_event_id)
179  if progress is not None:
180  progress.increment()
181 
182 del progress
183 
184 
185 #
186 # plot
187 #
188 
189 
190 fig = figure.Figure()
191 FigureCanvas(fig)
192 fig.set_size_inches((8., 8. / plotutil.golden_ratio))
193 axes = fig.gca()
194 axes.plot(x, y, "k.", markersize = 2.)
195 axes.set_xlim(-20, 60)
196 axes.set_ylim(-20, 60)
197 axes.set_title(r"Fast-Path vs.\ Data-defined $\ln \mathcal{L}$")
198 axes.set_xlabel(r"Data-defined $\ln \mathcal{L}$")
199 axes.set_ylabel(r"Fast-Path $\ln \mathcal{L}$")
200 fig.tight_layout(pad = 0.8)
201 fig.savefig("dlrs_diag%s" % options.output_format)