gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
lloidparts.py
Go to the documentation of this file.
1 # Copyright (C) 2009--2013 Kipp Cannon, Chad Hanna, Drew Keppel
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 2 of the License, or (at your
6 # option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 # Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 
17 ##
18 # @file
19 #
20 # A file that contains the lloidparts module code; Roughly speaking it
21 # implements the algorithm described in <a
22 # href=http://arxiv.org/abs/1107.2665>ApJ 748 136 (2012)</a>
23 #
24 #
25 # Review Status
26 #
27 # | Names | Hash | Date | Diff to Head of Master |
28 # | ------------------------------------- | ---------------------------------------- | ---------- | --------------------------- |
29 # | Sathya, Duncan Me, Jolien, Kipp, Chad | 2f5f73f15a1903dc7cc4383ef30a4187091797d1 | 2014-05-02 | <a href="@gstlal_inspiral_cgit_diff/python/lloidparts.py?id=HEAD&id2=2f5f73f15a1903dc7cc4383ef30a4187091797d1">lloidparts.py</a> |
30 #
31 # #### Actions
32 # - Feature request: do checkpointing when instruments are down
33 # - Feature request: need to hook up equivalent of "CAT 2" vetoes to online analysis when ready, and HW inj veto, etc.
34 # - Document the parameters in mkLLOIDmulti()
35 # - Check if bank ids are the same across different instruments
36 # - Feature request: Make time-frequency videos for interesting events
37 # - Inject signals of known, high SNR and measure loss
38 # - move the makesegmentsrcgate to before the matrix mixer, not in the current sum-of-squares control loop
39 # - Make conditional branches in the graph gray boxes
40 # - consider zero padding the beginning of jobs to get rid of mkdrop()
41 # - Decide how to properly normalize SNRs for incomplete filter segments (currently filters are not renormalized so the loss in SNR is bigger than might be expected)
42 # - Check and possibly fix the function that switches between time-domain and FFT convolution based on stride and number of samples
43 # - Consider if quality = 9 is right for downsampling (it should be plenty good, but maybe excessive?)
44 #
45 #
46 # #### Functions/classes not reviewed since they will be moved
47 # - DetectorData
48 # - mkSPIIRmulti
49 # - mkSPIIRhoftToSnrSlices
50 # - mkLLOIDSnrSlicesToTimeSliceChisq
51 # - mkLLOIDSnrChisqToTriggers
52 
53 ##
54 # @package lloidparts
55 #
56 # a module for building gstreamer graphs of the LLOID algorithm
57 #
58 
59 
60 #
61 # =============================================================================
62 #
63 # Preamble
64 #
65 # =============================================================================
66 #
67 
68 
69 import math
70 import numpy
71 
72 
73 import gi
74 gi.require_version('Gst', '1.0')
75 from gi.repository import GObject, Gst
76 GObject.threads_init()
77 Gst.init(None)
78 
79 
80 from gstlal import datasource
81 from gstlal import multirate_datasource
82 from gstlal import pipeparts
83 from gstlal import pipeio
84 from gstlal.stats.inspiral_lr import LnLRDensity
85 from lal import iterutils
86 
87 
88 #
89 # =============================================================================
90 #
91 # Pipeline Elements
92 #
93 # =============================================================================
94 #
95 
96 ##
97 # A "sum-of-squares" aggregator
98 #
99 # _Gstreamer graph describing this function:_
100 #
101 # @dot
102 # digraph G {
103 # rankdir="LR";
104 #
105 # // nodes
106 # node [shape=box, style=rounded];
107 #
108 # lal_adder
109 # lal_peak [URL="\ref pipeparts.mkpeak()", style=filled, color=grey, label="lal_peak\niff control_peak_samples > 0"];
110 # capsfilter [URL = "\ref pipeparts.mkcapsfilter()"];
111 # "mksegmentsrcgate()" [URL="\ref datasource.mksegmentsrcgate()"];
112 # tee [URL="\ref pipeparts.mktee()"];
113 # lal_checktimestamps [URL="\ref pipeparts.mkchecktimestamps()"];
114 #
115 # // connections
116 # "? sink 1" -> lal_adder;
117 # "? sink 2" -> lal_adder;
118 # "? sink N" -> lal_adder;
119 # lal_adder -> capsfilter;
120 # capsfilter -> lal_peak;
121 # lal_peak -> lal_checktimestamps;
122 # lal_checktimestamps -> tee;
123 # tee -> "? src";
124 # }
125 # @enddot
126 #
127 #
128 def mkcontrolsnksrc(pipeline, rate, verbose = False, suffix = None, control_peak_samples = None):
129  """!
130  This function implements a portion of a gstreamer graph to provide a
131  control signal for deciding when to reconstruct physical SNRS
132 
133  @param pipeline A reference to the gstreamer pipeline in which to add this graph
134  @param rate An integer representing the target sample rate of the resulting src
135  @param verbose Make verbose
136  @param suffix Log name for verbosity
137  @param control_peak_samples If nonzero, this would do peakfinding on the control signal with the window specified by this parameter. The peak finding would give a single sample of "on" state at the peak. This will cause far less CPU to be used if you only want to reconstruct SNR around the peak of the control signal.
138  """
139  #
140  # start with an adder and caps filter to select a sample rate
141  #
142 
143  snk = pipeparts.mkadder(pipeline, None)
144  src = pipeparts.mkcapsfilter(pipeline, snk, "audio/x-raw, rate=%d" % rate)
145 
146  #
147  # Add a peak finder on the control signal sample number
148  #
149 
150  if control_peak_samples > 0:
151  src = pipeparts.mkpeak(pipeline, src, control_peak_samples)
152 
153  #
154  # verbosity and a tee
155  #
156 
157  logname = suffix and "_%s" % suffix or ""
158  if verbose:
159  src = pipeparts.mkprogressreport(pipeline, src, "progress_sumsquares%s" % logname)
160  src = pipeparts.mkchecktimestamps(pipeline, src, "timestamps%s_sumsquares" % logname)
161  src = pipeparts.mktee(pipeline, src)
162 
163  #
164  # return the adder and tee
165  #
166 
167  return snk, src
168 
169 
170 ##
171 # _Gstreamer graph describing this function:_
172 #
173 # @dot
174 # digraph G {
175 # rankdir="LR";
176 #
177 # // nodes
178 # node [shape=box, style=rounded];
179 #
180 # lal_firbank [URL="\ref pipeparts.mkfirbank()"];
181 # lal_checktimestamps1 [URL="\ref pipeparts.mkchecktimestamps()"];
182 # lal_checktimestamps2 [URL="\ref pipeparts.mkchecktimestamps()"];
183 # queue [URL="\ref pipeparts.mkqueue()"];
184 # matrixmixer [URL="\ref pipeparts.mkmatrixmixer()", label="lal_matrixmixer\niff bank.mix_matrix", style=filled, color=grey];
185 #
186 # "? sink" -> lal_firbank;
187 # lal_firbank -> lal_checktimestamps1;
188 #
189 # // without control
190 #
191 # lal_checktimestamps1 -> queue [label="iff control_snk, control_src are None"];
192 # queue -> matrixmixer;
193 # matrixmixer -> lal_checktimestamps2;
194 # lal_checktimestamps2 -> "? src";
195 #
196 # // with control
197 #
198 # tee [URL="\ref pipeparts.mktee()"];
199 # queue2 [URL="\ref pipeparts.mkqueue()"];
200 # queue3 [URL="\ref pipeparts.mkqueue()"];
201 # queue4 [URL="\ref pipeparts.mkqueue()"];
202 # lal_checktimestamps3 [URL="\ref pipeparts.mkchecktimestamps()"];
203 # lal_checktimestamps4 [URL="\ref pipeparts.mkchecktimestamps()"];
204 # lal_checktimestamps5 [URL="\ref pipeparts.mkchecktimestamps()"];
205 # capsfilter [URL="\ref pipeparts.mkcapsfilter()"];
206 # gate [URL="\ref pipeparts.mkgate()"];
207 # "mkcontrolsnksrc()" [URL="\ref mkcontrolsnksrc()"];
208 # lal_sumsquares [URL="\ref pipeparts.mksumsquares()"];
209 # audioresample [URL="\ref pipeparts.mkresample()"];
210 #
211 #
212 # lal_checktimestamps1 -> tee [label="iff control_snk, control_src are not None"];
213 # tee -> lal_sumsquares -> queue2;
214 # queue2 -> lal_checktimestamps3;
215 # lal_checktimestamps3 -> audioresample;
216 # audioresample -> capsfilter;
217 # capsfilter -> lal_checktimestamps4;
218 # lal_checktimestamps4 -> "mkcontrolsnksrc()"
219 # "mkcontrolsnksrc()" -> queue3;
220 # queue3 -> gate;
221 # tee -> queue4 -> gate;
222 # gate -> lal_checktimestamps5;
223 # lal_checktimestamps5 -> "mksegmentsrcgate()";
224 # "mksegmentsrcgate()" -> matrixmixer;
225 #
226 # }
227 # @enddot
228 #
229 #
230 def mkLLOIDbranch(pipeline, src, bank, bank_fragment, control_input_tpl, gate_attack_length, gate_hold_length, block_duration, nxydump_segment = None, fir_stride = None, control_peak_time = None, reconstruction_segment_list = None):
231  """!
232  Make a single slice of one branch of the lloid graph, e.g. one instrument and one
233  template bank fragment. For details see: http://arxiv.org/abs/1107.2665
234 
235  Specifically this implements the filtering of multirate svd basis and
236  (conditional) resampling and reconstruction of the physical SNR
237 
238  @param pipeline The gstreamer pipeline in which to place this graph
239  @param src The source of data for this graph provided by a gstreamer element
240  @param bank The template bank class
241  @param bank_fragment The specific fragment (time slice) of the template bank in question
242  @param (control_snk, control_src) An optional tuple of the sink and source elements for a graph that will construct a control time series for the gate which aggregates the orthogonal snrs from each template slice. This is used to conditionally reconstruct the physical SNR of interesting times
243  @param gate_attack_length The attack length in samples for the lal_gate element that controls the reconstruction of physical SNRs
244  @param gate_hold_length The hold length in samples for the lal_gate element that controls the reconstruction of physical SNRs
245  @param block_duration The characteristic buffer size that is passed around, which is useful for constructing queues.
246  @param nxydump_segment Not used
247  @param fir_stride The target length of output buffers from lal_firbank in seconds. Directly effects latency. Making this short will force time-domain convolution. Otherwise FFT convolution will be done to save CPU cycles, but at higher latency.
248  @param control_peak_time The window over which to find peaks in the control signal. Shorter windows increase computational cost but probably also detection efficiency.
249  @param reconstruction_segment_list A segment list object that describes when the control signal should be on. This can be useful in e.g., only reconstructing physical SNRS around the time of injections, which can save an enormous amount of CPU time.
250  """
251  logname = "%s_%.2f.%.2f" % (bank.logname, bank_fragment.start, bank_fragment.end)
252 
253  control_snk, control_src = control_input_tpl
254 
255  #
256  # FIR filter bank. low frequency branches use time-domain
257  # convolution, high-frequency branches use FFT convolution with a
258  # block stride given by fir_stride.
259  #
260 
261  latency = -int(round(bank_fragment.start * bank_fragment.rate))
262  block_stride = int(fir_stride * bank_fragment.rate)
263 
264  # we figure an fft costs ~5 logN flops where N is duration + block
265  # stride. Time domain costs N * block_stride. So if block stride is
266  # less than about 5logN you might as well do time domain filtering
267  # FIXME This calculation should probably be made more rigorous
268  time_domain = 5 * numpy.log2((bank_fragment.end - bank_fragment.start) * bank_fragment.rate + block_stride) > block_stride
269 
270  src = pipeparts.mkfirbank(pipeline, src, latency = latency, fir_matrix = bank_fragment.orthogonal_template_bank, block_stride = block_stride, time_domain = time_domain)
271  src = pipeparts.mkchecktimestamps(pipeline, src, "timestamps_%s_after_firbank" % logname)
272  # uncomment reblock if you ever use really big ffts and want to cut them down a bit
273  #src = pipeparts.mkreblock(pipeline, src, block_duration = control_peak_time * gst.SECOND)
274  #src = pipeparts.mkchecktimestamps(pipeline, src, "timestamps_%s_after_firbank_reblock" % logname)
275  #src = pipeparts.mktee(pipeline, src) # comment-out the tee below if this is uncommented
276  #pipeparts.mknxydumpsink(pipeline, pipeparts.mkqueue(pipeline, src), "orthosnr_%s.dump" % logname, segment = nxydump_segment)
277 
278  #pipeparts.mkvideosink(pipeline, pipeparts.mkcapsfilter(pipeline, pipeparts.mkhistogramplot(pipeline, src), "video/x-raw-rgb, width=640, height=480, framerate=1/4"))
279  #pipeparts.mkogmvideosink(pipeline, pipeparts.mkcapsfilter(pipeline, pipeparts.mkchannelgram(pipeline, pipeparts.mkqueue(pipeline, src), plot_width = .125), "video/x-raw-rgb, width=640, height=480, framerate=64/1"), "orthosnr_channelgram_%s.ogv" % logname, verbose = True)
280 
281  #
282  # compute weighted sum-of-squares, feed to sum-of-squares
283  # aggregator
284  #
285 
286  if control_snk is not None and control_src is not None:
287  src = pipeparts.mktee(pipeline, src) # comment-out if the tee above is uncommented
288  elem = pipeparts.mkqueue(pipeline, pipeparts.mksumsquares(pipeline, src, weights = bank_fragment.sum_of_squares_weights), max_size_buffers = 0, max_size_bytes = 0, max_size_time = block_duration)
289  elem = pipeparts.mkchecktimestamps(pipeline, elem, "timestamps_%s_after_sumsquare" % logname)
290  elem = pipeparts.mkresample(pipeline, elem, quality = 9)
291  elem = pipeparts.mkchecktimestamps(pipeline, elem, "timestamps_%s_after_sumsquare_resampler" % logname)
292  elem.link(control_snk)
293 
294  #
295  # use sum-of-squares aggregate as gate control for
296  # orthogonal SNRs
297  #
298  # FIXME the queuing in this code is broken. enabling this
299  # causes lock-ups. there is latency in the construction of
300  # the composite detection statistic due to the need for
301  # resampling and because of the peak finding, therefore the
302  # source stream going into the gate needs to be queued
303  # until the composite detection statistic can catch up, but
304  # we don't know by how much (what we've got here doesn't
305  # work). there should not be a need to buffer the control
306  # stream at all, nor is there a need for the queuing to
307  # accomodate different latencies for different SNR slices,
308  # but we do require that all elements correctly modify
309  # segments events to reflect their latency and the actual
310  # time stamps of the data stream they will produce. it
311  # might be that not all elements are doing that correctly.
312  #
313  # FIXME we ignore the bank.gate_threshold parameter and
314  # just use 1e-100. this change was made when peak finding
315  # was put into the composite detector
316 
317  src = pipeparts.mkgate(
318  pipeline,
319  pipeparts.mkqueue(pipeline, src, max_size_buffers = 0, max_size_bytes = 0, max_size_time = 1 * int((2. * control_peak_time + float(abs(gate_attack_length) + abs(gate_hold_length)) / bank_fragment.rate) * Gst.SECOND)),
320  threshold = 1e-100,
321  attack_length = gate_attack_length,
322  hold_length = gate_hold_length,
323  control = control_src
324  )
325  src = pipeparts.mkchecktimestamps(pipeline, src, "timestamps_%s_after_gate" % logname)
326 
327  #
328  # optionally add a segment src and gate to only reconstruct around
329  # injections
330  #
331  # FIXME: set the names of these gates so their segments can be
332  # collected later? or else propagate this segment list into the
333  # output some other way.
334 
335  if reconstruction_segment_list is not None:
336  src = datasource.mksegmentsrcgate(pipeline, src, reconstruction_segment_list, invert_output = False)
337 
338  #
339  # reconstruct physical SNRs
340  #
341 
342  if bank_fragment.mix_matrix is not None:
343  src = pipeparts.mkmatrixmixer(pipeline, src, matrix = bank_fragment.mix_matrix)
344  src = pipeparts.mkchecktimestamps(pipeline, src, "timestamps_%s_after_matrixmixer" % logname)
345 
346  #
347  # done
348  #
349  # FIXME: find a way to use less memory without this hack
350 
351  del bank_fragment.orthogonal_template_bank
352  del bank_fragment.sum_of_squares_weights
353  del bank_fragment.mix_matrix
354 
355  return src
356 
357 
358 def mkLLOIDhoftToSnrSlices(pipeline, hoftdict, bank, control_snksrc, block_duration, verbose = False, logname = "", nxydump_segment = None, fir_stride = None, control_peak_time = None, snrslices = None, reconstruction_segment_list = None):
359  """!
360  Build the pipeline fragment that creates the SnrSlices associated with
361  different sample rates from hoft.
362 
363  @param reconstruction_segment_list A segment list object that describes when the control signal should be on. This can be useful in e.g., only reconstructing physical SNRS around the time of injections, which can save an enormous amount of CPU time.
364  """
365  #
366  # parameters
367  #
368 
369  rates = sorted(bank.get_rates())
370  output_rate = max(rates)
371 
372  # work out the upsample factors for the attack and hold calculations below
373  upsample_factor = dict((rate, rates[i+1] / rate) for i, rate in list(enumerate(rates))[:-1])
374  upsample_factor[output_rate] = 0
375 
376  autocorrelation_length = bank.autocorrelation_bank.shape[1]
377  assert autocorrelation_length % 2 == 1
378  autocorrelation_latency = -(autocorrelation_length - 1) / 2
379 
380  #
381  # loop over template bank slices
382  #
383 
384  branch_heads = dict((rate, set()) for rate in rates)
385  for bank_fragment in bank.bank_fragments:
386  # The attack and hold width has three parts
387  #
388  # 1) The audio resampler filter: 16 comes from the size of
389  # the audioresampler filter in samples for the next highest
390  # rate at quality 1. Note it must then be converted to the size
391  # at the current rate using the upsample_factor dictionary
392  # (which is 0 if you are at the max rate).
393  #
394  # 2) The chisq latency. You must have at least latency number
395  # of points before and after (at the maximum sample rate) to
396  # compute the chisq
397  #
398  # 3) A fudge factor to get the width of the peak. FIXME this
399  # is just set to 1/8th of a second
400  peak_half_width = upsample_factor[bank_fragment.rate] * 16 + int(math.ceil(-autocorrelation_latency * (float(bank_fragment.rate) / output_rate))) + int(math.ceil(bank_fragment.rate / 8.))
401  branch_heads[bank_fragment.rate].add(mkLLOIDbranch(
402  pipeline,
403  # FIXME: the size isn't ideal: the correct value
404  # depends on how much data is accumulated in the
405  # firbank element, and the value here is only
406  # approximate and not tied to the fir bank
407  # parameters so might not work if those change
408  pipeparts.mkqueue(pipeline, hoftdict[bank_fragment.rate], max_size_bytes = 0, max_size_buffers = 0, max_size_time = int((1 * fir_stride + int(math.ceil(bank.filter_length))) * Gst.SECOND)),
409  bank,
410  bank_fragment,
411  control_snksrc,
412  peak_half_width,
413  peak_half_width,
414  block_duration,
415  nxydump_segment = nxydump_segment,
416  fir_stride = fir_stride,
417  control_peak_time = control_peak_time,
418  reconstruction_segment_list = reconstruction_segment_list
419  ))
420 
421  #
422  # if the calling code has requested copies of the snr
423  # slices, sum together the highest sample rate streams and tee
424  # them off here. this needs to be done before constructing the
425  # adder network below in order to have access to this snr slice by
426  # itself. if we put this off until later it'll have all the other
427  # snrs added into it before we get a chance to tee it off
428  #
429 
430  if snrslices is not None:
431  rate, heads = output_rate, branch_heads[output_rate]
432  if len(heads) > 1:
433  #
434  # this sample rate has more than one snr stream.
435  # sum them together in an adder, which becomes the
436  # head of the stream at this sample rate
437  #
438 
439  branch_heads[rate] = pipeparts.mkadder(pipeline, (pipeparts.mkqueue(pipeline, head, max_size_bytes = 0, max_size_buffers = 0, max_size_time = block_duration) for head in heads))
440  else:
441  #
442  # this sample rate has only one stream. it's the
443  # head of the stream at this sample rate
444  #
445 
446  branch_heads[rate], = heads
447  branch_heads[rate] = pipeparts.mktee(pipeline, branch_heads[rate])
448  snrslices[rate] = pipeparts.mktogglecomplex(pipeline, branch_heads[rate])
449 
450  #
451  # the code below expects an interable of elements
452  #
453 
454  branch_heads[rate] = set([branch_heads[rate]])
455 
456  #
457  # sum the snr streams
458  #
459 
460  if True: # FIXME: make conditional on time-slice \chi^{2}
461  next_rate = dict(zip(rates, rates[1:]))
462  else:
463  next_rate = dict((rate, output_rate) for rate in rates if rate != output_rate)
464 
465  for rate, heads in sorted(branch_heads.items()):
466  if len(heads) > 1:
467  #
468  # this sample rate has more than one snr stream.
469  # sum them together in an adder, which becomes the
470  # head of the stream at this sample rate
471  #
472 
473  branch_heads[rate] = pipeparts.mkadder(pipeline, heads)
474  branch_heads[rate] = pipeparts.mkchecktimestamps(pipeline, branch_heads[rate], "timestamps_%s_after_%d_snr_adder" % (logname, rate))
475  else:
476  #
477  # this sample rate has only one stream. it's the
478  # head of the stream at this sample rate
479  #
480 
481  branch_heads[rate], = heads
482 
483  #
484  # resample if needed
485  #
486 
487  if rate in next_rate:
488  # NOTE: quality = 1 requires that the template
489  # slices are padded such that the Nyquist frequency
490  # is 1.5 times the highest frequency of the time
491  # slice. NOTE: the adder (that comes downstream of
492  # this) isn't quite smart enough to negotiate a
493  # common format among its upstream peers so the
494  # capsfilter is still required.
495  # NOTE uncomment this line to restore audioresample for
496  # upsampling
497  #branch_heads[rate] = pipeparts.mkcapsfilter(pipeline, pipeparts.mkresample(pipeline, branch_heads[rate], quality = 1), "audio/x-raw, rate=%d" % next_rate[rate])
498  branch_heads[rate] = pipeparts.mkcapsfilter(pipeline, pipeparts.mkinterpolator(pipeline, branch_heads[rate]), "audio/x-raw, rate=%d" % next_rate[rate])
499  branch_heads[rate] = pipeparts.mkchecktimestamps(pipeline, branch_heads[rate], "timestamps_%s_after_%d_to_%d_snr_resampler" % (logname, rate, next_rate[rate]))
500 
501  #
502  # if the calling code has requested copies of the snr
503  # slices, tee that off here. remember that we've already
504  # got the highest sample rate slice from above
505  #
506 
507  if snrslices is not None and rate != output_rate:
508  branch_heads[rate] = pipeparts.mktee(pipeline, branch_heads[rate])
509  snrslices[rate] = pipeparts.mktogglecomplex(pipeline, branch_heads[rate])
510 
511  #
512  # chain to next adder if this isn't the final answer
513  #
514 
515  if rate in next_rate:
516  branch_heads[next_rate[rate]].add(branch_heads.pop(rate))
517 
518  #
519  # done
520  #
521 
522  snr, = branch_heads.values() # make sure we've summed down to one stream
523  return pipeparts.mktogglecomplex(pipeline, snr)
524 
525 
526 def mkLLOIDSnrSlicesToTimeSliceChisq(pipeline, branch_heads, bank, block_duration):
527  """!
528  Build pipeline fragment that computes the TimeSliceChisq from SnrSlices.
529  """
530  #
531  # parameters
532  #
533 
534  rates = sorted(bank.get_rates())
535 
536  #
537  # compute the chifacs for each rate, store in ascending order in rate
538  #
539 
540  chifacsdict = dict((rate, []) for rate in rates)
541  for bank_fragment in bank.bank_fragments:
542  chifacsdict[bank_fragment.rate].append(bank_fragment.chifacs)
543  chifacs = []
544  for rate, facs in sorted(chifacsdict.items()):
545  chifacs.append(facs[0][0::2])
546  chifacs[-1] += facs[0][1::2]
547  for fac in facs[1:]:
548  chifacs[-1] += fac[0::2]
549  chifacs[-1] += fac[1::2]
550  chifacs[-1] /= 2.
551 
552  #
553  # create timeslicechisq element and add chifacs as a property
554  #
555 
556  chisq = Gst.ElementFactory.make("lal_timeslicechisq", None)
557  pipeline.add(chisq)
558 
559  #
560  # link the snrslices to the timeslicechisq element in ascending order in rate
561  #
562 
563  for rate, snrslice in sorted(branch_heads.items()):
564  pipeparts.mkqueue(pipeline, snrslice, max_size_bytes = 0, max_size_buffers = 0, max_size_time = block_duration).link(chisq)
565 
566  #
567  # set chifacs-matrix property, needs to be done after snrslices are linked in
568  #
569 
570  chisq.set_property("chifacs-matrix", chifacs)
571 
572  return pipeparts.mkqueue(pipeline, chisq, max_size_bytes = 0, max_size_buffers = 0, max_size_time = block_duration)
573 
574 
575 def mkLLOIDSnrChisqToTriggers(pipeline, snr, chisq, bank, verbose = False, nxydump_segment = None, logname = ""):
576  """!
577  Build pipeline fragment that converts single detector SNR and Chisq
578  into triggers.
579  """
580  #
581  # trigger generator and progress report
582  #
583 
584  head = pipeparts.mktriggergen(pipeline, snr, chisq, template_bank_filename = bank.template_bank_filename, snr_threshold = bank.snr_threshold, sigmasq = bank.sigmasq)
585  # FIXME: add ability to choose this
586  # "lal_blcbctriggergen", {"bank-filename": bank.template_bank_filename, "snr-thresh": bank.snr_threshold, "sigmasq": bank.sigmasq}
587  if verbose:
588  head = pipeparts.mkprogressreport(pipeline, head, "progress_xml_%s" % logname)
589 
590  #
591  # done
592  #
593 
594  return head
595 
596 
597 #
598 # many instruments, many template banks
599 #
600 
601 
602 def mkLLOIDmulti(pipeline, detectors, banks, psd, psd_fft_length = 32, ht_gate_threshold = float("inf"), veto_segments = None, verbose = False, nxydump_segment = None, chisq_type = 'autochisq', track_psd = False, fir_stride = 16, control_peak_time = 2, block_duration = Gst.SECOND, reconstruction_segment_list = None, track_latency = False):
603  """!
604  The multiple instrument, multiple bank LLOID algorithm
605  """
606 
607  #
608  # check for unrecognized chisq_types, non-unique bank IDs
609  #
610 
611  if chisq_type not in ['autochisq', 'timeslicechisq']:
612  raise ValueError("chisq_type must be either 'autochisq' or 'timeslicechisq', given %s" % chisq_type)
613  if any(tuple(iterutils.nonuniq(bank.bank_id for bank in banklist)) for banklist in banks.values()):
614  raise ValueError("bank IDs are not unique: %s" % "; ".join("for %s: %s" % (instrument, iterutils.nonuniq(bank.bank_id for bank in banklist)) for instrument, banklist in banks.items()))
615 
616  #
617  # construct dictionaries of whitened, conditioned, down-sampled
618  # h(t) streams. NOTE: we assume all banks for each instrument
619  # were generated with the same processed PSD for that instrument
620  # and just extract the first without checking that this assumption
621  # is correct
622  #
623 
624  assert psd_fft_length % 4 == 0, "psd_fft_length (= %g) must be multiple of 4" % psd_fft_length
625  hoftdicts = {}
626  for instrument in detectors.channel_dict:
627  src, statevector, dqvector = datasource.mkbasicsrc(pipeline, detectors, instrument, verbose)
628  if track_latency:
629  src = pipeparts.mklatency(pipeline, src, name = "%s_datasource_latency" % instrument, silent = True)
630  hoftdicts[instrument] = multirate_datasource.mkwhitened_multirate_src(
631  pipeline,
632  src = src,
633  rates = set(rate for bank in banks[instrument] for rate in bank.get_rates()),
634  instrument = instrument,
635  psd = psd[instrument],
636  psd_fft_length = psd_fft_length,
637  ht_gate_threshold = ht_gate_threshold,
638  veto_segments = veto_segments[instrument] if veto_segments is not None else None,
639  nxydump_segment = nxydump_segment,
640  track_psd = track_psd,
641  width = 32,
642  statevector = statevector,
643  dqvector = dqvector,
644  fir_whiten_reference_psd = banks[instrument][0].processed_psd,
645  track_latency = track_latency,
646  )
647 
648  #
649  # build gate control branches
650  #
651 
652  if control_peak_time > 0:
653  control_branch = {}
654  for instrument, bank in [(instrument, bank) for instrument, banklist in banks.items() for bank in banklist]:
655  suffix = "%s%s" % (instrument, (bank.logname and "_%s" % bank.logname or ""))
656  if instrument != "H2":
657  control_branch[(instrument, bank.bank_id)] = mkcontrolsnksrc(pipeline, max(bank.get_rates()), verbose = verbose, suffix = suffix, control_peak_samples = control_peak_time * max(bank.get_rates()))
658  #pipeparts.mknxydumpsink(pipeline, pipeparts.mkqueue(pipeline, control_branch[(instrument, bank.bank_id)][1]), "control_%s.dump" % suffix, segment = nxydump_segment)
659  else:
660  control_branch = None
661 
662  #
663  # construct trigger generators
664  #
665 
666  itacac_dict = {}
667  checked_ifo = []
668  for i, (instrument, bank) in enumerate([(instrument, bank) for instrument, banklist in banks.items() for bank in banklist]):
669  suffix = "%s%s" % (instrument, (bank.logname and "_%s" % bank.logname or ""))
670  if control_branch is not None:
671  if instrument != "H2":
672  control_snksrc = control_branch[(instrument, bank.bank_id)]
673  else:
674  control_snksrc = (None, control_branch[("H1", bank.bank_id)][1])
675  else:
676  control_snksrc = (None, None)
677  if chisq_type == 'timeslicechisq':
678  snrslices = {}
679  else:
680  snrslices = None
682  pipeline,
683  hoftdicts[instrument],
684  bank,
685  control_snksrc,
686  block_duration,
687  verbose = verbose,
688  logname = suffix,
689  nxydump_segment = nxydump_segment,
690  control_peak_time = control_peak_time,
691  fir_stride = fir_stride,
692  snrslices = snrslices,
693  reconstruction_segment_list = reconstruction_segment_list
694  )
695  if instrument not in checked_ifo:
696  if track_latency:
697  snr = pipeparts.mklatency(pipeline, snr, name = "%s_snrSlice_latency" % instrument, silent = True)
698  checked_ifo.append(instrument)
699  snr = pipeparts.mkchecktimestamps(pipeline, snr, "timestamps_%s_snr" % suffix)
700  # uncomment this tee if the diagnostic sinks below are
701  # needed
702  #snr = pipeparts.mktee(pipeline, snr)
703  if chisq_type == 'autochisq':
704  # 4 is about the lowest we can do stably for
705  # coincidence online...
706  # FIXME get this to work some day
707  #nsamps_window = max(bank.get_rates()) / 4
708  nsamps_window = 1 * max(bank.get_rates())
709  if bank.bank_id not in itacac_dict:
710  itacac_dict[bank.bank_id] = pipeparts.mkgeneric(pipeline, None, "lal_itacac")
711 
712  head = itacac_dict[bank.bank_id]
713  pad = head.get_request_pad("sink%d" % len(head.sinkpads))
714  if instrument == 'H1' or instrument == 'L1':
715  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)]:
716  pad.set_property(prop, val)
717  else:
718  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)]:
719  pad.set_property(prop, val)
720  else:
721  raise NotImplementedError("Currently only 'autochisq' is supported")
722  # replace this line with the commented-out line below if diagnostic sink is needed
723  snr.srcpads[0].link(pad)
724  #snr.get_request_pad("src_%d" % len(snr.srcpads)).link(pad)
725  # FIXME: find a way to use less memory without this hack
726  del bank.autocorrelation_bank
727  #pipeparts.mknxydumpsink(pipeline, pipeparts.mktogglecomplex(pipeline, pipeparts.mkqueue(pipeline, snr)), "snr_%s.dump" % suffix, segment = nxydump_segment)
728  #pipeparts.mkogmvideosink(pipeline, pipeparts.mkcapsfilter(pipeline, pipeparts.mkchannelgram(pipeline, pipeparts.mkqueue(pipeline, snr), plot_width = .125), "video/x-raw-rgb, width=640, height=480, framerate=64/1"), "snr_channelgram_%s.ogv" % suffix, audiosrc = pipeparts.mkaudioamplify(pipeline, pipeparts.mkqueue(pipeline, hoftdict[max(bank.get_rates())], max_size_time = 2 * int(math.ceil(bank.filter_length)) * gst.SECOND), 0.125), verbose = True)
729 
730  #
731  # done
732  #
733 
734  assert any(itacac_dict.values())
735  if track_latency:
736  itacac_dict[list(itacac_dict.keys())[0]] = pipeparts.mklatency(pipeline, itacac_dict[list(itacac_dict.keys())[0]], name = "all_itacac_latency", silent = True)
737  if verbose:
738  for bank_id, head in itacac_dict.items():
739  # FIXME Not sure why we need a queue here, but without
740  # the queue one injection job in ~5000 hangs
741  itacac_dict[bank_id] = pipeparts.mkprogressreport(pipeline, pipeparts.mkqueue(pipeline, head, max_size_buffers = 10, max_size_bytes = 0, max_size_time = 0), "progress_xml_bank_%s" % bank_id)
742  return itacac_dict
def mkLLOIDbranch
Gstreamer graph describing this function:
Definition: lloidparts.py:230
def mkcontrolsnksrc
A &quot;sum-of-squares&quot; aggregator.
Definition: lloidparts.py:128
def mkLLOIDmulti
The multiple instrument, multiple bank LLOID algorithm.
Definition: lloidparts.py:602
def mkLLOIDSnrChisqToTriggers
Build pipeline fragment that converts single detector SNR and Chisq into triggers.
Definition: lloidparts.py:575
def mkLLOIDhoftToSnrSlices
Build the pipeline fragment that creates the SnrSlices associated with different sample rates from ho...
Definition: lloidparts.py:358
def mkLLOIDSnrSlicesToTimeSliceChisq
Build pipeline fragment that computes the TimeSliceChisq from SnrSlices.
Definition: lloidparts.py:526