3 # Copyright (C) 2017,2019 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.
21 # =============================================================================
25 # =============================================================================
30 from fpconst
import NegInf
32 NegInf = float(
"-inf")
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
48 from optparse
import OptionParser
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
61 from lal.utils
import CacheEntry
62 from lalinspiral.thinca
import InspiralCoincDef
66 # =============================================================================
70 # =============================================================================
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()
82 required_options = ["candidates", "ranking_stat_cache"]
83 missing_options = [option for option in required_options if getattr(options, option) is None]
85 raise ValueError("%s is(arg) required" % ", ".join("--%s" % option.subst("_", "-") for option in missing_options))
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)))
92 raise ValueError("unexpected arguments %s" % " ".join(filenames))
94 return options, filenames
98 # =============================================================================
102 # =============================================================================
111 options, filenames = parse_command_line()
115 # load ranking statistic data. disable the fast-path code
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")
124 rankingstat.fast_path_stat_threshold = NegInf
125 rankingstat_index.update((template_id, rankingstat) for template_id in rankingstat.template_ids)
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())
143 # iterate over candidates, generate (ranking stat, fast-path stat) samples
146 cursor_outer = connection.cursor()
147 cursor_inner = connection.cursor()
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)
160 template_id = rankingstat_index.keys()[0]
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,)):
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,)))
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
176 y.append(fast_path_stat(**kwargs))
178 print >>out,
"%.16g %.16g %d" % (x[-1], y[-1], coinc_event_id)
179 if progress is not None:
190 fig = figure.Figure()
192 fig.set_size_inches((8., 8. / plotutil.golden_ratio))
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)