3 # Copyright (C) 2009-2014 Kipp Cannon, Chad Hanna, Drew Keppel
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 """Stream-based inspiral analysis tool"""
22 # =============================================================================
26 # =============================================================================
30 ### A program to analyze gravitational wave data for compact binary coalescence in real time or in an offline mode
36 ### label="gstlal_inspiral"
38 ### graph [fontname="Roman", fontsize=24];
39 ### edge [ fontname="Roman", fontsize=10 ];
40 ### node [fontname="Roman", shape=box, fontsize=11];
42 ### gracedb [label="GW\nCandidate\nDatabase", shape=oval, color=tomato3, style=filled];
45 ### subgraph clusterNodeN {
48 ### label="gstreamer pipeline";
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];
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];
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];
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];
74 ### H1src -> H1multirate;
75 ### L1src -> L1multirate;
76 ### V1src -> V1multirate;
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"];
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"];
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"];
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"];
115 ### Coincidence -> SigEst -> Thresh -> EventGen;
117 ### EventGen -> gracedb;
124 ### +------------------------------------------------+---------------------------------------------+------------+
125 ### | Names | Hash | Date |
126 ### +================================================+=============================================+============+
127 ### | Florent, Sathya, Duncan Me, Jolien, Kipp, Chad | 9074294d6b57f43651143b5f93210751de1fe55a | 2014-05-02 |
128 ### +------------------------------------------------+---------------------------------------------+------------+
134 from fpconst
import PosInf
136 # fpconst is not part of the standard library and might not be
138 PosInf = float(
"+inf")
139 from functools import reduce
143 from optparse import OptionGroup, OptionParser
148 from io import StringIO
156 gi.require_version('Gst', '1.0')
157 from gi.repository import GObject, Gst
158 GObject.threads_init()
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
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
187 GSTLAL_PROCESS_START_TIME = UTCToGPS(time.gmtime())
190 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
194 # Make sure we have sufficient resources
195 # We allocate far more memory than we need, so this is okay
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))
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
214 def service_domain(gracedb_search, gracedb_pipeline):
215 return
"%s_%s.%s" % (gracedb_pipeline.lower(), gracedb_search.lower(), servicediscovery.DEFAULT_SERVICE_DOMAIN)
219 # =============================================================================
223 # =============================================================================
227 def parse_command_line():
228 parser = OptionParser(
229 description = __doc__
232 # append all the datasource specific options
233 datasource.append_options(parser)
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)
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)
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)
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)
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)
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)
305 options, filenames = parser.parse_args()
309 # do this before messing with options object
312 process_params = options.__dict__.copy()
315 # extract data source configuration
318 detectors = datasource.GWDataSourceInfo(options)
321 # extract information about principle I/O files
324 # FIXME Put all svd banks for different detectors in one file.
326 if options.svd_bank_cache:
327 raise ValueError(
"cannot supply both --svd-bank and --svd-bank-cache")
329 svd_banks = list(map(inspiral.parse_svdbank_string, options.svd_bank))
330 except ValueError as e:
331 print(
"Unable to parse --svd-bank")
333 elif options.svd_bank_cache:
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))
342 missing_options.append(
"either --svd-bank-cache or at least one --svd-bank")
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")
353 missing_options.append("either --output-cache or at least one --output")
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")
364 if not options.time_slide_file:
365 missing_options.append(
"--time-slide-file")
368 raise ValueError(
"missing required option(s) %s" %
", ".join(sorted(missing_options)))
371 # check sanity of the input and output file collections
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)
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):
388 required_urls.append(filename)
389 for i in range(len(required_urls)):
391 required_urls[i] = ligolw_utils.local_path_from_url(required_urls[i])
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)]
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)))
400 # check sanity of overall configuration
403 if options.blind_injections and options.injections:
404 raise ValueError(
"cannot set both --blind-injections and --injections")
406 if options.data_source in (
"lvshm",
"framexmit"):
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(
"_",
"-"))
413 raise ValueError(
"missing required option(s) %s when --data-source is lvshm or framexmit" %
", ".join(missing_options))
415 if
"-" in options.job_tag or
"." in options.job_tag:
416 raise ValueError(
"invalid characters in --job-tag \"%s\"" % options.job_tag)
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))
421 # make an
"infinite" extent segment
422 detectors.seg = segments.segment(LIGOTimeGPS(0), LIGOTimeGPS(2000000000))
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
427 # FIXME: this is ugly, but we have to protect against busted shared memory partitions
428 if options.data_source ==
"lvshm":
430 for ifo in detectors.channel_dict.keys():
431 subprocess.call([
"smrepair", detectors.shm_part_dict[ifo]])
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:
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)
446 options.activation_counts = None
450 for option in [
"job_tag"]:
451 if getattr(options, option) is not None:
452 bad_options.append(
"--%s" % option.replace(
"_",
"-"))
454 raise ValueError(
"cannot set %s when --data-source is not lvshm or framexmit " %
", ".join(bad_options))
455 options.activation_counts = None
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))
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")
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")
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")
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)))
491 # Option checks complete
494 options.nxydump_segment, = segmentsUtils.from_range_strings([options.nxydump_segment], boundtype = LIGOTimeGPS)
496 if options.blind_injections is not None:
497 detectors.injection_filename = options.blind_injections
499 # Setup local caching
500 if options.local_frame_caching:
501 f, fname = tempfile.mkstemp(
".cache")
503 print(
"caching frame data locally to ", fname, file=sys.stderr)
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
527 # the injections are now present in the data so we don
't want to do them twice
528 detectors.injection_filename = None
531 return options, filenames, process_params, svd_banks, detectors
535 # =============================================================================
539 # =============================================================================
543 class OneTimeSignalHandler(object):
544 def __init__(self, pipeline):
545 self.pipeline = pipeline
548 def __call__(self, signum, frame):
551 print(
"*** SIG %d attempting graceful shutdown (this might take several minutes) ... ***" % signum, file=sys.stderr)
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)
561 print(
"*** received SIG %d %d times... ***" % (signum, self.count), file=sys.stderr)
565 # =============================================================================
569 # =============================================================================
574 # =============================================================================
578 # =============================================================================
587 options, filenames, process_params, svd_banks, detectors = parse_command_line()
589 if not options.check_time_stamps:
590 pipeparts.mkchecktimestamps = lambda pipeline, src, *args: src
594 # Parse the vetos segments file(s) if provided
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()
605 # Load the time slide vectors, and use them to define the complete
606 # instrument list for the network
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))))
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
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))))
633 psd = dict.fromkeys(all_instruments, None)
637 # Process svd banks in serial
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)):
643 # Checkpointing only supported for gzip files in offline analysis
644 # FIXME Implement a means by which to check for sqlite file
648 if options.data_source not in (
"lvshm",
"framexmit") and output_url.endswith(
'.gz'):
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)):
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)):
657 # File is OK and there is no need to process it,
658 # skip ahead in the loop
661 # File does not exist or is corrupted, need to
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)
668 # create a new, empty, Bottle application and make it the current
669 # default, then start http server(s) to serve it up
673 bottle.default_app.push()
674 # uncomment the next line to show tracebacks when something fails
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 = {
682 "pid": str(os.getpid()),
684 service_discovery = not options.disable_service_discovery,
685 verbose = options.verbose
690 # Set up a registry of the resources that this job provides
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"):
707 # only create links for GET methods
708 if route.method !=
"GET":
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))
718 # parse SVD template bank and expose bank metadata
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()
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()
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)
748 # Choose to optionally reconstruct segments around injections (not
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))))
759 reconstruction_segment_list = None
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)
774 print(
"assembling pipeline ...", file=sys.stderr)
776 pipeline = Gst.Pipeline(name=
"gstlal_inspiral")
777 mainloop = GObject.MainLoop()
781 detectors = detectors,
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"),
799 print(
"done", file=sys.stderr)
803 # Load/Initialize ranking statistic data.
808 if options.ranking_stat_input:
810 xmldoc = ligolw_utils.load_url(options.ranking_stat_input, verbose = options.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler)
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)
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)
829 if options.compress_ranking_stat:
831 print(
"compressing ranking stat...", file=sys.stderr)
832 rankingstat.numerator.horizon_history.compress(threshold = options.compress_ranking_stat_threshold)
834 print(
"...done.", file=sys.stderr)
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)
844 # construct and configure pipeline handler
849 print(
"initializing pipeline handler ...", file=sys.stderr)
850 handler = lloidhandler.Handler(
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,
860 offsetvectors = offsetvectors,
861 injection_filename = options.injections,
862 tmp_path = options.tmp_space,
864 verbose = options.verbose
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
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"),
899 print(
"... pipeline handler initialized", file=sys.stderr)
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())
907 print(
"attached %d, done" % len(appsinks), file=sys.stderr)
911 # if we request a dot graph of the pipeline, set it up
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)
925 if options.data_source in (
"lvshm",
"framexmit"):
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.
931 # this is only done in the online case because we want
932 # offline jobs to just die and not write partial databases
935 signal.signal(signal.SIGINT, OneTimeSignalHandler(pipeline))
936 signal.signal(signal.SIGTERM, OneTimeSignalHandler(pipeline))
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)
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")
949 if options.write_pipeline is not None:
950 pipeparts.write_dump_dot(pipeline,
"%s.%s" % (options.write_pipeline,
"PLAYING"), verbose = options.verbose)
953 print(
"running pipeline ...", file=sys.stderr)
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)
966 # Cleanup template bank temp files
971 for bank in banks[ifo]:
973 print(
"removing file: ", bank.template_bank_filename, file=sys.stderr)
974 os.remove(bank.template_bank_filename)
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).
985 bottle.default_app.pop()
989 # Set pipeline state to NULL and garbage collect the handler
998 if pipeline.set_state(Gst.State.NULL) != Gst.StateChangeReturn.SUCCESS:
999 raise RuntimeError(
"pipeline could not be set to NULL")
1003 # Cleanup local frame file cache
1007 if options.local_frame_caching:
1009 print(
"deleting temporary cache file ", detectors.frame_cache, file=sys.stderr)
1010 os.remove(detectors.frame_cache)
1011 del detectors.local_cache_list
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
1021 if options.data_source in (
"lvshm",
"framexmit"):
def mkLLOIDmulti
The multiple instrument, multiple bank LLOID algorithm.
def group
group a list roughly according to the distribution in parts, e.g.