#!/usr/bin/env python3
#
# Copyright (C) 2009-2013  Kipp Cannon, Chad Hanna, Drew Keppel
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

### A program to produce a variety of plots from a gstlal inspiral analysis, e.g. IFAR plots, missed found, etc.

#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


import bisect
from functools import reduce
import itertools
import json
import math
import operator
from optparse import OptionParser
import os
import sqlite3
import sys

import numpy
import scipy

import lal
from lal import gpstime
from lal import iterutils
from lal.utils import CacheEntry

from ligo import segments
from ligo.lw import dbtables
from ligo.lw import lsctables
from ligo.lw.utils import segments as ligolw_segments

from gstlal import far
from gstlal import dagparts
from gstlal.plots import summary as plotsumm
from gstlal.plots.util import golden_ratio


def format_column(column):
	return column.lower().replace(' ', '_').replace(':', '').replace(';', '')


def save_table(fname, fields, rows):
	### format data
	fields = [{'key': format_column(col), 'label': col, 'sortable': True} for col in fields]
	colnames = [field['key'] for field in fields]
	items = [{col: val for col, val in zip(colnames, row)} for row in rows]

	### write to disk
	with open(fname, 'w') as f:
		f.write(json.dumps({'fields': fields, 'items': items}))


class SimInspiral(lsctables.SimInspiral):
	@property
	def mtotal(self):
		return self.mass1 + self.mass2

	@property
	def chi(self):
		return (self.mass1 * self.spin1z + self.mass2 * self.spin2z) / self.mtotal


class SnglInspiral(lsctables.SnglInspiral):
	@property
	def mtotal(self):
		return self.mass1 + self.mass2

	@property
	def eta(self):
		return self.mass1 * self.mass2 / self.mtotal**2.

	@property
	def mchirp(self):
		return self.mtotal * self.eta**0.6

	@property
	def chi(self):
		return (self.mass1 * self.spin1z + self.mass2 * self.spin2z) / self.mtotal

lsctables.SimInspiralTable.RowType = SimInspiral
lsctables.SnglInspiralTable.RowType = SnglInspiral


__author__ = "Kipp Cannon <kipp.cannon@ligo.org>, Chad Hanna <channa@ligo.caltech.edu>"
__version__ = "git id %s" % "FIXME"
__date__ = "FIXME"


#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#


def parse_command_line():
	parser = OptionParser(
		version = "Name: %%prog\n%s" % "" # FIXME
	)
	parser.add_option("","--input-cache", help = "Also get the list of databases to process from this LAL cache.")
	parser.add_option("--user-tag", metavar = "user-tag", default = "ALL", help = "Set the prefix for output filenames (default = \"ALL\").")
	parser.add_option("--output-dir", metavar = "output-dir", default = ".", help = "Provide an output directory")
	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\").")
	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")
	parser.add_option("--extend-veto-segments", metavar = "float", type = float, help = "Pad segments by this number of seconds (on both sides)")
	parser.add_option("--segments-name", metavar = "name", default = "statevectorsegments", help = "Set the name of the segments that were analyzed (default = \"statevectorsegments\").")
	parser.add_option("--vetoes-name", metavar = "name", default = "vetoes", help = "Set the name of the veto segments (default = \"vetoes\").")
	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)
 0. Summary Table (top 10 loudest events globally across all zero lag triggers read in)
 1. Missed Found (Scatter plots of missed and found injections on several axes)
 2. Injection Parameter Accuracy Plots
 3. Background Vs Injection Plots (sngl detector triggers from coincs of snr, chisq, bank chisq, ...)
 4. Background Vs Injection Plots pairwise (SNR instrument 1 vs. instrument2, ...),
 5. Rate Vs Threshold (SNR histograms, IFAR histograms, ...)
 6. Injection Parameter Distribution Plots (The input parameters that went into inspinj, like mass1 vs mass2, ...)
""")
	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).")
	parser.add_option("--likelihood-file", metavar = "filename", help = "Path to the marginalized likelihood file.")
	# FIXME Add check that plot group 1 being generated if these options are given
	parser.add_option("--remove-precession", action = "store_true", help = "Ignore precessing injections when generating missed/found plots")
	parser.add_option("--isolate-precession", action = "store_true", help = "Only make missed/found plots for precessing injections")
	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.")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	options, filenames = parser.parse_args()

	if options.plot_group is not None:
		options.plot_group = sorted(list(map(int, options.plot_group)))

	if (options.plot_group is None or set(options.plot_group) & set((1, 5))) and options.likelihood_file is None:
		raise ValueError("Must provide --likelihood-file to generate plots in groups 1 and/or 5.")

	if not options.format:
		options.format = ["png"]

	if not filenames:
		filenames = []
	if options.input_cache:
		filenames.extend(c.path for c in map(CacheEntry, open(options.input_cache)))

	return options, filenames


#
# =============================================================================
#
#                                   Database
#
# =============================================================================
#


class CoincDatabase(object):
	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):
		"""
		Compute and record some summary information about the
		database.
		"""

		self.base = base
		self.connection = connection
		xmldoc = dbtables.get_xml(connection)
		self.all_segs_dict = {}

		cursor = connection.cursor()

		# find the tables
		try:
			self.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
		except ValueError:
			self.sngl_inspiral_table = None
		try:
			self.sim_inspiral_table = lsctables.SimInspiralTable.get_table(xmldoc)
		except ValueError:
			self.sim_inspiral_table = None
		try:
			self.coinc_def_table = lsctables.CoincDefTable.get_table(xmldoc)
			self.coinc_table = lsctables.CoincTable.get_table(xmldoc)
			self.time_slide_table = lsctables.TimeSlideTable.get_table(xmldoc)
		except ValueError:
			self.coinc_def_table = None
			self.coinc_table = None
			self.time_slide_table = None
		try:
			self.coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
		except ValueError:
			self.coinc_inspiral_table = None

		# determine a few coinc_definer IDs
		# FIXME:  don't hard-code the numbers
		if self.coinc_def_table is not None:
			try:
				self.ii_definer_id = self.coinc_def_table.get_coinc_def_id("inspiral", 0, create_new = False)
			except KeyError:
				self.ii_definer_id = None
			try:
				self.si_definer_id = self.coinc_def_table.get_coinc_def_id("inspiral", 1, create_new = False)
			except KeyError:
				self.si_definer_id = None
			try:
				self.sc_definer_id = self.coinc_def_table.get_coinc_def_id("inspiral", 2, create_new = False)
			except KeyError:
				self.sc_definer_id = None
		else:
			self.ii_definer_id = None
			self.si_definer_id = None
			self.sc_definer_id = None

		# retrieve the distinct on and participating instruments
		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,))]
		self.participating_instruments_combos = [frozenset(lsctables.instrumentsproperty.get(x)) for x, in cursor.execute("SELECT DISTINCT(ifos) FROM coinc_inspiral")]

		# get the segment lists
		self.seglists = ligolw_segments.segmenttable_get_by_name(xmldoc, data_segments_name).coalesce()
		if shrink_data_segments is not None:
			# Make sure all segments are at least long enough to be
			# contracted (e.g. if a segment is 32 seconds long but
			# the user is going to contract it by 17 seconds, then
			# the end time of the segment would come before the
			# start time of the segment. This is bad)
			for seglist in self.seglists.values():
				iterutils.inplace_filter(lambda s: abs(s) > 2*shrink_data_segments, seglist)
			self.seglists.contract(shrink_data_segments)
		self.instruments = set(self.seglists)
		if veto_segments_name is not None:
			self.veto_segments = ligolw_segments.segmenttable_get_by_name(xmldoc, veto_segments_name).coalesce()
			if extend_veto_segments is not None:
				self.veto_segments.protract(extend_veto_segments)
		else:
			self.veto_segments = segments.segmentlistdict()
		self.seglists -= self.veto_segments

		# get all the segments in the database to use as a summary
		for llwsegs in ligolw_segments.LigolwSegments(xmldoc).coalesce():
			seglists = self.all_segs_dict.setdefault(llwsegs.name, segments.segmentlistdict())
			# FIXME:  should be populating valid segments upstream
			seglists |= segments.segmentlistdict.fromkeys(llwsegs.instruments, llwsegs.active) #& llwsegs.valid)

		# get the live time
		if verbose:
			print >>sys.stderr, "calculating background livetimes: ",
		# retrieve background offset vectors
		self.offset_vectors = [offsetvector for offsetvector in dbtables.TimeSlideTable(connection = connection).as_dict().values() if any(offsetvector.values())]

		if verbose:
			print >>sys.stderr
		self.zerolag_livetime = {}
		self.background_livetime = {}
		for on_instruments in self.on_instruments_combos:
			tmpsegs = self.seglists.intersection(on_instruments) - self.seglists.union(self.instruments - on_instruments)
			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])))))
		# FIXME:  background livetime hard-coded to be same
		# as zero-lag livetime.  figure out what to do
		self.background_livetime.update(self.zerolag_livetime)

		# verbosity
		if verbose:
			print >>sys.stderr, "database overview:"
			for on_instruments in self.on_instruments_combos:
				print >>sys.stderr, "\tzero-lag livetime for %s: %f s" % ("+".join(sorted(on_instruments)), self.zerolag_livetime[on_instruments])
				print >>sys.stderr, "\tbackground livetime for %s: %f s" % ("+".join(sorted(on_instruments)), self.background_livetime[on_instruments])
			if self.sngl_inspiral_table is not None:
				print >>sys.stderr, "\tinspiral events: %d" % len(self.sngl_inspiral_table)
			if self.sim_inspiral_table is not None:
				print >>sys.stderr, "\tinjections: %d" % len(self.sim_inspiral_table)
			if self.time_slide_table is not None:
				print >>sys.stderr, "\ttime slides: %d" % cursor.execute("SELECT COUNT(DISTINCT(time_slide_id)) FROM time_slide").fetchone()[0]
			if self.coinc_def_table is not None:
				for description, n in cursor.execute("SELECT description, COUNT(*) FROM coinc_definer NATURAL JOIN coinc_event GROUP BY coinc_def_id"):
					print >>sys.stderr, "\t%s: %d" % (description, n)

		if plotsummary_json:
			data = []
			for on_instruments in self.on_instruments_combos:
				data.append(["zero-lag livetime for %s" % ("+".join(sorted(on_instruments))), str(self.zerolag_livetime[on_instruments])])
				data.append(["background livetime for %s" % ("+".join(sorted(on_instruments))), str(self.background_livetime[on_instruments])])
			if self.sngl_inspiral_table is not None:
				data.append(["inspiral events", str(len(self.sngl_inspiral_table))])
			if self.sim_inspiral_table is not None:
				data.append(["injections", str(len(self.sim_inspiral_table))])
			if self.time_slide_table is not None:
				data.append(["time slides", str(cursor.execute("SELECT COUNT(DISTINCT(time_slide_id)) FROM time_slide").fetchone()[0])])
			if self.coinc_def_table is not None:
				for description, n in cursor.execute("SELECT description, COUNT(*) FROM coinc_definer NATURAL JOIN coinc_event GROUP BY coinc_def_id"):
					data.append([description, str(n)])
			if self.sim_inspiral_table is None:
				save_table("%s_plot_summary.json" % self.base, ['Summary of database:', plotsummary_json], data)

#
# =============================================================================
#
#                                  Utilities
#
# =============================================================================
#

def sim_get_chirp_eff_dist(sim, instrument):
	return getattr(sim, "eff_dist_%s" % instrument[0].lower()) * sim.mchirp**(5./6.) / 1.22**(5./6.)

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")):
	if not arabics:
		return ""
	if i < arabics[0]:
		return roman(i, arabics[1:], romans[1:])
	return romans[0] + roman(i - arabics[0], arabics, romans)

def truncate(f, digits, si=True):
	assert digits > 0, 'number of digits must be positive'
	if si:
		return float(('%10.' + str(digits) + 'e') % f)
	else:
		return float(('%10.' + str(digits) + 'f') % f)


def create_sim_coinc_view(connection):
	"""
	Construct a sim_inspiral --> best matching coinc_event mapping.
	Only injections that match at least one coinc get an entry in this
	table.
	"""
	#
	# the log likelihood ratio stored in the likelihood column of the
	# coinc_event table is the ranking statistic.  the "best match" is
	# the coinc with the highest value in this column.  although it has
	# not been true in the past, there is now a one-to-one relationship
	# between the value of this ranking statistic and false-alarm rate,
	# therefore it is OK to order by log likelihood ratio and then,
	# later, impose a "detection" threshold based on false-alarm rate.
	#

	connection.cursor().execute("""
CREATE TEMPORARY TABLE
	sim_coinc_map_helper
AS
	SELECT a.event_id as sid,
		coinc_event.coinc_event_id as cid,
		coinc_event.likelihood as lr
	FROM coinc_event_map as a
		JOIN coinc_event_map AS b ON (b.coinc_event_id == a.coinc_event_id)
		JOIN coinc_event ON (coinc_event.coinc_event_id == b.event_id)
	WHERE a.table_name == 'sim_inspiral'
		AND b.table_name == 'coinc_event'
		AND NOT EXISTS (SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0);
	""")

	connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_coinc_map_helper_index ON sim_coinc_map_helper (sid, cid);")

	connection.cursor().execute("""
CREATE TEMPORARY TABLE
        sim_coinc_map
AS
        SELECT
                sim_inspiral.simulation_id AS simulation_id,
                (
                        SELECT
                                cid
                        FROM
				sim_coinc_map_helper
                        WHERE
                                sid = simulation_id
                        ORDER BY
                                lr
			DESC
                        LIMIT 1
                ) AS coinc_event_id
        FROM
                sim_inspiral
        WHERE
                coinc_event_id IS NOT NULL;

	""")

	connection.cursor().execute("DROP INDEX sim_coinc_map_helper_index;")

	contents.connection.cursor().execute("""
CREATE TEMPORARY TABLE
	sim_id_combined_far
AS
	SELECT
		coinc_inspiral.combined_far AS far, sim_coinc_map.simulation_id AS sim_id
	FROM
		sim_coinc_map
		JOIN coinc_inspiral ON ( coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id  )
	""")

	contents.connection.cursor().execute("""
CREATE TEMPORARY TABLE
	sim_id_sngl_id
	AS
		SELECT
			sim_coinc_map.simulation_id AS sim_id, sngl_inspiral.event_id AS sngl_id
		FROM
			sim_coinc_map
		JOIN coinc_event_map as mapA ON ( mapA.coinc_event_id == sim_coinc_map.coinc_event_id )
		JOIN sngl_inspiral ON ( sngl_inspiral.event_id == mapA.event_id )
	""")

	contents.connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_id_combined_far_index ON sim_id_combined_far (far, sim_id)")
	contents.connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_id_sngl_id_index ON sim_id_sngl_id (sim_id, sngl_id)")

	contents.connection.cursor().execute("""
CREATE TEMPORARY TABLE
	sim_sngl_far
	AS
		SELECT
			sim_inspiral.*,
			sngl_inspiral.*,
			sim_id_combined_far.far
		FROM
			sim_inspiral
			JOIN sim_id_sngl_id ON (
				sim_inspiral.simulation_id == sim_id_sngl_id.sim_id
			)
			JOIN sngl_inspiral ON (
				sngl_inspiral.event_id == sim_id_sngl_id.sngl_id
			)
			JOIN sim_id_combined_far ON (
				sim_id_combined_far.sim_id == sim_id_sngl_id.sim_id
			)
	""")

	contents.connection.cursor().execute("DROP INDEX sim_id_combined_far_index")
	contents.connection.cursor().execute("DROP INDEX sim_id_sngl_id_index")

#
# =============================================================================
#
#                      Summary Table
#
# =============================================================================
#


class SummaryTable(object):
	def __init__(self):
		self.candidates = []
		self.bgcandidates = []
		self.livetime = {}
		self.num_trigs = {}

	def add_contents(self, contents):
		self.base = contents.base
		if contents.sim_inspiral_table:
			#For now we only return summary information on non injections
			return
		self.candidates += contents.connection.cursor().execute("""
SELECT
	coinc_inspiral.combined_far,
	coinc_inspiral.false_alarm_rate,
	coinc_event.likelihood,
	coinc_inspiral.snr,
	coinc_inspiral.end_time + coinc_inspiral.end_time_ns * 1e-9,
	coinc_inspiral.mass,
	coinc_inspiral.mchirp,
	coinc_inspiral.ifos,
	coinc_event.instruments,
	(SELECT
		group_concat(sngl_inspiral.ifo || ":" || sngl_inspiral.snr || ":" || sngl_inspiral.chisq || ":" || sngl_inspiral.mass1 || ":" || sngl_inspiral.mass2 || ":" || sngl_inspiral.spin1z || ":" || sngl_inspiral.spin2z, " ")
	FROM
		sngl_inspiral
		JOIN coinc_event_map ON (
			sngl_inspiral.event_id == coinc_event_map.event_id AND coinc_event_map.table_name == "sngl_inspiral"
		)
	WHERE
		coinc_event_map.coinc_event_id == coinc_inspiral.coinc_event_id
	)
FROM
	coinc_inspiral
	JOIN coinc_event ON (
		coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
	)
WHERE
	NOT EXISTS(
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0
	)
	AND combined_far IS NOT NULL
ORDER BY
	combined_far
LIMIT 100
		""").fetchall()

		self.bgcandidates += contents.connection.cursor().execute("""
SELECT
	coinc_inspiral.combined_far,
	coinc_inspiral.false_alarm_rate,
	coinc_event.likelihood,
	coinc_inspiral.snr,
	coinc_inspiral.end_time + coinc_inspiral.end_time_ns * 1e-9,
	coinc_inspiral.mass,
	coinc_inspiral.mchirp,
	coinc_inspiral.ifos,
	coinc_event.instruments,
	(SELECT
		group_concat(sngl_inspiral.ifo || ":" || sngl_inspiral.snr || ":" || sngl_inspiral.chisq || ":" || sngl_inspiral.mass1 || ":" || sngl_inspiral.mass2 || ":" || sngl_inspiral.spin1z || ":" || sngl_inspiral.spin2z, " ")
	FROM
		sngl_inspiral
		JOIN coinc_event_map ON (
			sngl_inspiral.event_id == coinc_event_map.event_id AND coinc_event_map.table_name == "sngl_inspiral"
		)
	WHERE
		coinc_event_map.coinc_event_id == coinc_inspiral.coinc_event_id
	)
FROM
	coinc_inspiral
	JOIN coinc_event ON (
		coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
	)
WHERE
	EXISTS(
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0
	)
	AND combined_far IS NOT NULL
ORDER BY
	combined_far
LIMIT 100
		""").fetchall()


		contents.connection.cursor().execute("CREATE TEMPORARY TABLE distinct_ifos AS SELECT DISTINCT(ifos) AS ifos FROM coinc_inspiral")
		for instruments, num in contents.connection.cursor().execute("""
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;
"""):
			key = frozenset(lsctables.instrumentsproperty.get(instruments))
			self.num_trigs.setdefault(key,0)
			self.num_trigs[key] += num

		contents.connection.cursor().execute("DROP TABLE distinct_ifos")

		for on_instruments in set(contents.background_livetime) | set(contents.zerolag_livetime):
			self.livetime.setdefault(on_instruments, 0.0)

		for on_instruments, livetime in contents.zerolag_livetime.items():
			self.livetime[on_instruments] += livetime

	def write_candidate_json(self, candidates, fname):
		data = []
		fields = [
			"rank",
			"FAR (Hz)",
			"FAP",
			"ln L",
			"SNR",
			"GPS time",
			"UTC time",
			"M total",
			"M chirp",
			"Found IFOs",
			"On IFOs",
			"m1",
			"m2",
			"S_1z",
			"S_2z",
			"H1 SNR",
			"H1 chisq",
			"L1 SNR",
			"L1 chisq",
			"V1 SNR",
			"V1 chisq"
		]
		for rank, values in enumerate(candidates, 1):
			if values[0] is None:
				# FIXME this probably isn't the correct thing
				# to do...the issue is that the is_healthy()
				# conditions for cold booting an analysis go
				# like this:
				#
				# online analysis
				#     starts
				#       |------------------------------------------------->
				#                        ^                   ^
				#       |--------------| |                   |
				#       Extra time       LRs start to        FARs start to
				#       added to         be assigned         be assigned
				#       livetime
				#       without coincs
				#
				# there will be small biases due do the startup
				# being out of sync.
				#
				continue
			# 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
			row = [rank] + [truncate(float(v), 3) for v in values[:4]] + [truncate(float(values[4]), 6, si=False)]
			row.append(gpstime.gps_to_utc(float(values[4])).strftime("%Y-%m-%d %H:%M:%S"))
			row.extend([truncate(float(v), 3) for v in values[5:7]] + list(values[7:9]))

			# populate row with trigger data
			ifodict = {"H1": ['-', '-'], "L1": ['-', '-'], "V1": ['-', '-']}
			template_params = ['-'] * 4
			for ifo_row in values[9].split():
				ifodata = ifo_row.split(":")
				ifodict[ifodata[0]] = [truncate(float(v), 3) for v in ifodata[1:3]]
				template_params = [truncate(float(v), 3) for v in ifodata[3:]]

			# add template params + SNR/chi^2 for all ifos
			row.extend(template_params)
			for ifo in sorted(ifodict.keys()):
				row.extend(ifodict[ifo])

			# add row to table
			data.append(row)

		save_table(fname, fields, data)

	def finish(self):
		self.candidates.sort()
		self.write_candidate_json(self.candidates[:101], self.base+'summary_table.json')
		self.bgcandidates.sort()
		self.write_candidate_json(self.bgcandidates[:101], self.base+'bgsummary_table.json')
		yield None, None, None

#
# =============================================================================
#
#                      Injection Parameter Distributions
#
# =============================================================================
#


class InjectionParameterDistributionPlots(object):
	def __init__(self):
		self.injections = {}

	def add_contents(self, contents):
		if contents.sim_inspiral_table is None:
			# no injections
			return
		for values in contents.connection.cursor().execute("""
SELECT
	*
FROM
	sim_inspiral
			"""):
			sim = contents.sim_inspiral_table.row_from_cols(values)
			del sim.process_id, sim.source, sim.simulation_id
			instruments = frozenset(instrument for instrument, segments in contents.seglists.items() if sim.time_geocent in segments)
			self.injections.setdefault(sim.waveform, []).append(sim)

	def finish(self):
		for waveform, sims in self.injections.items():
			for col1, col2, ax1, ax2, name, aspect in [
				([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),
				([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),
				([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),
				([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),
				([sim.spin1z for sim in sims], [sim.spin2z for sim in sims], r"$s1_z$", r"$s2_z$", "sim_dist_spin1z_spin2z_%s", None)
			]:
				fig = plotsumm.plot_injection_param_dist(col1, col2, ax1, ax2, waveform)
				yield fig, name % (waveform), False


#
# =============================================================================
#
#                              Missed/Found Plot
#
# =============================================================================
#


class MissedFoundPlots(object):
	class MissedFound(object):
		def __init__(self, on_instruments, far_thresh, missed_found_plots, remove_precession, isolate_precession, snr_segments):
			self.on_instruments = on_instruments
			self.far_thresh = far_thresh
			self.found_in = {}
			self.missed_found_plots = missed_found_plots
			self.remove_precession = remove_precession
			self.isolate_precession = isolate_precession
			self.snr_segments = snr_segments

		def add_contents(self, contents):
			self.base = contents.base
			zerolag_segments = contents.seglists.intersection(self.on_instruments) - contents.seglists.union(contents.instruments - self.on_instruments)
			# why is this intersection being done?
			# FIXME:  why are "found" injections split up by
			# what instruments recovered them at all?  what is
			# going on?  this pipeline hasn't organized results
			# by instrument combination in at least a decade, I
			# have no idea why this code was written this way.
			# OMG I hate found/missed plots!  they're *so*
			# stupid.
			zerolag_segments &= self.snr_segments
			for values in contents.connection.cursor().execute("""
SELECT
	sim_inspiral.*,
	(
		SELECT
			coinc_inspiral.ifos
		FROM
			sim_coinc_map
			JOIN coinc_inspiral ON (
				coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id
			)
		WHERE
			sim_coinc_map.simulation_id == sim_inspiral.simulation_id
			AND coinc_inspiral.combined_far < ?
	)
FROM
	sim_inspiral
			""", (self.far_thresh if self.far_thresh is not None else float("+inf"),)):
				sim = contents.sim_inspiral_table.row_from_cols(values)
				del sim.process_id, sim.source, sim.simulation_id
				if sim.time_geocent in zerolag_segments:
					# any nonzero nonz spin -> precession_bool=True -> precessing injection
					# all zero nonz spin -> precession_bool=Fales -> non precesssing injection
					precession_bool = any(s != 0.0 for s in (sim.spin1x, sim.spin1y, sim.spin2x, sim.spin2y))
					if self.remove_precession and precession_bool:
						continue
					if self.isolate_precession and not precession_bool:
						continue
					participating_instruments = lsctables.instrumentsproperty.get(values[-1])
					if participating_instruments is not None:
						participating_instruments = frozenset(participating_instruments)
					self.found_in.setdefault(participating_instruments, []).append(sim)

		def finish(self):
			missed = self.found_in.pop(None, [])

			# Define decisive distance even if there is one instrument
			# FIXME We have NANs in the eff_distance column now so this
			# function does not work
			def decisive_distance(sim, instruments):
				if len(instruments) > 1:
					return sorted(sim_get_chirp_eff_dist(sim,instrument) for instrument in instruments)[1]
				else:
					return sim_get_chirp_eff_dist(sim,list(instruments)[0])
			def decisive_chirp_distance(sim, instruments):
				if len(instruments) > 1:
					return sorted(sim_get_chirp_eff_dist(sim,instrument) for instrument in instruments)[1]
				else:
					return sim_get_chirp_eff_dist(sim,list(instruments)[0])

			def decisive_charsnr(sim, oninstruments):
				if len(oninstruments) > 3:
					raise ValueError("More than 3 instruments not supported for injection snr calculation at this time.")
				else:
					alphas = {'H1':sim.alpha4, 'L1':sim.alpha5, 'V1':sim.alpha6}
					snrlist = []
					for ifo in oninstruments:
						snrlist.append(alphas[ifo])
					if len(snrlist) == 3:
						# Decisive SNR is second loudest for triple
						return sorted(snrlist)[1]
					else:
						# Decisive SNR for doubles and singles
						return sorted(snrlist)[0]

			for cnt, (title, x_label, x_func, y_label, y_func, filename_fragment) in enumerate((
				(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"),
				(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"),
				(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"),
				(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"),
				(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"),
				(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"),
				(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")
				)):
				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)}
				ifo_count_summary['missed'] = '---'
				found_data = {}
				for participating_instruments, sims in sorted(self.found_in.items(), key = (lambda x: lsctables.instrumentsproperty.set(x[0]))):
					if cnt == 0:
						ifo_count_summary["".join(sorted(participating_instruments))] = len(sims)
					found_data[participating_instruments] = (
						[x_func(sim) for sim in sims],
						[y_func(sim, participating_instruments) for sim in sims]
					)
				if missed:
					if cnt == 0:
						ifo_count_summary["missed"] = len(missed)
						for rank, sim in enumerate(missed):
							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)])
					missed_data = (
						[x_func(sim) for sim in missed],
						[y_func(sim, self.on_instruments) for sim in missed]
					)
				else:
					missed_data = None
				if cnt == 0:
					total_count = 0
					for ifos in ifo_count_summary.keys():
						if ifo_count_summary[ifos] != '---':
							total_count += ifo_count_summary[ifos]
					ifo_count_summary['total'] = total_count
					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']
					missed_found_row = ["".join(sorted(self.on_instruments))] + [ifo_count_summary[ifo_col] for ifo_col in ifo_columns]
					self.missed_found_plots.injection_summary_data.append(missed_found_row)
				fig = plotsumm.plot_missed_found(found_data, missed_data, x_label, y_label, title)
				yield fig, filename_fragment, False

			for cnt, (title, x_label, x_func, y_label, filename_fragment) in enumerate((
				(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"),
				(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"),
				(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"),
				(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"),
				(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")
			)):
				try:
					found_data = {}
					for participating_instruments, sims in sorted(self.found_in.items(), key = (lambda x: lsctables.instrumentsproperty.set(x[0]))):
						found_data[participating_instruments] = (
							[x_func(sim) for sim in sims],
							[decisive_charsnr(sim, self.on_instruments) for sim in sims]
						)
					if missed:
						missed_data = (
							[x_func(sim) for sim in missed],
							[decisive_charsnr(sim, self.on_instruments) for sim in missed]
						)
					else:
						missed_data = None
					fig = plotsumm.plot_missed_found(found_data, missed_data, x_label, y_label, title)
					yield fig, filename_fragment, False
				except ValueError:
					print >> sys.stderr, "Cannot create expected SNR plots, no positive values, probably the SNRs are not set"

	def __init__(self, far_thresh, remove_precession, isolate_precession, snr_segments):
		self.far_thresh = far_thresh
		self.plots = {}
		self.injection_summary_data = []
		self.missed_summary_data = []
		self.remove_precession = remove_precession
		self.isolate_precession = isolate_precession
		self.snr_segments = snr_segments
		self.instruments = set()

	def add_contents(self, contents):
		self.base = contents.base
		if contents.sim_inspiral_table is None:
			# no injections
			return
		for on_instruments in contents.on_instruments_combos:
			self.instruments.update(on_instruments)
		for on_instruments in contents.on_instruments_combos:
			if on_instruments not in self.plots:
				self.plots[on_instruments] = self.MissedFound(on_instruments, self.far_thresh, self, self.remove_precession, self.isolate_precession, self.snr_segments)
			self.plots[on_instruments].add_contents(contents)

	def finish(self):
		for on_instruments in sorted(self.plots.keys(), key=lambda item: (-len(item), item)):
			plot = self.plots[on_instruments]
			for fig, filename_fragment, is_open_box in plot.finish():
				yield fig, "%s_%s" % (filename_fragment, "".join(sorted(on_instruments))), is_open_box

		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)]
		ifo_columns.sort(key=lambda item: (-len(item), item))
		save_table(self.base + "_injection_summary.json", ["On Instruments"] + ifo_columns + ['Missed', 'Total'], self.injection_summary_data)
		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)


#
# =============================================================================
#
#                              Parameter Accuracy
#
# =============================================================================
#


class ParameterAccuracyPlots(object):
	def __init__(self, far_thresh):
		self.far_thresh = far_thresh
		self.sim_sngl_pairs = {}

	@staticmethod
	def get_inj_snr(sim, instrument):
		alphas = {'H1':'alpha4', 'L1':'alpha5', 'V1':'alpha6'}
		return getattr(sim, "%s" % alphas[instrument])

	def add_contents(self, contents):
		if contents.sim_inspiral_table is None:
			# not an injections file
			return
		n_simcolumns = len(contents.sim_inspiral_table.columnnames)

		for values in contents.connection.cursor().execute("SELECT * FROM sim_sngl_far"):
			if values[-1] <= self.far_thresh:
				sim = contents.sim_inspiral_table.row_from_cols(values)
				sngl = contents.sngl_inspiral_table.row_from_cols(values[n_simcolumns:])
				far = values[-1]
				del sim.process_id, sim.source, sim.simulation_id
				del sngl.process_id, sngl.event_id
				self.sim_sngl_pairs.setdefault((sim.waveform, sngl.ifo), []).append((sim, sngl, far))

	def finish(self):
		for (waveform, instrument), pairs in self.sim_sngl_pairs.items():
			fig = plotsumm.plot_param_accuracy_scatter(
				[sim.mchirp for sim, sngl, far in pairs],
				[sngl.mchirp - sim.mchirp for sim, sngl, far in pairs],
				[far for sim, sngl, far in pairs],
				r"Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
				r"Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
				"FAR (Hz)",
				r"Absolute $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "mchirp_acc_abs_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([sngl.mchirp - sim.mchirp for sim, sngl, far in pairs]),
				r"Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
				r"Absolute $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "mchirp_acc_abs_hist_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_scatter(
				[sim.mchirp for sim, sngl, far in pairs],
				[(sngl.mchirp - sim.mchirp) / sim.mchirp for sim, sngl, far in pairs],
				[far for sim, sngl, far in pairs],
				r"Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
				r"(Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$) / Inj. $M_{\mathrm{chirp}}$",
				"FAR (Hz)",
				r"Fractional $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "mchirp_acc_frac_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([(sngl.mchirp - sim.mchirp) / sim.mchirp for sim, sngl, far in pairs]),
				r"(Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$)/ Inj. $M_{\mathrm{chirp}}$",
				r"Fractional $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "mchirp_acc_frac_hist_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_scatter(
				[sim.mtotal for sim, sngl, far in pairs],
				[(sngl.mtotal - sim.mtotal) / sim.mtotal for sim, sngl, far in pairs],
				[far for sim, sngl, far in pairs],
				r"Inj. $M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)",
				r"(Rec. $M_{\mathrm{total}}$ - Inj. $M_{\mathrm{total}}$) / Inj. $M_{\mathrm{total}}$",
				"FAR (Hz)",
				r"Fractional $M_{\mathrm{total}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "mtotal_acc_frac_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([(sngl.mtotal - sim.mtotal) / sim.mtotal for sim, sngl, far in pairs]),
				r"(Rec. $M_{\mathrm{total}}$ - Inj. $M_{\mathrm{total}}$) / Inj. $M_{\mathrm{total}}$",
				r"Fractional $M_{\mathrm{total}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "mtotal_acc_frac_hist_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_scatter(
				[sim.eta for sim, sngl, far in pairs],
				[sngl.eta - sim.eta for sim, sngl, far in pairs],
				[far for sim, sngl, far in pairs],
				r"Inj. $\eta$",
				r"Rec. $\eta$ - Inj. $\eta$",
				"FAR (Hz)",
				r"Absolute $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "eta_acc_abs_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([sngl.eta - sim.eta for sim, sngl, far in pairs]),
				r"Rec. $\eta$ - Inj. $\eta$",
				r"Absolute $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "eta_acc_abs_hist_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_scatter(
				[sim.eta for sim, sngl, far in pairs],
				[(sngl.eta - sim.eta) / sim.eta for sim, sngl, far in pairs],
				[far for sim, sngl, far in pairs],
				r"Inj. $\eta$",
				r"(Rec. $\eta$ - Inj. $\eta$) / Inj. $\eta$",
				"FAR (Hz)",
				r"Fractional $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "eta_acc_frac_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([(sngl.eta - sim.eta) / sim.eta for sim, sngl, far in pairs]),
				r"(Rec. $\eta$ - Inj. $\eta$) / Inj. $\eta$",
				r"Fractional $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "eta_acc_frac_hist_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy(
				[sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}) for sim, sngl, far in pairs],
				[(sngl.end - sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}))*1000. for sim, sngl, far in pairs],
				r"Injection End Time (GPS s)",
				r"Rec. End Time - Injection End Time (ms)",
				r"End Time Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "t_acc_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([float(sngl.end - sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}))*1000. for sim, sngl, far in pairs]),
				r"Rec. End Time - Injection End Time (ms)",
				r"End Time Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "t_acc_hist_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy(
				[sim.chi for sim, sngl, far in pairs],
				[sngl.chi for sim, sngl, far in pairs],
				r"Inj. $\chi$",
				r"Rec. $\chi$",
				r"Effective Spin Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "chi_acc_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy(
				[self.get_inj_snr(sim, instrument) for sim, sngl, far in pairs],
				[sngl.snr for sim, sngl, far in pairs],
				r"Inj. SNR",
				r"Rec. SNR",
				r"SNR Recovery in %s (%s Injections)" % (instrument, waveform.replace("_", "\_")),
				loglog=max([self.get_inj_snr(sim, instrument) for sim, sngl, far in pairs]) > 20
			)
			yield fig, "snr_rec_scatter_%s_%s" % (waveform, instrument), False

			fig = plotsumm.plot_param_accuracy_histogram(
				numpy.array([(sngl.snr - self.get_inj_snr(sim, instrument)) for sim, sngl, far in pairs]),
				r"(Rec. SNR - Inj SNR)",
				r"SNR Diff in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
			)
			yield fig, "snr_diff_hist_%s_%s" % (waveform, instrument), False

#
# =============================================================================
#
#               Background vs. Injections --- Single Instrument
#
# =============================================================================
#


class BackgroundVsInjectionPlots(object):
	class Points(object):
		def __init__(self):
			self.snr = []
			self.chi2 = []
			self.bankveto = []
			self.mchirp = []
			self.eta = []
			self.chieff = []
			self.spin = []
			self.end_time = []

		def __bool__(self):
			return bool(self.snr)

	def __init__(self, snr_min):
		self.snr_min = snr_min
		self.injections = {}
		self.background = {}
		self.zerolag = {}

	def add_contents(self, contents):
		if contents.sim_inspiral_table is None:
			# non-injections file
			for values in contents.connection.cursor().execute("""
SELECT
	sngl_inspiral.*,
	EXISTS (
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id
			AND time_slide.offset != 0
	)
FROM
	coinc_event
	JOIN coinc_event_map ON (
		coinc_event_map.coinc_event_id == coinc_event.coinc_event_id
	)
	JOIN sngl_inspiral ON (
		coinc_event_map.table_name == 'sngl_inspiral'
		AND coinc_event_map.event_id == sngl_inspiral.event_id
	)
WHERE
	coinc_event.coinc_def_id == ?
			""", (contents.ii_definer_id,)):
				sngl = contents.sngl_inspiral_table.row_from_cols(values)
				eta = sngl.mass1 * sngl.mass2 / (sngl.mass1 + sngl.mass2)**2
				mtot = sngl.mass1 + sngl.mass2
				chieff = (sngl.mass1 * sngl.spin1z + sngl.mass2 * sngl.spin2z) / mtot
				instrument = sngl.ifo
				is_background = values[-1]
				if is_background:
					if instrument not in self.background:
						self.background[instrument] = self.Points()
					self.background[instrument].snr.append(sngl.snr)
					self.background[instrument].chi2.append(sngl.chisq)
					self.background[instrument].bankveto.append(sngl.bank_chisq)
					self.background[instrument].mchirp.append(mtot * eta**(3. / 5))
					self.background[instrument].eta.append(eta)
					self.background[instrument].chieff.append(chieff)
					self.background[instrument].end_time.append(float(sngl.end))
				else:
					if instrument not in self.zerolag:
						self.zerolag[instrument] = self.Points()
					self.zerolag[instrument].snr.append(sngl.snr)
					self.zerolag[instrument].chi2.append(sngl.chisq)
					self.zerolag[instrument].bankveto.append(sngl.bank_chisq)
					self.zerolag[instrument].mchirp.append(mtot * eta**(3. / 5))
					self.zerolag[instrument].eta.append(eta)
					self.zerolag[instrument].chieff.append(chieff)
					self.zerolag[instrument].end_time.append(float(sngl.end))
		else:
			# injections file
			n_simcolumns = len(contents.sim_inspiral_table.columnnames)
			for values in contents.connection.cursor().execute("SELECT * FROM sim_sngl_far"):
				sim = contents.sim_inspiral_table.row_from_cols(values)
				sngl = contents.sngl_inspiral_table.row_from_cols(values[n_simcolumns:])
				far = values[-1]
				eta = sngl.mass1 * sngl.mass2 / (sngl.mass1 + sngl.mass2)**2
				mtot = sngl.mass1 + sngl.mass2
				chieff = (sngl.mass1 * sngl.spin1z + sngl.mass2 * sngl.spin2z) / mtot
				instrument = sngl.ifo
				end_time = sngl.end
				# FIXME, what should this be?
				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)
				if end_time in contents.seglists[instrument]:
					if instrument not in self.injections:
						self.injections[instrument] = self.Points()
					self.injections[instrument].snr.append(sngl.snr)
					self.injections[instrument].chi2.append(sngl.chisq)
					self.injections[instrument].bankveto.append(sngl.bank_chisq)
					self.injections[instrument].mchirp.append(mtot * eta**(3. / 5))
					self.injections[instrument].eta.append(eta)
					self.injections[instrument].chieff.append(chieff)
					self.injections[instrument].spin.append(spin)

	def finish(self):
		for instrument in set(self.injections) | set(self.background) | set(self.zerolag):
			self.injections.setdefault(instrument, self.Points())
			self.background.setdefault(instrument, self.Points())
			self.zerolag.setdefault(instrument, self.Points())

		for instrument in self.background:
			fig = plotsumm.plot_snr_chi2_background(instrument, self.snr_min, self.injections, self.background)
			yield fig, "chi2_vs_rho_%s" % instrument, False

			fig = plotsumm.plot_snr_chi2_background(instrument, self.snr_min, self.injections, self.background, self.zerolag)
			yield fig, "chi2_vs_rho_%s" % instrument, True

			# the following plots require background and injections
			if self.background[instrument] and self.injections[instrument]:
				# for the following plots, sort injections by SNR -- descending
				sortable = numpy.array(self.injections[instrument].snr).argsort()[::-1]
				inj_mcs = numpy.array(self.injections[instrument].mchirp)[sortable]
				inj_etas = numpy.array(self.injections[instrument].eta)[sortable]
				inj_snrs = numpy.array(self.injections[instrument].snr)[sortable]
				inj_chisq = numpy.array(self.injections[instrument].chi2)[sortable]

				# sort background triggers by SNR -- ascending
				sortable = numpy.array(self.background[instrument].snr).argsort()
				bg_mcs = numpy.array(self.background[instrument].mchirp)[sortable]
				bg_etas = numpy.array(self.background[instrument].eta)[sortable]
				bg_snrs = numpy.array(self.background[instrument].snr)[sortable]
				bg_chisq = numpy.array(self.background[instrument].chi2)[sortable]
				bg_chieffs = numpy.array(self.background[instrument].chieff)[sortable]

				# mass dependence of chisq
				fig = plotsumm.plot_mass_chi2_snr2_background(inj_mcs, inj_chisq, inj_snrs, bg_mcs, bg_chisq, bg_snrs, instrument)
				yield fig, "chi2_vs_mc_vs_rho_%s" % instrument, False

				# background parameter distributions
				fig = plotsumm.plot_background_param_dist(
					bg_mcs, bg_etas, numpy.log10(bg_snrs),
					r"$M_\mathrm{chirp}$", r"$\eta$", "log(SNR) in %s" % instrument,
					r"Background Events in %s (Closed Box)" % instrument
				)
				yield fig, "bgparams_mchirp_vs_eta_vs_snr_%s" % instrument, False

				# background parameter distributions
				flow = 10 # arbitrary choice
				a0 = 5. / (256 * (numpy.pi * flow)**(8./3) )
				a3 = numpy.pi / (8 * (numpy.pi * flow)**(5./3) )
				bg_tau0s = a0 * (lal.MTSUN_SI * bg_mcs)**(-5./3)
				bg_tau3s = (a3 / bg_etas) * (bg_etas * bg_tau0s / a0)**(2./5)
				fig = plotsumm.plot_background_param_dist(
					bg_tau0s, bg_tau3s, numpy.log10(bg_snrs),
					r"$\tau_0$ (s)", r"$\tau_3$ (s)", "log(SNR) in %s" % instrument,
					r"Background Events in %s (Closed Box)" % instrument
				)
				yield fig, "bgparams_tau0_vs_tau3_vs_snr_%s" % instrument, False

				# background parameter distributions
				fig = plotsumm.plot_background_param_dist(
					bg_mcs, bg_chieffs, numpy.log10(bg_snrs),
					r"$M_\mathrm{chirp}$", r"$\chi_\mathrm{eff}$", "log(SNR) in %s" % instrument,
					r"Background Events in %s (Closed Box)" % instrument
				)
				yield fig, "bgparams_mchirp_vs_chieff_vs_snr_%s" % instrument, False


#
# =============================================================================
#
#               Background vs. Injections --- Multi Instrument
#
# =============================================================================
#


class BackgroundVsInjectionPlotsMulti(object):
	class Points(object):
		def __init__(self):
			self.background_snr = []
			self.injections_snr = []
			self.zerolag_snr = []
			self.background_deff = []
			self.injections_deff = []
			self.injections_mchirp = []
			self.injections_chieff = []
			self.zerolag_deff = []
			self.background_mchirp = []
			self.background_mtot = []
			self.background_eta = []
			self.background_chieff = []

	def __init__(self, snr_min):
		self.snr_min = snr_min
		self.points = {}

	def add_contents(self, contents):
		if contents.sim_inspiral_table is None:
			# non-injections file
			for values in contents.connection.cursor().execute("""
SELECT
	sngl_inspiral_x.*,
	sngl_inspiral_y.*,
	EXISTS (
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id
			AND time_slide.offset != 0
	)
FROM
	coinc_event
	JOIN coinc_event_map AS coinc_event_map_x ON (
		coinc_event_map_x.coinc_event_id == coinc_event.coinc_event_id
	)
	JOIN sngl_inspiral AS sngl_inspiral_x ON (
		coinc_event_map_x.table_name == 'sngl_inspiral'
		AND coinc_event_map_x.event_id == sngl_inspiral_x.event_id
	)
	JOIN coinc_event_map AS coinc_event_map_y ON (
		coinc_event_map_y.coinc_event_id == coinc_event.coinc_event_id
	)
	JOIN sngl_inspiral AS sngl_inspiral_y ON (
		coinc_event_map_y.table_name == 'sngl_inspiral'
		AND coinc_event_map_y.event_id == sngl_inspiral_y.event_id
	)
	JOIN coinc_inspiral ON (
		coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
	)
WHERE
	coinc_event.coinc_def_id == ?
	AND sngl_inspiral_x.ifo > sngl_inspiral_y.ifo
			""", (contents.ii_definer_id,)):
				x = contents.sngl_inspiral_table.row_from_cols(values)
				y = contents.sngl_inspiral_table.row_from_cols(values[len(contents.sngl_inspiral_table.columnnames):])
				is_background, = values[-1:]
				instrument_pair = (x.ifo, y.ifo)
				if instrument_pair not in self.points:
					self.points[instrument_pair] = self.Points()
				if is_background:
					self.points[instrument_pair].background_snr.append((x.snr, y.snr))
					eta = x.mass1 * x.mass2 / (x.mass1 + x.mass2)**2
					mtot = x.mass1 + x.mass2
					self.points[instrument_pair].background_eta.append(eta)
					self.points[instrument_pair].background_mtot.append(mtot)
					self.points[instrument_pair].background_mchirp.append(mtot * eta**(3./5))
					self.points[instrument_pair].background_chieff.append((x.mass1 * x.spin1z + x.mass2 * x.spin2z) / mtot)

				else:
					self.points[instrument_pair].zerolag_snr.append((x.snr, y.snr))
		else:
			# injections file
			for values in contents.connection.cursor().execute("""
SELECT
        sngl_inspiral_x.*,
        sngl_inspiral_y.*
FROM
	sngl_inspiral AS sngl_inspiral_x
		JOIN sim_id_sngl_id AS sim_id_sngl_id_x ON sim_id_sngl_id_x.sngl_id == sngl_inspiral_x.event_id
		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
WHERE
	sim_id_sngl_id_x.sim_id == sim_id_sngl_id_y.sim_id AND sngl_inspiral_x.ifo > sngl_inspiral_y.ifo;
			"""):
				x = contents.sngl_inspiral_table.row_from_cols(values)
				y = contents.sngl_inspiral_table.row_from_cols(values[len(contents.sngl_inspiral_table.columnnames):])
				instrument_pair = (x.ifo, y.ifo)
				if instrument_pair not in self.points:
					self.points[instrument_pair] = self.Points()
				self.points[instrument_pair].injections_snr.append((x.snr, y.snr))
				eta = x.mass1 * x.mass2 / (x.mass1 + x.mass2)**2
				mtot = x.mass1 + x.mass2
				self.points[instrument_pair].injections_mchirp.append(mtot * eta**(3./5))
				self.points[instrument_pair].injections_chieff.append((x.mass1 * x.spin1z + x.mass2 * x.spin2z) / mtot)


	def finish(self):
		for (x_instrument, y_instrument), points in self.points.items():
			fig = plotsumm.plot_param_background_multiifo(
				x_instrument, y_instrument, self.snr_min, "SNR", "$\rho$",
				points.injections_snr, points.background_snr
			)
			yield fig, "rho_%s_vs_%s" % (y_instrument, x_instrument), False

			fig = plotsumm.plot_param_background_multiifo(
				x_instrument, y_instrument, self.snr_min, "SNR", "$\rho$",
				points.injections_snr, points.background_snr, points.zerolag_snr
			)
			yield fig, "rho_%s_vs_%s" % (y_instrument, x_instrument), True

			fig = plotsumm.plot_param_background_multiifo(
				x_instrument, y_instrument, self.snr_min, "Effective Distance", "$D_{\mathrm{eff}}$",
				points.injections_deff, points.background_deff
			)
			yield fig, "deff_%s_vs_%s" % (y_instrument, x_instrument), False

			fig = plotsumm.plot_param_background_multiifo(
				x_instrument, y_instrument, self.snr_min, "Effective Distance", "$D_{\mathrm{eff}}$",
				points.injections_deff, points.background_deff, points.zerolag_deff
			)
			yield fig, "deff_%s_vs_%s" % (y_instrument, x_instrument), True


#
# =============================================================================
#
#                           Rate vs. Threshold Plots
#
# =============================================================================
#


class RateVsThreshold(object):
	def __init__(self, fapfar, snr_min):
		self.background_ln_likelihood_ratio = []
		self.zerolag_ln_likelihood_ratio = []
		self.background_far = []
		self.zerolag_far = []
		self.background_fap = []
		self.zerolag_fap = []
		self.background_snr = []
		self.zerolag_snr = []
		self.fapfar = fapfar
		self.snr_min = snr_min

	def add_contents(self, contents):
		if contents.sim_inspiral_table is not None:
			# skip injection documents
			return

		for ln_likelihood_ratio, far, fap, snr, is_background in connection.cursor().execute("""
SELECT
	coinc_event.likelihood,
	coinc_inspiral.combined_far,
	coinc_inspiral.false_alarm_rate,
	coinc_inspiral.snr,
	EXISTS (
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id
			AND time_slide.offset != 0
	)
FROM
	coinc_inspiral
	JOIN coinc_event ON (
		coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
	)
WHERE
	coinc_event.likelihood >= ?
		""", (self.fapfar.minrank,)):
			if far is None:
				continue
			if is_background:
				self.background_ln_likelihood_ratio.append(ln_likelihood_ratio)
				self.background_far.append(far)
				self.background_fap.append(fap)
				self.background_snr.append(snr)
			else:
				self.zerolag_ln_likelihood_ratio.append(ln_likelihood_ratio)
				self.zerolag_far.append(far)
				self.zerolag_fap.append(fap)
				self.zerolag_snr.append(snr)

	def finish(self):
		fig = plotsumm.plot_candidate_lnL_vs_snr(self.snr_min, self.background_snr, self.background_ln_likelihood_ratio)
		yield fig, "lr_vs_snr", False

		fig = plotsumm.plot_candidate_lnL_vs_snr(
			self.snr_min, self.background_snr, self.background_ln_likelihood_ratio,
			self.zerolag_snr, self.zerolag_ln_likelihood_ratio
		)
		yield fig, "lr_vs_snr", True

		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)]:
			if fars:
				# fars in ascending order --> ifars in descending order
				zerolag_stats = 1. / numpy.array(sorted(fars))
				fig = plotsumm.plot_rate_vs_ifar(zerolag_stats, self.fapfar, is_open_box)
				yield fig, "count_vs_ifar", is_open_box

			if ln_likelihood_ratio:
				# ln(L) in ascending order
				zerolag_stats = numpy.array(sorted(ln_likelihood_ratio, reverse = True))
				fig = plotsumm.plot_rate_vs_lnL(zerolag_stats, self.fapfar, is_open_box)
				yield fig, "count_vs_lr", is_open_box

		if self.background_ln_likelihood_ratio:
			background_stats = numpy.array(sorted(self.background_ln_likelihood_ratio, reverse = True))
			zerolag_stats = numpy.array(sorted(self.zerolag_ln_likelihood_ratio, reverse = True))
			fig = plotsumm.plot_rate_vs_background_lnL(zerolag_stats, background_stats, self.fapfar)
			yield fig, "count_vs_lr_fig3", True


class Segments(object):
	def __init__(self, base):
		self.all_segs_dict = {}
		self.data = []
		self.table = []
		self.base = base

	def add_contents(self, contents):
		# only process non-injection documents
		if contents.sim_inspiral_table is None:
			for name, seglists in contents.all_segs_dict.items():
				# need to use operator because Python won't
				# allow a function call on the LHS of |=
				# for some mystery reason.
				operator.ior(self.all_segs_dict.setdefault(name, segments.segmentlistdict()), seglists)

	def finish(self):
		segs = reduce(segments.segmentlistdict.__or__, self.all_segs_dict.values(), segments.segmentlistdict())
		self.extent = segs.extent_all()

		for name, seglists in self.all_segs_dict.items():
			for ifo, seglist in seglists.items():
				for seg in seglist:
					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])

			analyzable_instruments_set = set(segs.keys())
			for n in range(1, 1 + len(segs)):
				for ifo_combos in itertools.combinations(list(analyzable_instruments_set), n):
					this = segs.intersection(ifo_combos) - segs.union(analyzable_instruments_set - set(ifo_combos))
					if len(this) > 0:
						#FIXME inf is not handled properly
						start = float(this.extent()[0])
						end = float(this.extent()[1])
						if end == float("inf"):
							end = 2000000000.
						duration = end - start
						self.table.append([name, ",".join(ifo_combos), start, end, duration])

			self.table.insert(0, ["all", "all", float(self.extent[0]), float(self.extent[1]), float(abs(self.extent))])
			f = open("%s_segments.json" % self.base, "w")
			f.write(repr(self.data))
			f.close()
			save_table("%s_segment_table.json" % self.base, ["name", "ifos", "start", "end", "extent"], self.table)

			
#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#


#
# Parse command line
#


options, filenames = parse_command_line()


#
# Load likelihood input
#


if options.likelihood_file is not None:
	rankingstatpdf = far.marginalize_pdf_urls([options.likelihood_file], which = "RankingStatPDF", verbose = options.verbose)
else:
	rankingstatpdf = None
snr_min = far.inspiral_lr.LnLRDensity.snr_min
if rankingstatpdf is not None:
	fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
else:
	fapfar = None


#
# Initialize plots
#


def new_plots(plots, fapfar, far_thresh, remove_precession, isolate_precession, snr_segments):
	l = (
		SummaryTable(),
		MissedFoundPlots(far_thresh, remove_precession, isolate_precession, snr_segments),
		ParameterAccuracyPlots(far_thresh = far_thresh),
		BackgroundVsInjectionPlots(snr_min = snr_min),
		BackgroundVsInjectionPlotsMulti(snr_min = snr_min),
		RateVsThreshold(fapfar = fapfar, snr_min = snr_min),
		InjectionParameterDistributionPlots(),
	)
	if plots is None:
		plots = range(len(l))
	return [(i, l[i]) for i in plots]

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)


#
# Process files
#


seg_class = Segments(base = os.path.join(options.output_dir, options.user_tag))

for n, filename in enumerate(filenames):
	if options.verbose:
		print >>sys.stderr, "%d/%d: %s" % (n + 1, len(filenames), filename)
	with dbtables.workingcopy(filename, tmp_path = options.tmp_space, discard = True, verbose = options.verbose) as working_filename:
		connection = sqlite3.connect(str(working_filename))
		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)
		if contents.sim_inspiral_table is not None:
			create_sim_coinc_view(connection)
		seg_class.add_contents(contents)
		for plot_group, plot in plots:
			if options.verbose:
				print >>sys.stderr, "adding to plot group %d ..." % plot_group
			plot.add_contents(contents)
		connection.close()

seg_class.finish()


#
# Finish and write plots, deleting them as we go to save memory
#


filename_template = dagparts.T050017_filename("H1L1V1", "GSTLAL_INSPIRAL_PLOTSUMMARY_%s_%02d_%s_%s", contents.seglists.extent_all(), "%s", path = options.output_dir)
while len(plots):
	plot_group, plot = plots.pop(0)
	for fig, filename_fragment, is_open_box in plot.finish():
		if fig is not None:
			try:
				fig.tight_layout(rect=(0.03, 0.02, 0.98, 0.98))
			except ValueError:
				pass
		for fmt in options.format:
			if filename_fragment and fig:
				filename = filename_template % (options.user_tag, plot_group, filename_fragment, ("openbox" if is_open_box else "closedbox"), fmt)
				if options.verbose:
					print >>sys.stderr, "writing %s ..." % filename
				fig.savefig(filename)
