#!/usr/bin/env python3
#
# Copyright (C) 2011-2014 Chad Hanna
# Copyright (C) 2019      Patrick Godwin
#
# 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.


### The offline gstlal inspiral workflow generator; Use to make HTCondor DAGs to run CBC workflows
###
### Usage:
### ------
###
### It is rare that you would invoke this program in a standalone mode. Usually
### the inputs are complicated and best automated via a Makefile, e.g.,
### Makefile.triggers_example
###
### Diagram of the HTCondor workfow produced
### ----------------------------------------
###
### .. graphviz:: ../images/trigger_pipe.dot
###

"""
This program makes a dag to run gstlal_inspiral offline
"""

__author__ = 'Chad Hanna <chad.hanna@ligo.org>, Patrick Godwin <patrick.godwin@ligo.org>'

#----------------------------------------------------------
### imports

from collections import OrderedDict
from optparse import OptionParser
import os

import numpy

from lal.utils import CacheEntry

from ligo.lw import ligolw
from ligo.lw import lsctables
import ligo.lw.utils as ligolw_utils

from gstlal import inspiral_pipe
from gstlal import dagparts
from gstlal import datasource
from gstlal import paths as gstlal_config_paths


#----------------------------------------------------------
### ligolw initialization

class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
	pass
lsctables.use_in(LIGOLWContentHandler)


#----------------------------------------------------------
### command line options

def parse_command_line():
	parser = OptionParser(description = __doc__)

	# generic data source options
	datasource.append_options(parser)
	parser.add_option("--psd-fft-length", metavar = "s", default = 32, type = "int", help = "FFT length, default 32s.  Note that 50% will be used for zero-padding.")

	# reference_psd
	parser.add_option("--reference-psd", help = "Don't measure PSDs, use this one instead")

	# Template bank
	parser.add_option("--template-bank", metavar = "filename", help = "Set the template bank xml file.")
	parser.add_option("--mass-model", metavar = "filename", help = "Set the name of the mass model. Options are 'narrow-bns', 'broad-bns', 'bbh', 'ligo', 'detected-logm', 'uniform-template', or 'file'")
	parser.add_option("--mass-model-file", metavar = "filename", help = "Set the name of the mass model file, e.g., mass_model.h5.  Required if --mass-model=file")

	# dtdphi option
	parser.add_option("--dtdphi-file", metavar = "filename", action = "append", help = "dtdphi snr ratio pdfs to read from (hdf5 format)")

	# idq option
	parser.add_option("--idq-file", metavar = "filename", action = "append", help = "idq glitch file (hdf5 format)")

	# SVD bank construction options
	parser.add_option("--overlap", metavar = "num", type = "int", action = "append", help = "set the factor that describes the overlap of the sub banks, must be even!")
	parser.add_option("--autocorrelation-length", metavar = "str", default = '0:1000:351', help = "The chirp mass range and minimum number of samples to use for auto-chisquared. Formatted as min-chirp:max-chirp:AC-length. Samples should be odd. You MUST provide this in a continuous fashion across the entire covered mass space, i.e. 0:15:701,15:1000:351")
	parser.add_option("--samples-min", type = "int", action = "append", help = "The minimum number of samples to use for time slices default 1024 (can be given multiple times, one for each time --bank-cache is invoked)")
	parser.add_option("--samples-max-256", type = "int", default = 1024, help = "The maximum number of samples to use for time slices with frequencies above 256Hz, default 1024")
	parser.add_option("--samples-max-64", type = "int", default = 2048, help = "The maximum number of samples to use for time slices with frequencies above 64Hz, default 2048")
	parser.add_option("--samples-max", type = "int", default = 4096, help = "The maximum number of samples to use for time slices with frequencies below 64Hz, default 4096")
	parser.add_option("--bank-cache", metavar = "filenames", action = "append", help = "Set the bank cache files in format H1=H1.cache,H2=H2.cache, etc.. (can be given multiple times)")
	parser.add_option("--tolerance", metavar = "float", type = "float", default = 0.9999, help = "set the SVD tolerance, default 0.9999")
	parser.add_option("--flow", metavar = "num", type = "float", action = "append", help = "set the low frequency cutoff. Can be given multiple times.")
	parser.add_option("--fmax", metavar = "num", type = "float", default = 1600, help = "set the max frequency cutoff, default 1600 (Hz)")
	parser.add_option("--sample-rate", metavar = "Hz", type = "int", help = "Set the sample rate.  If not set, the sample rate will be based on the template frequency.  The sample rate must be at least twice the highest frequency in the templates. If provided it must be a power of two")
	parser.add_option("--identity-transform", action = "store_true", help = "Use identity transform, i.e. no SVD")

	# trigger generation options
	parser.add_option("--vetoes", metavar = "filename", help = "Set the veto xml file.")
	parser.add_option("--time-slide-file", metavar = "filename", help = "Set the time slide table xml file")
	parser.add_option("--inj-time-slide-file", metavar = "filename", help = "Set the time slide table xml file for injections")
	parser.add_option("--web-dir", metavar = "directory", help = "Set the web directory like /home/USER/public_html")
	parser.add_option("--fir-stride", type="int", metavar = "secs", default = 8, help = "Set the duration of the fft output blocks, default 8")
	parser.add_option("--control-peak-time", type="int", default = 8, metavar = "secs", help = "Set the peak finding time for the control signal, default 8")
	parser.add_option("--coincidence-threshold", metavar = "value", type = "float", default = 0.005, help = "Set the coincidence window in seconds (default = 0.005).  The light-travel time between instruments will be added automatically in the coincidence test.")
	parser.add_option("--min-instruments", metavar = "count", type = "int", default = 2, help = "Set the minimum number of instruments that must contribute triggers to form a candidate (default = 2).")
	parser.add_option("--reference-likelihood-file", metavar = "file", help = "Set a reference likelihood file to compute initial likelihood ratios. Required")
	parser.add_option("--num-banks", metavar = "str", help = "The number of parallel subbanks per gstlal_inspiral job. can be given as a list like 1,2,3,4 then it will split up the bank cache into N groups with M banks each.")
	parser.add_option("--ht-gate-threshold", type="float", help="set a threshold on whitened h(t) to veto glitches")
	parser.add_option("--ht-gate-threshold-linear", metavar = "mchirp_min:ht_gate_threshold_min-mchirp_max:ht_gate_threshold_max", type="string", help = "Set the threshold on whitened h(t) to mark samples as gaps (glitch removal) with a linear scale of mchirp")
	parser.add_option("--blind-injections", metavar = "filename", help = "Set the name of an injection file that will be added to the data without saving the sim_inspiral table or otherwise processing the data differently.  Has the effect of having hidden signals in the input data. Separate injection runs using the --injections option will still occur.")
	parser.add_option("--singles-threshold", default=float("inf"), action = "store", metavar="THRESH", help = "Set the SNR threshold at which to record single-instrument events in the output (default = +inf, i.e. don't retain singles).")
	parser.add_option("--gzip-test", default=False, action = "store_true", help = "Perform gzip --test on all output files.")
	parser.add_option("--verbose", action = "store_true", help = "Be verbose")
	parser.add_option("--disable-calc-inj-snr", default=False, action = "store_true", help = "Disable injection SNR calculation")
	parser.add_option("--ranking-stat-samples", metavar = "N", default = 2**24, type = "int", help = "Construct ranking statistic histograms by drawing this many samples from the ranking statistic generator (default = 2^24).")

	# Override the datasource injection option
	parser.remove_option("--injections")
	parser.add_option("--injections", action = "append", help = "append injection files to analyze. Must prepend filename with X:Y:, where X and Y are floats, e.g. 1.2:3.1:filename, so that the injections are only searched for in regions of the template bank with X <= chirp mass < Y.")

	# Data from a zero lag run in the case of an injection-only run.
	parser.add_option("--injection-only", default=False, action = "store_true", help = "Run an injection only analysis.")
	parser.add_option("--dist-stats-cache", metavar = "filename", help = "Set the cache file for dist stats (required iff running injection-only analysis)")
	parser.add_option("--svd-bank-cache", metavar = "filename", help = "Set the cache file for svd banks (required iff running injection-only analysis)")
	parser.add_option("--psd-cache", metavar = "filename", help = "Set the cache file for psd (required iff running injection-only analysis)")
	parser.add_option("--non-injection-db", metavar = "filename", help = "Set the non injection data base file (required iff running injection-only analysis)")
	parser.add_option("--marginalized-likelihood-file", metavar = "filename", help = "Set the marginalized likelihood file (required iff running injection-only analysis)")
	parser.add_option("--marginalized-likelihood-with-zerolag-file", metavar = "filename", help = "Set the marginalized likelihood with zerolag file (required iff running injection-only analysis)")

	# Condor commands
	parser.add_option("--condor-command", action = "append", default = [], metavar = "command=value", help = "set condor commands of the form command=value; can be given multiple times")
	parser.add_option("--max-inspiral-jobs", type="int", metavar = "jobs", help = "Set the maximum number of gstlal_inspiral jobs to run simultaneously, default no constraint.")
	parser.add_option("--singularity-image", metavar = "filename", help = "If set, uses the Singularity image provided as the build environment and sets Singularity-specific condor options.")

	options, filenames = parser.parse_args()

	if options.template_bank:
		bank_xmldoc = ligolw_utils.load_filename(options.template_bank, verbose = options.verbose, contenthandler = LIGOLWContentHandler)
		sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(bank_xmldoc)
		assert len(sngl_inspiral_table) == len(set([r.template_id for r in sngl_inspiral_table])), "Template bank ids are not unique"

	if options.mass_model not in ("narrow-bns", "broad-bns", "bbh", "ligo", "detected-logm", "uniform-template", "file"):
		raise ValueError("--mass-model must be 'narrow-bns', 'broad-bns', 'bbh', 'ligo', 'detected-logm', 'uniform-template', or 'file'")
	if options.mass_model == "file" and not options.mass_model_file:
		raise ValueError("--mass-model-file must be provided if --mass-model=file")

	if not options.dtdphi_file:
		options.dtdphi_file = [os.path.join(gstlal_config_paths["pkgdatadir"], "inspiral_dtdphi_pdf.h5")] * len(options.overlap)

	if len(options.dtdphi_file) != len(options.overlap):
		raise ValueError("You must provide as many dtdphi files as banks")

	if options.num_banks:
		options.num_banks = [int(v) for v in options.num_banks.split(",")]

	if options.sample_rate is not None and (not numpy.log2(options.sample_rate) == int(numpy.log2(options.sample_rate))):
		raise ValueError("--sample-rate must be a power of two")

	if not options.samples_min and not options.svd_bank_cache:
		options.samples_min = [1024]*len(options.bank_cache)

	if not options.overlap and not options.svd_bank_cache:
		options.overlap = [0]*len(options.bank_cache)

	if options.autocorrelation_length:
		options.autocorrelation_length = [v for v in options.autocorrelation_length.split(",")]
		if any(int(autocorrelation_length.split(':')[2]) % 2 ==0 for autocorrelation_length in options.autocorrelation_length):
			raise ValueError("The autocorrelation length must be an odd number of samples.")

	if not options.svd_bank_cache and any(overlap % 2 for overlap in options.overlap):
		raise ValueError("overlap must be even")

	if not options.svd_bank_cache and not (len(options.samples_min) == len(options.bank_cache) == len(options.overlap)):
		raise ValueError("must provide same number of inputs for --samples-min, --bank-cache, --overlap")

	missing_injection_options = []
	for option in ("dist_stats_cache", "svd_bank_cache", "psd_cache", "non_injection_db", "marginalized_likelihood_file", "marginalized_likelihood_with_zerolag_file"):
		if getattr(options, option) is None:
			missing_injection_options.append(option)
	if len(missing_injection_options) > 0 and len(missing_injection_options) < 6:
		raise ValueError("missing injection-only options %s." % ", ".join([option for option in missing_injection_options]))
	if len(missing_injection_options) == 0 and options.num_banks:
		raise ValueError("cant specify --num-banks in injection-only run")

	fail = ""
	required_options = []
	if len(missing_injection_options) == 6:
		required_options.append("bank_cache")

	for option in required_options:
		if getattr(options, option) is None:
			fail += "must provide option %s\n" % (option)
	if fail: raise ValueError(fail)

	#FIXME a hack to find the sql paths
	share_path = os.path.split(dagparts.which('gstlal_inspiral'))[0].replace('bin', 'share/gstlal')
	options.cluster_sql_file = os.path.join(share_path, 'simplify_and_cluster.sql')
	options.snr_cluster_sql_file = os.path.join(share_path, 'snr_simplify_and_cluster.sql')
	options.injection_snr_cluster_sql_file = os.path.join(share_path, 'inj_snr_simplify_and_cluster.sql')
	options.injection_sql_file = os.path.join(share_path, 'inj_simplify_and_cluster.sql')
	options.injection_proc_sql_file = os.path.join(share_path, 'simplify_proc_table_in_inj_file.sql')

	return options, filenames


#----------------------------------------------------------
### DAG utilities

def set_up_jobs(options):
	jobs = {}

	# default condor options
	default_condor_opts = OrderedDict()
	default_condor_opts['want_graceful_removal'] = "True"
	default_condor_opts['kill_sig'] = "15"
	default_condor_opts['request_cpus'] = "1"
	default_condor_opts['+MemoryUsage'] = "( 1000 ) * 2 / 3"
	default_condor_opts['request_memory'] = "( MemoryUsage ) * 3 / 2"
	default_condor_opts['periodic_hold'] = "( MemoryUsage >= ( ( RequestMemory ) * 3 / 2 ) )"
	default_condor_opts['periodic_release'] = "(JobStatus == 5) && ((CurrentTime - EnteredCurrentStatus) > 180) && (HoldReasonCode != 34)"

	if options.singularity_image:
		default_condor_opts['+SingularityImage'] = '"{}"'.format(options.singularity_image)

	# job-specific condor options
	ref_psd_condor_opts = default_condor_opts.copy()
	ref_psd_condor_opts['request_cpus'] = "2"

	calc_rank_pdf_condor_opts = default_condor_opts.copy()
	calc_rank_pdf_condor_opts['+MemoryUsage'] = "( 3000 ) * 2 / 3"
	calc_rank_pdf_condor_opts['request_cpus'] = "4"

	svd_condor_opts = default_condor_opts.copy()
	svd_condor_opts['+MemoryUsage'] = "( 7000 ) * 2 / 3"

	inj_snr_condor_opts = default_condor_opts.copy()
	inj_snr_condor_opts['+MemoryUsage'] = "( 2000 ) * 2 / 3"
	inj_snr_condor_opts['request_cpus'] = "2"

	inspiral_1ifo_condor_opts = default_condor_opts.copy()
	inspiral_1ifo_condor_opts['+MemoryUsage'] = "( 5000 ) * 2 / 3"

	inspiral_2ifo_condor_opts = default_condor_opts.copy()
	inspiral_2ifo_condor_opts['+MemoryUsage'] = "( 7000 ) * 2 / 3"

	inspiral_3ifo_condor_opts = default_condor_opts.copy()
	inspiral_3ifo_condor_opts['+MemoryUsage'] = "( 9000 ) * 2 / 3"
	inspiral_3ifo_condor_opts['request_cpus'] = "2"

	# set condor commands
	base_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, default_condor_opts)
	ref_psd_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, ref_psd_condor_opts)
	calc_rank_pdf_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, calc_rank_pdf_condor_opts)
	svd_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, svd_condor_opts)
	inj_snr_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, inj_snr_condor_opts)
	sh_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, {"want_graceful_removal":"True", "kill_sig":"15"})

	inspiral_1ifo_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, inspiral_1ifo_condor_opts)
	inspiral_2ifo_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, inspiral_2ifo_condor_opts)
	inspiral_3ifo_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, inspiral_3ifo_condor_opts)

	if options.injection_only:
		jobs['gstlalInspiral1IFO'] = None
		jobs['gstlalInspiral2IFO'] = None
		jobs['gstlalInspiral3IFO'] = None
		jobs['createPriorDistStats'] = None
		jobs['calcRankPDFs'] = None
		jobs['calcRankPDFsWithZerolag'] = None
		jobs['calcLikelihood'] = None
		jobs['marginalize'] = None
		jobs['marginalizeWithZerolag'] = None

	else:
		jobs['refPSD'] = dagparts.DAGJob("gstlal_reference_psd", condor_commands = ref_psd_condor_commands)
		jobs['medianPSD'] = dagparts.DAGJob("gstlal_median_of_psds", condor_commands = base_condor_commands)
		jobs['plotBanks'] = dagparts.DAGJob("gstlal_inspiral_plot_banks", condor_commands = base_condor_commands)
		jobs['svd'] = dagparts.DAGJob("gstlal_svd_bank", condor_commands = svd_condor_commands)
		jobs['model'] = dagparts.DAGJob("gstlal_inspiral_mass_model", condor_commands = base_condor_commands)
		jobs['modelAdd'] = dagparts.DAGJob("gstlal_inspiral_add_mass_models", condor_commands = base_condor_commands)
		jobs['horizon'] = dagparts.DAGJob("gstlal_plot_psd_horizon", condor_commands = base_condor_commands)
		jobs['gstlalInspiral1IFO'] = dagparts.DAGJob("gstlal_inspiral", tag_base="gstlal_inspiral_1ifo", condor_commands = inspiral_1ifo_condor_commands)
		jobs['gstlalInspiral2IFO'] = dagparts.DAGJob("gstlal_inspiral", tag_base="gstlal_inspiral_2ifo", condor_commands = inspiral_2ifo_condor_commands)
		jobs['gstlalInspiral3IFO'] = dagparts.DAGJob("gstlal_inspiral", tag_base="gstlal_inspiral_3ifo", condor_commands = inspiral_3ifo_condor_commands)
		jobs['createPriorDistStats'] = dagparts.DAGJob("gstlal_inspiral_create_prior_diststats", condor_commands = base_condor_commands)
		jobs['calcRankPDFs'] = dagparts.DAGJob("gstlal_inspiral_calc_rank_pdfs", condor_commands = calc_rank_pdf_condor_commands)
		jobs['calcRankPDFsWithZerolag'] = dagparts.DAGJob("gstlal_inspiral_calc_rank_pdfs", tag_base="gstlal_inspiral_calc_rank_pdfs_with_zerolag", condor_commands=calc_rank_pdf_condor_commands)
		jobs['calcLikelihood'] = dagparts.DAGJob("gstlal_inspiral_calc_likelihood", condor_commands = base_condor_commands)
		jobs['marginalize'] = dagparts.DAGJob("gstlal_inspiral_marginalize_likelihood", condor_commands = base_condor_commands)
		jobs['marginalizeWithZerolag'] = dagparts.DAGJob("gstlal_inspiral_marginalize_likelihood", tag_base="gstlal_inspiral_marginalize_likelihood_with_zerolag", condor_commands=base_condor_commands)

	# set up rest of jobs
	jobs['gstlalInspiralInj1IFO'] = dagparts.DAGJob("gstlal_inspiral", tag_base="gstlal_inspiral_inj_1ifo", condor_commands = inspiral_1ifo_condor_commands)
	jobs['gstlalInspiralInj2IFO'] = dagparts.DAGJob("gstlal_inspiral", tag_base="gstlal_inspiral_inj_2ifo", condor_commands = inspiral_2ifo_condor_commands)
	jobs['gstlalInspiralInj3IFO'] = dagparts.DAGJob("gstlal_inspiral", tag_base="gstlal_inspiral_inj_3ifo", condor_commands = inspiral_3ifo_condor_commands)
	jobs['injSplitter'] = dagparts.DAGJob("gstlal_injsplitter", tag_base="gstlal_injsplitter", condor_commands = base_condor_commands)
	jobs['gstlalInjSnr'] = dagparts.DAGJob("gstlal_inspiral_injection_snr", condor_commands = inj_snr_condor_commands)
	jobs['ligolwAdd'] = dagparts.DAGJob("ligolw_add", condor_commands = base_condor_commands)
	jobs['calcLikelihoodInj'] = dagparts.DAGJob("gstlal_inspiral_calc_likelihood", tag_base='gstlal_inspiral_calc_likelihood_inj', condor_commands=base_condor_commands)
	jobs['ComputeFarFromSnrChisqHistograms'] = dagparts.DAGJob("gstlal_compute_far_from_snr_chisq_histograms", condor_commands = base_condor_commands)
	jobs['ligolwInspinjFind'] = dagparts.DAGJob("lalapps_inspinjfind", condor_commands = base_condor_commands)
	jobs['toSqlite'] = dagparts.DAGJob("ligolw_sqlite", tag_base = "ligolw_sqlite_from_xml", condor_commands = base_condor_commands)
	jobs['toSqliteNoCache'] = dagparts.DAGJob("ligolw_sqlite", tag_base = "ligolw_sqlite_from_xml_final", condor_commands = base_condor_commands)
	jobs['toXML'] = dagparts.DAGJob("ligolw_sqlite", tag_base = "ligolw_sqlite_to_xml", condor_commands = base_condor_commands)
	jobs['lalappsRunSqlite'] = dagparts.DAGJob("lalapps_run_sqlite", condor_commands = base_condor_commands)
	jobs['plotSummary'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", condor_commands = base_condor_commands)
	jobs['plotSummaryIsolatePrecession'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", tag_base="gstlal_inspiral_plotsummary_isolated_precession", condor_commands=base_condor_commands)
	jobs['plotSnglInjSummary'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", tag_base = "gstlal_inspiral_plotsummary_inj", condor_commands=base_condor_commands)
	jobs['plotSnglInjSummaryIsolatePrecession'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", tag_base="gstlal_inspiral_plotsummary_isolated_precession_inj", condor_commands=base_condor_commands)
	jobs['plotSensitivity'] = dagparts.DAGJob("gstlal_inspiral_plot_sensitivity", condor_commands = base_condor_commands)
	jobs['summaryPage'] = dagparts.DAGJob("gstlal_inspiral_summary_page", condor_commands = base_condor_commands)
	jobs['plotBackground'] = dagparts.DAGJob("gstlal_inspiral_plot_background", condor_commands = base_condor_commands)
	jobs['cp'] = dagparts.DAGJob("cp", tag_base = "cp", condor_commands = sh_condor_commands)
	jobs['rm'] = dagparts.DAGJob("rm", tag_base = "rm_intermediate_merger_products", condor_commands = sh_condor_commands)

	return jobs


#----------------------------------------------------------
### main

if __name__ == '__main__':
	options, filenames = parse_command_line()

	if options.bank_cache or options.svd_bank_cache:
		detectors = datasource.GWDataSourceInfo(options)
		channel_dict = detectors.channel_dict
		boundary_seg = detectors.seg
	else:
		with open(options.rank_pdf_cache) as f:
			ce = CacheEntry(f.readline())
		boundary_seg = ce.segment
		instruments = ce.observatory

	# output directories
	output_dir = "plots"
	try:
		os.mkdir("logs")
	except:
		pass

	#
	# Set up DAG architecture
	#

	dag = dagparts.DAG("trigger_pipe")
	jobs = set_up_jobs(options)

	if options.max_inspiral_jobs is not None:
		dag.add_maxjobs_category("INSPIRAL", options.max_inspiral_jobs)

	# generate xml integrity checker (if requested) and pre-script to back up data
	inspiral_pipe.set_up_scripts(options)

	# Get mchirp boundaries of banks, maximum duration of templates, and analysis segments
	if options.bank_cache or options.psd_cache:
		if options.bank_cache:
			template_mchirp_dict, bank_cache, max_time = inspiral_pipe.get_bank_params(options)
			instrument_set = list(bank_cache.keys())

		if options.psd_cache:
			template_mchirp_dict, svd_nodes, max_time = inspiral_pipe.get_svd_bank_params(options.svd_bank_cache)
			instrument_set = list(svd_nodes.keys())

		segsdict = inspiral_pipe.analysis_segments(set(instrument_set), detectors.frame_segments, boundary_seg, max_time, options.min_instruments)
		instruments = "".join(sorted(instrument_set))

	if options.psd_cache:
		### reference psd jobs
		psd_nodes, ref_psd_parent_nodes = inspiral_pipe.inj_psd_layer(segsdict, options)
		ref_psd = inspiral_pipe.load_reference_psd(options)

	elif options.reference_psd:
		# load reference PSD
		ref_psd = inspiral_pipe.load_reference_psd(options)
		ref_psd_parent_nodes = []

	else:
		# Compute the PSDs for each segment
		psd_nodes = inspiral_pipe.ref_psd_layer(dag, jobs, [], segsdict, channel_dict, options)

		# plot the horizon distance
		inspiral_pipe.horizon_dist_layer(dag, jobs, psd_nodes, options, boundary_seg, output_dir, instruments)

		# compute the median PSD
		median_psd_node = inspiral_pipe.median_psd_layer(dag, jobs, psd_nodes, options, boundary_seg, instruments)
		ref_psd = median_psd_node.output_files["output-name"]
		ref_psd_parent_nodes = [median_psd_node]

	# Calculate Expected SNR jobs
	if not options.disable_calc_inj_snr:
		ligolw_add_nodes = inspiral_pipe.expected_snr_layer(dag, jobs, ref_psd_parent_nodes, options, num_split_inj_snr_jobs = 100)
	else:
		ligolw_add_nodes = []

	if options.injection_only:
		model_node = None
		model_file = options.mass_model_file
		svd_dtdphi_map, _ = inspiral_pipe.load_svd_dtdphi_map(options)
	else:
		# Compute SVD banks
		svd_nodes, template_mchirp_dict, svd_dtdphi_map = inspiral_pipe.svd_layer(dag, jobs, ref_psd_parent_nodes, ref_psd, bank_cache, options, boundary_seg, output_dir, template_mchirp_dict)

		# mass model
		model_node, model_file = inspiral_pipe.mass_model_layer(dag, jobs, ref_psd_parent_nodes, instruments, options, boundary_seg, ref_psd)

	# Inspiral jobs by segment
	inspiral_nodes, lloid_output, lloid_diststats = inspiral_pipe.inspiral_layer(dag, jobs, psd_nodes, svd_nodes, segsdict, options, channel_dict, template_mchirp_dict)

	# marginalize jobs
	marg_nodes = inspiral_pipe.marginalize_layer(dag, jobs, svd_nodes, lloid_output, lloid_diststats, options, boundary_seg, instrument_set, model_node, model_file, ref_psd, svd_dtdphi_map, options.idq_file)

	# calc rank PDF jobs
	rankpdf_nodes, rankpdf_zerolag_nodes = inspiral_pipe.calc_rank_pdf_layer(dag, jobs, marg_nodes, options, boundary_seg, instrument_set)

	# final marginalization step
	final_marg_nodes, margfiles_to_delete = inspiral_pipe.final_marginalize_layer(dag, jobs, rankpdf_nodes, rankpdf_zerolag_nodes, options)

	# likelihood jobs
	likelihood_nodes = inspiral_pipe.likelihood_layer(dag, jobs, marg_nodes, lloid_output, lloid_diststats, options, boundary_seg, instrument_set)

	# Setup clustering and/or merging
	# after all of the likelihood ranking and preclustering is finished put everything into single databases based on the injection file (or lack thereof)
	injdbs, noninjdb, final_sqlite_nodes, dbs_to_delete = inspiral_pipe.sql_cluster_and_merge_layer(dag, jobs, likelihood_nodes, ligolw_add_nodes, options, boundary_seg, instruments)

	# Compute FAR
	farnode = inspiral_pipe.compute_far_layer(dag, jobs, final_marg_nodes, injdbs, noninjdb, final_sqlite_nodes, options)

	# make summary plots
	plotnodes = inspiral_pipe.summary_plot_layer(dag, jobs, farnode, options, injdbs, noninjdb, output_dir)

	# make a web page
	inspiral_pipe.summary_page_layer(dag, jobs, plotnodes, options, boundary_seg, injdbs, output_dir)

	# rm intermediate merger products
	inspiral_pipe.clean_merger_products_layer(dag, jobs, plotnodes, dbs_to_delete, margfiles_to_delete)

	#
	# generate DAG files
	#

	dag.write_sub_files()
	dag.write_dag()
	dag.write_script()
	dag.write_cache()
