3 # Copyright (C) 2009-2013 Kipp Cannon, Chad Hanna, Drew Keppel
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.
19 ### A program to produce a variety of plots from a gstlal inspiral analysis, e.g. IFAR plots, missed found, etc.
22 # =============================================================================
26 # =============================================================================
31 from functools
import reduce
36 from optparse
import OptionParser
45 from lal
import gpstime
46 from lal
import iterutils
47 from lal.utils
import CacheEntry
49 from ligo
import segments
50 from ligo.lw
import dbtables
51 from ligo.lw
import lsctables
52 from ligo.lw.utils
import segments as ligolw_segments
54 from gstlal
import far
55 from gstlal
import dagparts
56 from gstlal.plots
import summary as plotsumm
57 from gstlal.plots.util
import golden_ratio
60 def format_column(column):
61 return column.lower().replace(
' ',
'_').replace(
':',
'').replace(
';',
'')
64 def save_table(fname, fields, rows):
66 fields = [{
'key': format_column(col),
'label': col,
'sortable': True}
for col in fields]
67 colnames = [field[
'key']
for field in fields]
68 items = [{col: val
for col, val in zip(colnames, row)}
for row in rows]
71 with open(fname,
'w') as f:
72 f.write(json.dumps({
'fields': fields,
'items': items}))
75 class SimInspiral(lsctables.SimInspiral):
78 return self.mass1 + self.mass2
82 return (self.mass1 * self.spin1z + self.mass2 * self.spin2z) / self.mtotal
85 class SnglInspiral(lsctables.SnglInspiral):
88 return self.mass1 + self.mass2
92 return self.mass1 * self.mass2 / self.mtotal**2.
96 return self.mtotal * self.eta**0.6
100 return (self.mass1 * self.spin1z + self.mass2 * self.spin2z) / self.mtotal
102 lsctables.SimInspiralTable.RowType = SimInspiral
103 lsctables.SnglInspiralTable.RowType = SnglInspiral
106 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>, Chad Hanna <channa@ligo.caltech.edu>"
107 __version__ = "git
id %s" % "FIXME"
112 # =============================================================================
116 # =============================================================================
120 def parse_command_line():
121 parser = OptionParser(
122 version =
"Name: %%prog\n%s" %
"" # FIXME
124 parser.add_option(
"",
"--input-cache", help =
"Also get the list of databases to process from this LAL cache.")
125 parser.add_option(
"--user-tag", metavar =
"user-tag", default =
"ALL", help =
"Set the prefix for output filenames (default = \"ALL\").")
126 parser.add_option(
"--output-dir", metavar =
"output-dir", default =
".", help =
"Provide an output directory")
127 parser.add_option(
"-f",
"--format", metavar =
"{\"png\",\"pdf\",\"svg\",\"eps\",...}", action =
"append", default = [], help =
"Set the output image format. Can be given multiple times (default = \"png\").")
128 parser.add_option(
"--shrink-data-segments", metavar =
"float", type = float, help =
"Shrink data segments by this much (on each side). e.g. specifying 2 will shrink each datasegment by 4 seconds")
129 parser.add_option(
"--extend-veto-segments", metavar =
"float", type = float, help =
"Pad segments by this number of seconds (on both sides)")
130 parser.add_option(
"--segments-name", metavar =
"name", default =
"statevectorsegments", help =
"Set the name of the segments that were analyzed (default = \"statevectorsegments\").")
131 parser.add_option(
"--vetoes-name", metavar =
"name", default =
"vetoes", help =
"Set the name of the veto segments (default = \"vetoes\").")
132 parser.add_option(
"--plot-group", metavar =
"number", action =
"append", default = None, help =
"""Generate the given plot group. Can be given multiple times (default = make all plot groups)
133 0. Summary Table (top 10 loudest events globally across all zero lag triggers read in)
134 1. Missed Found (Scatter plots of missed and found injections on several axes)
135 2. Injection Parameter Accuracy Plots
136 3. Background Vs Injection Plots (sngl detector triggers from coincs of snr, chisq, bank chisq, ...)
137 4. Background Vs Injection Plots pairwise (SNR instrument 1 vs. instrument2, ...),
138 5. Rate Vs Threshold (SNR histograms, IFAR histograms, ...)
139 6. Injection Parameter Distribution Plots (The input parameters that went into inspinj, like mass1 vs mass2, ...)
141 parser.add_option(
"--far-threshold", metavar =
"Hz", default = 1. / (30 * 86400), type =
"float", help =
"Set the FAR threshold for found injections (default = 1 / 30 days).")
142 parser.add_option(
"--likelihood-file", metavar =
"filename", help =
"Path to the marginalized likelihood file.")
143 # FIXME Add check that plot
group 1 being generated if these options are given
144 parser.add_option(
"--remove-precession", action =
"store_true", help =
"Ignore precessing injections when generating missed/found plots")
145 parser.add_option(
"--isolate-precession", action =
"store_true", help =
"Only make missed/found plots for precessing injections")
146 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.")
147 parser.add_option(
"-v",
"--verbose", action =
"store_true", help =
"Be verbose.")
148 options, filenames = parser.parse_args()
150 if options.plot_group is not None:
151 options.plot_group = sorted(list(map(int, options.plot_group)))
153 if (options.plot_group is None or set(options.plot_group) & set((1, 5))) and options.likelihood_file is None:
154 raise ValueError(
"Must provide --likelihood-file to generate plots in groups 1 and/or 5.")
156 if not options.format:
157 options.format = [
"png"]
161 if options.input_cache:
162 filenames.extend(c.path for c in map(CacheEntry, open(options.input_cache)))
164 return options, filenames
168 # =============================================================================
172 # =============================================================================
176 class CoincDatabase(object):
177 def __init__(self, connection, data_segments_name, veto_segments_name = None, verbose = False, plotsummary_json = None, base = None, program_name =
"gstlal_inspiral", shrink_data_segments = None, extend_veto_segments = None):
179 Compute and record some summary information about the
184 self.connection = connection
185 xmldoc = dbtables.get_xml(connection)
186 self.all_segs_dict = {}
188 cursor = connection.cursor()
192 self.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
194 self.sngl_inspiral_table = None
196 self.sim_inspiral_table = lsctables.SimInspiralTable.get_table(xmldoc)
198 self.sim_inspiral_table = None
200 self.coinc_def_table = lsctables.CoincDefTable.get_table(xmldoc)
201 self.coinc_table = lsctables.CoincTable.get_table(xmldoc)
202 self.time_slide_table = lsctables.TimeSlideTable.get_table(xmldoc)
204 self.coinc_def_table = None
205 self.coinc_table = None
206 self.time_slide_table = None
208 self.coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
210 self.coinc_inspiral_table = None
212 # determine a few coinc_definer IDs
213 # FIXME: don't hard-code the numbers
214 if self.coinc_def_table is not None:
216 self.ii_definer_id =
self.coinc_def_table.get_coinc_def_id(
"inspiral", 0, create_new = False)
218 self.ii_definer_id = None
220 self.si_definer_id =
self.coinc_def_table.get_coinc_def_id(
"inspiral", 1, create_new = False)
222 self.si_definer_id = None
224 self.sc_definer_id =
self.coinc_def_table.get_coinc_def_id(
"inspiral", 2, create_new = False)
226 self.sc_definer_id = None
228 self.ii_definer_id = None
229 self.si_definer_id = None
230 self.sc_definer_id = None
232 # retrieve the distinct on and participating instruments
233 self.on_instruments_combos = [frozenset(lsctables.instrumentsproperty.get(x))
for x, in cursor.execute(
"SELECT DISTINCT(instruments) FROM coinc_event WHERE coinc_def_id == ?", (
self.ii_definer_id,))]
234 self.participating_instruments_combos = [frozenset(lsctables.instrumentsproperty.get(x))
for x, in cursor.execute(
"SELECT DISTINCT(ifos) FROM coinc_inspiral")]
236 # get the segment lists
237 self.seglists = ligolw_segments.segmenttable_get_by_name(xmldoc, data_segments_name).coalesce()
238 if shrink_data_segments is not None:
239 # Make sure all segments are at least long enough to be
240 # contracted (e.g. if a segment is 32 seconds long but
241 # the user is going to contract it by 17 seconds, then
242 # the end time of the segment would come before the
243 # start time of the segment. This is bad)
244 for seglist in
self.seglists.values():
245 iterutils.inplace_filter(lambda s: abs(s) > 2*shrink_data_segments, seglist)
246 self.seglists.contract(shrink_data_segments)
247 self.instruments = set(
self.seglists)
248 if veto_segments_name is not None:
249 self.veto_segments = ligolw_segments.segmenttable_get_by_name(xmldoc, veto_segments_name).coalesce()
250 if extend_veto_segments is not None:
251 self.veto_segments.protract(extend_veto_segments)
253 self.veto_segments = segments.segmentlistdict()
254 self.seglists -= self.veto_segments
256 # get all the segments in the database to use as a summary
257 for llwsegs in ligolw_segments.LigolwSegments(xmldoc).coalesce():
258 seglists =
self.all_segs_dict.setdefault(llwsegs.name, segments.segmentlistdict())
259 # FIXME: should be populating valid segments upstream
260 seglists |= segments.segmentlistdict.fromkeys(llwsegs.instruments, llwsegs.active) #& llwsegs.valid)
264 print >>sys.stderr,
"calculating background livetimes: ",
265 # retrieve background offset vectors
266 self.offset_vectors = [offsetvector
for offsetvector in dbtables.TimeSlideTable(connection = connection).as_dict().values()
if any(offsetvector.values())]
270 self.zerolag_livetime = {}
271 self.background_livetime = {}
272 for on_instruments in
self.on_instruments_combos:
273 tmpsegs =
self.seglists.intersection(on_instruments) -
self.seglists.union(
self.instruments - on_instruments)
274 self.zerolag_livetime[on_instruments] = float(abs(sum(abs(seg)
for seg in tmpsegs
if numpy.isfinite(
float(seg[0])) and numpy.isfinite(
float(seg[1])))))
275 # FIXME: background livetime hard-coded to be same
276 # as zero-lag livetime. figure out what to
do
277 self.background_livetime.update(
self.zerolag_livetime)
281 print >>sys.stderr,
"database overview:"
282 for on_instruments in
self.on_instruments_combos:
283 print >>sys.stderr,
"\tzero-lag livetime for %s: %f s" % (
"+".join(sorted(on_instruments)),
self.zerolag_livetime[on_instruments])
284 print >>sys.stderr,
"\tbackground livetime for %s: %f s" % (
"+".join(sorted(on_instruments)),
self.background_livetime[on_instruments])
285 if self.sngl_inspiral_table is not None:
286 print >>sys.stderr,
"\tinspiral events: %d" % len(
self.sngl_inspiral_table)
287 if self.sim_inspiral_table is not None:
288 print >>sys.stderr,
"\tinjections: %d" % len(
self.sim_inspiral_table)
289 if self.time_slide_table is not None:
290 print >>sys.stderr, "\ttime slides: %d" % cursor.execute("SELECT COUNT(DISTINCT(time_slide_id)) FROM time_slide").fetchone()[0]
291 if self.coinc_def_table is not None:
292 for description, n in cursor.execute("SELECT description, COUNT(*) FROM coinc_definer NATURAL JOIN coinc_event GROUP BY coinc_def_id"):
293 print >>sys.stderr, "\t%s: %d" % (description, n)
297 for on_instruments in self.on_instruments_combos:
298 data.append(["zero-lag livetime for %s" % ("+".join(sorted(on_instruments))), str(self.zerolag_livetime[on_instruments])])
299 data.append(["background livetime for %s" % ("+".join(sorted(on_instruments))), str(self.background_livetime[on_instruments])])
300 if self.sngl_inspiral_table is not None:
301 data.append(["inspiral events", str(len(self.sngl_inspiral_table))])
302 if self.sim_inspiral_table is not None:
303 data.append(["injections", str(len(self.sim_inspiral_table))])
304 if self.time_slide_table is not None:
305 data.append(["time slides", str(cursor.execute("SELECT COUNT(DISTINCT(time_slide_id)) FROM time_slide").fetchone()[0])])
306 if self.coinc_def_table is not None:
307 for description, n in cursor.execute("SELECT description, COUNT(*) FROM coinc_definer NATURAL JOIN coinc_event GROUP BY coinc_def_id"):
308 data.append([description, str(n)])
309 if self.sim_inspiral_table is None:
310 save_table("%s_plot_summary.json" % self.base, ['Summary of database:', plotsummary_json], data)
313 # =============================================================================
317 # =============================================================================
320 def sim_get_chirp_eff_dist(sim, instrument):
321 return getattr(sim,
"eff_dist_%s" % instrument[0].lower()) * sim.mchirp**(5./6.) / 1.22**(5./6.)
323 def roman(i, arabics = (1000,900,500,400,100,90,50,40,10,9,5,4,1), romans = (
"m",
"cm",
"d",
"cd",
"c",
"xc",
"l",
"xl",
"x",
"ix",
"v",
"iv",
"i")):
327 return roman(i, arabics[1:], romans[1:])
328 return romans[0] + roman(i - arabics[0], arabics, romans)
330 def truncate(f, digits, si=True):
331 assert digits > 0,
'number of digits must be positive'
333 return float((
'%10.' + str(digits) +
'e') % f)
335 return float((
'%10.' + str(digits) +
'f') % f)
338 def create_sim_coinc_view(connection):
340 Construct a sim_inspiral --> best matching coinc_event mapping.
341 Only injections that match at least one coinc get an entry in this
345 # the log likelihood ratio stored in the likelihood column of the
346 # coinc_event table is the ranking statistic. the
"best match" is
347 # the coinc with the highest value in this column. although it has
348 # not been true in the past, there is now a one-to-one relationship
349 # between the value of this ranking statistic and false-alarm rate,
350 # therefore it is OK to order by log likelihood ratio and then,
351 # later, impose a
"detection" threshold based on false-alarm rate.
354 connection.cursor().execute(
"""
355 CREATE TEMPORARY TABLE
358 SELECT a.event_id as sid,
359 coinc_event.coinc_event_id as cid,
360 coinc_event.likelihood as lr
361 FROM coinc_event_map as a
362 JOIN coinc_event_map AS b ON (b.coinc_event_id == a.coinc_event_id)
363 JOIN coinc_event ON (coinc_event.coinc_event_id == b.event_id)
364 WHERE a.table_name == 'sim_inspiral'
365 AND b.table_name == 'coinc_event'
366 AND NOT EXISTS (SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0);
369 connection.cursor().execute(
"CREATE INDEX IF NOT EXISTS sim_coinc_map_helper_index ON sim_coinc_map_helper (sid, cid);")
371 connection.cursor().execute(
"""
372 CREATE TEMPORARY TABLE
376 sim_inspiral.simulation_id AS simulation_id,
392 coinc_event_id IS NOT NULL;
396 connection.cursor().execute(
"DROP INDEX sim_coinc_map_helper_index;")
398 contents.connection.cursor().execute(
"""
399 CREATE TEMPORARY TABLE
403 coinc_inspiral.combined_far AS far, sim_coinc_map.simulation_id AS sim_id
406 JOIN coinc_inspiral ON ( coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id )
409 contents.connection.cursor().execute(
"""
410 CREATE TEMPORARY TABLE
414 sim_coinc_map.simulation_id AS sim_id, sngl_inspiral.event_id AS sngl_id
417 JOIN coinc_event_map as mapA ON ( mapA.coinc_event_id == sim_coinc_map.coinc_event_id )
418 JOIN sngl_inspiral ON ( sngl_inspiral.event_id == mapA.event_id )
421 contents.connection.cursor().execute(
"CREATE INDEX IF NOT EXISTS sim_id_combined_far_index ON sim_id_combined_far (far, sim_id)")
422 contents.connection.cursor().execute(
"CREATE INDEX IF NOT EXISTS sim_id_sngl_id_index ON sim_id_sngl_id (sim_id, sngl_id)")
424 contents.connection.cursor().execute(
"""
425 CREATE TEMPORARY TABLE
431 sim_id_combined_far.far
434 JOIN sim_id_sngl_id ON (
435 sim_inspiral.simulation_id == sim_id_sngl_id.sim_id
437 JOIN sngl_inspiral ON (
438 sngl_inspiral.event_id == sim_id_sngl_id.sngl_id
440 JOIN sim_id_combined_far ON (
441 sim_id_combined_far.sim_id == sim_id_sngl_id.sim_id
445 contents.connection.cursor().execute(
"DROP INDEX sim_id_combined_far_index")
446 contents.connection.cursor().execute(
"DROP INDEX sim_id_sngl_id_index")
449 # =============================================================================
453 # =============================================================================
457 class SummaryTable(object):
460 self.bgcandidates = []
464 def add_contents(
self, contents):
465 self.base = contents.base
466 if contents.sim_inspiral_table:
467 #For now we only return summary information on non injections
469 self.candidates += contents.connection.cursor().execute(
"""
471 coinc_inspiral.combined_far,
472 coinc_inspiral.false_alarm_rate,
473 coinc_event.likelihood,
475 coinc_inspiral.end_time + coinc_inspiral.end_time_ns * 1e-9,
477 coinc_inspiral.mchirp,
479 coinc_event.instruments,
481 group_concat(sngl_inspiral.ifo || ":
" || sngl_inspiral.snr || ":
" || sngl_inspiral.chisq || ":
" || sngl_inspiral.mass1 || ":
" || sngl_inspiral.mass2 || ":
" || sngl_inspiral.spin1z || ":
" || sngl_inspiral.spin2z, " ")
484 JOIN coinc_event_map ON (
485 sngl_inspiral.event_id == coinc_event_map.event_id AND coinc_event_map.table_name == "sngl_inspiral
"
488 coinc_event_map.coinc_event_id == coinc_inspiral.coinc_event_id
492 JOIN coinc_event ON (
493 coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
502 time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0
504 AND combined_far IS NOT NULL
510 self.bgcandidates += contents.connection.cursor().execute(
"""
512 coinc_inspiral.combined_far,
513 coinc_inspiral.false_alarm_rate,
514 coinc_event.likelihood,
516 coinc_inspiral.end_time + coinc_inspiral.end_time_ns * 1e-9,
518 coinc_inspiral.mchirp,
520 coinc_event.instruments,
522 group_concat(sngl_inspiral.ifo || ":
" || sngl_inspiral.snr || ":
" || sngl_inspiral.chisq || ":
" || sngl_inspiral.mass1 || ":
" || sngl_inspiral.mass2 || ":
" || sngl_inspiral.spin1z || ":
" || sngl_inspiral.spin2z, " ")
525 JOIN coinc_event_map ON (
526 sngl_inspiral.event_id == coinc_event_map.event_id AND coinc_event_map.table_name == "sngl_inspiral
"
529 coinc_event_map.coinc_event_id == coinc_inspiral.coinc_event_id
533 JOIN coinc_event ON (
534 coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
543 time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0
545 AND combined_far IS NOT NULL
552 contents.connection.cursor().execute(
"CREATE TEMPORARY TABLE distinct_ifos AS SELECT DISTINCT(ifos) AS ifos FROM coinc_inspiral")
553 for instruments, num in contents.connection.cursor().execute(
"""
554 SELECT distinct_ifos.ifos, count(*) FROM coinc_inspiral JOIN distinct_ifos ON (distinct_ifos.ifos==coinc_inspiral.ifos) JOIN coinc_event ON (coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id) WHERE coinc_inspiral.ifos==distinct_ifos.ifos AND NOT EXISTS(SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0) GROUP BY distinct_ifos.ifos;
556 key = frozenset(lsctables.instrumentsproperty.get(instruments))
557 self.num_trigs.setdefault(key,0)
558 self.num_trigs[key] += num
560 contents.connection.cursor().execute(
"DROP TABLE distinct_ifos")
562 for on_instruments in set(contents.background_livetime) | set(contents.zerolag_livetime):
563 self.livetime.setdefault(on_instruments, 0.0)
565 for on_instruments, livetime in contents.zerolag_livetime.items():
566 self.livetime[on_instruments] += livetime
568 def write_candidate_json(self, candidates, fname):
593 for rank, values in enumerate(candidates, 1):
594 if values[0] is None:
595 # FIXME this probably isn
't the correct thing
596 # to do...the issue is that the is_healthy()
597 # conditions for cold booting an analysis go
602 # |------------------------------------------------->
604 # |--------------| | |
605 # Extra time LRs start to FARs start to
606 # added to be assigned be assigned
610 # there will be small biases due do the startup
614 # values[9] is a string that is e.g., H1:4.8993754:1.0139208:2.061641:1.145543 L1:8.2582664:1.1890973:2.061641:1.145543
615 row = [rank] + [truncate(float(v), 3) for v in values[:4]] + [truncate(float(values[4]), 6, si=False)]
616 row.append(gpstime.gps_to_utc(float(values[4])).strftime("%Y-%m-%d %H:%M:%S"))
617 row.extend([truncate(float(v), 3) for v in values[5:7]] + list(values[7:9]))
619 # populate row with trigger data
620 ifodict = {"H1": ['-
', '-
'], "L1": ['-
', '-
'], "V1": ['-
', '-
']}
621 template_params = ['-
'] * 4
622 for ifo_row in values[9].split():
623 ifodata = ifo_row.split(":")
624 ifodict[ifodata[0]] = [truncate(float(v), 3) for v in ifodata[1:3]]
625 template_params = [truncate(float(v), 3) for v in ifodata[3:]]
627 # add template params + SNR/chi^2 for all ifos
628 row.extend(template_params)
629 for ifo in sorted(ifodict.keys()):
630 row.extend(ifodict[ifo])
635 save_table(fname, fields, data)
638 self.candidates.sort()
639 self.write_candidate_json(self.candidates[:101], self.base+'summary_table.json
')
640 self.bgcandidates.sort()
641 self.write_candidate_json(self.bgcandidates[:101], self.base+'bgsummary_table.json
')
642 yield None, None, None
645 # =============================================================================
647 # Injection Parameter Distributions
649 # =============================================================================
653 class InjectionParameterDistributionPlots(object):
657 def add_contents(self, contents):
658 if contents.sim_inspiral_table is None:
661 for values in contents.connection.cursor().execute("""
667 sim = contents.sim_inspiral_table.row_from_cols(values)
668 del sim.process_id, sim.source, sim.simulation_id
669 instruments = frozenset(instrument for instrument, segments in contents.seglists.items() if sim.time_geocent in segments)
670 self.injections.setdefault(sim.waveform, []).append(sim)
673 for waveform, sims in self.injections.items():
674 for col1, col2, ax1, ax2, name, aspect in [
675 ([sim.mass1 for sim in sims], [sim.mass2 for sim in sims], r"$M_{1}$ ($\mathrm{M}_{\odot}$)", r"$M_{2}$ ($\mathrm{M}_{\odot}$)", "sim_dist_m1_m2_%s", None),
676 ([float(sim.time_geocent) for sim in sims], [math.log10(sim.distance) for sim in sims], r"$\textrm{Time (s)}$", r"$\log_{10} (\mathrm{distance} / 1\,\mathrm{Mpc})$", "sim_dist_time_distance_%s", None),
677 ([sim.longitude * 12 / math.pi for sim in sims], [math.sin(sim.latitude) for sim in sims], r"$\textrm{RA (h)}$", r"$\sin \mathrm{dec}$", "sim_dist_ra_dec_%s", None),
678 ([math.cos(sim.inclination) for sim in sims], [sim.polarization for sim in sims], r"$\cos \mathrm{inclination}$", r"$\textrm{Polarization (rad)}$", "sim_dist_inc_pol_%s", None),
679 ([sim.spin1z for sim in sims], [sim.spin2z for sim in sims], r"$s1_z$", r"$s2_z$", "sim_dist_spin1z_spin2z_%s", None)
681 fig = plotsumm.plot_injection_param_dist(col1, col2, ax1, ax2, waveform)
682 yield fig, name % (waveform), False
686 # =============================================================================
690 # =============================================================================
694 class MissedFoundPlots(object):
695 class MissedFound(object):
696 def __init__(self, on_instruments, far_thresh, missed_found_plots, remove_precession, isolate_precession, snr_segments):
697 self.on_instruments = on_instruments
698 self.far_thresh = far_thresh
700 self.missed_found_plots = missed_found_plots
701 self.remove_precession = remove_precession
702 self.isolate_precession = isolate_precession
703 self.snr_segments = snr_segments
705 def add_contents(self, contents):
706 self.base = contents.base
707 zerolag_segments = contents.seglists.intersection(self.on_instruments) - contents.seglists.union(contents.instruments - self.on_instruments)
708 # why is this intersection being done?
709 # FIXME: why are "found" injections split up by
710 # what instruments recovered them at all? what is
711 # going on? this pipeline hasn't organized results
712 # by instrument combination in at least a decade, I
713 # have no idea why this code was written this way.
714 # OMG I hate found/missed plots! they
're *so*
716 zerolag_segments &= self.snr_segments
717 for values in contents.connection.cursor().execute("""
725 JOIN coinc_inspiral ON (
726 coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id
729 sim_coinc_map.simulation_id == sim_inspiral.simulation_id
730 AND coinc_inspiral.combined_far < ?
734 """, (self.far_thresh if self.far_thresh is not None else float("+inf"),)):
735 sim = contents.sim_inspiral_table.row_from_cols(values)
736 del sim.process_id, sim.source, sim.simulation_id
737 if sim.time_geocent in zerolag_segments:
738 # any nonzero nonz spin -> precession_bool=True -> precessing injection
739 # all zero nonz spin -> precession_bool=Fales -> non precesssing injection
740 precession_bool = any(s != 0.0 for s in (sim.spin1x, sim.spin1y, sim.spin2x, sim.spin2y))
741 if self.remove_precession and precession_bool:
743 if self.isolate_precession and not precession_bool:
745 participating_instruments = lsctables.instrumentsproperty.get(values[-1])
746 if participating_instruments is not None:
747 participating_instruments = frozenset(participating_instruments)
748 self.found_in.setdefault(participating_instruments, []).append(sim)
751 missed = self.found_in.pop(None, [])
753 # Define decisive distance even if there is one instrument
754 # FIXME We have NANs in the eff_distance column now so this
755 # function does not work
756 def decisive_distance(sim, instruments):
757 if len(instruments) > 1:
758 return sorted(sim_get_chirp_eff_dist(sim,instrument) for instrument in instruments)[1]
760 return sim_get_chirp_eff_dist(sim,list(instruments)[0])
761 def decisive_chirp_distance(sim, instruments):
762 if len(instruments) > 1:
763 return sorted(sim_get_chirp_eff_dist(sim,instrument) for instrument in instruments)[1]
765 return sim_get_chirp_eff_dist(sim,list(instruments)[0])
767 def decisive_charsnr(sim, oninstruments):
768 if len(oninstruments) > 3:
769 raise ValueError("More than 3 instruments not supported for injection snr calculation at this time.")
771 alphas = {'H1
':sim.alpha4, 'L1
':sim.alpha5, 'V1
':sim.alpha6}
773 for ifo in oninstruments:
774 snrlist.append(alphas[ifo])
775 if len(snrlist) == 3:
776 # Decisive SNR is second loudest for triple
777 return sorted(snrlist)[1]
779 # Decisive SNR for doubles and singles
780 return sorted(snrlist)[0]
782 for cnt, (title, x_label, x_func, y_label, y_func, filename_fragment) in enumerate((
783 (r"$\textrm{Distance vs.\ Chirp Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"$D$ ($\mathrm{Mpc}$)", lambda sim, instruments: sim.distance, "d_vs_mchirp"),
784 (r"$\textrm{Decisive Distance vs.\ Chirp Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_mchirp"),
785 (r"$\textrm{Chirp Decisive Distance vs.\ Chirp Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"$\mathrm{Decisive} D_{\mathrm{chirp, eff}}$ ($\mathrm{Mpc}$)", decisive_chirp_distance, "chirpdist_vs_mchirp"),
786 (r"$\textrm{Chirp Decisive Distance vs.\ Eta (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$\eta$", lambda sim: sim.eta, r"$\mathrm{Decisive} D_{\mathrm{chirp, eff}}$ ($\mathrm{Mpc}$)", decisive_chirp_distance, "chirpdist_vs_eta"),
787 (r"$\textrm{Decisive Distance vs.\ Total Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mass1 + sim.mass2, r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_mtotal"),
788 (r"$\textrm{Decisive Distance vs.\ Effective Spin (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$\chi$", lambda sim: (sim.spin1z*sim.mass1 + sim.spin2z*sim.mass2)/(sim.mass1 + sim.mass2), r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_chi"),
789 (r"$\textrm{Decisive Distance vs.\ Time (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"GPS Time (s)", lambda sim: sim.time_geocent, r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_t")
791 ifo_count_summary = {''.join(sorted(combo)): '---
' for num_ifos in range(1, len(self.missed_found_plots.instruments)+1) for combo in sorted(list(itertools.combinations(self.missed_found_plots.instruments, num_ifos)), reverse=True)}
792 ifo_count_summary['missed
'] = '---
'
794 for participating_instruments, sims in sorted(self.found_in.items(), key = (lambda x: lsctables.instrumentsproperty.set(x[0]))):
796 ifo_count_summary["".join(sorted(participating_instruments))] = len(sims)
797 found_data[participating_instruments] = (
798 [x_func(sim) for sim in sims],
799 [y_func(sim, participating_instruments) for sim in sims]
803 ifo_count_summary["missed"] = len(missed)
804 for rank, sim in enumerate(missed):
805 self.missed_found_plots.missed_summary_data.append(["".join(sorted(self.on_instruments)), sim.waveform, float(sim.time_at_instrument("H1", {"H1": 0.0})), float(sim.time_at_instrument("L1", {"L1": 0.0})), float(sim.time_at_instrument("V1", {"V1": 0.0})), sim.mass1, sim.mass2, sim.spin1x, sim.spin1y, sim.spin1z, sim.spin2x, sim.spin2y, sim.spin2z, sim.distance, decisive_chirp_distance(sim, self.on_instruments), sim.inclination, sim.alpha4, sim.alpha5, sim.alpha6, decisive_charsnr(sim, self.on_instruments)])
807 [x_func(sim) for sim in missed],
808 [y_func(sim, self.on_instruments) for sim in missed]
814 for ifos in ifo_count_summary.keys():
815 if ifo_count_summary[ifos] != '---
':
816 total_count += ifo_count_summary[ifos]
817 ifo_count_summary['total
'] = total_count
818 ifo_columns = sorted([key for key in ifo_count_summary.keys() if 'missed
' not in key and 'total
' not in key], key=lambda item: (-len(item), item)) + ['missed
', 'total
']
819 missed_found_row = ["".join(sorted(self.on_instruments))] + [ifo_count_summary[ifo_col] for ifo_col in ifo_columns]
820 self.missed_found_plots.injection_summary_data.append(missed_found_row)
821 fig = plotsumm.plot_missed_found(found_data, missed_data, x_label, y_label, title)
822 yield fig, filename_fragment, False
824 for cnt, (title, x_label, x_func, y_label, filename_fragment) in enumerate((
825 (r"Decisive Characteristic SNR vs.\ Chirp Mass (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"Decisive Characteristic SNR", "dec_expsnr_vs_mchirp"),
826 (r"Decisive Characteristic SNR vs.\ Total Mass (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mass1 + sim.mass2, r"Decisive Characteristic SNR", "dec_expsnr_vs_mtotal"),
827 (r"Decisive Characteristic SNR vs.\ Eta (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$\eta$", lambda sim: sim.eta, r"Decisive Characteristic SNR", "dec_expsnr_vs_eta"),
828 (r"Decisive Characteristic SNR vs.\ Effective Spin (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$\chi$", lambda sim: (sim.spin1z*sim.mass1 + sim.spin2z*sim.mass2)/(sim.mass1 + sim.mass2), r"Decisive Characteristic SNR", "dec_expsnr_vs_chi"),
829 (r"Decisive Characteristic SNR vs.\ Time (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"GPS Time (s)", lambda sim: sim.time_geocent, r"Decisivive Characteristic SNR", "dec_expsnr_vs_t")
833 for participating_instruments, sims in sorted(self.found_in.items(), key = (lambda x: lsctables.instrumentsproperty.set(x[0]))):
834 found_data[participating_instruments] = (
835 [x_func(sim) for sim in sims],
836 [decisive_charsnr(sim, self.on_instruments) for sim in sims]
840 [x_func(sim) for sim in missed],
841 [decisive_charsnr(sim, self.on_instruments) for sim in missed]
845 fig = plotsumm.plot_missed_found(found_data, missed_data, x_label, y_label, title)
846 yield fig, filename_fragment, False
848 print >> sys.stderr, "Cannot create expected SNR plots, no positive values, probably the SNRs are not set"
850 def __init__(self, far_thresh, remove_precession, isolate_precession, snr_segments):
851 self.far_thresh = far_thresh
853 self.injection_summary_data = []
854 self.missed_summary_data = []
855 self.remove_precession = remove_precession
856 self.isolate_precession = isolate_precession
857 self.snr_segments = snr_segments
858 self.instruments = set()
860 def add_contents(self, contents):
861 self.base = contents.base
862 if contents.sim_inspiral_table is None:
865 for on_instruments in contents.on_instruments_combos:
866 self.instruments.update(on_instruments)
867 for on_instruments in contents.on_instruments_combos:
868 if on_instruments not in self.plots:
869 self.plots[on_instruments] = self.MissedFound(on_instruments, self.far_thresh, self, self.remove_precession, self.isolate_precession, self.snr_segments)
870 self.plots[on_instruments].add_contents(contents)
873 for on_instruments in sorted(self.plots.keys(), key=lambda item: (-len(item), item)):
874 plot = self.plots[on_instruments]
875 for fig, filename_fragment, is_open_box in plot.finish():
876 yield fig, "%s_%s" % (filename_fragment, "".join(sorted(on_instruments))), is_open_box
878 ifo_columns = [''.join(sorted(combo)) for num_ifos in range(1, len(self.instruments)+1) for combo in sorted(list(itertools.combinations(self.instruments, num_ifos)), reverse=True)]
879 ifo_columns.sort(key=lambda item: (-len(item), item))
880 save_table(self.base + "_injection_summary.json", ["On Instruments"] + ifo_columns + ['Missed
', 'Total
'], self.injection_summary_data)
881 save_table(self.base + "_missed_summary.json", ["On Instruments", "Waveform", "H1 time", "L1 time", "V1 time", "m1", "m2", "S_1x", "S_1y", "S_1z", "S_2x", "S_2y", "S_2z", "D (Mpc)", "Decisive D chirp,eff (Mpc)" , "Inclination", "H1 SNR", "L1 SNR", "V1 SNR", "Decisive SNR"], self.missed_summary_data)
885 # =============================================================================
889 # =============================================================================
893 class ParameterAccuracyPlots(object):
894 def __init__(self, far_thresh):
895 self.far_thresh = far_thresh
896 self.sim_sngl_pairs = {}
899 def get_inj_snr(sim, instrument):
900 alphas = {'H1
':'alpha4
', 'L1
':'alpha5
', 'V1
':'alpha6
'}
901 return getattr(sim, "%s" % alphas[instrument])
903 def add_contents(self, contents):
904 if contents.sim_inspiral_table is None:
905 # not an injections file
907 n_simcolumns = len(contents.sim_inspiral_table.columnnames)
909 for values in contents.connection.cursor().execute("SELECT * FROM sim_sngl_far"):
910 if values[-1] <= self.far_thresh:
911 sim = contents.sim_inspiral_table.row_from_cols(values)
912 sngl = contents.sngl_inspiral_table.row_from_cols(values[n_simcolumns:])
914 del sim.process_id, sim.source, sim.simulation_id
915 del sngl.process_id, sngl.event_id
916 self.sim_sngl_pairs.setdefault((sim.waveform, sngl.ifo), []).append((sim, sngl, far))
919 for (waveform, instrument), pairs in self.sim_sngl_pairs.items():
920 fig = plotsumm.plot_param_accuracy_scatter(
921 [sim.mchirp for sim, sngl, far in pairs],
922 [sngl.mchirp - sim.mchirp for sim, sngl, far in pairs],
923 [far for sim, sngl, far in pairs],
924 r"Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
925 r"Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
927 r"Absolute $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
929 yield fig, "mchirp_acc_abs_scatter_%s_%s" % (waveform, instrument), False
931 fig = plotsumm.plot_param_accuracy_histogram(
932 numpy.array([sngl.mchirp - sim.mchirp for sim, sngl, far in pairs]),
933 r"Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
934 r"Absolute $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
936 yield fig, "mchirp_acc_abs_hist_%s_%s" % (waveform, instrument), False
938 fig = plotsumm.plot_param_accuracy_scatter(
939 [sim.mchirp for sim, sngl, far in pairs],
940 [(sngl.mchirp - sim.mchirp) / sim.mchirp for sim, sngl, far in pairs],
941 [far for sim, sngl, far in pairs],
942 r"Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
943 r"(Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$) / Inj. $M_{\mathrm{chirp}}$",
945 r"Fractional $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
947 yield fig, "mchirp_acc_frac_scatter_%s_%s" % (waveform, instrument), False
949 fig = plotsumm.plot_param_accuracy_histogram(
950 numpy.array([(sngl.mchirp - sim.mchirp) / sim.mchirp for sim, sngl, far in pairs]),
951 r"(Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$)/ Inj. $M_{\mathrm{chirp}}$",
952 r"Fractional $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
954 yield fig, "mchirp_acc_frac_hist_%s_%s" % (waveform, instrument), False
956 fig = plotsumm.plot_param_accuracy_scatter(
957 [sim.mtotal for sim, sngl, far in pairs],
958 [(sngl.mtotal - sim.mtotal) / sim.mtotal for sim, sngl, far in pairs],
959 [far for sim, sngl, far in pairs],
960 r"Inj. $M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)",
961 r"(Rec. $M_{\mathrm{total}}$ - Inj. $M_{\mathrm{total}}$) / Inj. $M_{\mathrm{total}}$",
963 r"Fractional $M_{\mathrm{total}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
965 yield fig, "mtotal_acc_frac_scatter_%s_%s" % (waveform, instrument), False
967 fig = plotsumm.plot_param_accuracy_histogram(
968 numpy.array([(sngl.mtotal - sim.mtotal) / sim.mtotal for sim, sngl, far in pairs]),
969 r"(Rec. $M_{\mathrm{total}}$ - Inj. $M_{\mathrm{total}}$) / Inj. $M_{\mathrm{total}}$",
970 r"Fractional $M_{\mathrm{total}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
972 yield fig, "mtotal_acc_frac_hist_%s_%s" % (waveform, instrument), False
974 fig = plotsumm.plot_param_accuracy_scatter(
975 [sim.eta for sim, sngl, far in pairs],
976 [sngl.eta - sim.eta for sim, sngl, far in pairs],
977 [far for sim, sngl, far in pairs],
979 r"Rec. $\eta$ - Inj. $\eta$",
981 r"Absolute $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
983 yield fig, "eta_acc_abs_scatter_%s_%s" % (waveform, instrument), False
985 fig = plotsumm.plot_param_accuracy_histogram(
986 numpy.array([sngl.eta - sim.eta for sim, sngl, far in pairs]),
987 r"Rec. $\eta$ - Inj. $\eta$",
988 r"Absolute $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
990 yield fig, "eta_acc_abs_hist_%s_%s" % (waveform, instrument), False
992 fig = plotsumm.plot_param_accuracy_scatter(
993 [sim.eta for sim, sngl, far in pairs],
994 [(sngl.eta - sim.eta) / sim.eta for sim, sngl, far in pairs],
995 [far for sim, sngl, far in pairs],
997 r"(Rec. $\eta$ - Inj. $\eta$) / Inj. $\eta$",
999 r"Fractional $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1001 yield fig, "eta_acc_frac_scatter_%s_%s" % (waveform, instrument), False
1003 fig = plotsumm.plot_param_accuracy_histogram(
1004 numpy.array([(sngl.eta - sim.eta) / sim.eta for sim, sngl, far in pairs]),
1005 r"(Rec. $\eta$ - Inj. $\eta$) / Inj. $\eta$",
1006 r"Fractional $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1008 yield fig, "eta_acc_frac_hist_%s_%s" % (waveform, instrument), False
1010 fig = plotsumm.plot_param_accuracy(
1011 [sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}) for sim, sngl, far in pairs],
1012 [(sngl.end - sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}))*1000. for sim, sngl, far in pairs],
1013 r"Injection End Time (GPS s)",
1014 r"Rec. End Time - Injection End Time (ms)",
1015 r"End Time Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1017 yield fig, "t_acc_scatter_%s_%s" % (waveform, instrument), False
1019 fig = plotsumm.plot_param_accuracy_histogram(
1020 numpy.array([float(sngl.end - sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}))*1000. for sim, sngl, far in pairs]),
1021 r"Rec. End Time - Injection End Time (ms)",
1022 r"End Time Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1024 yield fig, "t_acc_hist_%s_%s" % (waveform, instrument), False
1026 fig = plotsumm.plot_param_accuracy(
1027 [sim.chi for sim, sngl, far in pairs],
1028 [sngl.chi for sim, sngl, far in pairs],
1031 r"Effective Spin Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1033 yield fig, "chi_acc_scatter_%s_%s" % (waveform, instrument), False
1035 fig = plotsumm.plot_param_accuracy(
1036 [self.get_inj_snr(sim, instrument) for sim, sngl, far in pairs],
1037 [sngl.snr for sim, sngl, far in pairs],
1040 r"SNR Recovery in %s (%s Injections)" % (instrument, waveform.replace("_", "\_")),
1041 loglog=max([self.get_inj_snr(sim, instrument) for sim, sngl, far in pairs]) > 20
1043 yield fig, "snr_rec_scatter_%s_%s" % (waveform, instrument), False
1045 fig = plotsumm.plot_param_accuracy_histogram(
1046 numpy.array([(sngl.snr - self.get_inj_snr(sim, instrument)) for sim, sngl, far in pairs]),
1047 r"(Rec. SNR - Inj SNR)",
1048 r"SNR Diff in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1050 yield fig, "snr_diff_hist_%s_%s" % (waveform, instrument), False
1053 # =============================================================================
1055 # Background vs. Injections --- Single Instrument
1057 # =============================================================================
1061 class BackgroundVsInjectionPlots(object):
1062 class Points(object):
1074 return bool(self.snr)
1076 def __init__(self, snr_min):
1077 self.snr_min = snr_min
1078 self.injections = {}
1079 self.background = {}
1082 def add_contents(self, contents):
1083 if contents.sim_inspiral_table is None:
1084 # non-injections file
1085 for values in contents.connection.cursor().execute("""
1094 time_slide.time_slide_id == coinc_event.time_slide_id
1095 AND time_slide.offset != 0
1099 JOIN coinc_event_map ON (
1100 coinc_event_map.coinc_event_id == coinc_event.coinc_event_id
1102 JOIN sngl_inspiral ON (
1103 coinc_event_map.table_name == 'sngl_inspiral
'
1104 AND coinc_event_map.event_id == sngl_inspiral.event_id
1107 coinc_event.coinc_def_id == ?
1108 """, (contents.ii_definer_id,)):
1109 sngl = contents.sngl_inspiral_table.row_from_cols(values)
1110 eta = sngl.mass1 * sngl.mass2 / (sngl.mass1 + sngl.mass2)**2
1111 mtot = sngl.mass1 + sngl.mass2
1112 chieff = (sngl.mass1 * sngl.spin1z + sngl.mass2 * sngl.spin2z) / mtot
1113 instrument = sngl.ifo
1114 is_background = values[-1]
1116 if instrument not in self.background:
1117 self.background[instrument] = self.Points()
1118 self.background[instrument].snr.append(sngl.snr)
1119 self.background[instrument].chi2.append(sngl.chisq)
1120 self.background[instrument].bankveto.append(sngl.bank_chisq)
1121 self.background[instrument].mchirp.append(mtot * eta**(3. / 5))
1122 self.background[instrument].eta.append(eta)
1123 self.background[instrument].chieff.append(chieff)
1124 self.background[instrument].end_time.append(float(sngl.end))
1126 if instrument not in self.zerolag:
1127 self.zerolag[instrument] = self.Points()
1128 self.zerolag[instrument].snr.append(sngl.snr)
1129 self.zerolag[instrument].chi2.append(sngl.chisq)
1130 self.zerolag[instrument].bankveto.append(sngl.bank_chisq)
1131 self.zerolag[instrument].mchirp.append(mtot * eta**(3. / 5))
1132 self.zerolag[instrument].eta.append(eta)
1133 self.zerolag[instrument].chieff.append(chieff)
1134 self.zerolag[instrument].end_time.append(float(sngl.end))
1137 n_simcolumns = len(contents.sim_inspiral_table.columnnames)
1138 for values in contents.connection.cursor().execute("SELECT * FROM sim_sngl_far"):
1139 sim = contents.sim_inspiral_table.row_from_cols(values)
1140 sngl = contents.sngl_inspiral_table.row_from_cols(values[n_simcolumns:])
1142 eta = sngl.mass1 * sngl.mass2 / (sngl.mass1 + sngl.mass2)**2
1143 mtot = sngl.mass1 + sngl.mass2
1144 chieff = (sngl.mass1 * sngl.spin1z + sngl.mass2 * sngl.spin2z) / mtot
1145 instrument = sngl.ifo
1147 # FIXME, what should this be?
1148 spin = (sim.mass1 * (sim.spin1x**2 + sim.spin1y**2 + sim.spin1z**2)**.5 + sim.mass2 * (sim.spin1x**2 + sim.spin1y**2 + sim.spin1**2)**.5 ) / (sim.mass1 + sim.mass2)
1149 if end_time in contents.seglists[instrument]:
1150 if instrument not in self.injections:
1151 self.injections[instrument] = self.Points()
1152 self.injections[instrument].snr.append(sngl.snr)
1153 self.injections[instrument].chi2.append(sngl.chisq)
1154 self.injections[instrument].bankveto.append(sngl.bank_chisq)
1155 self.injections[instrument].mchirp.append(mtot * eta**(3. / 5))
1156 self.injections[instrument].eta.append(eta)
1157 self.injections[instrument].chieff.append(chieff)
1158 self.injections[instrument].spin.append(spin)
1161 for instrument in set(self.injections) | set(self.background) | set(self.zerolag):
1162 self.injections.setdefault(instrument, self.Points())
1163 self.background.setdefault(instrument, self.Points())
1164 self.zerolag.setdefault(instrument, self.Points())
1166 for instrument in self.background:
1167 fig = plotsumm.plot_snr_chi2_background(instrument, self.snr_min, self.injections, self.background)
1168 yield fig, "chi2_vs_rho_%s" % instrument, False
1170 fig = plotsumm.plot_snr_chi2_background(instrument, self.snr_min, self.injections, self.background, self.zerolag)
1171 yield fig, "chi2_vs_rho_%s" % instrument, True
1173 # the following plots require background and injections
1174 if self.background[instrument] and self.injections[instrument]:
1175 # for the following plots, sort injections by SNR -- descending
1176 sortable = numpy.array(self.injections[instrument].snr).argsort()[::-1]
1177 inj_mcs = numpy.array(self.injections[instrument].mchirp)[sortable]
1178 inj_etas = numpy.array(self.injections[instrument].eta)[sortable]
1179 inj_snrs = numpy.array(self.injections[instrument].snr)[sortable]
1180 inj_chisq = numpy.array(self.injections[instrument].chi2)[sortable]
1182 # sort background triggers by SNR -- ascending
1183 sortable = numpy.array(self.background[instrument].snr).argsort()
1184 bg_mcs = numpy.array(self.background[instrument].mchirp)[sortable]
1185 bg_etas = numpy.array(self.background[instrument].eta)[sortable]
1186 bg_snrs = numpy.array(self.background[instrument].snr)[sortable]
1187 bg_chisq = numpy.array(self.background[instrument].chi2)[sortable]
1188 bg_chieffs = numpy.array(self.background[instrument].chieff)[sortable]
1190 # mass dependence of chisq
1191 fig = plotsumm.plot_mass_chi2_snr2_background(inj_mcs, inj_chisq, inj_snrs, bg_mcs, bg_chisq, bg_snrs, instrument)
1192 yield fig, "chi2_vs_mc_vs_rho_%s" % instrument, False
1194 # background parameter distributions
1195 fig = plotsumm.plot_background_param_dist(
1196 bg_mcs, bg_etas, numpy.log10(bg_snrs),
1197 r"$M_\mathrm{chirp}$", r"$\eta$", "log(SNR) in %s" % instrument,
1198 r"Background Events in %s (Closed Box)" % instrument
1200 yield fig, "bgparams_mchirp_vs_eta_vs_snr_%s" % instrument, False
1202 # background parameter distributions
1203 flow = 10 # arbitrary choice
1204 a0 = 5. / (256 * (numpy.pi * flow)**(8./3) )
1205 a3 = numpy.pi / (8 * (numpy.pi * flow)**(5./3) )
1206 bg_tau0s = a0 * (lal.MTSUN_SI * bg_mcs)**(-5./3)
1207 bg_tau3s = (a3 / bg_etas) * (bg_etas * bg_tau0s / a0)**(2./5)
1208 fig = plotsumm.plot_background_param_dist(
1209 bg_tau0s, bg_tau3s, numpy.log10(bg_snrs),
1210 r"$\tau_0$ (s)", r"$\tau_3$ (s)", "log(SNR) in %s" % instrument,
1211 r"Background Events in %s (Closed Box)" % instrument
1213 yield fig, "bgparams_tau0_vs_tau3_vs_snr_%s" % instrument, False
1215 # background parameter distributions
1216 fig = plotsumm.plot_background_param_dist(
1217 bg_mcs, bg_chieffs, numpy.log10(bg_snrs),
1218 r"$M_\mathrm{chirp}$", r"$\chi_\mathrm{eff}$", "log(SNR) in %s" % instrument,
1219 r"Background Events in %s (Closed Box)" % instrument
1221 yield fig, "bgparams_mchirp_vs_chieff_vs_snr_%s" % instrument, False
1225 # =============================================================================
1227 # Background vs. Injections --- Multi Instrument
1229 # =============================================================================
1233 class BackgroundVsInjectionPlotsMulti(object):
1234 class Points(object):
1236 self.background_snr = []
1237 self.injections_snr = []
1238 self.zerolag_snr = []
1239 self.background_deff = []
1240 self.injections_deff = []
1241 self.injections_mchirp = []
1242 self.injections_chieff = []
1243 self.zerolag_deff = []
1244 self.background_mchirp = []
1245 self.background_mtot = []
1246 self.background_eta = []
1247 self.background_chieff = []
1249 def __init__(self, snr_min):
1250 self.snr_min = snr_min
1253 def add_contents(self, contents):
1254 if contents.sim_inspiral_table is None:
1255 # non-injections file
1256 for values in contents.connection.cursor().execute("""
1266 time_slide.time_slide_id == coinc_event.time_slide_id
1267 AND time_slide.offset != 0
1271 JOIN coinc_event_map AS coinc_event_map_x ON (
1272 coinc_event_map_x.coinc_event_id == coinc_event.coinc_event_id
1274 JOIN sngl_inspiral AS sngl_inspiral_x ON (
1275 coinc_event_map_x.table_name == 'sngl_inspiral
'
1276 AND coinc_event_map_x.event_id == sngl_inspiral_x.event_id
1278 JOIN coinc_event_map AS coinc_event_map_y ON (
1279 coinc_event_map_y.coinc_event_id == coinc_event.coinc_event_id
1281 JOIN sngl_inspiral AS sngl_inspiral_y ON (
1282 coinc_event_map_y.table_name == 'sngl_inspiral
'
1283 AND coinc_event_map_y.event_id == sngl_inspiral_y.event_id
1285 JOIN coinc_inspiral ON (
1286 coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
1289 coinc_event.coinc_def_id == ?
1290 AND sngl_inspiral_x.ifo > sngl_inspiral_y.ifo
1291 """, (contents.ii_definer_id,)):
1292 x = contents.sngl_inspiral_table.row_from_cols(values)
1293 y = contents.sngl_inspiral_table.row_from_cols(values[len(contents.sngl_inspiral_table.columnnames):])
1294 is_background, = values[-1:]
1295 instrument_pair = (x.ifo, y.ifo)
1296 if instrument_pair not in self.points:
1297 self.points[instrument_pair] = self.Points()
1299 self.points[instrument_pair].background_snr.append((x.snr, y.snr))
1300 eta = x.mass1 * x.mass2 / (x.mass1 + x.mass2)**2
1301 mtot = x.mass1 + x.mass2
1302 self.points[instrument_pair].background_eta.append(eta)
1303 self.points[instrument_pair].background_mtot.append(mtot)
1304 self.points[instrument_pair].background_mchirp.append(mtot * eta**(3./5))
1305 self.points[instrument_pair].background_chieff.append((x.mass1 * x.spin1z + x.mass2 * x.spin2z) / mtot)
1308 self.points[instrument_pair].zerolag_snr.append((x.snr, y.snr))
1311 for values in contents.connection.cursor().execute("""
1316 sngl_inspiral AS sngl_inspiral_x
1317 JOIN sim_id_sngl_id AS sim_id_sngl_id_x ON sim_id_sngl_id_x.sngl_id == sngl_inspiral_x.event_id
1318 JOIN sngl_inspiral AS sngl_inspiral_y JOIN sim_id_sngl_id AS sim_id_sngl_id_y ON sim_id_sngl_id_y.sngl_id == sngl_inspiral_y.event_id
1320 sim_id_sngl_id_x.sim_id == sim_id_sngl_id_y.sim_id AND sngl_inspiral_x.ifo > sngl_inspiral_y.ifo;
1322 x = contents.sngl_inspiral_table.row_from_cols(values)
1323 y = contents.sngl_inspiral_table.row_from_cols(values[len(contents.sngl_inspiral_table.columnnames):])
1324 instrument_pair = (x.ifo, y.ifo)
1325 if instrument_pair not in self.points:
1326 self.points[instrument_pair] = self.Points()
1327 self.points[instrument_pair].injections_snr.append((x.snr, y.snr))
1328 eta = x.mass1 * x.mass2 / (x.mass1 + x.mass2)**2
1329 mtot = x.mass1 + x.mass2
1330 self.points[instrument_pair].injections_mchirp.append(mtot * eta**(3./5))
1331 self.points[instrument_pair].injections_chieff.append((x.mass1 * x.spin1z + x.mass2 * x.spin2z) / mtot)
1335 for (x_instrument, y_instrument), points in self.points.items():
1336 fig = plotsumm.plot_param_background_multiifo(
1337 x_instrument, y_instrument, self.snr_min, "SNR", "$\rho$",
1338 points.injections_snr, points.background_snr
1340 yield fig, "rho_%s_vs_%s" % (y_instrument, x_instrument), False
1342 fig = plotsumm.plot_param_background_multiifo(
1343 x_instrument, y_instrument, self.snr_min, "SNR", "$\rho$",
1344 points.injections_snr, points.background_snr, points.zerolag_snr
1346 yield fig, "rho_%s_vs_%s" % (y_instrument, x_instrument), True
1348 fig = plotsumm.plot_param_background_multiifo(
1349 x_instrument, y_instrument, self.snr_min, "Effective Distance", "$D_{\mathrm{eff}}$",
1350 points.injections_deff, points.background_deff
1352 yield fig, "deff_%s_vs_%s" % (y_instrument, x_instrument), False
1354 fig = plotsumm.plot_param_background_multiifo(
1355 x_instrument, y_instrument, self.snr_min, "Effective Distance", "$D_{\mathrm{eff}}$",
1356 points.injections_deff, points.background_deff, points.zerolag_deff
1358 yield fig, "deff_%s_vs_%s" % (y_instrument, x_instrument), True
1362 # =============================================================================
1364 # Rate vs. Threshold Plots
1366 # =============================================================================
1370 class RateVsThreshold(object):
1371 def __init__(self, fapfar, snr_min):
1372 self.background_ln_likelihood_ratio = []
1373 self.zerolag_ln_likelihood_ratio = []
1374 self.background_far = []
1375 self.zerolag_far = []
1376 self.background_fap = []
1377 self.zerolag_fap = []
1378 self.background_snr = []
1379 self.zerolag_snr = []
1380 self.fapfar = fapfar
1381 self.snr_min = snr_min
1383 def add_contents(self, contents):
1384 if contents.sim_inspiral_table is not None:
1385 # skip injection documents
1388 for ln_likelihood_ratio, far, fap, snr, is_background in connection.cursor().execute("""
1390 coinc_event.likelihood,
1391 coinc_inspiral.combined_far,
1392 coinc_inspiral.false_alarm_rate,
1400 time_slide.time_slide_id == coinc_event.time_slide_id
1401 AND time_slide.offset != 0
1405 JOIN coinc_event ON (
1406 coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
1409 coinc_event.likelihood >= ?
1410 """, (self.fapfar.minrank,)):
1414 self.background_ln_likelihood_ratio.append(ln_likelihood_ratio)
1415 self.background_far.append(far)
1416 self.background_fap.append(fap)
1417 self.background_snr.append(snr)
1419 self.zerolag_ln_likelihood_ratio.append(ln_likelihood_ratio)
1420 self.zerolag_far.append(far)
1421 self.zerolag_fap.append(fap)
1422 self.zerolag_snr.append(snr)
1425 fig = plotsumm.plot_candidate_lnL_vs_snr(self.snr_min, self.background_snr, self.background_ln_likelihood_ratio)
1426 yield fig, "lr_vs_snr", False
1428 fig = plotsumm.plot_candidate_lnL_vs_snr(
1429 self.snr_min, self.background_snr, self.background_ln_likelihood_ratio,
1430 self.zerolag_snr, self.zerolag_ln_likelihood_ratio
1432 yield fig, "lr_vs_snr", True
1434 for ln_likelihood_ratio, fars, is_open_box in [(self.zerolag_ln_likelihood_ratio, self.zerolag_far, True), (self.background_ln_likelihood_ratio, self.background_far, False)]:
1436 # fars in ascending order --> ifars in descending order
1437 zerolag_stats = 1. / numpy.array(sorted(fars))
1438 fig = plotsumm.plot_rate_vs_ifar(zerolag_stats, self.fapfar, is_open_box)
1439 yield fig, "count_vs_ifar", is_open_box
1441 if ln_likelihood_ratio:
1442 # ln(L) in ascending order
1443 zerolag_stats = numpy.array(sorted(ln_likelihood_ratio, reverse = True))
1444 fig = plotsumm.plot_rate_vs_lnL(zerolag_stats, self.fapfar, is_open_box)
1445 yield fig, "count_vs_lr", is_open_box
1447 if self.background_ln_likelihood_ratio:
1448 background_stats = numpy.array(sorted(self.background_ln_likelihood_ratio, reverse = True))
1449 zerolag_stats = numpy.array(sorted(self.zerolag_ln_likelihood_ratio, reverse = True))
1450 fig = plotsumm.plot_rate_vs_background_lnL(zerolag_stats, background_stats, self.fapfar)
1451 yield fig, "count_vs_lr_fig3", True
1454 class Segments(object):
1455 def __init__(self, base):
1456 self.all_segs_dict = {}
1461 def add_contents(self, contents):
1462 # only process non-injection documents
1463 if contents.sim_inspiral_table is None:
1464 for name, seglists in contents.all_segs_dict.items():
1465 # need to use operator because Python won't
1466 # allow a function call on the LHS of |=
1467 # for some mystery reason.
1468 operator.ior(self.all_segs_dict.setdefault(name, segments.segmentlistdict()), seglists)
1471 segs = reduce(segments.segmentlistdict.__or__, self.all_segs_dict.values(), segments.segmentlistdict())
1472 self.extent = segs.extent_all()
1474 for name, seglists in self.all_segs_dict.items():
1475 for ifo, seglist in seglists.items():
1477 self.data.append([
"%s: %s" % (str(ifo), str(name)),
"",
"%.2f-%.2f" % (float(seg[0]), float(seg[1])), float(seg[0])*1000 + 315964800000 - 17000, float(seg[1])*1000 + 315964800000 - 17000])
1479 analyzable_instruments_set = set(segs.keys())
1480 for n in range(1, 1 + len(segs)):
1481 for ifo_combos in itertools.combinations(list(analyzable_instruments_set), n):
1482 this = segs.intersection(ifo_combos) - segs.union(analyzable_instruments_set - set(ifo_combos))
1484 #FIXME inf is not handled properly
1485 start = float(this.extent()[0])
1486 end = float(this.extent()[1])
1487 if end == float(
"inf"):
1489 duration = end - start
1490 self.table.append([name,
",".join(ifo_combos), start, end, duration])
1492 self.table.insert(0, [
"all",
"all", float(self.extent[0]), float(self.extent[1]), float(abs(self.extent))])
1493 f = open(
"%s_segments.json" % self.base,
"w")
1494 f.write(repr(self.data))
1496 save_table(
"%s_segment_table.json" % self.base, [
"name",
"ifos",
"start",
"end",
"extent"], self.table)
1500 # =============================================================================
1504 # =============================================================================
1509 # Parse command line
1513 options, filenames = parse_command_line()
1517 # Load likelihood input
1521 if options.likelihood_file is not None:
1522 rankingstatpdf = far.marginalize_pdf_urls([options.likelihood_file], which =
"RankingStatPDF", verbose = options.verbose)
1524 rankingstatpdf = None
1525 snr_min = far.inspiral_lr.LnLRDensity.snr_min
1526 if rankingstatpdf is not None:
1527 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
1537 def new_plots(plots, fapfar, far_thresh, remove_precession, isolate_precession, snr_segments):
1540 MissedFoundPlots(far_thresh, remove_precession, isolate_precession, snr_segments),
1541 ParameterAccuracyPlots(far_thresh = far_thresh),
1542 BackgroundVsInjectionPlots(snr_min = snr_min),
1543 BackgroundVsInjectionPlotsMulti(snr_min = snr_min),
1544 RateVsThreshold(fapfar = fapfar, snr_min = snr_min),
1545 InjectionParameterDistributionPlots(),
1548 plots = range(len(l))
1549 return [(i, l[i]) for i in plots]
1551 plots = new_plots(options.plot_group, fapfar, options.far_threshold, options.remove_precession, options.isolate_precession, rankingstatpdf.segments if rankingstatpdf is not None else None)
1559 seg_class = Segments(base = os.path.join(options.output_dir, options.user_tag))
1561 for n, filename in enumerate(filenames):
1563 print >>sys.stderr,
"%d/%d: %s" % (n + 1, len(filenames), filename)
1564 with dbtables.workingcopy(filename, tmp_path = options.tmp_space, discard = True, verbose = options.verbose) as working_filename:
1565 connection = sqlite3.connect(str(working_filename))
1566 contents = CoincDatabase(connection, options.segments_name, veto_segments_name = options.vetoes_name, verbose = options.verbose, plotsummary_json = os.path.split(filename)[-1].replace(
".sqlite",
"").replace(
".tmp",
""), base = os.path.join(options.output_dir, options.user_tag), extend_veto_segments = options.extend_veto_segments, shrink_data_segments = options.shrink_data_segments)
1567 if contents.sim_inspiral_table is not None:
1568 create_sim_coinc_view(connection)
1569 seg_class.add_contents(contents)
1570 for plot_group, plot in plots:
1572 print >>sys.stderr,
"adding to plot group %d ..." % plot_group
1573 plot.add_contents(contents)
1580 # Finish and write plots, deleting them as we go to save memory
1584 filename_template = dagparts.T050017_filename(
"H1L1V1",
"GSTLAL_INSPIRAL_PLOTSUMMARY_%s_%02d_%s_%s", contents.seglists.extent_all(),
"%s", path = options.output_dir)
1586 plot_group, plot = plots.pop(0)
1587 for fig, filename_fragment, is_open_box in plot.finish():
1590 fig.tight_layout(rect=(0.03, 0.02, 0.98, 0.98))
1593 for fmt in options.format:
1594 if filename_fragment and fig:
1595 filename = filename_template % (options.user_tag, plot_group, filename_fragment, (
"openbox" if is_open_box else
"closedbox"), fmt)
1597 print >>sys.stderr,
"writing %s ..." % filename
1598 fig.savefig(filename)
def group
group a list roughly according to the distribution in parts, e.g.