gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_calc_snr
1 #!/usr/bin/env python3
2 
3 """
4 Typical Usages:
5 
6 Re-calculating GraceDb gstlal candidates. This assumes you are login to LIGO-Caltech Computing Cluster and
7 all data (svd banks, psd ...) are availible on the gracedb and the cluster. You also need obtain certificate
8 via "ligo-proxy-init" before using this option. Use --save to save the svd banks and psd to disk.
9 
10 Example 1: Calculate SNRs for two detectors.
11 $ ligo-proxy-init chiwai.chan
12 $ gstlal_inspiral_calc_snr \
13 --gid G348519 \
14 --observatory H \
15 --observatory L \
16 --type H1_HOFT_C00 \
17 --type L1_HOFT_C00 \
18 --min-instruments 2 \
19 --time-slide-file tisi.xml\
20 --track-psd \
21 --outdir outputs \
22 --ranking-stat-output rankingstat.xml.gz \
23 --coinc-output followup_coinc.xml.gz \
24 --verbose
25 
26 Example 2: Calculate SNRs for single detector.
27 $ ligo-proxy-init chiwai.chan
28 $ gstlal_inspiral_calc_snr \
29 --gid G347846 \
30 --observatory L \
31 --frame-segments-file framesegments.xml \
32 --frame-segments-name framesegments \
33 --time-slide-file tisi.xml\
34 --min-instruments 1 \
35 --type L1_HOFT_C00 \
36 --track-psd \
37 --outdir outputs \
38 --ranking-stat-output rankingstat.xml.gz \
39 --coinc-output followup_coinc.xml.gz \
40 --verbose
41 
42 Calculate SNR using LLOID method. You should have access to svd banks and reference psd for this option. For
43 filter particular template in the svd banks, you should know the --bank-number and the --row-number of the template;
44 Otherwise, if only --bank-number is provided, SNRs for all templates in the sub-bank will be produced. To limit the
45 output size, use --start and --end to specify the range of SNR in GPS time.
46 
47 Example: G348519
48 $ gstlal_inspiral_calc_snr \
49 --mode 0\
50 --data-source frames \
51 --channel-name H1=GDS-CALIB_STRAIN \
52 --channel-name L1=GDS-CALIB_STRAIN \
53 --frame-cache frame.cache \
54 --gps-start-time 1251009527 \
55 --gps-end-time 1251009527 \
56 --time-slide-file tisi.xml\
57 --reference-psd psd.xml.gz \
58 --track-psd \
59 --min-instruments 2 \
60 --svd-bank H1:H1-GSTLAL_SVD_BANK_258-0-0.xml.gz,L1:L1-GSTLAL_SVD_BANK_258-0-0.xml.gz \
61 --bank-number 0 \
62 --row-number 203 \
63 --outdir outputs \
64 --ranking-stat-output rankingstat.xml.gz \
65 --coinc-output followup_coinc.xml.gz \
66 --start 1251010522 \
67 --end 1251010532 \
68 --verbose
69 
70 Calculate SNR using Finite Impulse Response. Typically, you won't use this option unless you simply want to calculate SNR for one particular
71 template and you don't have access to the corresponding svd bank which contains the template. To use this option, You should have a Bank file,
72 see svd_bank_snr.write_bank(). To limit the output size, use --start and --end to specify the range of SNR in GPS time.
73 
74 Example: G348519
75 $ gstlal_inspiral_calc_snr \
76 --mode 1\
77 --data-source "frames" \
78 --channel-name H1=GDS-CALIB_STRAIN \
79 --channel-name L1=GDS-CALIB_STRAIN \
80 --frame-cache frame.cache \
81 --time-slide-file tisi.xml\
82 --gps-start-time 1251009527 \
83 --gps-end-time 1251011527 \
84 --reference-psd psd.xml.gz \
85 --track-psd \
86 --min-instruments 2 \
87 --bank H1:H1_templates.xml.gz,L1:L1_templates.xml.gz \
88 --outdir outputs \
89 --ranking-stat-output rankingstat.xml.gz \
90 --coinc-output followup_coinc.xml.gz \
91 --start 1251010522 \
92 --end 1251010532 \
93 --verbose
94 """
95 from collections import defaultdict
96 from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
97 import math
98 import os
99 import sys
100 import time
101 
102 from gstlal import datasource
103 from gstlal import far
104 from gstlal import inspiral
105 from gstlal import lloidparts
106 from gstlal import multirate_datasource
107 from gstlal import pipeio
108 from gstlal import pipeparts
109 from gstlal import reference_psd
110 from gstlal import simulation
111 from gstlal import svd_bank
112 from gstlal import svd_bank_snr
113 from gstlal.stats.inspiral_lr import LnLRDensity
114 
115 import gi
116 gi.require_version('Gst', '1.0')
117 gi.require_version('GstAudio', '1.0')
118 from gi.repository import GObject, Gst, GstAudio
119 GObject.threads_init()
120 Gst.init(None)
121 
122 import lal
123 from lal import LIGOTimeGPS
124 from lal import UTCToGPS
125 import lal.series
126 
127 from ligo import segments
128 from ligo.lw import ligolw
129 from ligo.lw import utils as ligolw_utils
130 from ligo.lw import param as ligolw_param
131 from ligo.lw import array as ligolw_array
132 from ligo.lw import lsctables
133 from ligo.lw import table
134 from ligo.lw.utils import segments as ligolw_segments
135 
136 @ligolw_param.use_in
137 @ligolw_array.use_in
138 @lsctables.use_in
139 class ContentHandler(ligolw.LIGOLWContentHandler):
140  pass
141 
142 
143 @lsctables.use_in
144 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
145  pass
146 
147 
148 # disable mkchecktimestamps()
149 # FIXME: python plugin broken until we switch to Python 3
150 pipeparts.mkchecktimestamps = lambda pipeline, src, *args: src
151 
152 def parse_command_line():
153  parser = OptionParser(description = "Using gstlal inspiral pipeline to calculate SNR for template(s)")
154 
155  datasource.append_options(parser)
156 
157  group = OptionGroup(parser, "Whiten / PSD Options", "Adjust noise spectrum estimation parameter")
158  group.add_option("--reference-psd", metavar = "filename", help = "Load noise spectrum from LIGO light-weight XML file (optional).")
159  group.add_option("--psd-fft-length", metavar = "seconds", default = 32, type = "int", help = "Length of the FFT used to whiten strain data (default = 32 s).")
160  group.add_option("--track-psd", action = "store_true", help = "Enable dynamic PSD tracking. Enabled by default if --reference-psd is not given.")
161  group.add_option("--zero-pad", metavar = "seconds", default = 0, type = "int", help = "The zero padding of the Hanning window in seconds (default = 0).")
162  group.add_option("--average-samples", default = 64, type = "int", help = "The number of samples used to estimate the average value of the PSD")
163  group.add_option("--median-samples", default = 7, type = "int", help = "The number of samples used to estimate the median value of the PSD")
164  parser.add_option_group(group)
165 
166  group = OptionGroup(parser, "Template Options", "Choose a template from a SVD bank file / a bank file (see svd_bank_snr.Bank).")
167  group.add_option("--svd-bank", metavar = "filename", help = "A LIGO light-weight xml / xml.gz file containing svd bank information. These can be given as a comma separated list such as H1:file1,H2:file2,L1:file3 to analyze multiple instruments (require)." )
168  group.add_option("--coinc", metavar = "filename", help = "The coinc.xml file associated with --svd-bank. This is used to find the --bank-number and --row-number for a particular event. If given, the --bank-number and --row-number will be overwritten. (optional)")
169  group.add_option("--bank-number", type = "int", help = "Bank id is of the form <int>ID_<int>N where N is the sub bank id. (optional). SNRs in all banks will be used if it is not given.")
170  group.add_option("--bank-counts", type = "int", default = 1, help = "Number of banks to used; Counted from --bank-number; default = 1")
171  group.add_option("--row-number", type = "int", help = "The row number of the template (optional). All the SNRs will be outputed if it is not given.")
172  group.add_option("--row-counts", type = "int", default = 1, help = "Number of rows to be outputted; Counted from --row-number; default = 1")
173  group.add_option("--bank", metavar = "filename", help = "LIGO light-weight xml.gz file(s) containing only one template. These can be given as a comma separated list such as H1:file1,H2:file2,L1:file3. Expecting one template only for each file (require).")
174  parser.add_option_group(group)
175 
176  group = OptionGroup(parser, "Data Quality Options", "Adjust data quality handling")
177  group.add_option("--ht-gate-threshold", metavar= "sigma", type = "float", default = float("inf"), help = "Set the threshold on whitened h(t) to excise glitches in units of standard deviation (defalut = inf). ")
178  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).")
179  group.add_option("--veto-segments-name", metavar = "name", default = "vetoes", help = "Set the name of the LIGO light-weight XML file from which to load vetoes (default = 'veto') (optional).")
180  parser.add_option_group(group)
181 
182  group = OptionGroup(parser, "GraceDb Event Options", "Produce SNR time series for gstlal gracedb event.")
183  group.add_option("--gid", metavar = "gracedb event id", type = "str", help = "The gracedb event id.")
184  group.add_option("--observatory", metavar = "OBS", type = "str", action = "append", help = "Name of the observatory (H,L,V ...), also see gwdatafind.")
185  group.add_option("--type", metavar = "frame type", type = "str", action = "append", help = "Name of the observatory (H,L,V ...), also see gwdatafind.")
186  group.add_option("--time-span", metavar = "seconds", type = "int", default = 500, help = "The time span around the event's trigger time, must be larger or equal to 500s (default = 500).")
187  parser.add_option_group(group)
188 
189  group = OptionGroup(parser, "Trigger Generator Control / Outputs Options", "Adjust the trigger generator's behaviors and its outputs.")
190  group.add_option("--FAR-trialsfactor", metavar = "trials", type = "float", default = 1.0, help = "Add trials factor to FAR before uploading to gracedb (default = 1.0).")
191  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 (optional).")
192  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)")
193  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.")
194  group.add_option("--zerolag-rankingstat-pdf", metavar = "url", 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.")
195  group.add_option("--time-slide-file", metavar = "filename", help = "Set the name of the xml file to get time slide offsets (require).")
196  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).")
197  group.add_option("--singles-threshold", metavar = "SNR", type = "float", default = float("inf"), help = "Set the SNR threshold at which to record single-instrument events in the output (default = +inf, i.e. don't retain singles).")
198  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).")
199  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 (default = 0.005).")
200 
201  group.add_option("--gracedb-service-url", metavar = "url", type = "str", help = "Fake graceDb service url. This can only be a local url (optional).")
202  group.add_option("--gracedb-far-threshold", metavar = "Hertz", type = "float", help = "False-alarm rate threshold for fake gracedb uploads in Hertz (default = do not upload to gracedb).")
203  group.add_option("--gracedb-group", metavar = "name", default = "Test", help = "Gracedb group to which to upload events (default = 'Test').")
204  group.add_option("--gracedb-pipeline", metavar = "name", default = "gstlal", help = "Name of pipeline to provide in fake GracedB uploads (default = 'gstlal').")
205  group.add_option("--gracedb-search", metavar = "name", default = "event-followup", help = "Name of search to provide in fake GracedB uploads (default = 'event-followup').")
206  group.add_option("--reconstruction-segment", metavar = "start:stop", action = "append", help = "Only reconstruct the SNRs for this time interval. Note: Use this carefully, this is not compatible with the option --start and --end. This is only added for coincidence document (optional).")
207  group.add_option("--ranking-stat-output", metavar = "filename", default = None, help = "Set the name of the file to which to write ranking statistic data collected from triggers. This will not be prefixed by --outdir (optional).")
208  group.add_option("--coinc-output", metavar = "filename", help = "Set the name of the LIGO light-weight XML output file *.{xml,xml.gz} or an SQLite database *.sqlite. This will not be prefixed by --outdir (default is disable coinc output) (Providing this would also enable triggers generation, otherwise trigger generator is not added to the pipeline).")
209  parser.add_option_group(group)
210 
211  group = OptionGroup(parser, "Output Control Options", "Control SNR outputs.")
212  group.add_option("--outdir", metavar = "directory", default = ".", type = "str", help = "Output directory for SNR(s) (default = .).")
213  group.add_option("--complex", action = "store_true", help = "Choose whether to output the complex snr or not.")
214  group.add_option("--start", metavar = "seconds", type = "float", help = "Start SNR time series at GPS time '--start' (require).")
215  group.add_option("--end", metavar = "seconds", type = "float", help = "End SNR time series at GPS time '--end' (require).")
216  parser.add_option_group(group)
217 
218  group = OptionGroup(parser, "Program Options", "Control Program Behaviour.")
219  group.add_option("--fir-stride", metavar = "seconds", type = "float", default = 8, help = "Set the length of the fir filter stride in seconds. default = 8")
220  group.add_option("--verbose", action = "store_true", help = "Be verbsoe.")
221  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).")
222  group.add_option("--save", action = "store_true", default = False, help = "Save frame cache / svd bank / psd if using --gid (default = False).")
223  group.add_option("--mode", metavar = "method", type = "int", default = 0, help = "The method (0 = LLOID / 1 = FIR) that is used to calculate SNR (default = 0).")
224  group.add_option("--output-width", metavar = "bits", type = "int", default = 32, help = "The size of the output data, can only be 32 or 64 bits (default = 32 bits).")
225  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.")
226  parser.add_option_group(group)
227 
228  options, args = parser.parse_args()
229 
230  #
231  # Bait out from here if --gid is provided, else continue setting the program
232  #
233 
234  if options.gid is not None:
235  # Setting up inputs for GraceDb event, this will overwrite svd-bank/template/psd related inputs.
236  if options.observatory is None or options.type is None:
237  raise ValueError("When using --gid, --observatory and --type must be provided.")
238  else:
239  gwdata_metavars = svd_bank_snr.framecache_from_event(options.gid, options.observatory, options.type, time_span = options.time_span, outdir = options.outdir, verbose = options.verbose)
240  # We can hardcoded here, since we know all the information from gracedb.
241  # This assume everything on the gracedb are correct and complete which could go wrong in the future.
242  # (e.g files are deleted)
243  options.data_source = "frames"
244  options.frame_cache = os.path.join(options.outdir, "frame.cache")
245  options.gps_start_time = gwdata_metavars["gps_start_time"][0]
246  options.gps_end_time = gwdata_metavars["gps_end_time"][0]
247  options.channel_name = gwdata_metavars["channels_name"]
248  options.instrument = gwdata_metavars["instruments"]
249  gw_data_source_info = datasource.GWDataSourceInfo(options)
250 
251  # FIXME: Adjustable parameters, hardcoded here for simplicity.
252  trigger_time = min(gwdata_metavars["trigger_times"])
253  options.start = trigger_time - 5
254  options.end = trigger_time + 5
255 
256  # It must be using LLOID
257  options.mode = 0
258 
259  psds_dict = svd_bank_snr.psd_from_event(options.gid, save = options.save, verbose = options.verbose)
260 
261  banks_dict, options.bank_number, options.row_number = svd_bank_snr.svd_banks_from_event(options.gid, save = options.save, verbose = options.verbose)
262 
263  # bait out from here
264  return options, gw_data_source_info, banks_dict, psds_dict
265 
266  #
267  # Do general program options checking
268  #
269 
270  if options.outdir is None:
271  missing_required_options.append("--outdir")
272 
273  # Check SNRs series output
274  if options.start is None or options.end is None:
275  raise ValueError("Must have --start and --end.")
276  elif options.start >= options.end:
277  raise ValueError("--start must less than --end.")
278 
279  #
280  # Setting up GW data
281  #
282 
283  # Extra handle for SNRs output because SNRs are not stable initially and have padding at the end
284  # FIXME: the 50s is hardcoded and only use to avoid snr being unstable due to edge effect when doing convoluion
285  gw_data_source_info = datasource.GWDataSourceInfo(options)
286  if options.start - gw_data_source_info.seg[0] <= 50 or gw_data_source_info.seg[1] - options.end <= 50:
287  raise ValueError("Check your inputted --start / --end or your frame file. You should have a long enough data such that, the --start/--end is larger/less than the start/end of your data at least 50s. ")
288 
289  #
290  # Setting up PSD
291  #
292 
293  if options.reference_psd:
294  psd = lal.series.read_psd_xmldoc(ligolw_utils.load_url(options.reference_psd, contenthandler = lal.series.PSDContentHandler))
295  # Check if there enough reference psds for GW data
296  if set(psd) < set(gw_data_source_info.channel_dict):
297  raise ValueError("Missing PSD(s) for %s." % (", ".join(sorted(set(gw_data_source_info.channel_dict) - set(psd)))))
298  else:
299  psd = dict((ifo, None) for ifo in set(gw_data_source_info.channel_dict))
300  options.track_psd = True
301 
302  #
303  # Setting up SVD banks (mode 0 = LLOID) or template table (mode 1 = FIR)
304  #
305 
306  assert options.bank_counts >= 1, "Number of banks to be used and outputted must be larger than or equals to 1."
307  assert options.row_counts >= 1, "Number of rows to be outputted must be larger than or equals to 1."
308  # Use LLOID method
309  if options.mode == 0:
310  missing_required_options = []
311  # Checking required options
312  if options.svd_bank is None:
313  missing_required_options.append("--svd-bank")
314  # Raise VauleError is required option(s) is/are missing
315  if missing_required_options:
316  raise ValueError("Missing required option(s) %s" % ", ".join(sorted(missing_required_options)))
317 
318  # Setting up SVD bank
319  bank_urls = inspiral.parse_svdbank_string(options.svd_bank)
320 
321  # Check if there are enough svd banks for GW data
322  if set(bank_urls) < set(gw_data_source_info.channel_dict):
323  raise ValueError("Missing SVD bank(s) for %s." % (", ".join(sorted(set(gw_data_source_info.channel_dict) - set(bank_urls)))))
324 
325  banks_dict = inspiral.parse_bank_files(bank_urls, options.verbose)
326 
327  # Scan for the --bank-number and --row-number if --coinc is given
328  if options.coinc is not None:
329  coinc_xmldoc = ligolw_utils.load_url(options.coinc, verbose = options.verbose, contenthandler = ContentHandler)
330  options.bank_number, options.row_number = svd_bank_snr.scan_svd_banks_for_row(coinc_xmldoc, banks_dict)
331 
332  # Use Finite Impulse Response
333  elif options.mode == 1:
334  missing_required_options = []
335  # Checking required options
336  if options.bank is None:
337  missing_required_options.append("--bank")
338  # Raise VauleError is required option(s) is/are missing
339  if missing_required_options:
340  raise ValueError("Missing required option(s) %s" % ", ".join(sorted(missing_required_options)))
341 
342  bank_urls = inspiral.parse_svdbank_string(options.bank)
343  banks_dict = svd_bank_snr.parse_bank_files(bank_urls)
344 
345  # Check if there enough templates for GW data
346  if set(banks_dict) < set(gw_data_source_info.channel_dict):
347  raise ValueError("Missing table(s) for %s." % (", ".join(sorted(set(gw_data_source_info.channel_dict) - set(banks_dict)))))
348 
349  # Unknown mode
350  else:
351  raise ValueError("Invalid mode: %d" % options.mode)
352 
353  #
354  # Check if --bank-number and --row-number is valid
355  #
356  for banks in banks_dict.values():
357  if options.bank_number is not None and options.row_number is not None:
358  if not (0 <= options.bank_number < len(banks)) :
359  raise ValueError("Invaild --bank-number %d. Possible id [0-%d)\n" % (options.bank_number, len(banks)))
360  if not (0 <= options.row_number < len(banks[options.bank_number].sngl_inspiral_table)):
361  raise ValueError("No such template: Invaild --row-number %d. Possible range [0-%d)\n" % (options.row_number, len(banks[options.bank_number].sngl_inspiral_table)))
362  elif options.bank_number is None and options.row_number is not None:
363  # Just pick one bank
364  if not (0 <= options.row_number < len(banks[0].sngl_inspiral_table)):
365  raise ValueError("No such template: Invaild --row-number %d. Possible range [0-%d)\n" % (options.row_number, len(banks[0].sngl_inspiral_table)))
366  elif options.bank_number is not None and options.row_number is None:
367  if not (0 <= options.bank_number < len(banks)) :
368  raise ValueError("Invaild --bank-number %d. Possible id [0-%d)\n" % (options.bank_number, len(banks)))
369  else:
370  # Just to be clear
371  pass
372 
373  return options, gw_data_source_info, banks_dict, psd
374 
375 options, gw_data_source_info, banks_dict, psds_dict = parse_command_line()
376 
377 #====================================================================================================
378 #
379 # Post Setup
380 #
381 #====================================================================================================
382 
383 # Prepare veto segements
384 if options.veto_segments_file is not None:
385  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()
386 else:
387  veto_segments = None
388 
389 # Choose to optionally reconstruct segments around chosen segement.
390 # Reconstruct segment around injections is disable.
391 # if options.injections:
392 # offset_padding = max(math.ceil(abs(row.end))+1 for bank in banks_dict.values()[0] for row in bank.sngl_inspiral_table)
393 # reconstruction_segment_list = simulation.sim_inspiral_to_segment_list(options.injections, pad = offset_padding)
394 if options.reconstruction_segment:
395  reconstruction_segment_list = segments.segmentlist()
396  for reconstruction_segment in options.reconstruction_segment:
397  t0, t1 = reconstruction_segment.split(":")
398  reconstruction_segment_list.append(segments.segment(LIGOTimeGPS(int(t0)), LIGOTimeGPS(int(t1))))
399 else:
400  reconstruction_segment_list = None
401 #====================================================================================================
402 #
403 # main
404 #
405 #====================================================================================================
406 
407 if options.verbose:
408  sys.stderr.write("Building pipeline...\n")
409 
410 pipeline = Gst.Pipeline(name = "gstlal_inspiral_SNR")
411 mainloop = GObject.MainLoop()
412 
413 #
414 # Construct Default Pipeline Handler
415 #
416 
417 
418 bank_slicing = slice(None, None, None) if options.bank_number is None else slice(options.bank_number, options.bank_number+options.bank_counts, 1)
419 bank_start = options.bank_number if options.bank_number is not None else 0
420 bank_snrs_dict = defaultdict(list)
421 for instrument in gw_data_source_info.channel_dict:
422  for num, bank in enumerate(banks_dict[instrument][bank_slicing], bank_start):
423  bank_snrs_dict[instrument].append(svd_bank_snr.Bank_SNR(options.start, options.end, instrument, bank, bank_number = num, method = "FIR" if options.mode else "LLOID"))
424 
425 snr_document = svd_bank_snr.SignalNoiseRatioDocument(bank_snrs_dict, verbose = options.verbose)
426 
427 if options.coinc_output == None:
428  handler = svd_bank_snr.SimpleSNRHandler(pipeline, mainloop, snr_document, verbose = options.verbose)
429 else:
430  handler = svd_bank_snr.Handler(snr_document, verbose = options.verbose)
431 snr_appsync = pipeparts.AppSync(appsink_new_buffer = handler.appsink_new_snr_buffer)
432 
433 #
434 # Construct Pipeline
435 #
436 
437 itacac_dict = {}
438 for instrument in gw_data_source_info.channel_dict:
439  src, statevector, dqvector = datasource.mkbasicsrc(pipeline, gw_data_source_info, instrument, options.verbose)
440  hoft = multirate_datasource.mkwhitened_multirate_src(
441  pipeline,
442  src,
443  set(rate for bank_SNRs in bank_snrs_dict[instrument] for rate in bank_SNRs.bank.get_rates()),
444  instrument,
445  dqvector = dqvector,
446  fir_whiten_reference_psd = bank.processed_psd,
447  ht_gate_threshold = options.ht_gate_threshold,
448  psd = psds_dict[instrument],
449  psd_fft_length = options.psd_fft_length,
450  statevector = statevector,
451  track_psd = options.track_psd,
452  veto_segments = veto_segments,
453  width = options.output_width
454  )
455 
456  for index, bank_SNR in enumerate(bank_snrs_dict[instrument]):
457  bank = bank_SNR.bank
458  if options.mode == 0:
459  snr = lloidparts.mkLLOIDhoftToSnrSlices(
460  pipeline,
461  hoft,
462  bank,
463  (None, None),
464  1 * Gst.SECOND,
465  control_peak_time = options.control_peak_time,
466  fir_stride = options.fir_stride,
467  logname = instrument,
468  nxydump_segment = None,
469  reconstruction_segment_list = reconstruction_segment_list,
470  snrslices = None,
471  verbose = options.verbose
472  )
473  else:
474  fir_matrix = []
475  for template in bank.templates:
476  fir_matrix += [template.real, template.imag]
477  snr = pipeparts.mktogglecomplex(
478  pipeline,
479  pipeparts.mkfirbank(
480  pipeline,
481  hoft[bank.sample_rate],
482  latency = 0,
483  fir_matrix = fir_matrix,
484  block_stride = 16 * bank.sample_rate,
485  time_domain = False
486  )
487  )
488  # Construct SNR handler by default and terminate the pipeline at here
489  if options.coinc_output == None:
490  snr_appsync.add_sink(pipeline, snr, name = "%s_%d" % (instrument, index))
491  # Construct optional trigger generator
492  else:
493  snr = pipeparts.mktee(pipeline, snr)
494  snr_appsync.add_sink(pipeline, pipeparts.mkqueue(pipeline, snr), name = "%s_%d" % (instrument, index))
495 
496  nsamps_window = 1 * max(bank.get_rates())
497  if bank.bank_id not in itacac_dict:
498  itacac_dict[bank.bank_id] = pipeparts.mkgeneric(pipeline, None, "lal_itacac")
499  head = itacac_dict[bank.bank_id]
500  pad = head.get_request_pad("sink%d" % len(head.sinkpads))
501  for prop, val in [("n", nsamps_window), ("snr-thresh", LnLRDensity.snr_min), ("bank_filename", bank.template_bank_filename), ("sigmasq", bank.sigmasq), ("autocorrelation_matrix", pipeio.repack_complex_array_to_real(bank.autocorrelation_bank)), ("autocorrelation_mask", bank.autocorrelation_mask)]:
502  pad.set_property(prop, val)
503  pipeparts.mkqueue(pipeline, snr).srcpads[0].link(pad)
504 
505 #
506 # Construct optional LLOID handler instead if --coinc-output is provided
507 #
508 
509 if options.coinc_output != None:
510  # Prepare offsetvectors
511  offsetvectors = lsctables.TimeSlideTable.get_table(ligolw_utils.load_filename(options.time_slide_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose)).as_dict().values()
512  all_instruments = reduce(lambda a, b: a | set(b), offsetvectors, set())
513  if len(all_instruments) < options.min_instruments:
514  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))
515  if not (all_instruments >= set(gw_data_source_info.channel_dict)):
516  raise ValueError("--time-slide-file names %s but have channel names for %s" % (", ".join(sorted(all_instruments)), ", ".join(sorted(gw_data_source_info.channel_dict))))
517 
518  # Load template ids and horizon_factors
519  sngl_inspiral_table = banks_dict.values()[0][options.bank_number or 0].sngl_inspiral_table.copy()
520  horizon_factors = {}
521  for bank in banks_dict.values()[0]:
522  sngl_inspiral_table.extend(bank.sngl_inspiral_table)
523  horizon_factors.update(bank.horizon_factors)
524  template_ids = frozenset(row.template_id for row in sngl_inspiral_table)
525 
526  if options.ranking_stat_input:
527  xmldoc = ligolw_utils.load_url(options.ranking_stat_input, verbose = options.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler)
528  rankingstat, _ = far.parse_likelihood_control_doc(xmldoc)
529  if rankingstat is None:
530  raise ValueError("--ranking-stat-input does not contain parameter distribution data.")
531  if rankingstat.template_ids is None:
532  rankingstat.template_ids = template_ids
533  elif rankingstat.template_ids != template_ids:
534  raise ValueError("--ranking-stat-input has wrong template ids.")
535  if rankingstat.instruments != all_instruments:
536  raise ValueError("--ranking-stat-input does not have the same instruments as defined in --time-slide-file.")
537  if rankingstat.delta_t != options.coincidence_threshold:
538  raise ValueError("--ranking-stat-input does not have the same delta_t as --coincidence-threshold.")
539  if rankingstat.min_instruments != options.min_instruments:
540  raise ValueError("--ranking-stat-input does not have the same min_instruments as --min-instruments.")
541  rankingstat.numerator.set_horizon_factors(horizon_factors)
542  else:
543  rankingstat = far.RankingStat(
544  template_ids = template_ids,
545  instruments = set(gw_data_source_info.channel_dict),
546  delta_t = options.coincidence_threshold,
547  min_instruments = options.min_instruments,
548  horizon_factors = horizon_factors
549  )
550 
551  coincs_document = inspiral.CoincsDocument(
552  url = options.coinc_output,
553  process_params = options.__dict__.copy(),
554  process_start_time = UTCToGPS(time.gmtime()),
555  comment = options.comment,
556  instruments = rankingstat.instruments,
557  seg = gw_data_source_info.seg,
558  offsetvectors = offsetvectors,
559  injection_filename = options.injections,
560  tmp_path = options.tmp_space,
561  replace_file = True,
562  verbose = options.verbose
563  )
564 
565  handler.init(
566  mainloop,
567  pipeline,
568  coincs_document,
569  rankingstat,
570  banks_dict.values()[0][options.bank_number].horizon_distance_func,
571  gracedbwrapper = inspiral.GracedBWrapper(
572  rankingstat.instruments,
573  far_threshold = options.gracedb_far_threshold,
574  min_instruments = options.min_instruments,
575  group = options.gracedb_group,
576  search = options.gracedb_search,
577  pipeline = options.gracedb_pipeline,
578  service_url = options.gracedb_service_url,
579  upload_auxiliary_data = True,
580  verbose = options.verbose
581  ),
582  zerolag_rankingstatpdf_url = options.zerolag_rankingstat_pdf,
583  rankingstatpdf_url = options.ranking_stat_pdf,
584  ranking_stat_output_url = options.ranking_stat_output,
585  ranking_stat_input_url = options.ranking_stat_input,
586  likelihood_snapshot_interval = options.likelihood_snapshot_interval,
587  sngls_snr_threshold = options.singles_threshold,
588  FAR_trialsfactor = options.FAR_trialsfactor,
589  verbose = options.verbose
590  )
591 
592  assert len(itacac_dict.keys()) >= 1
593  trigger_appsync = pipeparts.AppSync(appsink_new_buffer = handler.appsink_new_buffer)
594  trigger_appsinks = set(trigger_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 itacac_dict.items())
595 
596 #
597 # Run pipeline
598 #
599 
600 if options.verbose:
601  sys.stderr.write("Setting pipeline state to READY...\n")
602 if pipeline.set_state(Gst.State.READY) != Gst.StateChangeReturn.SUCCESS:
603  raise RuntimeError("pipeline cannot enter ready state.")
604 
605 datasource.pipeline_seek_for_gps(pipeline, *gw_data_source_info.seg)
606 
607 if options.verbose:
608  sys.stderr.write("Seting pipeline state to PLAYING...\n")
609 if pipeline.set_state(Gst.State.PLAYING) != Gst.StateChangeReturn.SUCCESS:
610  raise RuntimeError("pipeline cannot enter playing state.")
611 if options.verbose:
612  sys.stderr.write("Calculating SNR...\n")
613 
614 mainloop.run()
615 
616 if options.verbose:
617  sys.stderr.write("Calculation done.\n")
618 if pipeline.set_state(Gst.State.NULL) != Gst.StateChangeReturn.SUCCESS:
619  raise RuntimeError("pipeline could not be set to NULL.")
620 
621 # Write outputs
622 if options.coinc_output != None:
623  handler.write_output_url(url = options.coinc_output)
624 handler.write_snrs(options.outdir, row_number = options.row_number, counts = options.row_counts, COMPLEX = options.complex)
625 
def svd_banks_from_event
def group
group a list roughly according to the distribution in parts, e.g.
def framecache_from_event