gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
cbc_template_fir.py
1 # Copyright (C) 2009 LIGO Scientific Collaboration
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 __doc__= """
19 The python module to implement SVD decomposed FIR filtering
20 
21 **Review Status**
22 
23 STATUS: reviewed with actions
24 
25 +-----------------------------------------------------+------------------------------------------+------------+
26 | Names | Hash | Date |
27 +=====================================================+==========================================+============+
28 | Florent, Sathya, Duncan Me, Jolien, Kipp, Chad | 7536db9d496be9a014559f4e273e1e856047bf71 | 2014-04-30 |
29 +-----------------------------------------------------+------------------------------------------+------------+
30 | Florent, Surabhi, Tjonnie, Kent, Jolien, Kipp, Chad | d84a8446a056ce92625b042148c2d9ef9cd8bb0d | 2015-05-12 |
31 +-----------------------------------------------------+------------------------------------------+------------+
32 
33 **Action items**
34 
35 - Consider changing the order of interpolation and smoothing the PSD
36 - move sigma squared calculation somewhere and get them updated dynamically
37 - possibly use ROM stuff, possibly use low-order polynomial approx computed on the fly from the template as it's generated
38 - remove lefttukeywindow()
39 - use template_bank_row.coa_phase == 0. in SimInspiralFD() call, make sure itac adjusts the phase it assigns to triggers from the template coa_phase
40 - change "assumes fhigh" to "asserts fhigh"
41 - move assert epoch_time into condition_imr_waveform(), should be assert -len(data) <= epoch_time * sample_rate < 0
42 """
43 
44 
45 #
46 # =============================================================================
47 #
48 # Preamble
49 #
50 # =============================================================================
51 #
52 
53 
54 import bisect
55 import cmath
56 import math
57 import numpy
58 import sys
59 import os
60 
61 
62 import lal
63 from lal import LIGOTimeGPS
64 import lalsimulation as lalsim
65 
66 
67 from gstlal import spawaveform
68 
69 
70 from gstlal import chirptime
71 from gstlal import reference_psd
72 from gstlal import templates
73 
74 try: ### optional dependency for movingmedian
75  import pandas
76 except ImportError:
77  pandas = None
78 
79 
80 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>, Chad Hanna <chad.hanna@ligo.org>, Drew Keppel <drew.keppel@ligo.org>"
81 __version__ = "FIXME"
82 __date__ = "FIXME"
83 
84 # a macro to switch between a conventional whitener and a fir whitener below
85 try:
86  if int(os.environ["GSTLAL_FIR_WHITEN"]):
87  FIR_WHITENER = True
88  else:
89  FIR_WHITENER = False
90 except KeyError:
91  print("You must set the environment variable GSTLAL_FIR_WHITEN to either 0 or 1. 1 enables causal whitening. 0 is the traditional acausal whitening filter", file=sys.stderr)
92  raise
93 
94 #
95 # =============================================================================
96 #
97 # Inspiral Template Stuff
98 #
99 # =============================================================================
100 #
101 
102 def create_FIR_whitener_kernel(length, duration, sample_rate, psd):
103  assert psd
104  #
105  # Add another COMPLEX16TimeSeries and COMPLEX16FrequencySeries for kernel's FFT (Leo)
106  #
107 
108  # Add another FFT plan for kernel FFT (Leo)
109  fwdplan_kernel = lal.CreateForwardCOMPLEX16FFTPlan(length, 1)
110  kernel_tseries = lal.CreateCOMPLEX16TimeSeries(
111  name = "timeseries of whitening kernel",
112  epoch = LIGOTimeGPS(0.),
113  f0 = 0.,
114  deltaT = 1.0 / sample_rate,
115  length = length,
116  sampleUnits = lal.Unit("strain")
117  )
118  kernel_fseries = lal.CreateCOMPLEX16FrequencySeries(
119  name = "freqseries of whitening kernel",
120  epoch = LIGOTimeGPS(0),
121  f0 = 0.0,
122  deltaF = 1.0 / duration,
123  length = length,
124  sampleUnits = lal.Unit("strain s")
125  )
126 
127  #
128  # Obtain a kernel of zero-latency whitening filter and
129  # adjust its length (Leo)
130  #
131 
132  psd_fir_kernel = reference_psd.PSDFirKernel()
133  (kernel, latency, fir_rate) = psd_fir_kernel.psd_to_linear_phase_whitening_fir_kernel(psd, nyquist = sample_rate / 2.0)
134  (kernel, theta) = psd_fir_kernel.linear_phase_fir_kernel_to_minimum_phase_whitening_fir_kernel(kernel, fir_rate)
135  kernel = kernel[-1::-1]
136  # FIXME this is off by one sample, but shouldn't be. Look at the miminum phase function
137  # assert len(kernel) == length
138  if len(kernel) < length:
139  kernel = numpy.append(kernel, numpy.zeros(length - len(kernel)))
140  else:
141  kernel = kernel[:length]
142 
143  kernel_tseries.data.data = kernel
144 
145  #
146  # FFT of the kernel
147  #
148 
149  lal.COMPLEX16TimeFreqFFT(kernel_fseries, kernel_tseries, fwdplan_kernel) #FIXME
150 
151  return kernel_fseries
152 
153 def taperzero_fseries(fseries, minfs = (35.0, 40.0), maxfs = (1800., 2048.)):
154  """
155  A function to taper the psd to infinity for given min/max frequencies
156 
157  :psd: A real8 frequency series containing the psd
158  :newdeltaF (Hz): The target delta F to interpolate to
159  :minfs (Hz): The frequency boundaries over which to taper the spectrum to infinity. i.e., frequencies below the first item in the tuple will have an infinite spectrum, the second item in the tuple will not be changed. A taper from 0 to infinity is applied in between. The PSD is also tapered from 0.85 * Nyquist to Nyquist.
160  :smoothing_frequency (Hz): The target frequency resolution after smoothing. Lines with bandwidths << smoothing_frequency are removed via a median calculation. Remaining features will be blurred out to this resolution.
161 
162  :returns: A tapered psd
163 
164  """
165 
166  #
167  # store the psd horizon before tapering
168  #
169 
170  data = fseries.data.data
171  norm_before = numpy.dot(data.conj(), data).real
172 
173  #
174  # taper to infinity to turn this psd into an effective band pass filter
175  #
176 
177  deltaF = fseries.deltaF
178  kmin = int(minfs[0] / deltaF)
179  kmax = int(minfs[1] / deltaF)
180  data[(len(data)//2 + 1) - kmin + 1:(len(data)//2 + 1) + kmin] = 0.
181  data[(len(data)//2 + 1) + kmin:(len(data)//2 + 1) + kmax] *= numpy.sin(numpy.arange(kmax-kmin) / (kmax-kmin-1.) * numpy.pi / 2.0)**4
182  data[(len(data)//2 + 1) - kmax:(len(data)//2 + 1) - kmin] *= numpy.cos(numpy.arange(kmax-kmin) / (kmax-kmin-1.) * numpy.pi / 2.0)**4
183 
184  kmin = int(maxfs[0] / deltaF) - 1
185  kmax = int(maxfs[1] / deltaF) - 1
186  data[(len(data)//2 + 1) + kmax:] = data[:-(len(data)//2 + 1) - kmax] = 0.
187  data[(len(data)//2 + 1) + kmin:(len(data)//2 + 1) + kmax] *= numpy.cos(numpy.arange(kmax-kmin) / (kmax-kmin-1.) * numpy.pi / 2.0)**4
188  data[(len(data)//2 + 1) - kmax:(len(data)//2 + 1) - kmin] *= numpy.sin(numpy.arange(kmax-kmin) / (kmax-kmin-1.) * numpy.pi / 2.0)**4
189 
190  #
191  # renormalize after tapering
192  #
193 
194  fseries.data.data = data * math.sqrt(norm_before / numpy.dot(data.conj(), data).real)
195 
196  #
197  # done
198  #
199 
200  return fseries
201 
202 
203 def tukeywindow(data, samps = 200.):
204  assert (len(data) >= 2 * samps) # make sure that the user is requesting something sane
205  tp = float(samps) / len(data)
206  return lal.CreateTukeyREAL8Window(len(data), tp).data.data
207 
208 
209 def generate_template(template_bank_row, approximant, sample_rate, duration, f_low, f_high, amporder = 0, order = 7, fwdplan = None, fworkspace = None):
210  """
211  Generate a single frequency-domain template, which
212  1. is band-limited between f_low and f_high,
213  2. has an IFFT which is duration seconds long and
214  3. has an IFFT which is sampled at sample_rate Hz
215  """
216  if approximant not in templates.gstlal_approximants:
217  raise ValueError("Unsupported approximant given %s" % approximant)
218  assert f_high <= sample_rate // 2
219 
220  # FIXME use hcross somday?
221  # We don't here because it is not guaranteed to be orthogonal
222  # and we add orthogonal phase later
223 
224  parameters = {}
225  parameters['m1'] = lal.MSUN_SI * template_bank_row.mass1
226  parameters['m2'] = lal.MSUN_SI * template_bank_row.mass2
227  parameters['S1x'] = template_bank_row.spin1x
228  parameters['S1y'] = template_bank_row.spin1y
229  parameters['S1z'] = template_bank_row.spin1z
230  parameters['S2x'] = template_bank_row.spin2x
231  parameters['S2y'] = template_bank_row.spin2y
232  parameters['S2z'] = template_bank_row.spin2z
233  parameters['distance'] = 1.e6 * lal.PC_SI
234  parameters['inclination'] = 0.
235  parameters['phiRef'] = 0.
236  parameters['longAscNodes'] = 0.
237  parameters['eccentricity'] = 0.
238  parameters['meanPerAno'] = 0.
239  parameters['deltaF'] = 1.0 / duration
240  parameters['f_min'] = f_low
241  parameters['f_max'] = f_high
242  parameters['f_ref'] = 0.
243  parameters['LALparams'] = None
244  parameters['approximant'] = lalsim.GetApproximantFromString(str(approximant))
245 
246  hplus, hcross = lalsim.SimInspiralFD(**parameters)
247  assert len(hplus.data.data) == int(round(f_high * duration)) +1
248  # pad the output vector if the sample rate was higher than the
249  # requested final frequency
250  if f_high < sample_rate / 2:
251  fseries = lal.CreateCOMPLEX16FrequencySeries(
252  name = hplus.name,
253  epoch = hplus.epoch,
254  f0 = hplus.f0,
255  deltaF = hplus.deltaF,
256  length = int(round(sample_rate * duration))//2 +1,
257  sampleUnits = hplus.sampleUnits
258  )
259  fseries.data.data = numpy.zeros(fseries.data.length)
260  fseries.data.data[:hplus.data.length] = hplus.data.data[:]
261  hplus = fseries
262  return hplus
263 
264 
265 def condition_imr_template(approximant, data, epoch_time, sample_rate_max, max_ringtime):
266  assert -len(data) / sample_rate_max <= epoch_time < 0.0, "Epoch returned follows a different convention"
267  # find the index for the peak sample using the epoch returned by
268  # the waveform generator
269  epoch_index = -int(epoch_time*sample_rate_max) - 1
270  # align the peaks according to an overestimate of max rinddown
271  # time for a given split bank
272  target_index = len(data)-1 - int(sample_rate_max * max_ringtime)
273  # rotate phase so that sample with peak amplitude is real
274  phase = numpy.arctan2(data[epoch_index].imag, data[epoch_index].real)
275  data *= numpy.exp(-1.j * phase)
276  data = numpy.roll(data, target_index-epoch_index)
277  # re-taper the ends of the waveform that got cyclically permuted
278  # around the ring
279  tukey_beta = 2. * abs(target_index - epoch_index) / float(len(data))
280  assert 0. <= tukey_beta <= 1., "waveform got rolled WAY too much"
281  data *= lal.CreateTukeyREAL8Window(len(data), tukey_beta).data.data
282  # done
283  return data, target_index
284 
285 
286 def condition_ear_warn_template(approximant, data, epoch_time, sample_rate_max, max_shift_time):
287  assert -len(data) / sample_rate_max <= epoch_time < 0.0, "Epoch returned follows a different convention"
288  # find the index for the peak sample using the epoch returned by
289  # the waveform generator
290  epoch_index = -int(epoch_time*sample_rate_max) - 1
291  # move the early warning waveforms forward according to the waveform
292  # that spends the longest in going from fhigh to ISCO in a given
293  # split bank. This effectively ends some waveforms at f < fhigh
294  target_index = int(sample_rate_max * max_shift_time)
295  data = numpy.roll(data, target_index-epoch_index)
296  return data, target_index
297 
298 
299 def compute_autocorrelation_mask( autocorrelation ):
300  '''
301  Given an autocorrelation time series, estimate the optimal
302  autocorrelation length to use and return a matrix which masks
303  out the unwanted elements. FIXME TODO for now just returns
304  ones
305  '''
306  return numpy.ones( autocorrelation.shape, dtype="int" )
307 
308 
309 def movingmedian(interval, window_size):
310  if pandas: ### use pandas implementation if available
311  tmp = numpy.copy(interval)
312  if pandas.__version__ >= '0.18.1':
313  tmp[window_size : len(interval) - window_size] = numpy.array(pandas.Series(tmp).rolling(2 * window_size).median()[2 * window_size - 1 : -1])
314  else:
315  tmp[window_size : len(interval) - window_size] = pandas.rolling_median(tmp, 2 * window_size)[2 * window_size - 1 : -1]
316  else:
317  interval = list(interval)
318  tmp = numpy.copy(interval)
319  A = None
320  As = None
321  prev = None
322  for i in range(window_size, len(interval)-window_size):
323  if A is None:
324  A = interval[i-window_size:i+window_size]
325  ix = numpy.argsort(A)
326  As = list(numpy.array(A)[ix])
327  else:
328  newdata = interval[i+window_size-1]
329  A = A + [newdata]
330  bisect.insort(As, newdata)
331  if len(As) % 2:
332  tmp[i] = As[len(As)//2]
333  else:
334  tmp[i] = (As[len(As)//2-1] + As[len(As)//2]) / 2.
335  prev = A.pop(0)
336  del As[bisect.bisect_left(As, prev)]
337  return tmp
338 
339 
340 def movingaverage(interval, window_size):
341  window = lal.CreateTukeyREAL8Window(window_size, 0.5).data.data
342  return numpy.convolve(interval, window, 'same')
343 
344 
345 def condition_psd(psd, newdeltaF, minfs = (35.0, 40.0), maxfs = (1800., 2048.), smoothing_frequency = 4.):
346  """
347  A function to condition the psd that will be used to whiten waveforms
348 
349  @param psd A real8 frequency series containing the psd
350  @param newdeltaF (Hz) The target delta F to interpolate to
351  @param minfs (Hz) The frequency boundaries over which to taper the spectrum to infinity. i.e., frequencies below the first item in the tuple will have an infinite spectrum, the second item in the tuple will not be changed. A taper from 0 to infinity is applied in between. The PSD is also tapered from 0.85 * Nyquist to Nyquist.
352  @param smoothing_frequency (Hz) The target frequency resolution after smoothing. Lines with bandwidths << smoothing_frequency are removed via a median calculation. Remaining features will be blurred out to this resolution.
353 
354  returns a conditioned psd
355  """
356 
357  #
358  # store the psd horizon before conditioning
359  #
360 
361  horizon_distance = reference_psd.HorizonDistance(minfs[1], maxfs[0], psd.deltaF, 1.4, 1.4)
362  horizon_before = horizon_distance(psd, 8.0)[0]
363 
364  #
365  # interpolate to new \Delta f
366  #
367 
368  psd = reference_psd.interpolate_psd(psd, newdeltaF)
369 
370  #
371  # Smooth the psd
372  #
373 
374  psddata = psd.data.data
375  avgwindow = int(smoothing_frequency / newdeltaF)
376  psddata = movingmedian(psddata, avgwindow)
377  psddata = movingaverage(psddata, avgwindow)
378  psd.data.data = psddata
379 
380  #
381  # Tapering psd in either side up to infinity if a frequency-domain whitener is used, returns a psd without tapering otherwise.
382  # For a time-domain whitener, the tapering is effectively done as a part of deriving a frequency series of the FIR-whitner kernel
383  #
384  if not FIR_WHITENER:
385  #
386  # Taper to infinity to turn this psd into an effective band pass filter
387  #
388 
389  psddata = psd.data.data
390  kmin = int(minfs[0] / newdeltaF)
391  kmax = int(minfs[1] / newdeltaF)
392  psddata[:kmin] = float('Inf')
393  psddata[kmin:kmax] /= numpy.sin(numpy.arange(kmax-kmin) / (kmax-kmin-1.) * numpy.pi / 2.0)**4
394 
395  kmin = int(maxfs[0] / newdeltaF)
396  kmax = int(maxfs[1] / newdeltaF)
397  psddata[kmax:] = float('Inf')
398  psddata[kmin:kmax] /= numpy.cos(numpy.arange(kmax-kmin) / (kmax-kmin-1.) * numpy.pi / 2.0)**4
399 
400  psd.data.data = psddata
401 
402  #
403  # compute the psd horizon after conditioning and renormalize
404  #
405 
406  horizon_after = horizon_distance(psd, 8.0)[0]
407 
408  psddata = psd.data.data
409  psd.data.data = psddata * (horizon_after / horizon_before)**2
410 
411  #
412  # done
413  #
414 
415  return psd
416 
417 
418 class templates_workspace(object):
419  def __init__(self, template_table, approximant, psd, f_low, time_slices, autocorrelation_length = None, fhigh = None):
420  self.template_table = template_table
421  self.approximant = approximant
422  self.f_low = f_low
423  self.time_slices = time_slices
424  self.autocorrelation_length = autocorrelation_length
425  self.fhigh = fhigh
426  self.sample_rate_max = max(time_slices["rate"])
427  self.duration = max(time_slices["end"])
428  self.length_max = int(round(self.duration * self.sample_rate_max))
429 
430  if self.fhigh is None:
431  self.fhigh = self.sample_rate_max / 2.
432  # Some input checking to avoid incomprehensible error messages
433  if not self.template_table:
434  raise ValueError("template list is empty")
435  if self.f_low < 0.:
436  raise ValueError("f_low must be >= 0. %s" % repr(self.f_low))
437 
438  # working f_low to actually use for generating the waveform. pick
439  # template with lowest chirp mass, compute its duration starting
440  # from f_low; the extra time is 10% of this plus 3 cycles (3 /
441  # f_low); invert to obtain f_low corresponding to desired padding.
442  # NOTE: because SimInspiralChirpStartFrequencyBound() does not
443  # account for spin, we set the spins to 0 in the call to
444  # SimInspiralChirpTimeBound() regardless of the component's spins.
445  template = min(self.template_table, key = lambda row: row.mchirp)
446  tchirp = lalsim.SimInspiralChirpTimeBound(self.f_low, template.mass1 * lal.MSUN_SI, template.mass2 * lal.MSUN_SI, 0., 0.)
447  self.working_f_low = lalsim.SimInspiralChirpStartFrequencyBound(1.1 * tchirp + 3. / self.f_low, template.mass1 * lal.MSUN_SI, template.mass2 * lal.MSUN_SI)
448 
449  # Add duration of PSD to template length for PSD ringing, round up to power of 2 count of samples
450  self.working_length = templates.ceil_pow_2(self.length_max + round(1./psd.deltaF * self.sample_rate_max))
451  self.working_duration = float(self.working_length) / self.sample_rate_max
452 
453  if psd is not None:
454  # Smooth the PSD and interpolate to required resolution
455  self.psd = condition_psd(psd, 1.0 / self.working_duration, minfs = (self.working_f_low, self.f_low), maxfs = (self.sample_rate_max / 2.0 * 0.90, self.sample_rate_max / 2.0))
456 
457  if FIR_WHITENER:
458  # Compute a frequency response of the time-domain whitening kernel and effectively taper the psd by zero-ing some elements for a FIR kernel
459  self.kernel_fseries = taperzero_fseries(create_FIR_whitener_kernel(self.working_length, self.working_duration, self.sample_rate_max, self.psd),\
460  minfs = (self.working_f_low, self.f_low),\
461  maxfs = (self.sample_rate_max / 2.0 * 0.90, self.sample_rate_max / 2.0)\
462  )
463 
464  self.revplan = lal.CreateReverseCOMPLEX16FFTPlan(self.working_length, 1)
465  self.fwdplan = lal.CreateForwardREAL8FFTPlan(self.working_length, 1)
466  self.tseries = lal.CreateCOMPLEX16TimeSeries(
467  name = "timeseries",
468  epoch = LIGOTimeGPS(0.),
469  f0 = 0.,
470  deltaT = 1.0 / self.sample_rate_max,
471  length = self.working_length,
472  sampleUnits = lal.Unit("strain")
473  )
474  self.fworkspace = lal.CreateCOMPLEX16FrequencySeries(
475  name = "template",
476  epoch = LIGOTimeGPS(0),
477  f0 = 0.0,
478  deltaF = 1.0 / self.working_duration,
479  length = self.working_length // 2 + 1,
480  sampleUnits = lal.Unit("strain s")
481  )
482 
483  # Calculate the maximum ring down time or maximum shift time
484  if approximant in templates.gstlal_IMR_approximants:
485  self.max_ringtime = max([chirptime.ringtime(row.mass1*lal.MSUN_SI + row.mass2*lal.MSUN_SI, chirptime.overestimate_j_from_chi(max(row.spin1z, row.spin2z))) for row in self.template_table])
486  else:
487  if self.sample_rate_max > 2. * self.fhigh:
488  # Calculate the maximum time we need to shift the early warning
489  # waveforms forward by, calculated by the 3.5 approximation from
490  # fhigh to ISCO.
491  self.max_shift_time = max([spawaveform.chirptime(row.mass1, row.mass2, 7, fhigh, 0., spawaveform.computechi(row.mass1, row.mass2, row.spin1z, row.spin2z)) for row in self.template_table])
492 
493  #
494  # Generate each template, downsampling as we go to save memory
495  # generate "cosine" component of frequency-domain template.
496  # waveform is generated for a canonical distance of 1 Mpc.
497  #
498 
499  def make_whitened_template(self, template_table_row):
500  # FIXME: This is won't work
501  #assert template_table_row in self.template_table, "The input Sngl_Inspiral:Table is not found in the workspace."
502 
503  # Create template
504  fseries = generate_template(template_table_row, self.approximant, self.sample_rate_max, self.working_duration, self.f_low, self.fhigh, fwdplan = self.fwdplan, fworkspace = self.fworkspace)
505 
506  if FIR_WHITENER:
507  #
508  # Compute a product of freq series of the whitening kernel and the template (convolution in time domain) then add quadrature phase
509  #
510  assert (len(self.kernel_fseries.data.data) // 2 + 1) == len(fseries.data.data), "the size of whitening kernel freq series does not match with a given format of COMPLEX16FrequencySeries."
511  fseries.data.data *= self.kernel_fseries.data.data[len(self.kernel_fseries.data.data) // 2 - 1:]
513  else:
514  #
515  # whiten and add quadrature phase ("sine" component)
516  #
517 
518  if self.psd is not None:
519  lal.WhitenCOMPLEX16FrequencySeries(fseries, self.psd)
521 
522  #
523  # compute time-domain autocorrelation function
524  #
525 
526  if self.autocorrelation_length is not None:
527  autocorrelation = templates.normalized_autocorrelation(fseries, self.revplan).data.data
528  else:
529  autocorrelation = None
530 
531  #
532  # transform template to time domain
533  #
534 
535  lal.COMPLEX16FreqTimeFFT(self.tseries, fseries, self.revplan)
536 
537  data = self.tseries.data.data
538  epoch_time = fseries.epoch.gpsSeconds + fseries.epoch.gpsNanoSeconds*1.e-9
539 
540  #
541  # extract the portion to be used for filtering
542  #
543 
544  #
545  # condition the template if necessary (e.g. line up IMR
546  # waveforms by peak amplitude)
547  #
548 
549  if self.approximant in templates.gstlal_IMR_approximants:
550  data, target_index = condition_imr_template(self.approximant, data, epoch_time, self.sample_rate_max, self.max_ringtime)
551  # record the new end times for the waveforms (since we performed the shifts)
552  template_table_row.end = LIGOTimeGPS(float(target_index-(len(data) - 1.))/self.sample_rate_max)
553  else:
554  if self.sample_rate_max > self.fhigh*2.:
555  data, target_index = condition_ear_warn_template(self.approximant, data, epoch_time, self.sample_rate_max, self.max_shift_time)
556  data *= tukeywindow(data, samps = 32)
557  # record the new end times for the waveforms (since we performed the shifts)
558  template_table_row.end = LIGOTimeGPS(float(target_index)/self.sample_rate_max)
559  else:
560  data *= tukeywindow(data, samps = 32)
561 
562  data = data[-self.length_max:]
563 
564  #
565  # normalize so that inner product of template with itself
566  # is 2
567  #
568 
569  norm = abs(numpy.dot(data, numpy.conj(data)))
570  data *= cmath.sqrt(2 / norm)
571 
572  #
573  # sigmasq = 2 \sum_{k=0}^{N-1} |\tilde{h}_{k}|^2 / S_{k} \Delta f
574  #
575  # XLALWhitenCOMPLEX16FrequencySeries() computed
576  #
577  # \tilde{h}'_{k} = \sqrt{2 \Delta f} \tilde{h}_{k} / \sqrt{S_{k}}
578  #
579  # and XLALCOMPLEX16FreqTimeFFT() computed
580  #
581  # h'_{j} = \Delta f \sum_{k=0}^{N-1} exp(2\pi i j k / N) \tilde{h}'_{k}
582  #
583  # therefore, "norm" is
584  #
585  # \sum_{j} |h'_{j}|^{2} = (\Delta f)^{2} \sum_{j} \sum_{k=0}^{N-1} \sum_{k'=0}^{N-1} exp(2\pi i j (k-k') / N) \tilde{h}'_{k} \tilde{h}'^{*}_{k'}
586  # = (\Delta f)^{2} \sum_{k=0}^{N-1} \sum_{k'=0}^{N-1} \tilde{h}'_{k} \tilde{h}'^{*}_{k'} \sum_{j} exp(2\pi i j (k-k') / N)
587  # = (\Delta f)^{2} N \sum_{k=0}^{N-1} |\tilde{h}'_{k}|^{2}
588  # = (\Delta f)^{2} N 2 \Delta f \sum_{k=0}^{N-1} |\tilde{h}_{k}|^{2} / S_{k}
589  # = (\Delta f)^{2} N sigmasq
590  #
591  # and \Delta f = 1 / (N \Delta t), so "norm" is
592  #
593  # \sum_{j} |h'_{j}|^{2} = 1 / (N \Delta t^2) sigmasq
594  #
595  # therefore
596  #
597  # sigmasq = norm * N * (\Delta t)^2
598  #
599 
600  sigmasq = norm * len(data) / self.sample_rate_max**2.
601 
602  return data, autocorrelation, sigmasq
603 
604 
605 def generate_templates(template_table, approximant, psd, f_low, time_slices, autocorrelation_length = None, fhigh = None, verbose = False):
606  # Create workspace for making template bank
607  workspace = templates_workspace(template_table, approximant, psd, f_low, time_slices, autocorrelation_length = autocorrelation_length, fhigh = fhigh)
608 
609  # Check parity of autocorrelation length
610  if autocorrelation_length is not None:
611  if not (autocorrelation_length % 2):
612  raise ValueError("autocorrelation_length must be odd (got %d)".format(autocorrelation_length))
613  autocorrelation_bank = numpy.zeros((len(template_table), autocorrelation_length), dtype = "cdouble")
614  autocorrelation_mask = compute_autocorrelation_mask( autocorrelation_bank )
615  else:
616  autocorrelation_bank = None
617  autocorrelation_mask = None
618 
619  # Multiply by 2 * length of the number of sngl_inspiral rows to get the sine/cosine phases.
620  template_bank = [numpy.zeros((2 * len(template_table), int(round(rate*(end-begin)))), dtype = "double") for rate,begin,end in time_slices]
621 
622  # Store the original normalization of the waveform. After
623  # whitening, the waveforms are normalized. Use the sigmasq factors
624  # to get back the original waveform.
625  sigmasq = []
626 
627  for i, row in enumerate(template_table):
628  if verbose:
629  print("generating template %d/%d: m1 = %g, m2 = %g, s1x = %g, s1y = %g, s1z = %g, s2x = %g, s2y = %g, s2z = %g" % (i + 1, len(template_table), row.mass1, row.mass2, row.spin1x, row.spin1y, row.spin1z, row.spin2x, row.spin2y, row.spin2z), file=sys.stderr)
630  # FIXME: ensure the row is in template_table
631  template, autocorrelation, this_sigmasq = workspace.make_whitened_template(row)
632 
633  sigmasq.append(this_sigmasq)
634 
635  if autocorrelation is not None:
636  autocorrelation_bank[i, ::-1] = numpy.concatenate((autocorrelation[-(autocorrelation_length // 2):], autocorrelation[:(autocorrelation_length // 2 + 1)]))
637 
638  #
639  # copy real and imaginary parts into adjacent (real-valued)
640  # rows of template bank
641  #
642 
643  for j, time_slice in enumerate(time_slices):
644  # start and end times are measured *backwards* from
645  # template end; subtract from n to convert to
646  # start and end index; end:start is the slice to
647  # extract, but there's also an amount added equal
648  # to 1 less than the stride that I can't explain
649  # but probaby has something to do with the reversal
650  # of the open/closed boundary conditions through
651  # all of this (argh! Chad!)
652 
653  stride = int(round(workspace.sample_rate_max / time_slice['rate']))
654  begin_index = workspace.length_max - int(round(time_slice['begin'] * workspace.sample_rate_max)) + stride - 1
655  end_index = workspace.length_max - int(round(time_slice['end'] * workspace.sample_rate_max)) + stride - 1
656  # make sure the rates are commensurate
657  assert stride * time_slice['rate'] == workspace.sample_rate_max
658 
659  # extract every stride-th sample. we multiply by
660  # \sqrt{stride} to maintain inner product
661  # normalization so that the templates still appear
662  # to be unit vectors at the reduced sample rate.
663  # note that the svd returns unit basis vectors
664  # regardless so this factor has no effect on the
665  # normalization of the basis vectors used for
666  # filtering but it ensures that the chifacs values
667  # have the correct relative normalization.
668  template_bank[j][(2*i+0),:] = template.real[end_index:begin_index:stride] * math.sqrt(stride)
669  template_bank[j][(2*i+1),:] = template.imag[end_index:begin_index:stride] * math.sqrt(stride)
670 
671  return template_bank, autocorrelation_bank, autocorrelation_mask, sigmasq, workspace
672 
673 
674 def decompose_templates(template_bank, tolerance, identity = False):
675  #
676  # sum-of-squares for each template (row).
677  #
678 
679  chifacs = (template_bank * template_bank).sum(1)
680 
681  #
682  # this turns this function into a no-op: the output "basis
683  # vectors" are exactly the input templates and the reconstruction
684  # matrix is absent (triggers pipeline construction code to omit
685  # matrixmixer element)
686  #
687 
688  if identity:
689  return template_bank, None, None, chifacs
690 
691  #
692  # adjust tolerance according to local norm
693  #
694 
695  tolerance = 1 - (1 - tolerance) / chifacs.max()
696 
697  #
698  # S.V.D.
699  #
700 
701  U, s, Vh = spawaveform.svd(template_bank.T,mod=True,inplace=True)
702 
703  #
704  # determine component count
705  #
706 
707  residual = numpy.sqrt((s * s).cumsum() / numpy.dot(s, s))
708  # FIXME in an ad hoc way force at least 6 principle components
709  n = max(min(residual.searchsorted(tolerance) + 1, len(s)), 6)
710 
711  #
712  # clip decomposition, pre-multiply Vh by s
713  #
714 
715  U = U[:,:n]
716  Vh = numpy.dot(numpy.diag(s), Vh)[:n,:]
717  s = s[:n]
718 
719  #
720  # renormalize the truncated SVD approximation of these template
721  # waveform slices making sure their squares still add up to chifacs.
722  # This is done by renormalizing the sum of the square of the
723  # singular value weighted reconstruction coefficients associated with
724  # each template.
725  #
726 
727  V2 = (Vh * Vh).sum(0)
728  for idx,v2 in enumerate(V2):
729  Vh[:, idx] *= numpy.sqrt(chifacs[idx] / v2)
730 
731  #
732  # done.
733  #
734 
735  return U.T, s, Vh, chifacs
def ceil_pow_2
Definition: templates.py:228
def ringtime
Definition: chirptime.py:94
def overestimate_j_from_chi
Definition: chirptime.py:120
def normalized_autocorrelation
Definition: templates.py:201