inspiral_pipe.py 53.6 KB
Newer Older
1
# Copyright (C) 2013--2014  Kipp Cannon, Chad Hanna
2
# Copyright (C) 2019        Patrick Godwin
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# 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.

18
##
19 20
# @file
#
21
# A file that contains the inspiral_pipe module code; used to construct condor dags
22 23 24
#

##
25
# @package inspiral_pipe
26
#
27
# A module that contains the inspiral_pipe module code; used to construct condor dags
Chad Hanna's avatar
Chad Hanna committed
28 29 30
#
# ### Review Status
#
31 32 33
# | Names                                          | Hash                                        | Date       | Diff to Head of Master      |
# | -------------------------------------------    | ------------------------------------------- | ---------- | --------------------------- |
# | Florent, Sathya, Duncan Me, Jolien, Kipp, Chad | 8a6ea41398be79c00bdc27456ddeb1b590b0f68e    | 2014-06-18 | <a href="@gstlal_inspiral_cgit_diff/python/inspiral_pipe.py?id=HEAD&id2=8a6ea41398be79c00bdc27456ddeb1b590b0f68e">inspiral_pipe.py</a> |
34
#
Chad Hanna's avatar
Chad Hanna committed
35 36 37 38
# #### Actions
#
# - In inspiral_pipe.py Fix the InsiralJob.___init___: fix the arguments
# - On line 201, fix the comment or explain what the comment is meant to be
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#
# imports
#

import copy
import doctest
import functools
import itertools
import os
import socket
import stat

import lal.series
from lal.utils import CacheEntry

55
from ligo import segments
56 57
from ligo.lw import lsctables, ligolw
from ligo.lw import utils as ligolw_utils
58 59 60 61

from gstlal import dagparts
from gstlal import datasource
from gstlal import inspiral
62
from gstlal import svd_bank
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603


#
# LIGOLW initialization
#


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


#
# DAG layers
#


def ref_psd_layer(dag, jobs, parent_nodes, segsdict, channel_dict, options):
	psd_nodes = {}
	for ifos in segsdict:
		this_channel_dict = dict((k, channel_dict[k]) for k in ifos if k in channel_dict)
		for seg in segsdict[ifos]:
			psd_path = subdir_path([jobs['refPSD'].output_path, str(int(seg[0]))[:5]])
			psd_nodes[(ifos, seg)] = dagparts.DAGNode(
				jobs['refPSD'],
				dag,
				parent_nodes = parent_nodes,
				opts = {
					"gps-start-time":int(seg[0]),
					"gps-end-time":int(seg[1]),
					"data-source":"frames",
					"channel-name":datasource.pipeline_channel_list_from_channel_dict(this_channel_dict, ifos = ifos),
					"psd-fft-length":options.psd_fft_length,
					"frame-segments-name": options.frame_segments_name
				},
				input_files = {
					"frame-cache":options.frame_cache,
					"frame-segments-file":options.frame_segments_file
				},
				output_files = {
					"write-psd":dagparts.T050017_filename(ifos, "REFERENCE_PSD", seg, '.xml.gz', path = psd_path)
				},
			)

	# Make the reference PSD cache
	# FIXME Use machinery in inspiral_pipe.py to create reference_psd.cache
	with open('reference_psd.cache', "w") as output_cache_file:
		for node in psd_nodes.values():
			output_cache_file.write("%s\n" % CacheEntry.from_T050017("file://localhost%s" % os.path.abspath(node.output_files["write-psd"])))

	return psd_nodes

def median_psd_layer(dag, jobs, parent_nodes, options, boundary_seg, instruments):
	gpsmod5 = str(int(boundary_seg[0]))[:5]
	median_psd_path = subdir_path([jobs['medianPSD'].output_path, gpsmod5])

	# FIXME Use machinery in inspiral_pipe.py to create reference_psd.cache
	median_psd_nodes = []
	for chunk, nodes in enumerate(dagparts.groups(parent_nodes.values(), 50)):
		median_psd_node = \
			dagparts.DAGNode(jobs['medianPSD'], dag,
				parent_nodes = parent_nodes.values(),
				input_files = {"": [node.output_files["write-psd"] for node in nodes]},
				output_files = {"output-name": dagparts.T050017_filename(instruments, "REFERENCE_PSD_CHUNK_%04d" % chunk, boundary_seg, '.xml.gz', path = median_psd_path)}
			)
		median_psd_nodes.append(median_psd_node)

	median_psd_node = \
		dagparts.DAGNode(jobs['medianPSD'], dag,
			parent_nodes = median_psd_nodes,
			input_files = {"": [node.output_files["output-name"] for node in median_psd_nodes]},
			output_files = {"output-name": dagparts.T050017_filename(instruments, "REFERENCE_PSD", boundary_seg, '.xml.gz', path = subdir_path([jobs['medianPSD'].output_path, gpsmod5]))}
		)
	return median_psd_node

def svd_layer(dag, jobs, parent_nodes, psd, bank_cache, options, seg, output_dir, template_mchirp_dict):
	svd_nodes = {}
	new_template_mchirp_dict = {}
	svd_dtdphi_map = {}
	for ifo, list_of_svd_caches in bank_cache.items():
		bin_offset = 0
		for j, svd_caches in enumerate(list_of_svd_caches):
			svd_caches = map(CacheEntry, open(svd_caches))
			for i, individual_svd_cache in enumerate(ce.path for ce in svd_caches):
				# First sort out the clipleft, clipright options
				clipleft = []
				clipright = []
				ids = []
				mchirp_interval = (float("inf"), 0)
				individual_svd_cache = map(CacheEntry, open(individual_svd_cache))
				for n, f in enumerate(ce.path for ce in individual_svd_cache):
					# handle template bank clipping
					clipleft.append(options.overlap[j] / 2)
					clipright.append(options.overlap[j] / 2)
					ids.append("%d_%d" % (i+bin_offset, n))
					if f in template_mchirp_dict:
						mchirp_interval = (min(mchirp_interval[0], template_mchirp_dict[f][0]), max(mchirp_interval[1], template_mchirp_dict[f][1]))
					svd_dtdphi_map["%04d" % (i+bin_offset)] = options.dtdphi_file[j]

				svd_bank_name = dagparts.T050017_filename(ifo, '%04d_SVD' % (i+bin_offset,), seg, '.xml.gz', path = jobs['svd'].output_path)
				if '%04d' % (i+bin_offset,) not in new_template_mchirp_dict and mchirp_interval != (float("inf"), 0):
					new_template_mchirp_dict['%04d' % (i+bin_offset,)] = mchirp_interval

				svdnode = dagparts.DAGNode(
					jobs['svd'],
					dag,
					parent_nodes = parent_nodes,
					opts = {
						"svd-tolerance":options.tolerance,
						"flow":options.flow[j],
						"sample-rate":options.sample_rate,
						"clipleft":clipleft,
						"clipright":clipright,
						"samples-min":options.samples_min[j],
						"samples-max-256":options.samples_max_256,
						"samples-max-64":options.samples_max_64,
						"samples-max":options.samples_max,
						"autocorrelation-length":options.autocorrelation_length,
						"bank-id":ids,
						"identity-transform":options.identity_transform,
						"ortho-gate-fap":0.5
					},
					input_files = {"reference-psd":psd},
					input_cache_files = {"template-bank-cache":[ce.path for ce in individual_svd_cache]},
					input_cache_file_name = os.path.basename(svd_bank_name).replace(".xml.gz", ".cache"),
					output_files = {"write-svd":svd_bank_name},
				)

				# impose a priority to help with depth first submission
				svdnode.set_priority(99)
				svd_nodes.setdefault(ifo, []).append(svdnode)
			bin_offset += i+1

	# Plot template/svd bank jobs
	primary_ifo = bank_cache.keys()[0]
	dagparts.DAGNode(
		jobs['plotBanks'],
		dag,
		parent_nodes = sum(svd_nodes.values(),[]),
		opts = {"plot-template-bank":"", "output-dir": output_dir},
		input_files = {"template-bank-file":options.template_bank},
	)

	return svd_nodes, new_template_mchirp_dict, svd_dtdphi_map


def inspiral_layer(dag, jobs, psd_nodes, svd_nodes, segsdict, options, channel_dict, template_mchirp_dict):
	inspiral_nodes = {}
	for ifos in segsdict:
		# FIXME: handles more than 3 ifos with same cpu/memory requests
		inspiral_name = 'gstlalInspiral%dIFO' % min(len(ifos), 3)
		inspiral_inj_name = 'gstlalInspiralInj%dIFO' % min(len(ifos), 3)

		# setup dictionaries to hold the inspiral nodes
		inspiral_nodes[(ifos, None)] = {}
		ignore = {}
		injection_files = []
		for injections in options.injections:
			min_chirp_mass, max_chirp_mass, injections = injections.split(':')
			injection_files.append(injections)
			min_chirp_mass, max_chirp_mass = float(min_chirp_mass), float(max_chirp_mass)
			inspiral_nodes[(ifos, sim_tag_from_inj_file(injections))] = {}
			ignore[injections] = []
			for bgbin_index, bounds in sorted(template_mchirp_dict.items(), key = lambda (k,v): int(k)):
				if max_chirp_mass <= bounds[0]:
					ignore[injections].append(int(bgbin_index))
					# NOTE putting a break here assumes that the min chirp mass
					# in a subbank increases with bin number, i.e. XXXX+1 has a
					# greater minimum chirpmass than XXXX, for all XXXX. Note
					# that the reverse is not true, bin XXXX+1 may have a lower
					# max chirpmass than bin XXXX.
				elif min_chirp_mass > bounds[1]:
					ignore[injections].append(int(bgbin_index))

		# FIXME choose better splitting?
		numchunks = 50

		# only use a channel dict with the relevant channels
		this_channel_dict = dict((k, channel_dict[k]) for k in ifos if k in channel_dict)

		# get the svd bank strings
		svd_bank_strings_full = create_svd_bank_strings(svd_nodes, instruments = this_channel_dict.keys())

		# get a mapping between chunk counter and bgbin for setting priorities
		bgbin_chunk_map = {}

		for seg in segsdict[ifos]:
			if injection_files:
				output_seg_inj_path = subdir_path([jobs[inspiral_inj_name].output_path, str(int(seg[0]))[:5]])

			if jobs[inspiral_name] is None:
				# injection-only run
				inspiral_nodes[(ifos, None)].setdefault(seg, [None])

			else:
				output_seg_path = subdir_path([jobs[inspiral_name].output_path, str(int(seg[0]))[:5]])
				for chunk_counter, svd_bank_strings in enumerate(dagparts.groups(svd_bank_strings_full, numchunks)):
					bgbin_indices = ['%04d' % (i + numchunks * chunk_counter,) for i,s in enumerate(svd_bank_strings)]
					# setup output names
					output_paths = [subdir_path([output_seg_path, bgbin_indices[i]]) for i, s in enumerate(svd_bank_strings)]
					output_names = [dagparts.T050017_filename(ifos, '%s_LLOID' % idx, seg, '.xml.gz', path = path) for idx, path in zip(bgbin_indices, output_paths)]
					dist_stat_names = [dagparts.T050017_filename(ifos, '%s_DIST_STATS' % idx, seg, '.xml.gz', path = path) for idx, path in zip(bgbin_indices, output_paths)]

					for bgbin in bgbin_indices:
						bgbin_chunk_map.setdefault(bgbin, chunk_counter)

					# Calculate the appropriate ht-gate-threshold values according to the scale given
					threshold_values = get_threshold_values(template_mchirp_dict, bgbin_indices, svd_bank_strings, options)

					# non injection node
					noninjnode = dagparts.DAGNode(jobs[inspiral_name], dag,
						parent_nodes = sum((svd_node_list[numchunks*chunk_counter:numchunks*(chunk_counter+1)] for svd_node_list in svd_nodes.values()),[]),
						opts = {
							"psd-fft-length":options.psd_fft_length,
							"ht-gate-threshold":threshold_values,
							"frame-segments-name":options.frame_segments_name,
							"gps-start-time":int(seg[0]),
							"gps-end-time":int(seg[1]),
							"channel-name":datasource.pipeline_channel_list_from_channel_dict(this_channel_dict),
							"tmp-space":dagparts.condor_scratch_space(),
							"track-psd":"",
							"control-peak-time":options.control_peak_time,
							"coincidence-threshold":options.coincidence_threshold,
							"singles-threshold":options.singles_threshold,
							"fir-stride":options.fir_stride,
							"data-source":"frames",
							"local-frame-caching":"",
							"min-instruments":options.min_instruments,
							"reference-likelihood-file":options.reference_likelihood_file
						},
						input_files = {
							"time-slide-file":options.time_slide_file,
							"frame-cache":options.frame_cache,
							"frame-segments-file":options.frame_segments_file,
							"reference-psd":psd_nodes[(ifos, seg)].output_files["write-psd"],
							"blind-injections":options.blind_injections,
							"veto-segments-file":options.vetoes,
						},
						input_cache_files = {"svd-bank-cache":svd_bank_cache_maker(svd_bank_strings)},
						output_cache_files = {
							"output-cache":output_names,
							"ranking-stat-output-cache":dist_stat_names
						}
					)

					# Set a post script to check for file integrity
					if options.gzip_test:
						noninjnode.set_post_script("gzip_test.sh")
						noninjnode.add_post_script_arg(" ".join(output_names + dist_stat_names))

					# impose a priority to help with depth first submission
					noninjnode.set_priority(chunk_counter+15)

					inspiral_nodes[(ifos, None)].setdefault(seg, []).append(noninjnode)

			# process injections
			for injections in injection_files:
				# setup output names
				sim_name = sim_tag_from_inj_file(injections)

				bgbin_svd_bank_strings = [bgbin_svdbank for i, bgbin_svdbank in enumerate(zip(sorted(template_mchirp_dict.keys()), svd_bank_strings_full)) if i not in ignore[injections]]

				for chunk_counter, bgbin_list in enumerate(dagparts.groups(bgbin_svd_bank_strings, numchunks)):
					bgbin_indices, svd_bank_strings = zip(*bgbin_list)
					output_paths = [subdir_path([output_seg_inj_path, bgbin_index]) for bgbin_index in bgbin_indices]
					output_names = [dagparts.T050017_filename(ifos, '%s_LLOID_%s' % (idx, sim_name), seg, '.xml.gz', path = path) for idx, path in zip(bgbin_indices, output_paths)]
					svd_names = [s for i, s in enumerate(svd_bank_cache_maker(svd_bank_strings, injection = True))]
					try:
						reference_psd = psd_nodes[(ifos, seg)].output_files["write-psd"]
						parents = [svd_node_list[int(bgbin_index)] for svd_node_list in svd_nodes.values() for bgbin_index in bgbin_indices]
					except AttributeError: ### injection-only run
						reference_psd = psd_nodes[(ifos, seg)]
						parents = []

					svd_files = [CacheEntry.from_T050017(filename) for filename in svd_names]
					input_cache_name = dagparts.group_T050017_filename_from_T050017_files(svd_files, '.cache').replace('SVD', 'SVD_%s' % sim_name)

					# Calculate the appropriate ht-gate-threshold values according to the scale given
					threshold_values = get_threshold_values(template_mchirp_dict, bgbin_indices, svd_bank_strings, options)

					# setup injection node
					# FIXME: handles more than 3 ifos with same cpu/memory requests
					injnode = dagparts.DAGNode(jobs[inspiral_inj_name], dag,
						parent_nodes = parents,
						opts = {
							"psd-fft-length":options.psd_fft_length,
							"ht-gate-threshold":threshold_values,
							"frame-segments-name":options.frame_segments_name,
							"gps-start-time":int(seg[0]),
							"gps-end-time":int(seg[1]),
							"channel-name":datasource.pipeline_channel_list_from_channel_dict(this_channel_dict),
							"tmp-space":dagparts.condor_scratch_space(),
							"track-psd":"",
							"control-peak-time":options.control_peak_time,
							"coincidence-threshold":options.coincidence_threshold,
							"singles-threshold":options.singles_threshold,
							"fir-stride":options.fir_stride,
							"data-source":"frames",
							"local-frame-caching":"",
							"min-instruments":options.min_instruments,
							"reference-likelihood-file":options.reference_likelihood_file
						},
						input_files = {
							"time-slide-file":options.inj_time_slide_file,
							"frame-cache":options.frame_cache,
							"frame-segments-file":options.frame_segments_file,
							"reference-psd":reference_psd,
							"veto-segments-file":options.vetoes,
							"injections": injections
						},
						input_cache_files = {"svd-bank-cache":svd_names},
						input_cache_file_name = input_cache_name,
						output_cache_files = {"output-cache":output_names}
					)
					# Set a post script to check for file integrity
					if options.gzip_test:
						injnode.set_post_script("gzip_test.sh")
						injnode.add_post_script_arg(" ".join(output_names))

					# impose a priority to help with depth first submission
					if bgbin_chunk_map:
						injnode.set_priority(bgbin_chunk_map[bgbin_indices[-1]]+1)
					else:
						injnode.set_priority(chunk_counter+1)

					inspiral_nodes[(ifos, sim_name)].setdefault(seg, []).append(injnode)

	# Replace mchirplo:mchirphi:inj.xml with inj.xml
	options.injections = [inj.split(':')[-1] for inj in options.injections]

	# NOTE: Adapt the output of the gstlal_inspiral jobs to be suitable for the remainder of this analysis
	lloid_output, lloid_diststats = adapt_gstlal_inspiral_output(inspiral_nodes, options, segsdict)

	return inspiral_nodes, lloid_output, lloid_diststats


def expected_snr_layer(dag, jobs, ref_psd_parent_nodes, options, num_split_inj_snr_jobs):
	ligolw_add_nodes = []
	for inj in options.injections:
		inj_snr_nodes = []

		inj_splitter_node = dagparts.DAGNode(jobs['injSplitter'], dag, parent_nodes=[],
			opts = {
				"output-path":jobs['injSplitter'].output_path,
				"usertag": sim_tag_from_inj_file(inj.split(":")[-1]),
				"nsplit": num_split_inj_snr_jobs
			},
			input_files = {"": inj.split(":")[-1]}
		)
		inj_splitter_node.set_priority(98)

		# FIXME Use machinery in inspiral_pipe.py to create reference_psd.cache
		injection_files = ["%s/%s_INJ_SPLIT_%04d.xml" % (jobs['injSplitter'].output_path, sim_tag_from_inj_file(inj.split(":")[-1]), i) for i in range(num_split_inj_snr_jobs)]
		for injection_file in injection_files:
			injSNRnode = dagparts.DAGNode(jobs['gstlalInjSnr'], dag, parent_nodes=ref_psd_parent_nodes + [inj_splitter_node],
				# FIXME somehow choose the actual flow based on mass?
				# max(flow) is chosen for performance not
				# correctness hopefully though it will be good
				# enough
				opts = {"flow":max(options.flow),"fmax":options.fmax},
				input_files = {
					"injection-file": injection_file,
					"reference-psd-cache": "reference_psd.cache"
				}
			)
			injSNRnode.set_priority(98)
			inj_snr_nodes.append(injSNRnode)

		addnode = dagparts.DAGNode(jobs['ligolwAdd'], dag, parent_nodes=inj_snr_nodes,
			input_files = {"": ' '.join(injection_files)},
			output_files = {"output": inj.split(":")[-1]}
		)

		ligolw_add_nodes.append(dagparts.DAGNode(jobs['lalappsRunSqlite'], dag, parent_nodes = [addnode],
			opts = {"sql-file":options.injection_proc_sql_file, "tmp-space":dagparts.condor_scratch_space()},
			input_files = {"":addnode.output_files["output"]}
			)
		)
	return ligolw_add_nodes


def summary_plot_layer(dag, jobs, farnode, options, injdbs, noninjdb, output_dir):
	plotnodes = []

	### common plot options
	common_plot_opts = {
		"segments-name": options.frame_segments_name,
		"tmp-space": dagparts.condor_scratch_space(),
		"output-dir": output_dir,
		"likelihood-file":"post_marginalized_likelihood.xml.gz",
		"shrink-data-segments": 32.0,
		"extend-veto-segments": 8.,
	}
	sensitivity_opts = {
		"output-dir":output_dir,
		"tmp-space":dagparts.condor_scratch_space(),
		"veto-segments-name":"vetoes",
		"bin-by-source-type":"",
		"dist-bins":200,
		"data-segments-name":"datasegments"
	}

	### plot summary
	opts = {"user-tag": "ALL_LLOID_COMBINED", "remove-precession": ""}
	opts.update(common_plot_opts)
	plotnodes.append(dagparts.DAGNode(jobs['plotSummary'], dag, parent_nodes=[farnode],
		opts = opts,
		input_files = {"": [noninjdb] + injdbs}
	))

	### isolated precession plot summary
	opts = {"user-tag": "PRECESSION_LLOID_COMBINED", "isolate-precession": "", "plot-group": 1}
	opts.update(common_plot_opts)
	plotnodes.append(dagparts.DAGNode(jobs['plotSummaryIsolatePrecession'], dag, parent_nodes=[farnode],
		opts = opts,
		input_files = {"":[noninjdb] + injdbs}
	))

	for injdb in injdbs:
		### individual injection plot summary
		opts = {"user-tag": injdb.replace(".sqlite","").split("-")[1], "remove-precession": "", "plot-group": 1}
		opts.update(common_plot_opts)
		plotnodes.append(dagparts.DAGNode(jobs['plotSnglInjSummary'], dag, parent_nodes=[farnode],
			opts = opts,
			input_files = {"":[noninjdb] + [injdb]}
		))

		### isolated precession injection plot summary
		opts = {"user-tag": injdb.replace(".sqlite","").split("-")[1].replace("ALL_LLOID","PRECESSION_LLOID"), "isolate-precession": "", "plot-group": 1}
		opts.update(common_plot_opts)
		plotnodes.append(dagparts.DAGNode(jobs['plotSnglInjSummaryIsolatePrecession'], dag, parent_nodes=[farnode],
			opts = opts,
			input_files = {"":[noninjdb] + [injdb]}
		))

	### sensitivity plots
	opts = {"user-tag": "ALL_LLOID_COMBINED"}
	opts.update(sensitivity_opts)
	plotnodes.append(dagparts.DAGNode(jobs['plotSensitivity'], dag, parent_nodes=[farnode],
		opts = opts,
		input_files = {"zero-lag-database": noninjdb, "": injdbs}
	))

	for injdb in injdbs:
		opts = {"user-tag": injdb.replace(".sqlite","").split("-")[1]}
		opts.update(sensitivity_opts)
		plotnodes.append(dagparts.DAGNode(jobs['plotSensitivity'], dag, parent_nodes=[farnode],
			opts = opts,
			input_files = {"zero-lag-database": noninjdb, "": injdb}
		))

	### background plots
	plotnodes.append(dagparts.DAGNode(jobs['plotBackground'], dag, parent_nodes = [farnode],
		opts = {"user-tag":"ALL_LLOID_COMBINED", "output-dir":output_dir},
		input_files = {"":"post_marginalized_likelihood.xml.gz", "database":noninjdb}
	))

	return plotnodes


def clean_merger_products_layer(dag, jobs, plotnodes, dbs_to_delete, margfiles_to_delete):
	"""clean intermediate merger products
	"""
	for db in dbs_to_delete:
		dagparts.DAGNode(jobs['rm'], dag, parent_nodes = plotnodes,
			input_files = {"": db}
		)

	for margfile in margfiles_to_delete:
		dagparts.DAGNode(jobs['rm'], dag, parent_nodes = plotnodes,
			input_files = {"": margfile}
		)
	return None


def inj_psd_layer(segsdict, options):
	psd_nodes = {}
	psd_cache_files = {}
	for ce in map(CacheEntry, open(options.psd_cache)):
		psd_cache_files.setdefault(frozenset(lsctables.instrumentsproperty.get(ce.observatory)), []).append((ce.segment, ce.path))
	for ifos in segsdict:
		reference_psd_files = sorted(psd_cache_files[ifos], key = lambda (s, p): s)
		ref_psd_file_num = 0
		for seg in segsdict[ifos]:
			while int(reference_psd_files[ref_psd_file_num][0][0]) < int(seg[0]):
				ref_psd_file_num += 1
			psd_nodes[(ifos, seg)] = reference_psd_files[ref_psd_file_num][1]
	ref_psd_parent_nodes = []
	return psd_nodes, ref_psd_parent_nodes


def mass_model_layer(dag, jobs, parent_nodes, instruments, options, seg, psd):
	"""mass model node
	"""
	if options.mass_model_file is None:
		# choose, arbitrarily, the lowest instrument in alphabetical order
		model_file_name = dagparts.T050017_filename(instruments, 'ALL_MASS_MODEL', seg, '.h5', path = jobs['model'].output_path)
		model_node = dagparts.DAGNode(jobs['model'], dag,
			input_files = {"template-bank": options.template_bank, "reference-psd": psd},
			opts = {"model":options.mass_model},
			output_files = {"output": model_file_name},
			parent_nodes = parent_nodes
		)
		return [model_node], model_file_name
	else:
		return [], options.mass_model_file


def merge_cluster_layer(dag, jobs, parent_nodes, db, db_cache, sqlfile, input_files=None):
	"""merge and cluster from sqlite database
	"""
	if input_files:
		input_ = {"": input_files}
	else:
		input_ = {}

	# Merge database into chunks
	sqlitenode = dagparts.DAGNode(jobs['toSqlite'], dag, parent_nodes = parent_nodes,
		opts = {"replace":"", "tmp-space":dagparts.condor_scratch_space()},
		input_files = input_,
		input_cache_files = {"input-cache": db_cache},
		output_files = {"database":db},
		input_cache_file_name = os.path.basename(db).replace('.sqlite','.cache')
	)

	# cluster database
	return dagparts.DAGNode(jobs['lalappsRunSqlite'], dag, parent_nodes = [sqlitenode],
		opts = {"sql-file": sqlfile, "tmp-space": dagparts.condor_scratch_space()},
		input_files = {"": db}
	)


def marginalize_layer(dag, jobs, svd_nodes, lloid_output, lloid_diststats, options, boundary_seg, instrument_set, model_node, model_file, ref_psd, svd_dtdphi_map):
	instruments = "".join(sorted(instrument_set))
	margnodes = {}

	# NOTE! we rely on there being identical templates in each instrument,
	# so we just take one of the values of the svd_nodes which are a dictionary
	# FIXME, the svd nodes list has to be the same as the sorted keys of
	# lloid_output.  svd nodes should be made into a dictionary much
	# earlier in the code to prevent a mishap
604 605
	if svd_nodes:
		one_ifo_svd_nodes = dict(("%04d" % n, [node]) for n, node in enumerate( svd_nodes.values()[0]))
606 607 608 609 610 611 612 613 614 615 616

	# Here n counts the bins
	# FIXME - this is broken for injection dags right now because of marg nodes
	# first non-injections, which will get skipped if this is an injections-only run
	for bin_key in sorted(lloid_output[None].keys()):
		outputs = lloid_output[None][bin_key]
		diststats = lloid_diststats[bin_key]
		inputs = [o[0] for o in outputs]
		parents = dagparts.flatten([o[1] for o in outputs])
		rankfile = functools.partial(get_rank_file, instruments, boundary_seg, bin_key)

617 618 619 620 621 622 623
		if svd_nodes:
			parent_nodes = [one_ifo_svd_nodes[bin_key]] + model_node
			svd_file = one_ifo_svd_nodes[bin_key].output_files["write-svd"]
		else:
			parent_nodes = model_node
			svd_file = dagparts.T050017_filename(ifo, '%s_SVD' % bin_key, boundary_arg, '.xml.gz', path = jobs['svd'].output_path)

624 625 626 627
		# FIXME we keep this here in case we someday want to have a
		# mass bin dependent prior, but it really doesn't matter for
		# the time being.
		priornode = dagparts.DAGNode(jobs['createPriorDistStats'], dag,
628
			parent_nodes = parent_nodes,
629 630 631 632 633 634 635 636
			opts = {
				"instrument": instrument_set,
				"background-prior": 1,
				"min-instruments": options.min_instruments,
				"coincidence-threshold":options.coincidence_threshold,
				"df": "bandwidth"
			},
			input_files = {
637
				"svd-file": svd_file,
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
				"mass-model-file": model_file,
				"dtdphi-file": svd_dtdphi_map[bin_key],
				"psd-xml": ref_psd
			},
			output_files = {"write-likelihood": rankfile('CREATE_PRIOR_DIST_STATS', job=jobs['createPriorDistStats'])}
		)
		# Create a file that has the priors *and* all of the diststats
		# for a given bin marginalized over time. This is all that will
		# be needed to compute the likelihood
		diststats_per_bin_node = dagparts.DAGNode(jobs['marginalize'], dag,
			parent_nodes = [priornode] + parents,
			opts = {"marginalize": "ranking-stat"},
			input_cache_files = {"likelihood-cache": diststats + [priornode.output_files["write-likelihood"]]},
			output_files = {"output": rankfile('MARG_DIST_STATS', job=jobs['marginalize'])},
			input_cache_file_name = rankfile('MARG_DIST_STATS')
		)

		margnodes[bin_key] = diststats_per_bin_node

	return margnodes


def calc_rank_pdf_layer(dag, jobs, marg_nodes, options, boundary_seg, instrument_set):
	rankpdf_nodes = []
	rankpdf_zerolag_nodes = []
	instruments = "".join(sorted(instrument_set))

	# Here n counts the bins
	for bin_key in sorted(marg_nodes.keys()):
		rankfile = functools.partial(get_rank_file, instruments, boundary_seg, bin_key)

		calcranknode = dagparts.DAGNode(jobs['calcRankPDFs'], dag,
			parent_nodes = [marg_nodes[bin_key]],
			opts = {"ranking-stat-samples":options.ranking_stat_samples},
			input_files = {"": marg_nodes[bin_key].output_files["output"]},
			output_files = {"output": rankfile('CALC_RANK_PDFS', job=jobs['calcRankPDFs'])},
		)

		calcrankzerolagnode = dagparts.DAGNode(jobs['calcRankPDFsWithZerolag'], dag,
			parent_nodes = [marg_nodes[bin_key]],
			opts = {"add-zerolag-to-background": "", "ranking-stat-samples": options.ranking_stat_samples},
			input_files = {"": marg_nodes[bin_key].output_files["output"]},
			output_files = {"output": rankfile('CALC_RANK_PDFS_WZL', job=jobs['calcRankPDFsWithZerolag'])},
		)

		rankpdf_nodes.append(calcranknode)
		rankpdf_zerolag_nodes.append(calcrankzerolagnode)

	return rankpdf_nodes, rankpdf_zerolag_nodes


def likelihood_layer(dag, jobs, marg_nodes, lloid_output, lloid_diststats, options, boundary_seg, instrument_set):
	likelihood_nodes = {}
	instruments = "".join(sorted(instrument_set))

	# non-injection jobs
	for bin_key in sorted(lloid_output[None].keys()):
		outputs = lloid_output[None][bin_key]
		diststats = lloid_diststats[bin_key]
		inputs = [o[0] for o in outputs]

		# (input files for next job, dist stat files, parents for next job)
		likelihood_nodes[None, bin_key] = (inputs, marg_nodes[bin_key].output_files["output"], [marg_nodes[bin_key]])

	# injection jobs
	for inj in options.injections:
		lloid_nodes = lloid_output[sim_tag_from_inj_file(inj)]
		for bin_key in sorted(lloid_nodes.keys()):
			outputs = lloid_nodes[bin_key]
			diststats = lloid_diststats[bin_key]
			if outputs is not None:
				inputs = [o[0] for o in outputs]
				parents = dagparts.flatten([o[1] for o in outputs])

				parents.append(marg_nodes[bin_key])
				likelihood_url = marg_nodes[bin_key].output_files["output"]
				likelihood_nodes[sim_tag_from_inj_file(inj), bin_key] = (inputs, likelihood_url, parents)

	return likelihood_nodes


def sql_cluster_and_merge_layer(dag, jobs, likelihood_nodes, ligolw_add_nodes, options, boundary_seg, instruments):
	num_chunks = 100
	innodes = {}

	# after assigning the likelihoods cluster and merge by sub bank and whether or not it was an injection run
	for (sim_tag, bin_key), (inputs, likelihood_url, parents) in sorted(likelihood_nodes.items()):
		db = inputs_to_db(jobs, inputs, job_type = 'toSqliteNoCache')
		xml = inputs_to_db(jobs, inputs, job_type = 'ligolwAdd').replace(".sqlite", ".xml.gz")
		snr_cluster_sql_file = options.snr_cluster_sql_file if sim_tag is None else options.injection_snr_cluster_sql_file
		cluster_sql_file = options.cluster_sql_file if sim_tag is None else options.injection_sql_file

		# cluster sub banks
		cluster_node = dagparts.DAGNode(jobs['lalappsRunSqlite'], dag, parent_nodes = parents,
			opts = {"sql-file": snr_cluster_sql_file, "tmp-space":dagparts.condor_scratch_space()},
			input_files = {"":inputs}
			)

		# merge sub banks
		merge_node = dagparts.DAGNode(jobs['ligolwAdd'], dag, parent_nodes = [cluster_node],
			input_files = {"":inputs},
			output_files = {"output":xml}
			)

		# cluster and simplify sub banks
		cluster_node = dagparts.DAGNode(jobs['lalappsRunSqlite'], dag, parent_nodes = [merge_node],
			opts = {"sql-file": snr_cluster_sql_file, "tmp-space":dagparts.condor_scratch_space()},
			input_files = {"":xml}
			)

		# assign likelihoods
		likelihood_node = dagparts.DAGNode(jobs['calcLikelihood'], dag,
			parent_nodes = [cluster_node],
			opts = {"tmp-space":dagparts.condor_scratch_space()},
			input_files = {"likelihood-url":likelihood_url, "": xml}
			)

		sqlitenode = dagparts.DAGNode(jobs['toSqliteNoCache'], dag, parent_nodes = [likelihood_node],
			opts = {"replace":"", "tmp-space":dagparts.condor_scratch_space()},
			input_files = {"":xml},
			output_files = {"database":db},
		)
		sqlitenode = dagparts.DAGNode(jobs['lalappsRunSqlite'], dag, parent_nodes = [sqlitenode],
			opts = {"sql-file": cluster_sql_file, "tmp-space":dagparts.condor_scratch_space()},
			input_files = {"":db}
		)

		innodes.setdefault(sim_tag_from_inj_file(sim_tag) if sim_tag else None, []).append(sqlitenode)

	# make sure outnodes has a None key, even if its value is an empty list
	# FIXME injection dag is broken
	innodes.setdefault(None, [])

	if options.vetoes is None:
		vetoes = []
	else:
		vetoes = [options.vetoes]

	chunk_nodes = []
	dbs_to_delete = []
	# Process the chirp mass bins in chunks to paralellize the merging process
	for chunk, nodes in enumerate(dagparts.groups(innodes[None], num_chunks)):
		try:
			dbs = [node.input_files[""] for node in nodes]
			parents = nodes

		except AttributeError:
			# analysis started at merger step but seeded by lloid files which
			# have already been merged into one file per background
			# bin, thus the analysis will begin at this point
			dbs = nodes
			parents = []

		dbfiles = [CacheEntry.from_T050017("file://localhost%s" % os.path.abspath(filename)) for filename in dbs]
		noninjdb = dagparts.group_T050017_filename_from_T050017_files(dbfiles, '.sqlite', path = jobs['toSqlite'].output_path)

		# Merge and cluster the final non injection database
		noninjsqlitenode = merge_cluster_layer(dag, jobs, parents, noninjdb, dbs, options.cluster_sql_file)
		chunk_nodes.append(noninjsqlitenode)
		dbs_to_delete.append(noninjdb)

	# Merge the final non injection database
	outnodes = []
	injdbs = []
	if options.non_injection_db: #### injection-only run
		noninjdb = options.non_injection_db
	else:
		final_nodes = []
		for chunk, nodes in enumerate(dagparts.groups(innodes[None], num_chunks)):
			noninjdb = dagparts.T050017_filename(instruments, 'PART_LLOID_CHUNK_%04d' % chunk, boundary_seg, '.sqlite')

			# cluster the final non injection database
			noninjsqlitenode = merge_cluster_layer(dag, jobs, nodes, noninjdb, [node.input_files[""] for node in nodes], options.cluster_sql_file)
			final_nodes.append(noninjsqlitenode)

		input_files = (vetoes + [options.frame_segments_file])
		input_cache_files = [node.input_files[""] for node in final_nodes]
		noninjdb = dagparts.T050017_filename(instruments, 'ALL_LLOID', boundary_seg, '.sqlite')
		noninjsqlitenode = merge_cluster_layer(dag, jobs, final_nodes, noninjdb, input_cache_files, options.cluster_sql_file, input_files=input_files)

		cpnode = dagparts.DAGNode(jobs['cp'], dag, parent_nodes = [noninjsqlitenode],
			input_files = {"":"%s %s" % (noninjdb, noninjdb.replace('ALL_LLOID', 'ALL_LLOID_WZL'))}
		)

		outnodes.append(cpnode)

	if options.injections:
		iterable_injections = options.injections
	else:
		iterable_injections = options.injections_for_merger

	for injections in iterable_injections:
		# extract only the nodes that were used for injections
		chunk_nodes = []

		for chunk, injnodes in enumerate(dagparts.groups(innodes[sim_tag_from_inj_file(injections)], num_chunks)):
			try:
				dbs = [injnode.input_files[""] for injnode in injnodes]
				parents = injnodes
			except AttributeError:
				dbs = injnodes
				parents = []

			# Setup the final output names, etc.
			dbfiles = [CacheEntry.from_T050017("file://localhost%s" % os.path.abspath(filename)) for filename in dbs]
			injdb = dagparts.group_T050017_filename_from_T050017_files(dbfiles, '.sqlite', path = jobs['toSqlite'].output_path)

			# merge and cluster
			clusternode = merge_cluster_layer(dag, jobs, parents, injdb, dbs, options.cluster_sql_file)
			chunk_nodes.append(clusternode)
			dbs_to_delete.append(injdb)


		final_nodes = []
		for chunk, injnodes in enumerate(dagparts.groups(innodes[sim_tag_from_inj_file(injections)], num_chunks)):
			# Setup the final output names, etc.
			injdb = dagparts.T050017_filename(instruments, 'PART_LLOID_%s_CHUNK_%04d' % (sim_tag_from_inj_file(injections), chunk), boundary_seg, '.sqlite')

			# merge and cluster
			clusternode = merge_cluster_layer(dag, jobs, injnodes, injdb, [node.input_files[""] for node in injnodes], options.cluster_sql_file)
			final_nodes.append(clusternode)

		# Setup the final output names, etc.
		injdb = dagparts.T050017_filename(instruments, 'ALL_LLOID_%s' % sim_tag_from_inj_file(injections), boundary_seg, '.sqlite')
		injdbs.append(injdb)
		injxml = injdb.replace('.sqlite','.xml.gz')

		xml_input = injxml

		# merge and cluster
		parent_nodes = final_nodes + ligolw_add_nodes
		input_files = (vetoes + [options.frame_segments_file, injections])
		input_cache_files = [node.input_files[""] for node in final_nodes]
		clusternode = merge_cluster_layer(dag, jobs, parent_nodes, injdb, input_cache_files, options.cluster_sql_file, input_files=input_files)

		clusternode = dagparts.DAGNode(jobs['toXML'], dag, parent_nodes = [clusternode],
			opts = {"tmp-space":dagparts.condor_scratch_space()},
			output_files = {"extract":injxml},
			input_files = {"database":injdb}
		)

		inspinjnode = dagparts.DAGNode(jobs['ligolwInspinjFind'], dag, parent_nodes = [clusternode],
			opts = {"time-window":0.9},
			input_files = {"":injxml}
		)

		sqlitenode = dagparts.DAGNode(jobs['toSqliteNoCache'], dag, parent_nodes = [inspinjnode],
			opts = {"replace":"", "tmp-space":dagparts.condor_scratch_space()},
			output_files = {"database":injdb},
			input_files = {"":xml_input}
		)

		cpnode = dagparts.DAGNode(jobs['cp'], dag, parent_nodes = [sqlitenode],
			input_files = {"":"%s %s" % (injdb, injdb.replace('ALL_LLOID', 'ALL_LLOID_WZL'))}
		)

		outnodes.append(cpnode)

	return injdbs, noninjdb, outnodes, dbs_to_delete


def final_marginalize_layer(dag, jobs, rankpdf_nodes, rankpdf_zerolag_nodes, options):
	ranknodes = [rankpdf_nodes, rankpdf_zerolag_nodes]
	margjobs = [jobs['marginalize'], jobs['marginalizeWithZerolag']]
	margfiles = [options.marginalized_likelihood_file, options.marginalized_likelihood_file]
	filesuffixs = ['', '_with_zerolag']

	margnum = 16
	all_margcache = []
	all_margnodes = []
	final_margnodes = []
	for nodes, job, margfile, filesuffix in zip(ranknodes, margjobs, margfiles, filesuffixs):
		try:
			margin = [node.output_files["output"] for node in nodes]
			parents = nodes
		except AttributeError: ### analysis started at merger step
			margin = nodes
			parents = []

		margnodes = []
		margcache = []

		# split up the marginalization into groups of 10
		# FIXME: is it actually groups of 10 or groups of 16?
		for margchunk in dagparts.groups(margin, margnum):
			if nodes:
				marg_ce = [CacheEntry.from_T050017("file://localhost%s" % os.path.abspath(filename)) for filename in margchunk]
				margcache.append(dagparts.group_T050017_filename_from_T050017_files(marg_ce, '.xml.gz', path = job.output_path))
				margnodes.append(dagparts.DAGNode(job, dag, parent_nodes = parents,
					opts = {"marginalize": "ranking-stat-pdf"},
					output_files = {"output": margcache[-1]},
					input_cache_files = {"likelihood-cache": margchunk},
					input_cache_file_name = os.path.basename(margcache[-1]).replace('.xml.gz','.cache')
				))

		all_margcache.append(margcache)
		all_margnodes.append(margnodes)

	if not options.marginalized_likelihood_file: ### not an injection-only run
		for nodes, job, margnodes, margcache, margfile, filesuffix in zip(ranknodes, margjobs, all_margnodes, all_margcache, margfiles, filesuffixs):
			final_margnodes.append(dagparts.DAGNode(job, dag, parent_nodes = margnodes,
				opts = {"marginalize": "ranking-stat-pdf"},
				output_files = {"output": "marginalized_likelihood%s.xml.gz"%filesuffix},
				input_cache_files = {"likelihood-cache": margcache},
				input_cache_file_name = "marginalized_likelihood%s.cache"%filesuffix
			))

	return final_margnodes, dagparts.flatten(all_margcache)


def compute_far_layer(dag, jobs, margnodes, injdbs, noninjdb, final_sqlite_nodes, options):
	"""compute FAPs and FARs
	"""
	margfiles = [options.marginalized_likelihood_file, options.marginalized_likelihood_file]
	filesuffixs = ['', '_with_zerolag']

	for margnode, margfile, filesuffix in zip(margnodes, margfiles, filesuffixs):
		if options.marginalized_likelihood_file: ### injection-only run
			parents = final_sqlite_nodes
			marginalized_likelihood_file = margfile

		else:
			parents = [margnode] + final_sqlite_nodes
			marginalized_likelihood_file = margnode.output_files["output"]

		farnode = dagparts.DAGNode(jobs['ComputeFarFromSnrChisqHistograms'], dag, parent_nodes = parents,
			opts = {"tmp-space":dagparts.condor_scratch_space()},
			input_files = {
				"background-bins-file": marginalized_likelihood_file,
				"injection-db": [injdb.replace('ALL_LLOID', 'ALL_LLOID_WZL') for injdb in injdbs] if 'zerolag' in filesuffix else injdbs,
				"non-injection-db": noninjdb.replace('ALL_LLOID', 'ALL_LLOID_WZL') if 'zerolag' in filesuffix else noninjdb
			}
		)

		if 'zerolag' not in filesuffix:
			outnode = farnode

	return outnode


def horizon_dist_layer(dag, jobs, psd_nodes, options, boundary_seg, output_dir, instruments):
	"""calculate horizon distance
	"""
	dagparts.DAGNode(jobs['horizon'], dag,
		parent_nodes = psd_nodes.values(),
		input_files = {"":[node.output_files["write-psd"] for node in psd_nodes.values()]},
		output_files = {"":dagparts.T050017_filename(instruments, "HORIZON", boundary_seg, '.png', path = output_dir)}
	)


def summary_page_layer(dag, jobs, plotnodes, options, boundary_seg, injdbs, output_dir):
	"""create a summary page
	"""
	output_user_tags = ["ALL_LLOID_COMBINED", "PRECESSION_LLOID_COMBINED"]
	output_user_tags.extend([injdb.replace(".sqlite","").split("-")[1] for injdb in injdbs])
	output_user_tags.extend([injdb.replace(".sqlite","").split("-")[1].replace("ALL_LLOID", "PRECESSION_LLOID") for injdb in injdbs])

	dagparts.DAGNode(jobs['summaryPage'], dag, parent_nodes = plotnodes,
		opts = {
			"title":"gstlal-%d-%d-closed-box" % (int(boundary_seg[0]), int(boundary_seg[1])),
			"webserver-dir":options.web_dir,
			"glob-path":output_dir,
			"output-user-tag":output_user_tags
		}
	)
Chad Hanna's avatar
Chad Hanna committed
1003

1004 1005

#
Chad Hanna's avatar
Chad Hanna committed
1006
# environment utilities
1007 1008
#

Chad Hanna's avatar
Chad Hanna committed
1009

1010 1011 1012 1013 1014 1015 1016 1017
def webserver_url():
	"""!
	The stupid pet tricks to find webserver on the LDG.
	"""
	host = socket.getfqdn()
	#FIXME add more hosts as you need them
	if "cit" in host or "ligo.caltech.edu" in host:
		return "https://ldas-jobs.ligo.caltech.edu"
1018
	if ".phys.uwm.edu" in host or ".cgca.uwm.edu" in host or ".nemo.uwm.edu" in host:
1019
		return "https://ldas-jobs.cgca.uwm.edu"
1020 1021 1022 1023 1024
	# FIXME:  this next system does not have a web server, but not
	# having a web server is treated as a fatal error so we have to
	# make something up if we want to make progress
	if ".icrr.u-tokyo.ac.jp" in host:
		return "https://ldas-jobs.icrr.u-tokyo.ac.jp"
1025 1026 1027 1028

	raise NotImplementedError("I don't know where the webserver is for this environment")


1029 1030 1031 1032 1033
#
# DAG utilities
#


1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
def load_analysis_output(options):
	# load triggers
	bgbin_lloid_map = {}
	for ce in map(CacheEntry, open(options.lloid_cache)):
		try:
			bgbin_idx, _, inj = ce.description.split('_', 2)
		except:
			bgbin_idx, _ = ce.description.split('_', 1)
			inj = None
		finally:
			bgbin_lloid_map.setdefault(sim_tag_from_inj_file(inj), []).append(ce.path)

	# load dist stats
	lloid_diststats = {}
	boundary_seg = None
	for ce in map(CacheEntry, open(options.dist_stats_cache)):
		if 'DIST_STATS' in ce.description:
			lloid_diststats[ce.description.split("_")[0]] = [ce.path]
			if not boundary_seg:
				boundary_seg = ce.segment

	# load svd dtdphi map
	svd_dtdphi_map = {}
	bank_cache = load_bank_cache(options)
	instrument_set = bank_cache.keys()
	for ifo, list_of_svd_caches in bank_cache.items():
		bin_offset = 0
		for j, svd_caches in enumerate(list_of_svd_caches):
			for i, individual_svd_cache in enumerate(ce.path for ce in map(CacheEntry, open(svd_caches))):
				svd_dtdphi_map["%04d" % (i+bin_offset)] = options.dtdphi_file[j]

	return bgbin_lloid_map, lloid_diststats, svd_dtdphi_map, instrument_set, boundary_seg


1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
def get_threshold_values(template_mchirp_dict, bgbin_indices, svd_bank_strings, options):
	"""Calculate the appropriate ht-gate-threshold values according to the scale given
	"""
	if options.ht_gate_threshold_linear is not None:
		# A scale is given
		mchirp_min, ht_gate_threshold_min, mchirp_max, ht_gate_threshold_max = [float(y) for x in options.ht_gate_threshold_linear.split("-") for y in x.split(":")]
		# use max mchirp in a given svd bank to decide gate threshold
		bank_mchirps = [template_mchirp_dict[bgbin_index][1] for bgbin_index in bgbin_indices]
		gate_mchirp_ratio = (ht_gate_threshold_max - ht_gate_threshold_min)/(mchirp_max - mchirp_min)
		return [gate_mchirp_ratio*(bank_mchirp - mchirp_min) + ht_gate_threshold_min for bank_mchirp in bank_mchirps]
	elif options.ht_gate_threshold is not None:
		return [options.ht_gate_threshold]*len(svd_bank_strings) # Use the ht-gate-threshold value given
	else:
		return None


def inputs_to_db(jobs, inputs, job_type = 'toSqlite'):
	dbfiles = [CacheEntry.from_T050017("file://localhost%s" % os.path.abspath(filename)) for filename in inputs]
	db = dagparts.group_T050017_filename_from_T050017_files(dbfiles, '.sqlite')
	return os.path.join(subdir_path([jobs[job_type].output_path, CacheEntry.from_T050017(db).description[:4]]), db)


def cache_to_db(cache, jobs):
	hi_index = cache[-1].description.split('_')[0]
	db = os.path.join(jobs['toSqlite'].output_path, os.path.basename(cache[-1].path))
	db.replace(hi_index, '%04d' % ((int(hi_index) + 1) / options.num_files_per_background_bin - 1,))
	return db


def get_rank_file(instruments, boundary_seg, n, basename, job=None):
	if job:
		return dagparts.T050017_filename(instruments, '_'.join([n, basename]), boundary_seg, '.xml.gz', path = job.output_path)
	else:
		return dagparts.T050017_filename(instruments, '_'.join([n, basename]), boundary_seg, '.cache')


1104
#
Chad Hanna's avatar
Chad Hanna committed
1105
# Utility functions
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
#


def group(inlist, parts):
	"""!
	group a list roughly according to the distribution in parts, e.g.

	>>> A = range(12)
	>>> B = [2,3]
	>>> for g in group(A,B):
	...     print g
1117
	...
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
	[0, 1]
	[2, 3]
	[4, 5]
	[6, 7, 8]
	[9, 10, 11]
	"""
	mult_factor = len(inlist) // sum(parts) + 1
	l = copy.deepcopy(inlist)
	for i, p in enumerate(parts):
		for j in range(mult_factor):
			if not l:
				break
			yield l[:p]
			del l[:p]
Chad Hanna's avatar
Chad Hanna committed
1132 1133 1134


def parse_cache_str(instr):
1135 1136 1137 1138
	"""!
	A way to decode a command line option that specifies different bank
	caches for different detectors, e.g.,

1139
	>>> bankcache = parse_cache_str("H1=H1_split_bank.cache,L1=L1_split_bank.cache,V1=V1_split_bank.cache")
1140 1141 1142 1143
	>>> bankcache
	{'V1': 'V1_split_bank.cache', 'H1': 'H1_split_bank.cache', 'L1': 'L1_split_bank.cache'}
	"""

Chad Hanna's avatar
Chad Hanna committed
1144 1145 1146 1147 1148 1149 1150 1151
	dictcache = {}
	if instr is None: return dictcache
	for c in instr.split(','):
		ifo = c.split("=")[0]
		cache = c.replace(ifo+"=","")
		dictcache[ifo] = cache
	return dictcache

1152

1153
def build_bank_groups(cachedict, numbanks = [2], maxjobs = None):
1154 1155 1156 1157 1158 1159
	"""!
	given a dictionary of bank cache files keyed by ifo from .e.g.,
	parse_cache_str(), group the banks into suitable size chunks for a single svd
	bank file according to numbanks.  Note, numbanks can be should be a list and uses
	the algorithm in the group() function
	"""
1160
	outstrs = []
1161
	ifos = sorted(cachedict.keys())
1162
	files = zip(*[[CacheEntry(f).path for f in open(cachedict[ifo],'r').readlines()] for ifo in ifos])
1163
	for n, bank_group in enumerate(group(files, numbanks)):
gstlalcbc's avatar
gstlalcbc committed
1164
		if maxjobs is not None and n > maxjobs:
Chad Hanna's avatar
Chad Hanna committed
1165
			break
1166
		c = dict(zip(ifos, zip(*bank_group)))
1167
		outstrs.append(c)
Chad Hanna's avatar
Chad Hanna committed
1168

1169
	return outstrs
1170

1171

1172 1173
def get_svd_bank_params_online(svd_bank_cache):
	template_mchirp_dict = {}
1174
	for ce in [CacheEntry(f) for f in open(svd_bank_cache)]:
1175 1176
		if not template_mchirp_dict.setdefault("%04d" % int(ce.description.split("_")[3]), []):
			min_mchirp, max_mchirp = float("inf"), 0
1177
			xmldoc = ligolw_utils.load_url(ce.path, contenthandler = svd_bank.DefaultContentHandler)
1178 1179 1180 1181 1182 1183 1184 1185
			for root in (elem for elem in xmldoc.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == "gstlal_svd_bank_Bank"):
				snglinspiraltable = lsctables.SnglInspiralTable.get_table(root)
				mchirp_column = snglinspiraltable.getColumnByName("mchirp")
				min_mchirp, max_mchirp = min(min_mchirp, min(mchirp_column)), max(max_mchirp, max(mchirp_column))
			template_mchirp_dict["%04d" % int(ce.description.split("_")[3])] = (min_mchirp, max_mchirp)
			xmldoc.unlink()
	return template_mchirp_dict

1186

1187 1188 1189 1190 1191
def get_svd_bank_params(svd_bank_cache, online = False):
	if not online:
		bgbin_file_map = {}
		max_time = 0
	template_mchirp_dict = {}
1192
	for ce in sorted([CacheEntry(f) for f in open(svd_bank_cache)], cmp = lambda x,y: cmp(int(x.description.split("_")[0]), int(y.description.split("_")[0]))):
1193 1194 1195 1196
		if not online:
			bgbin_file_map.setdefault(ce.observatory, []).append(ce.path)
		if not template_mchirp_dict.setdefault(ce.description.split("_")[0], []):
			min_mchirp, max_mchirp = float("inf"), 0
1197
			xmldoc = ligolw_utils.load_url(ce.path, contenthandler = svd_bank.DefaultContentHandler)
1198
			for root in (elem for elem in xmldoc.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == "gstlal_svd_bank_Bank"):
1199
				snglinspiraltable = lsctables.SnglInspiralTable.get_table(root)
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
				mchirp_column = snglinspiraltable.getColumnByName("mchirp")
				min_mchirp, max_mchirp = min(min_mchirp, min(mchirp_column)), max(max_mchirp, max(mchirp_column))
				if not online:
					max_time = max(max_time, max(snglinspiraltable.getColumnByName("template_duration")))
			template_mchirp_dict[ce.description.split("_")[0]] = (min_mchirp, max_mchirp)
			xmldoc.unlink()
	if not online:
		return template_mchirp_dict, bgbin_file_map, max_time
	else:
		return template_mchirp_dict
1210 1211


1212 1213 1214 1215 1216 1217
def sim_tag_from_inj_file(injections):
	if injections is None:
		return None
	return injections.replace('.xml', '').replace('.gz', '').replace('-','_')


1218
def load_bank_cache(options):
1219 1220 1221 1222 1223 1224 1225
	bank_cache = {}
	for bank_cache_str in options.bank_cache:
		for c in bank_cache_str.split(','):
			ifo = c.split("=")[0]
			cache = c.replace(ifo+"=","")
			bank_cache.setdefault(ifo, []).append(cache)

1226 1227 1228 1229 1230 1231
	return bank_cache


def get_bank_params(options, verbose = False):
	bank_cache = load_bank_cache(options)

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
	max_time = 0
	template_mchirp_dict = {}
	for n, cache in enumerate(bank_cache.values()[0]):
		for ce in map(CacheEntry, open(cache)):
			for ce in map(CacheEntry, open(ce.path)):
				xmldoc = ligolw_utils.load_filename(ce.path, verbose = verbose, contenthandler = LIGOLWContentHandler)
				snglinspiraltable = lsctables.SnglInspiralTable.get_table(xmldoc)
				max_time = max(max_time, max(snglinspiraltable.getColumnByName('template_duration')))
				idx = options.overlap[n]/2
				template_mchirp_dict[ce.path] = [min(snglinspiraltable.getColumnByName('mchirp')[idx:-idx]), max(snglinspiraltable.getColumnByName('mchirp')[idx:-idx])]
				xmldoc.unlink()

	return template_mchirp_dict, bank_cache, max_time


def subdir_path(dirlist):
	output_path = '/'.join(dirlist)
	try:
		os.mkdir(output_path)
	except:
		pass
	return output_path


def analysis_segments(analyzable_instruments_set, allsegs, boundary_seg, max_template_length, min_instruments = 2):
	"""get a dictionary of all the disjoint 2+ detector combination segments
	"""
	segsdict = segments.segmentlistdict()
	# 512 seconds for the whitener to settle + the maximum template_length FIXME don't hard code
	start_pad = 512 + max_template_length
	# Chosen so that the overlap is only a ~5% hit in run time for long segments...
	segment_length = int(5 * start_pad)
	for n in range(min_instruments, 1 + len(analyzable_instruments_set)):
		for ifo_combos in itertools.combinations(list(analyzable_instruments_set), n):
			segsdict[frozenset(ifo_combos)] = allsegs.intersection(ifo_combos) - allsegs.union(analyzable_instruments_set - set(ifo_combos))
			segsdict[frozenset(ifo_combos)] &= segments.segmentlist([boundary_seg])
			segsdict[frozenset(ifo_combos)] = segsdict[frozenset(ifo_combos)].protract(start_pad)
			segsdict[frozenset(ifo_combos)] = dagparts.breakupsegs(segsdict[frozenset(ifo_combos)], segment_length, start_pad)
			if not segsdict[frozenset(ifo_combos)]:
				del segsdict[frozenset(ifo_combos)]
	return segsdict


def create_svd_bank_strings(svd_nodes, instruments = None):
	# FIXME assume that the number of svd nodes is the same per ifo, a good assumption though
	outstrings = []
	for i in range(len(svd_nodes.values()[0])):
		svd_bank_string = ""
		for ifo in svd_nodes:
			if instruments is not None and ifo not in instruments:
				continue
			try:
				svd_bank_string += "%s:%s," % (ifo, svd_nodes[ifo][i].output_files["write-svd"])
			except AttributeError:
				svd_bank_string += "%s:%s," % (ifo, svd_nodes[ifo][i])
		svd_bank_string = svd_bank_string.strip(",")
		outstrings.append(svd_bank_string)
	return outstrings


def svd_bank_cache_maker(svd_bank_strings, injection = False):
	if injection:
		dir_name = "gstlal_inspiral_inj"
	else:
		dir_name = "gstlal_inspiral"
	svd_cache_entries = []
	parsed_svd_bank_strings = [inspiral.parse_svdbank_string(single_svd_bank_string) for single_svd_bank_string in svd_bank_strings]
	for svd_bank_parsed_dict in parsed_svd_bank_strings:
		for filename in svd_bank_parsed_dict.itervalues():
			svd_cache_entries.append(CacheEntry.from_T050017(filename))

	return [svd_cache_entry.url for svd_cache_entry in svd_cache_entries]


def adapt_gstlal_inspiral_output(inspiral_nodes, options, segsdict):
	# first get the previous output in a usable form
	lloid_output = {}
	for inj in options.injections + [None]:
		lloid_output[sim_tag_from_inj_file(inj)] = {}
	lloid_diststats = {}
	if options.dist_stats_cache:
		for ce in map(CacheEntry, open(options.dist_stats_cache)):
			lloid_diststats[ce.description.split("_")[0]] = [ce.path]
	for ifos in segsdict:
		for seg in segsdict[ifos]:
			# iterate over the mass space chunks for each segment
			for node in inspiral_nodes[(ifos, None)][seg]:
				if node is None:
					break
				len_out_files = len(node.output_files["output-cache"])
				for f in node.output_files["output-cache"]:
					# Store the output files and the node for use as a parent dependency
					lloid_output[None].setdefault(CacheEntry.from_T050017(f).description.split("_")[0], []).append((f, [node]))
				for f in node.output_files["ranking-stat-output-cache"]:
					lloid_diststats.setdefault(CacheEntry.from_T050017(f).description.split("_")[0] ,[]).append(f)
			for inj in options.injections:
				for injnode in inspiral_nodes[(ifos, sim_tag_from_inj_file(inj))][seg]:
					if injnode is None:
						continue
					for f in injnode.output_files["output-cache"]:
						# Store the output files and the node and injnode for use as a parent dependencies
						bgbin_index = CacheEntry.from_T050017(f).description.split("_")[0]
						try:
							lloid_output[sim_tag_from_inj_file(inj)].setdefault(bgbin_index, []).append((f, lloid_output[None][bgbin_index][-1][1]+[injnode]))
						except KeyError:
							lloid_output[sim_tag_from_inj_file(inj)].setdefault(bgbin_index, []).append((f, [injnode]))

	return lloid_output, lloid_diststats


def set_up_scripts(options):
	# Make an xml integrity checker
	if options.gzip_test:
		with open("gzip_test.sh", "w") as f:
			f.write("#!/bin/bash\nsleep 60\ngzip --test $@")
		os.chmod("gzip_test.sh", stat.S_IRUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH | stat.S_IWUSR)

	# A pre script to backup data before feeding to lossy programs
	# (e.g. clustering routines)
	with open("store_raw.sh", "w") as f:
		f.write("""#!/bin/bash
		for f in $@;do mkdir -p $(dirname $f)/raw;cp $f $(dirname $f)/raw/$(basename $f);done""")
	os.chmod("store_raw.sh", stat.S_IRUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH | stat.S_IWUSR)


def load_reference_psd(options):
	ref_psd = lal.series.read_psd_xmldoc(ligolw_utils.load_filename(options.reference_psd, verbose = options.verbose, contenthandler = lal.series.PSDContentHandler))

	# FIXME Use machinery in inspiral_pipe.py to create reference_psd.cache
	with open('reference_psd.cache', "w") as output_cache_file:
		output_cache_file.write("%s\n" % CacheEntry.from_T050017("file://localhost%s" % os.path.abspath(options.reference_psd)))

	return ref_psd



1368 1369 1370
if __name__ == "__main__":
	import doctest
	doctest.testmod()