gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2009-2014 Kipp Cannon, Chad Hanna, Drew Keppel
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 """Stream-based inspiral analysis tool"""
19 
20 
21 #
22 # =============================================================================
23 #
24 # Preamble
25 #
26 # =============================================================================
27 #
28 
29 
30 ### A program to analyze gravitational wave data for compact binary coalescence in real time or in an offline mode
31 ###
32 ### .. graphviz::
33 ###
34 ### digraph llpipe {
35 ### labeljust = "r";
36 ### label="gstlal_inspiral"
37 ### rankdir=LR;
38 ### graph [fontname="Roman", fontsize=24];
39 ### edge [ fontname="Roman", fontsize=10 ];
40 ### node [fontname="Roman", shape=box, fontsize=11];
41 ###
42 ### gracedb [label="GW\nCandidate\nDatabase", shape=oval, color=tomato3, style=filled];
43 ###
44 ###
45 ### subgraph clusterNodeN {
46 ###
47 ### style=rounded;
48 ### label="gstreamer pipeline";
49 ### labeljust = "r";
50 ### fontsize = 14;
51 ###
52 ### H1src [label="H1 data source:\n mkbasicsrc()", color=red4];
53 ### L1src [label="L1 data source:\n mkbasicsrc()", color=green4];
54 ### V1src [label="V1 data source:\n mkbasicsrc()", color=magenta4];
55 ###
56 ### H1multirate [label="H1 whitening and downsampling:\nmkwhitened_multirate_src()", color=red4];
57 ### L1multirate [label="L1 whitening and downsampling:\nmkwhitened_multirate_src()", color=green4];
58 ### V1multirate [label="V1 whitening and downsampling:\nmkwhitened_multirate_src()", color=magenta4];
59 ###
60 ### H1LLOID [label="H1 LLOID filtering engine:\nmkLLOIDmulti()", color=red4];
61 ### L1LLOID [label="L1 LLOID filtering engine:\nmkLLOIDmulti()", color=green4];
62 ### V1LLOID [label="V1 LLOID filtering engine:\nmkLLOIDmulti()", color=magenta4];
63 ###
64 ### H1Trig1 [label="H1 Triggering:\nsub bank 1", color=red4];
65 ### L1Trig1 [label="L1 Triggering:\nsub bank 1", color=green4];
66 ### V1Trig1 [label="V1 Triggering:\nsub bank 1", color=magenta4];
67 ### H1Trig2 [label="H1 Triggering:\nsub bank 2", color=red4];
68 ### L1Trig2 [label="L1 Triggering:\nsub bank 2", color=green4];
69 ### V1Trig2 [label="V1 Triggering:\nsub bank 2", color=magenta4];
70 ### H1TrigN [label="H1 Triggering:\nsub bank N", color=red4];
71 ### L1TrigN [label="L1 Triggering:\nsub bank N", color=green4];
72 ### V1TrigN [label="V1 Triggering:\nsub bank N", color=magenta4];
73 ###
74 ### H1src -> H1multirate;
75 ### L1src -> L1multirate;
76 ### V1src -> V1multirate;
77 ###
78 ### H1multirate -> H1LLOID [label="h(t) 4096Hz"];
79 ### L1multirate -> L1LLOID [label="h(t) 4096Hz"];
80 ### V1multirate -> V1LLOID [label="h(t) 4096Hz"];
81 ### H1multirate -> H1LLOID [label="h(t) 2048Hz"];
82 ### L1multirate -> L1LLOID [label="h(t) 2048Hz"];
83 ### V1multirate -> V1LLOID [label="h(t) 2048Hz"];
84 ### H1multirate -> H1LLOID [label="h(t) Nth-pow-of-2 Hz"];
85 ### L1multirate -> L1LLOID [label="h(t) Nth-pow-of-2 Hz"];
86 ### V1multirate -> V1LLOID [label="h(t) Nth-pow-of-2 Hz"];
87 ###
88 ### H1LLOID -> H1Trig1 [label="SNRs sub bank 1"];
89 ### L1LLOID -> L1Trig1 [label="SNRs sub bank 1"];
90 ### V1LLOID -> V1Trig1 [label="SNRs sub bank 1"];
91 ### H1LLOID -> H1Trig2 [label="SNRs sub bank 2"];
92 ### L1LLOID -> L1Trig2 [label="SNRs sub bank 2"];
93 ### V1LLOID -> V1Trig2 [label="SNRs sub bank 2"];
94 ### H1LLOID -> H1TrigN [label="SNRs sub bank N"];
95 ### L1LLOID -> L1TrigN [label="SNRs sub bank N"];
96 ### V1LLOID -> V1TrigN [label="SNRs sub bank N"];
97 ### }
98 ###
99 ###
100 ### Coincidence [label="Coincidence\nO(1)s latency"];
101 ### SigEst [label="Significance\nEstimation\nO(1)s latency"];
102 ### Thresh [label="Thresholding\nO(1)s latency"];
103 ### EventGen [label="Event\nGeneration\nO(1)s latency"];
104 ###
105 ### H1Trig1 -> Coincidence [label="Trigs sub bank 1"];
106 ### L1Trig1 -> Coincidence [label="Trigs sub bank 1"];
107 ### V1Trig1 -> Coincidence [label="Trigs sub bank 1"];
108 ### H1Trig2 -> Coincidence [label="Trigs sub bank 2"];
109 ### L1Trig2 -> Coincidence [label="Trigs sub bank 2"];
110 ### V1Trig2 -> Coincidence [label="Trigs sub bank 2"];
111 ### H1TrigN -> Coincidence [label="Trigs sub bank N"];
112 ### L1TrigN -> Coincidence [label="Trigs sub bank N"];
113 ### V1TrigN -> Coincidence [label="Trigs sub bank N"];
114 ###
115 ### Coincidence -> SigEst -> Thresh -> EventGen;
116 ###
117 ### EventGen -> gracedb;
118 ###
119 ### }
120 ###
121 ### Review Status
122 ### -------------
123 ###
124 ### +------------------------------------------------+---------------------------------------------+------------+
125 ### | Names | Hash | Date |
126 ### +================================================+=============================================+============+
127 ### | Florent, Sathya, Duncan Me, Jolien, Kipp, Chad | 9074294d6b57f43651143b5f93210751de1fe55a | 2014-05-02 |
128 ### +------------------------------------------------+---------------------------------------------+------------+
129 ###
130 
131 
132 import base64
133 try:
134  from fpconst import PosInf
135 except ImportError:
136  # fpconst is not part of the standard library and might not be
137  # available
138  PosInf = float("+inf")
139 from functools import reduce
140 import gzip
141 import itertools
142 import math
143 from optparse import OptionGroup, OptionParser
144 import os
145 import resource
146 import signal
147 import socket
148 from io import StringIO
149 import sys
150 import tempfile
151 import time
152 import uuid
153 import warnings
154 
155 import gi
156 gi.require_version('Gst', '1.0')
157 from gi.repository import GObject, Gst
158 GObject.threads_init()
159 Gst.init(None)
160 
161 import lal
162 from lal import LIGOTimeGPS
163 from lal import UTCToGPS
164 from lal.utils import CacheEntry
165 from ligo.gracedb.rest import DEFAULT_SERVICE_URL as gracedb_default_service_url
166 
167 from ligo import segments
168 from ligo.segments import utils as segmentsUtils
169 from ligo.lw import ligolw
170 from ligo.lw import lsctables
171 from ligo.lw import utils as ligolw_utils
172 from ligo.lw.utils import segments as ligolw_segments
173 from gstlal import bottle
174 from gstlal import datasource
175 from gstlal import far
176 from gstlal import httpinterface
177 from gstlal import hoftcache
178 from gstlal import inspiral
179 from gstlal import lloidhandler
180 from gstlal import lloidparts
181 from gstlal import pipeparts
182 from gstlal import reference_psd
183 from gstlal import servicediscovery
184 from gstlal import simulation
185 from gstlal import svd_bank
186 
187 GSTLAL_PROCESS_START_TIME = UTCToGPS(time.gmtime())
188 
189 @lsctables.use_in
190 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
191  pass
192 
193 #
194 # Make sure we have sufficient resources
195 # We allocate far more memory than we need, so this is okay
196 #
197 
198 def setrlimit(res, lim):
199  hard_lim = resource.getrlimit(res)[1]
200  resource.setrlimit(res, (lim if lim is not None else hard_lim, hard_lim))
201 
202 if sys.platform == "linux":
203  # set the number of processes and total set size up to hard limit and
204  # shrink the per-thread stack size (default is 10 MiB)
205  setrlimit(resource.RLIMIT_NPROC, None)
206  setrlimit(resource.RLIMIT_AS, None)
207  setrlimit(resource.RLIMIT_RSS, None)
208  # FIXME: tests at CIT show that this next tweak has no effect. it's
209  # possible that SL7 has lowered the default stack size from SL6 and we
210  # don't need to do this anymore. remove?
211  setrlimit(resource.RLIMIT_STACK, 1024 * 1024) # 1 MiB per thread
212 
213 
214 def service_domain(gracedb_search, gracedb_pipeline):
215  return "%s_%s.%s" % (gracedb_pipeline.lower(), gracedb_search.lower(), servicediscovery.DEFAULT_SERVICE_DOMAIN)
216 
217 
218 #
219 # =============================================================================
220 #
221 # Command Line
222 #
223 # =============================================================================
224 #
225 
226 
227 def parse_command_line():
228  parser = OptionParser(
229  description = __doc__
230  )
231 
232  # append all the datasource specific options
233  datasource.append_options(parser)
234 
235  group = OptionGroup(parser, "PSD Options", "Adjust noise spectrum estimation parameters")
236  group.add_option("--psd-fft-length", metavar = "seconds", default = 32, type = "int", help = "The length of the FFT used to used to whiten the data (default is 32 s).")
237  group.add_option("--reference-psd", metavar = "filename", help = "Instead of measuring the noise spectrum, load the spectrum from this LIGO light-weight XML file (optional).")
238  group.add_option("--track-psd", action = "store_true", help = "Enable dynamic PSD tracking. Always enabled if --reference-psd is not given.")
239  parser.add_option_group(group)
240 
241  group = OptionGroup(parser, "Data Qualtiy", "Adjust data quality handling")
242  group.add_option("--ht-gate-threshold", metavar = "sigma", type = "float", action = "append", default = [], help = "Set the threshold on whitened h(t) to excise a glitches in units of standard deviations (optional). If given, exactly as many h(t) thresholds must be set as svd-bank files will be processed (see --svd-bank).")
243  group.add_option("--veto-segments-file", metavar = "filename", help = "Set the name of the LIGO light-weight XML file from which to load vetoes (optional).")
244  group.add_option("--veto-segments-name", metavar = "name", help = "Set the name of the segments to extract from the segment tables and use as the veto list.", default = "vetoes")
245  parser.add_option_group(group)
246 
247  group = OptionGroup(parser, "Trigger Generator", "Adjust trigger generator behaviour")
248  group.add_option("--control-peak-time", metavar = "seconds", type = "int", help = "Set a time window in seconds to find peaks in the control signal (optional, default is to disable composite detection statistic).")
249  group.add_option("--output", metavar = "filename", action = "append", default = [], help = "Set the name of the LIGO light-weight XML output file *.{xml,xml.gz} or an SQLite database *.sqlite (required). Can be given multiple times. Exactly as many output files must be specified as svd-bank files will be processed (see --svd-bank).")
250  group.add_option("--output-cache", metavar = "filename", help = "Provide a cache of output files. This can be used instead of giving multiple --output options. Cannot be combined with --output.")
251  group.add_option("--svd-bank", metavar = "filename", action = "append", default = [], help = "Set the name of the LIGO light-weight XML file from which to load the svd bank for a given instrument in the form ifo:file. These can be given as a comma separated list such as H1:file1,H2:file2,L1:file3 to analyze multiple instruments. This option can be given multiple times, unless --data-source is lvshm or framexmit in which case it must be given exactly once. If given multiple times, the banks will be processed one-by-one, in order. At least one svd bank for at least 2 detectors is required, but see also --svd-bank-cache.")
252  group.add_option("--svd-bank-cache", metavar = "filename", help = "Provide a cache file of svd-bank files. This can be used instead of giving multiple --svd-bank options. Cannot be combined with --svd-bank options.")
253  # NOTE: the clustering SQL scripts search for this option in the
254  # process_params table to determine the threshold below which it
255  # can delete uninteresting singles after the coincs are ranked. if
256  # the name of this option is changed, be sure to update
257  # simplify_and_cluster.sql and derivatives
258  group.add_option("--singles-threshold", metavar = "SNR", type = "float", default = PosInf, help = "Set the SNR threshold at which to record single-instrument events in the output (default = +inf, i.e. don't retain singles).")
259  parser.add_option_group(group)
260 
261  group = OptionGroup(parser, "Ranking Statistic Options", "Adjust ranking statistic behaviour")
262  group.add_option("--cap-singles", action = "store_true", help = "Cap singles to 1 / livetime if computing FAR. No effect otherwise")
263  group.add_option("--far-trials-factor", metavar = "trials", type = "float", default = 1.0, help = "Add trials factor to FAR before uploading to gracedb")
264  group.add_option("--chisq-type", metavar = "type", default = "autochisq", help = "Choose the type of chisq computation to perform. Must be one of (autochisq|timeslicechisq). The default is autochisq.")
265  group.add_option("--coincidence-threshold", metavar = "seconds", type = "float", default = 0.005, help = "Set the coincidence window in seconds (default = 0.005 s). The light-travel time between instruments will be added automatically in the coincidence test.")
266  group.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).")
267  group.add_option("--ranking-stat-input", metavar = "url", help = "Set the URL from which to load a ranking statistic definition. When this is enabled, signal candidates will have ranking statistic values assigned on-the-fly. Required when --data-source is lvshm or framexmit; must also set --likelihood-snapshot-interval.")
268  group.add_option("--ranking-stat-output", metavar = "filename", action = "append", default = [], help = "Set the name of the file to which to write ranking statistic data collected from triggers (optional). Can be given more than once. If given, exactly as many must be provided as there are --svd-bank options and they will be writen to in order.")
269  group.add_option("--ranking-stat-output-cache", metavar = "filename", help = "Provide a cache of ranking statistic output files. This can be used instead of giving multiple --ranking-stat-output options. Cannot be combined with --ranking-stat-output.")
270  group.add_option("--compress-ranking-stat", action = "store_true", help = "Choose whether to compress the ranking stat upon start up. Only used when --ranking-stat-input is set.")
271  group.add_option("--compress-ranking-stat-threshold", type = "float", default = 0.03, help = "Only keep horizon distance values that differ by this much, fractionally, from their neighbours (default = 0.03).")
272  group.add_option("--likelihood-snapshot-interval", type = "float", metavar = "seconds", help = "How often to snapshot candidate and ranking statistic data to disk when running online.")
273  group.add_option("--ranking-stat-pdf", metavar = "url", help = "Set the URL from which to load the ranking statistic PDF. This is used to compute false-alarm probabilities and false-alarm rates and is required for online operation (when --data-source is framexmit or lvshm). It is forbidden for offline operation (all other data sources)")
274  group.add_option("--time-slide-file", metavar = "filename", help = "Set the name of the xml file to get time slide offsets (required).")
275  group.add_option("--zerolag-rankingstat-pdf", metavar = "url", action = "append", help = "Record a histogram of the likelihood ratio ranking statistic values assigned to zero-lag candidates in this XML file. This is used to construct the extinction model and set the overall false-alarm rate normalization during online running. If it does not exist at start-up, a new file will be initialized, otherwise the counts will be added to the file's contents. Required when --data-source is lvshm or framexmit; optional otherwise. If given, exactly as many must be provided as there are --svd-bank options and they will be used in order.")
276  group.add_option("--activation-counts-file", metavar = "filename", help = "Set the name of the h5 file containing activation counts for multicomponent p-astro.")
277  parser.add_option_group(group)
278 
279  group = OptionGroup(parser, "GracedB Options", "Adjust GracedB interaction")
280  group.add_option("--gracedb-far-threshold", metavar = "Hertz", type = "float", help = "False-alarm rate threshold for gracedb uploads in Hertz (default = do not upload to gracedb).")
281  group.add_option("--gracedb-group", metavar = "name", default = "Test", help = "Gracedb group to which to upload events (default is Test).")
282  group.add_option("--gracedb-pipeline", metavar = "name", default = "gstlal", help = "Name of pipeline to provide in GracedB uploads (default is gstlal).")
283  group.add_option("--gracedb-search", metavar = "name", default = "LowMass", help = "Name of search to provide in GracedB uploads (default is LowMass).")
284  group.add_option("--gracedb-label", action = "append", help = "Labels to apply to gracedb uploads. Can be applied multiple times.")
285  group.add_option("--gracedb-service-url", metavar = "url", default = gracedb_default_service_url, help = "Override default GracedB service url (optional, default is %s)." % gracedb_default_service_url)
286  group.add_option("--delay-uploads", action = "store_true", help = "Choose whether to delay uploads to allow aggregation of events downstream from many gstlal_inspiral jobs (default is False).")
287  parser.add_option_group(group)
288 
289  group = OptionGroup(parser, "Program Behaviour")
290  group.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. --injections must not be specified in this case")
291  group.add_option("--check-time-stamps", action = "store_true", help = "Turn on time stamp checking")
292  group.add_option("--comment", metavar = "message", help = "Set the string to be recorded in comment and tag columns in various places in the output file (optional).")
293  group.add_option("--fir-stride", metavar = "seconds", type = "float", default = 8, help = "Set the length of the fir filter stride in seconds. default = 8")
294  group.add_option("--job-tag", metavar = "tag", help = "Set the string to identify this job and register the resources it provides on a node. Should be 4 digits of the form 0001, 0002, etc.; may not contain \".\" nor \"-\".")
295  group.add_option("--local-frame-caching", action = "store_true", help = "Pre-reads frame data, performs downsampling, and stores to local filespace. ")
296  group.add_option("--nxydump-segment", metavar = "start:stop", default = ":", help = "Set the time interval to dump from nxydump elments (optional). The default is \":\", i.e. dump all time.")
297  group.add_option("--reconstruction-segment", metavar = "start:stop", action = "append", help = "Only reconstruct the SNRs for this time interval (optional). Can be provided multiple times.")
298  group.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.")
299  group.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")
300  group.add_option("--write-pipeline", metavar = "filename", help = "Write a DOT graph description of the as-built pipeline to this file (optional). The environment variable GST_DEBUG_DUMP_DOT_DIR must be set for this option to work.")
301  group.add_option("--output-kafka-server", metavar = "addr", help = "Set the server address and port number for output data. Optional, e.g., 10.14.0.112:9092")
302  group.add_option("--disable-service-discovery", action = "store_true", help = "Disable service discovery. This disables gstlal_inspiral jobs from being able to advertise the location of the services it provides.")
303  parser.add_option_group(group)
304 
305  options, filenames = parser.parse_args()
306  missing_options = []
307 
308  #
309  # do this before messing with options object
310  #
311 
312  process_params = options.__dict__.copy()
313 
314  #
315  # extract data source configuration
316  #
317 
318  detectors = datasource.GWDataSourceInfo(options)
319 
320  #
321  # extract information about principle I/O files
322  #
323 
324  # FIXME Put all svd banks for different detectors in one file.
325  if options.svd_bank:
326  if options.svd_bank_cache:
327  raise ValueError("cannot supply both --svd-bank and --svd-bank-cache")
328  try:
329  svd_banks = list(map(inspiral.parse_svdbank_string, options.svd_bank))
330  except ValueError as e:
331  print("Unable to parse --svd-bank")
332  raise
333  elif options.svd_bank_cache:
334  svd_banks = []
335  svd_bank_cache = list(map(CacheEntry, open(options.svd_bank_cache)))
336  if not svd_bank_cache:
337  raise ValueError("--svd-bank-cache is empty")
338  svd_bank_cache.sort(key = lambda cache_entry: cache_entry.description)
339  for key, seq in itertools.groupby(svd_bank_cache, key = lambda cache_entry: cache_entry.description):
340  svd_banks.append(dict((cache_entry.observatory, cache_entry.url) for cache_entry in seq))
341  else:
342  missing_options.append("either --svd-bank-cache or at least one --svd-bank")
343 
344  if options.output:
345  if options.output_cache:
346  raise ValueError("cannot supply both --output and --output-cache")
347  elif options.output_cache:
348  # do this out-of-place to preserve process_params' contents
349  options.output = [CacheEntry(line).url for line in open(options.output_cache)]
350  if not options.output:
351  raise ValueError("--output-cache is empty")
352  else:
353  missing_options.append("either --output-cache or at least one --output")
354 
355  if options.ranking_stat_output:
356  if options.ranking_stat_output_cache:
357  raise ValueError("cannot supply both --ranking-stat-output and --ranking-stat-output-cache")
358  elif options.ranking_stat_output_cache:
359  # do this out-of-place to preserve process_params' contents
360  options.ranking_stat_output = [CacheEntry(line).url for line in open(options.ranking_stat_output_cache)]
361  if not options.ranking_stat_output:
362  raise ValueError("--ranking-stat-output-cache is empty")
363 
364  if not options.time_slide_file:
365  missing_options.append("--time-slide-file")
366 
367  if missing_options:
368  raise ValueError("missing required option(s) %s" % ", ".join(sorted(missing_options)))
369 
370  #
371  # check sanity of the input and output file collections
372  #
373 
374  if len(svd_banks) != len(options.output):
375  raise ValueError("must supply exactly as many --svd-bank options as --output")
376  if options.ranking_stat_output and len(options.ranking_stat_output) != len(options.output):
377  raise ValueError("must supply either none or exactly as many --ranking-stat-output options as --output")
378  if options.likelihood_snapshot_interval and not options.ranking_stat_output:
379  raise ValueError("must set --ranking-stat-output when --likelihood-snapshot-interval is set")
380  if options.ranking_stat_output is None or len(options.ranking_stat_output) == 0:
381  options.ranking_stat_output = [None] * len(options.output)
382 
383  required_urls = [options.time_slide_file]
384  for svd_bank_set in svd_banks:
385  required_urls += svd_bank_set.values()
386  for filename in (options.veto_segments_file, options.injections, options.blind_injections, options.reference_psd):
387  if filename:
388  required_urls.append(filename)
389  for i in range(len(required_urls)):
390  try:
391  required_urls[i] = ligolw_utils.local_path_from_url(required_urls[i])
392  except ValueError:
393  required_urls[i] = None
394  missing_files = [filename for filename in required_urls if filename is not None and not os.access(filename, os.R_OK)]
395 
396  if missing_files:
397  raise ValueError("one or more required files cannot be found or are not readable: %s" % ", ".join("'%s'" % filename for filename in sorted(missing_files)))
398 
399  #
400  # check sanity of overall configuration
401  #
402 
403  if options.blind_injections and options.injections:
404  raise ValueError("cannot set both --blind-injections and --injections")
405 
406  if options.data_source in ("lvshm", "framexmit"):
407  missing_options = []
408  for option in ["job_tag", "ranking_stat_input", "ranking_stat_pdf", "zerolag_rankingstat_pdf"]:
409  if getattr(options, option) is None:
410  missing_options.append("--%s" %option.replace("_","-"))
411 
412  if missing_options:
413  raise ValueError("missing required option(s) %s when --data-source is lvshm or framexmit" % ", ".join(missing_options))
414 
415  if "-" in options.job_tag or "." in options.job_tag:
416  raise ValueError("invalid characters in --job-tag \"%s\"" % options.job_tag)
417 
418  if len(svd_banks) > 1:
419  raise ValueError("more than one --svd-bank not allowed when --datasource is lvshm or framexmit, have %d" % len(svd_banks))
420 
421  # make an "infinite" extent segment
422  detectors.seg = segments.segment(LIGOTimeGPS(0), LIGOTimeGPS(2000000000))
423 
424  # this gets set so that if you log into a node you can find out what the job id is easily
425  os.environ['GSTLAL_LL_JOB'] = options.job_tag
426 
427  # FIXME: this is ugly, but we have to protect against busted shared memory partitions
428  if options.data_source == "lvshm":
429  import subprocess
430  for ifo in detectors.channel_dict.keys():
431  subprocess.call(["smrepair", detectors.shm_part_dict[ifo]])
432 
433  # FIXME REMOVE THIS. We need to get a better way of passing
434  # configuration information like this around. Putting file
435  # links into the prior dist stats is an options but it is also
436  # becoming cumbersome since it is easy to not then have the
437  # files it refers to...
438  if options.activation_counts_file is not None:
439  import h5py
440  import numpy
441  with h5py.File(options.activation_counts_file) as ac_file:
442  options.activation_counts = dict((k, float(numpy.array(v))) for k, v in ac_file[options.job_tag].items())
443  # record the total number of bins
444  options.activation_counts['num_bins'] = len(ac_file)
445  else:
446  options.activation_counts = None
447 
448  else:
449  bad_options = []
450  for option in ["job_tag"]:
451  if getattr(options, option) is not None:
452  bad_options.append("--%s" % option.replace("_","-"))
453  if bad_options:
454  raise ValueError("cannot set %s when --data-source is not lvshm or framexmit " % ", ".join(bad_options))
455  options.activation_counts = None
456 
457  if options.reference_psd is None:
458  options.track_psd = True
459  if options.psd_fft_length < 4:
460  raise ValueError("--psd-fft-length cannot be less than 4")
461  if options.psd_fft_length < 32:
462  warnings.warn("It is not advised to choose PSD lengths below 32s, since a loss in sensitivity may occur")
463  if options.local_frame_caching and not options.data_source == "frames":
464  raise ValueError("--local-frame-caching can only be used if --data-source is frames")
465  if options.chisq_type not in ["autochisq", "timeslicechisq"]:
466  raise ValueError("--chisq-type must be one of (autochisq|timeslicechisq), got %s" % (options.chisq_type))
467 
468  if options.likelihood_snapshot_interval is not None and options.likelihood_snapshot_interval <= 0.:
469  raise ValueError("--likelihood-snapshot-interval cannot be <= 0")
470  if options.ranking_stat_input:
471  if not options.likelihood_snapshot_interval:
472  raise ValueError("must set --likelihood-snapshot-interval when --ranking-stat-input is set")
473 
474  if not options.ht_gate_threshold:
475  # default threshold is +inf = disable feature.
476  options.ht_gate_threshold = [float("inf")] * len(svd_banks)
477  elif len(options.ht_gate_threshold) != len(svd_banks):
478  raise ValueError("must supply either none or exactly as many --ht-gate-threshold values options as --svd-bank")
479 
480  if not options.zerolag_rankingstat_pdf:
481  options.zerolag_rankingstat_pdf = [None] * len(svd_banks)
482  elif len(options.zerolag_rankingstat_pdf) != len(svd_banks):
483  raise ValueError("must supply either none or exactly as many --zerolag-rankingstat-pdf options as --svd-bank")
484 
485  if options.min_instruments < 1:
486  raise ValueError("--min-instruments must be >= 1")
487  if options.min_instruments > len(detectors.channel_dict):
488  raise ValueError("--min-instruments (%d) is greater than the number of --channel-name's (%d)" % (options.min_instruments, len(detectors.channel_dict)))
489 
490  #
491  # Option checks complete
492  #
493 
494  options.nxydump_segment, = segmentsUtils.from_range_strings([options.nxydump_segment], boundtype = LIGOTimeGPS)
495 
496  if options.blind_injections is not None:
497  detectors.injection_filename = options.blind_injections
498 
499  # Setup local caching
500  if options.local_frame_caching:
501  f, fname = tempfile.mkstemp(".cache")
502  if options.verbose:
503  print("caching frame data locally to ", fname, file=sys.stderr)
504  f = open(fname, "w")
505  # FIXME: should try to down-sample if possible. there are
506  # MDCs data sets floating around whose streams do not start
507  # on integer second boundaries, however, and it's possible
508  # to trigger a failure in the frame muxer if those get
509  # down-sampled so for now we're not doing any resampling.
510  # later, when we don't care about those MDCs, we can go
511  # back to down-sampling. if not being able to down-sample
512  # is a problem in the meantime, I think the best way
513  # forward is to clip the start of said streams using a drop
514  # element and a (to be written) buffer probe that figures
515  # out how many samples to clip off the start of the stream.
516  # FIXME shouldn't use tempfile.gettempdir() directly, use
517  # _CONDOR_SCRATCH_DIR like glue??
518  # FIXME, note that at least for now condor sets TMPDIR to the
519  # run scratch space so this *will* work properly
520  detectors.local_cache_list = hoftcache.cache_hoft(detectors, output_path = tempfile.gettempdir(), verbose = options.verbose)
521  for cacheentry in detectors.local_cache_list:
522  # Guarantee a lal cache complient file with only integer starts and durations.
523  cacheentry.segment = segments.segment( int(cacheentry.segment[0]), int(math.ceil(cacheentry.segment[1])) )
524  print(str(cacheentry), file=f)
525  detectors.frame_cache = fname
526 
527  # the injections are now present in the data so we don't want to do them twice
528  detectors.injection_filename = None
529 
530  # we're done
531  return options, filenames, process_params, svd_banks, detectors
532 
533 
534 #
535 # =============================================================================
536 #
537 # Signal Handler
538 #
539 # =============================================================================
540 #
541 
542 
543 class OneTimeSignalHandler(object):
544  def __init__(self, pipeline):
545  self.pipeline = pipeline
546  self.count = 0
547 
548  def __call__(self, signum, frame):
549  self.count += 1
550  if self.count == 1:
551  print("*** SIG %d attempting graceful shutdown (this might take several minutes) ... ***" % signum, file=sys.stderr)
552  try:
553  #FIXME how do I choose a timestamp?
554  self.pipeline.get_bus().post(lloidhandler.message_new_checkpoint(self.pipeline, timestamp = inspiral.now().ns()))
555  if not self.pipeline.send_event(Gst.Event.new_eos()):
556  raise Exception("pipeline.send_event(EOS) returned failure")
557  except Exception as e:
558  print("graceful shutdown failed: %s\naborting." % str(e), file=sys.stderr)
559  os._exit(1)
560  else:
561  print("*** received SIG %d %d times... ***" % (signum, self.count), file=sys.stderr)
562 
563 
564 #
565 # =============================================================================
566 #
567 # Horizon Distances
568 #
569 # =============================================================================
570 #
571 
572 
573 #
574 # =============================================================================
575 #
576 # Main
577 #
578 # =============================================================================
579 #
580 
581 
582 #
583 # parse command line
584 #
585 
586 
587 options, filenames, process_params, svd_banks, detectors = parse_command_line()
588 
589 if not options.check_time_stamps:
590  pipeparts.mkchecktimestamps = lambda pipeline, src, *args: src
591 
592 
593 #
594 # Parse the vetos segments file(s) if provided
595 #
596 
597 
598 if options.veto_segments_file is not None:
599  veto_segments = ligolw_segments.segmenttable_get_by_name(ligolw_utils.load_filename(options.veto_segments_file, verbose = options.verbose, contenthandler = LIGOLWContentHandler), options.veto_segments_name).coalesce()
600 else:
601  veto_segments = None
602 
603 
604 #
605 # Load the time slide vectors, and use them to define the complete
606 # instrument list for the network
607 #
608 
609 
610 offsetvectors = lsctables.TimeSlideTable.get_table(ligolw_utils.load_filename(options.time_slide_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose)).as_dict().values()
611 all_instruments = reduce(lambda a, b: a | set(b), offsetvectors, set())
612 if len(all_instruments) < options.min_instruments:
613  raise ValueError("--time-slide-file \"%s\" names %s but we need at least %d instruments" % (options.time_slide_file, ", ".join(sorted(all_instruments)), options.min_instruments))
614 if not (all_instruments >= set(detectors.channel_dict)):
615  raise ValueError("--time-slide-file names %s but have channel names for %s" % (", ".join(sorted(all_instruments)), ", ".join(sorted(detectors.channel_dict))))
616 
617 
618 #
619 # set up the PSDs
620 #
621 # There are three modes for psds in this program
622 # 1) --reference-psd without --track-psd - a fixed psd (provided by the user) will be used to whiten the data
623 # 2) --track-psd without --reference-psd - a psd will me measured and used on the fly
624 # 3) --track-psd with --reference-psd - a psd will be measured on the fly, but the first guess will come from the users provided psd
625 #
626 
627 
628 if options.reference_psd is not None:
629  psd = lal.series.read_psd_xmldoc(ligolw_utils.load_filename(options.reference_psd, verbose = options.verbose, contenthandler = lal.series.PSDContentHandler))
630  if set(detectors.channel_dict) - set(psd):
631  raise ValueError("missing PSD(s) for %s" % ", ".join(sorted(set(detectors.channel_dict) - set(psd))))
632 else:
633  psd = dict.fromkeys(all_instruments, None)
634 
635 
636 #
637 # Process svd banks in serial
638 #
639 
640 
641 for output_file_number, (svd_bank_url_dict, output_url, ranking_stat_output_url, zerolag_rankingstat_pdf, ht_gate_threshold) in enumerate(zip(svd_banks, options.output, options.ranking_stat_output, options.zerolag_rankingstat_pdf, options.ht_gate_threshold)):
642  #
643  # Checkpointing only supported for gzip files in offline analysis
644  # FIXME Implement a means by which to check for sqlite file
645  # validity
646  #
647 
648  if options.data_source not in ("lvshm", "framexmit") and output_url.endswith('.gz'):
649  try:
650  # a single .read() would be easier but looping over
651  # lines uses less memory
652  for line in gzip.open(ligolw_utils.local_path_from_url(output_url)):
653  pass
654  if ranking_stat_output_url is not None:
655  for line in gzip.open(ligolw_utils.local_path_from_url(ranking_stat_output_url)):
656  pass
657  # File is OK and there is no need to process it,
658  # skip ahead in the loop
659  continue
660  except IOError:
661  # File does not exist or is corrupted, need to
662  # reprocess
663  print("Checkpoint: {0} of {1} files completed and continuing with {2}".format(output_file_number, len(options.output), os.path.basename(output_url)), file=sys.stderr)
664  pass
665 
666 
667  #
668  # create a new, empty, Bottle application and make it the current
669  # default, then start http server(s) to serve it up
670  #
671 
672 
673  bottle.default_app.push()
674  # uncomment the next line to show tracebacks when something fails
675  # in the web server
676  #bottle.app().catchall = False
677  httpservers = httpinterface.HTTPServers(
678  service_name = "%s.gstlal_inspiral" % (options.job_tag if options.job_tag is not None else base64.urlsafe_b64encode(uuid.uuid4().bytes)),
679  service_domain = service_domain(options.gracedb_search, options.gracedb_pipeline),
680  service_properties = {
681  "cwd": os.getcwd(),
682  "pid": str(os.getpid()),
683  },
684  service_discovery = not options.disable_service_discovery,
685  verbose = options.verbose
686  )
687 
688 
689  #
690  # Set up a registry of the resources that this job provides
691  #
692 
693 
694  @bottle.route("/")
695  @bottle.route("/index.html")
696  def index(job_tag = options.job_tag, instruments = all_instruments):
697  # get the host and port to report in the links from the
698  # request we've received so that the URLs contain the IP
699  # address by which client has contacted us
700  netloc = bottle.request.urlparts[1]
701  server_address = "http://%s" % netloc
702  yield "<html><body>\n<h3>%s %s %s %s</h3>\n<p>\n" % (job_tag, os.environ.get("GSTLAL_LL_JOB"), netloc, " ".join(sorted(instruments)))
703  for route in sorted(bottle.default_app().routes, key = lambda route: route.rule):
704  # don't create links back to this page
705  if route.rule in ("/", "/index.html"):
706  continue
707  # only create links for GET methods
708  if route.method != "GET":
709  continue
710  yield "<a href=\"%s%s\">%s</a><br>\n" % (server_address, route.rule, route.rule)
711  yield "</p>\n</body></html>"
712  # FIXME: get service-discovery working, then don't do this
713  if "GSTLAL_LL_JOB" in os.environ:
714  open("%s_registry.txt" % os.environ["GSTLAL_LL_JOB"], "w").write("http://%s:%s/\n" % (socket.gethostname(), httpservers[0][0].port))
715 
716 
717  #
718  # parse SVD template bank and expose bank metadata
719  #
720 
721 
722  banks = inspiral.parse_bank_files(svd_bank_url_dict, verbose = options.verbose)
723  # assume all instruments have the same templates, just extract them
724  # from one of the instruments at random
725  sngl_inspiral_table = list(banks.values())[0][0].sngl_inspiral_table.copy()
726  horizon_factors = {}
727  for bank in list(banks.values())[0]:
728  sngl_inspiral_table.extend(bank.sngl_inspiral_table)
729  horizon_factors.update(bank.horizon_factors)
730  @bottle.route("/template_bank.xml.gz")
731  def get_template_bank_xml(sngl_inspiral_table = sngl_inspiral_table):
732  xmldoc = ligolw.Document()
733  xmldoc.appendChild(ligolw.LIGO_LW())
734  map(xmldoc.childNodes[-1].appendChild(sngl_inspiral_table.copy()).append, sngl_inspiral_table)
735  output = StringIO.StringIO()
736  ligolw_utils.write_fileobj(xmldoc, output, compress = "gz")
737  outstr = output.getvalue()
738  output.close()
739  return outstr
740  template_ids = frozenset(row.template_id for row in sngl_inspiral_table)
741  assert set(horizon_factors) == template_ids, "horizon factors are not assigned for each template id"
742  assert len(template_ids) == len(sngl_inspiral_table), "template IDs are not unique within the template bank"
743  @bottle.route("/template_ids.txt")
744  def get_template_ids(template_ids = sorted(template_ids)):
745  return "\n".join("%d" % template_id for template_id in template_ids)
746 
747 
748  # Choose to optionally reconstruct segments around injections (not
749  # blind injections!)
750  if options.injections:
751  offset_padding = max(math.ceil(abs(row.end))+1 for bank in list(banks.items())[0][-1] for row in bank.sngl_inspiral_table)
752  reconstruction_segment_list = simulation.sim_inspiral_to_segment_list(options.injections, pad = offset_padding)
753  elif options.reconstruction_segment:
754  reconstruction_segment_list = segments.segmentlist()
755  for reconstruction_segment in options.reconstruction_segment:
756  t0, t1 = reconstruction_segment.split(":")
757  reconstruction_segment_list.append(segments.segment(LIGOTimeGPS(int(t0)), LIGOTimeGPS(int(t1))))
758  else:
759  reconstruction_segment_list = None
760 
761 
762  @bottle.route("/bank.txt")
763  def get_filter_length_and_chirpmass(banks = banks):
764  bank = banks.values()[0][0] #FIXME maybe shouldn't just take the first ones
765  yield '%.14g %.4g %.4g' % (float(inspiral.now()), bank.filter_length, bank.sngl_inspiral_table[0].mchirp)
766 
767 
768  #
769  # Build pipeline
770  #
771 
772 
773  if options.verbose:
774  print("assembling pipeline ...", file=sys.stderr)
775 
776  pipeline = Gst.Pipeline(name="gstlal_inspiral")
777  mainloop = GObject.MainLoop()
778 
779  triggersrc = lloidparts.mkLLOIDmulti(
780  pipeline,
781  detectors = detectors,
782  banks = banks,
783  psd = psd,
784  psd_fft_length = options.psd_fft_length,
785  ht_gate_threshold = ht_gate_threshold,
786  veto_segments = veto_segments,
787  verbose = options.verbose,
788  nxydump_segment = options.nxydump_segment,
789  chisq_type = options.chisq_type,
790  track_psd = options.track_psd,
791  control_peak_time = options.control_peak_time,
792  fir_stride = options.fir_stride,
793  reconstruction_segment_list = reconstruction_segment_list,
794  track_latency = options.data_source in ("lvshm", "framexmit"),
795  )
796 
797 
798  if options.verbose:
799  print("done", file=sys.stderr)
800 
801 
802  #
803  # Load/Initialize ranking statistic data.
804  #
805 
806 
807  rankingstat = None
808  if options.ranking_stat_input:
809  try:
810  xmldoc = ligolw_utils.load_url(options.ranking_stat_input, verbose = options.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler)
811  except IOError:
812  print("warning: '%s' not found or cannot be loaded; will fall back to newly-initialized ranking statistic" % options.ranking_stat_input, file=sys.stderr)
813  else:
814  rankingstat, _ = far.parse_likelihood_control_doc(xmldoc)
815  if rankingstat is None:
816  raise ValueError("\"%s\" does not contain parameter distribution data" % options.ranking_stat_input)
817  if rankingstat.delta_t != options.coincidence_threshold:
818  raise ValueError("\"%s\" is for delta_t=%g, we need %g" % (options.ranking_stat_input, rankingstat.denominator.delta_t, options.coincidence_threshold))
819  if rankingstat.min_instruments != options.min_instruments:
820  raise ValueError("\"%s\" is for min instruments = %d but we need %d" % (options.ranking_stat_input, rankingstat.denominator.min_instruments, options.min_instruments))
821  if rankingstat.instruments != all_instruments:
822  raise ValueError("\"%s\" is for %s but we need %s" % (options.ranking_stat_input, ", ".join(sorted(rankingstat.instruments)), ", ".join(sorted(all_instruments))))
823  if rankingstat.template_ids is None:
824  rankingstat.template_ids = template_ids
825  elif rankingstat.template_ids != template_ids:
826  raise ValueError("\"%s\" is for the wrong templates" % options.ranking_stat_input)
827  rankingstat.numerator.set_horizon_factors(horizon_factors)
828 
829  if options.compress_ranking_stat:
830  if options.verbose:
831  print("compressing ranking stat...", file=sys.stderr)
832  rankingstat.numerator.horizon_history.compress(threshold = options.compress_ranking_stat_threshold)
833  if options.verbose:
834  print("...done.", file=sys.stderr)
835 
836  xmldoc.unlink()
837  del xmldoc
838 
839  if rankingstat is None:
840  rankingstat = far.RankingStat(template_ids = template_ids, instruments = all_instruments, delta_t = options.coincidence_threshold, min_instruments = options.min_instruments, horizon_factors = horizon_factors)
841 
842 
843  #
844  # construct and configure pipeline handler
845  #
846 
847 
848  if options.verbose:
849  print("initializing pipeline handler ...", file=sys.stderr)
850  handler = lloidhandler.Handler(
851  mainloop = mainloop,
852  pipeline = pipeline,
853  coincs_document = inspiral.CoincsDocument(
854  url = output_url or "%s-%s_LLOID-%d-%d.xml.gz" % (lsctables.instrumentsproperty.set(detectors.channel_dict.keys()).replace(",", ""), options.job_tag, int(detectors.seg[0]), int(abs(detectors.seg))),
855  process_params = process_params,
856  process_start_time = GSTLAL_PROCESS_START_TIME,
857  comment = options.comment,
858  instruments = rankingstat.instruments,
859  seg = detectors.seg,
860  offsetvectors = offsetvectors,
861  injection_filename = options.injections,
862  tmp_path = options.tmp_space,
863  replace_file = True,
864  verbose = options.verbose
865  ),
866  rankingstat = rankingstat,
867  horizon_distance_func = list(banks.values())[0][0].horizon_distance_func,# they should all be the same
868  gracedbwrapper = inspiral.GracedBWrapper(
869  instruments = rankingstat.instruments,
870  far_threshold = options.gracedb_far_threshold,
871  min_instruments = options.min_instruments,
872  group = options.gracedb_group,
873  search = options.gracedb_search,
874  label = options.gracedb_label,
875  pipeline = options.gracedb_pipeline,
876  service_url = options.gracedb_service_url,
877  delay_uploads = options.delay_uploads,
878  kafka_server = options.output_kafka_server,
879  upload_auxiliary_data = True,
880  delta_t = options.coincidence_threshold,
881  verbose = options.verbose
882  ),
883  ranking_stat_input_url = options.ranking_stat_input,
884  ranking_stat_output_url = ranking_stat_output_url,
885  rankingstatpdf_url = options.ranking_stat_pdf,
886  zerolag_rankingstatpdf_url = zerolag_rankingstat_pdf,
887  likelihood_snapshot_interval = options.likelihood_snapshot_interval,
888  sngls_snr_threshold = options.singles_threshold,
889  tag = options.job_tag,
890  kafka_server = options.output_kafka_server,
891  cluster = True,#options.data_source in ("lvshm", "framexmit"),# If uncommented, we only cluster when running online
892  cap_singles = options.cap_singles,
893  FAR_trialsfactor = options.far_trials_factor,
894  activation_counts = options.activation_counts,
895  verbose = options.verbose,
896  track_latency = options.data_source in ("lvshm", "framexmit"),
897  )
898  if options.verbose:
899  print("... pipeline handler initialized", file=sys.stderr)
900 
901  if options.verbose:
902  print("attaching appsinks to pipeline ...", file=sys.stderr)
903  appsync = pipeparts.AppSync(appsink_new_buffer = handler.appsink_new_buffer)
904  appsinks = set(appsync.add_sink(pipeline, src, caps = Gst.Caps.from_string("application/x-lal-snglinspiral"), name = "bank_%s_sink" % bank_id) for bank_id, src in triggersrc.items())
905 
906  if options.verbose:
907  print("attached %d, done" % len(appsinks), file=sys.stderr)
908 
909 
910  #
911  # if we request a dot graph of the pipeline, set it up
912  #
913 
914 
915  if options.write_pipeline is not None:
916  pipeparts.connect_appsink_dump_dot(pipeline, appsinks, options.write_pipeline, options.verbose)
917  pipeparts.write_dump_dot(pipeline, "%s.%s" % (options.write_pipeline, "NULL"), verbose = options.verbose)
918 
919 
920  #
921  # Run pipeline
922  #
923 
924 
925  if options.data_source in ("lvshm", "framexmit"):
926  #
927  # setup sigint handler to shutdown pipeline. this is how
928  # the program stops gracefully, it is the only way to stop
929  # it. Otherwise it runs forever man.
930  #
931  # this is only done in the online case because we want
932  # offline jobs to just die and not write partial databases
933  #
934 
935  signal.signal(signal.SIGINT, OneTimeSignalHandler(pipeline))
936  signal.signal(signal.SIGTERM, OneTimeSignalHandler(pipeline))
937 
938 
939  if options.verbose:
940  print("setting pipeline state to ready ...", file=sys.stderr)
941  if pipeline.set_state(Gst.State.READY) != Gst.StateChangeReturn.SUCCESS:
942  raise RuntimeError("pipeline did not enter ready state")
943  datasource.pipeline_seek_for_gps(pipeline, *detectors.seg)
944  if options.verbose:
945  print("setting pipeline state to playing ...", file=sys.stderr)
946  if pipeline.set_state(Gst.State.PLAYING) != Gst.StateChangeReturn.SUCCESS:
947  raise RuntimeError("pipeline did not enter playing state")
948 
949  if options.write_pipeline is not None:
950  pipeparts.write_dump_dot(pipeline, "%s.%s" % (options.write_pipeline, "PLAYING"), verbose = options.verbose)
951 
952  if options.verbose:
953  print("running pipeline ...", file=sys.stderr)
954  mainloop.run()
955 
956 
957  #
958  # write output file
959  #
960 
961 
962  handler.write_output_url(url = output_url or handler.T050017_filename("%s_LLOID" % options.job_tag, "xml.gz"), description = "%s_LLOID" % options.job_tag, verbose = options.verbose)
963 
964 
965  #
966  # Cleanup template bank temp files
967  #
968 
969 
970  for ifo in banks:
971  for bank in banks[ifo]:
972  if options.verbose:
973  print("removing file: ", bank.template_bank_filename, file=sys.stderr)
974  os.remove(bank.template_bank_filename)
975 
976 
977  #
978  # Shutdown the web interface servers and garbage collect the Bottle
979  # app. This should release the references the Bottle app's routes
980  # hold to the pipeline's data (like template banks and so on).
981  #
982 
983 
984  del httpservers
985  bottle.default_app.pop()
986 
987 
988  #
989  # Set pipeline state to NULL and garbage collect the handler
990  #
991 
992 
993  del triggersrc
994  del handler.pipeline
995  del handler
996  del bank
997  del banks
998  if pipeline.set_state(Gst.State.NULL) != Gst.StateChangeReturn.SUCCESS:
999  raise RuntimeError("pipeline could not be set to NULL")
1000 
1001 
1002 #
1003 # Cleanup local frame file cache
1004 #
1005 
1006 
1007 if options.local_frame_caching:
1008  if options.verbose:
1009  print("deleting temporary cache file ", detectors.frame_cache, file=sys.stderr)
1010  os.remove(detectors.frame_cache)
1011  del detectors.local_cache_list
1012 
1013 
1014 #
1015 # done. online pipeline always ends with an error code so that dagman does
1016 # not mark the job "done" and the job will be restarted when the dag is
1017 # restarted.
1018 #
1019 
1020 
1021 if options.data_source in ("lvshm", "framexmit"):
1022  sys.exit(1)
def mkLLOIDmulti
The multiple instrument, multiple bank LLOID algorithm.
Definition: lloidparts.py:602
def group
group a list roughly according to the distribution in parts, e.g.