gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
templates.py
Go to the documentation of this file.
1 # Copyright (C) 2009--2013 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 ## @file
18 # A module to implement template slicing and other operations as part of the LLOID aglorithm
19 #
20 # ### Review Status
21 #
22 # | Names | Hash | Date | Diff to Head of Master |
23 # | ------------------------------------------- | ------------------------------------------- | ---------- | --------------------------- |
24 # | Florent, Sathya, Duncan Me, Jolien, Kipp, Chad | 7536db9d496be9a014559f4e273e1e856047bf71 | 2014-04-29 | <a href="@gstlal_inspiral_cgit_diff/python/templates.py?id=HEAD&id2=7536db9d496be9a014559f4e273e1e856047bf71">templates.py</a> |
25 #
26 # #### Actions
27 #
28 # - Performance of time slices could be improved by e.g., not using powers of 2 for time slice sample size. This might also simplify the code
29 #
30 
31 ## @package templates
32 
33 #
34 # =============================================================================
35 #
36 # Preamble
37 #
38 # =============================================================================
39 #
40 
41 
42 import math
43 import numpy
44 import sys
45 
46 
47 import lal
48 import lalsimulation as lalsim
49 
50 
51 from gstlal import chirptime
52 
53 
54 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>, Chad Hanna <chad.hanna@ligo.org>, Drew Keppel <drew.keppel@ligo.org>"
55 __version__ = "FIXME"
56 __date__ = "FIXME"
57 
58 
59 #
60 # =============================================================================
61 #
62 # Stuff
63 #
64 # =============================================================================
65 #
66 
67 
68 gstlal_FD_approximants = set((
69  'IMRPhenomC',
70  'SEOBNRv4_ROM',
71  'SEOBNRv2_ROM_DoubleSpin',
72  'TaylorF2',
73  'TaylorF2RedSpin',
74  'TaylorF2RedSpinTidal'
75 ))
76 gstlal_TD_approximants = set((
77  'EOBNRv2',
78  'TaylorT1',
79  'TaylorT2',
80  'TaylorT3',
81  'TaylorT4'
82 ))
83 gstlal_IMR_approximants = set((
84  'EOBNRv2',
85  'IMRPhenomC',
86  'SEOBNRv4_ROM',
87  'SEOBNRv2_ROM_DoubleSpin'
88 ))
89 gstlal_approximants = gstlal_FD_approximants | gstlal_TD_approximants
90 
91 assert gstlal_IMR_approximants <= gstlal_approximants, "gstlal_IMR_approximants contains values not listed in gstlal_approximants"
92 
93 
94 def gstlal_valid_approximant(appx_str):
95  try:
96  lalsim.GetApproximantFromString(str(appx_str))
97  except RuntimeError:
98  raise ValueError("Approximant not supported by lalsimulation: %s" % appx_str)
99  if appx_str not in gstlal_approximants:
100  raise ValueError("Approximant not currently supported by gstlal, but is supported by lalsimulation: %s. Please consider preparing a patch" % appx_str)
101 
102 
103 class QuadraturePhase(object):
104  """
105  A tool for generating the quadrature phase of a real-valued
106  template.
107 
108  Example:
109 
110  >>> import numpy
111  >>> import lal
112  >>> q = QuadraturePhase(128) # initialize for 128-sample templates
113  >>> inseries = lal.CreateREAL8TimeSeries(deltaT = 1.0 / 128, length = 128)
114  >>> inseries.data.data = numpy.cos(numpy.arange(128, dtype = "double") * 2 * numpy.pi / 128) # one cycle of cos(t)
115  >>> outseries = q(inseries) # output has cos(t) in real part, sin(t) in imaginary part
116  """
117  def __init__(self, n):
118  """
119  Initialize. n is the size, in samples, of the templates to
120  be processed. This is used to pre-allocate work space.
121  """
122  self.n = n
123  self.fwdplan = lal.CreateForwardREAL8FFTPlan(n, 1)
124  self.revplan = lal.CreateReverseCOMPLEX16FFTPlan(n, 1)
125  self.in_fseries = lalfft.prepare_fseries_for_real8tseries(lal.CreateREAL8TimeSeries(deltaT = 1.0, length = n))
126 
127 
128  @staticmethod
129  def add_quadrature_phase(fseries, n):
130  """
131  From the Fourier transform of a real-valued function of
132  time, compute and return the Fourier transform of the
133  complex-valued function of time whose real component is the
134  original time series and whose imaginary component is the
135  quadrature phase of the real part. fseries is a LAL
136  COMPLEX16FrequencySeries and n is the number of samples in
137  the original time series.
138  """
139  #
140  # positive frequencies include Nyquist if n is even
141  #
142 
143  have_nyquist = not (n % 2)
144 
145  #
146  # shuffle frequency bins
147  #
148 
149  positive_frequencies = numpy.array(fseries.data.data) # work with copy
150  positive_frequencies[0] = 0 # set DC to zero
151  zeros = numpy.zeros((len(positive_frequencies),), dtype = "cdouble")
152  if have_nyquist:
153  # complex transform never includes positive Nyquist
154  positive_frequencies = positive_frequencies[:-1]
155 
156  #
157  # prepare output frequency series
158  #
159 
160  out_fseries = lal.CreateCOMPLEX16FrequencySeries(
161  name = fseries.name,
162  epoch = fseries.epoch,
163  f0 = fseries.f0, # caution: only 0 is supported
164  deltaF = fseries.deltaF,
165  sampleUnits = fseries.sampleUnits,
166  length = len(zeros) + len(positive_frequencies) - 1
167  )
168  out_fseries.data.data = numpy.concatenate((zeros, 2 * positive_frequencies[1:]))
169 
170  return out_fseries
171 
172 
173  def __call__(self, tseries):
174  """
175  Transform the real-valued time series stored in tseries
176  into a complex-valued time series. The return value is a
177  newly-allocated complex time series. The input time series
178  is stored in the real part of the output time series, and
179  the complex part stores the quadrature phase.
180  """
181  #
182  # transform to frequency series
183  #
184 
185  lal.REAL8TimeFreqFFT(self.in_fseries, tseries, self.fwdplan)
186 
187  #
188  # transform to complex time series
189  #
190 
191  tseries = lal.CreateCOMPLEX16TimeSeries(length = self.n)
192  lal.COMPLEX16FreqTimeFFT(tseries, self.add_quadrature_phase(self.in_fseries, self.n), self.revplan)
193 
194  #
195  # done
196  #
197 
198  return tseries
199 
200 
201 def normalized_autocorrelation(fseries, revplan):
202  data = fseries.data.data
203  fseries = lal.CreateCOMPLEX16FrequencySeries(
204  name = fseries.name,
205  epoch = fseries.epoch,
206  f0 = fseries.f0,
207  deltaF = fseries.deltaF,
208  sampleUnits = fseries.sampleUnits,
209  length = len(data)
210  )
211  fseries.data.data = data * numpy.conj(data)
212  tseries = lal.CreateCOMPLEX16TimeSeries(
213  name = "timeseries",
214  epoch = fseries.epoch,
215  f0 = fseries.f0,
216  deltaT = 1. / (len(data)*fseries.deltaF),
217  length = len(data),
218  sampleUnits = lal.DimensionlessUnit
219  )
220  tseries.data.data = numpy.empty((len(data),), dtype = "cdouble")
221  lal.COMPLEX16FreqTimeFFT(tseries, fseries, revplan)
222  data = tseries.data.data
223  tseries.data.data = data / data[0]
224  return tseries
225 
226 
227 # Round a number up to the nearest power of 2
228 def ceil_pow_2(x):
229  x = int(math.ceil(x))
230  x -= 1
231  n = 1
232  while n and (x & (x + 1)):
233  x |= x >> n
234  n *= 2
235  return x + 1
236 
237 
238 def time_slices(
239  sngl_inspiral_rows,
240  flow = 40,
241  fhigh = 900,
242  padding = 1.5,
243  samples_min = 1024,
244  samples_max_256 = 1024,
245  samples_max_64 = 2048,
246  samples_max = 4096,
247  sample_rate = None,
248  verbose = False
249 ):
250  """
251  The function time_frequency_boundaries splits a template bank up by
252  times for which different sampling rates are appropriate.
253 
254  The function returns a list of 3-tuples of the form (rate,begin,end)
255  where rate is the sampling rate and begin/end mark the boundaries
256  during which the given rate is guaranteed to be appropriate (no
257  template exceeds a frequency of Nyquist/padding during these times).
258 
259  @param sngl_inspiral_rows The snigle inspiral rows for this sub bank
260  @param flow The low frequency to generate the waveform from
261  @param fhigh The maximum frequency for generating the waveform
262  @param padding Allow a template to be generated up to Nyquist / padding for any slice
263  @param samples_min The minimum number of samples to use in any time slice
264  @param samples_max_256 The maximum number of samples to have in any time slice greater than or equal to 256 Hz
265  @param samples_max_64 The maximum number of samples to have in any time slice greater than or equal to 64 Hz
266  @param samples_max The maximum number of samples in any time slice below 64 Hz
267  @param verbose Be verbose
268  """
269 
270  #
271  # DETERMINE A SET OF ALLOWED SAMPLE RATES
272  #
273 
274  # We only allow sample rates that are powers of two. The upper limit
275  # is set by the sampling rate for h(t), which is 16384Hz. The lower
276  # limit is set arbitrarily to be 32Hz.
277  allowed_rates = [16384,8192,4096,2048,1024,512,256,128,64,32]
278 
279  # Remove too-small and too-big sample rates base on input params.
280  sample_rate_min = ceil_pow_2( 2 * padding * flow )
281  if sample_rate is None:
282  sample_rate_max = ceil_pow_2( 2 * fhigh )
283  else:
284  # note that sample rate is ensured to be a power of 2 in gstlal_svd_bank
285  sample_rate_max = sample_rate
286  allowed_rates = [rate for rate in allowed_rates if sample_rate_min <= rate <= sample_rate_max]
287 
288  #
289  # FIND TIMES WHEN THESE SAMPLE RATES ARE OK TO USE
290  #
291 
292  # How many sample points should be included in a chunk?
293  # We need to balance the need to have few chunks with the
294  # need to have small chunks.
295  # We choose the min size such that the template matrix
296  # has its time dimension at least as large as its template dimension.
297  # The max size is chosen based on experience, which shows that
298  # SVDs of matrices bigger than m x 8192 are very slow.
299  segment_samples_min = max(ceil_pow_2( 2*len(sngl_inspiral_rows) ),samples_min)
300 
301  # For each allowed sampling rate with associated Nyquist frequency fN,
302  # determine the greatest amount of time any template in the bank spends
303  # between fN/2 and fhigh.
304  # fN/2 is given by sampling_rate/4 and is the next lowest Nyquist frequency
305  # We pad this so that we only start a new lower frequency sampling rate
306  # when all the waveforms are a fraction (padding-1) below the fN/2.
307  time_freq_boundaries = []
308  accum_time = 0
309 
310  # Get the low frequency staring points for the chirptimes at a given
311  # rate. This is always a factor of 2*padding smaller than the rate
312  # below to gaurantee that the waveform doesn't cross the Nyquist rate
313  # in the next time slice. The last element should always be the
314  # requested flow. The allowed rates won't go below that by
315  # construction.
316  rates_below = [r/(2.*padding) for r in allowed_rates[1:]] + [flow]
317 
318  for this_flow, rate in zip(rates_below, allowed_rates):
319  if rate >= 256:
320  segment_samples_max = samples_max_256
321  elif rate >= 64:
322  segment_samples_max = samples_max_64
323  else:
324  segment_samples_max = samples_max
325 
326  if segment_samples_min > segment_samples_max:
327  raise ValueError("The input template bank must have fewer than %d templates, but had %d." % (segment_samples_max, 2 * len(sngl_inspiral_rows)))
328 
329  longest_chirp = max(chirptime.imr_time(this_flow, row.mass1 * lal.MSUN_SI, row.mass2 * lal.MSUN_SI, row.spin1z, row.spin2z) for row in sngl_inspiral_rows)
330 
331  # Do any of the templates go beyond the accumulated time?
332  # If so, we need to add some blocks at this sampling rate.
333  # If not, we can skip this sampling rate and move on to the next lower one.
334  if longest_chirp > accum_time:
335  # How many small/large blocks are needed to cover this band?
336  number_large_blocks = int(numpy.floor( rate*(longest_chirp-accum_time) / segment_samples_max ))
337  number_small_blocks = int(numpy.ceil( rate*(longest_chirp-accum_time) / segment_samples_min )
338  - number_large_blocks*segment_samples_max/segment_samples_min)
339 
340  # Add small blocks first, since the templates change more rapidly
341  # near the end of the template and therefore have more significant
342  # components in the SVD.
343  exponent = 0
344  while number_small_blocks > 0:
345  if number_small_blocks % 2 == 1:
346  time_freq_boundaries.append((rate,
347  accum_time,
348  accum_time+float(2**exponent)*segment_samples_min/rate))
349  accum_time += float(2**exponent)*segment_samples_min/rate
350  exponent += 1
351  number_small_blocks = number_small_blocks >> 1 # bit shift to right, dropping LSB
352 
353 
354  # Now add the big blocks
355  for idx in range(number_large_blocks):
356  time_freq_boundaries.append((rate,
357  accum_time,
358  accum_time+(1./rate)*segment_samples_max))
359  accum_time += (1./rate)*segment_samples_max
360 
361  if verbose:
362  print("Time freq boundaries: ", file=sys.stderr)
363  print(time_freq_boundaries, file=sys.stderr)
364 
365  return numpy.array(time_freq_boundaries,dtype=[('rate','int'),('begin','float'),('end','float')])
366 
367 
368 def hplus_of_f(m1, m2, s1, s2, f_min, f_max, delta_f):
369  farr = numpy.linspace(0, f_max, f_max / delta_f + delta_f)
370  spin1 = [0., 0., s1]; spin2 = [0., 0., s2]
371  hp, hc = lalsim.SimInspiralFD(
372  m1 * lal.MSUN_SI, m2 * lal.MSUN_SI,
373  spin1[0], spin1[1], spin1[2],
374  spin2[0], spin2[1], spin2[2],
375  1.0, # distance (m)
376  0.0,
377  0.0, # reference orbital phase (rad)
378  0.0, # longitude of ascending nodes (rad)
379  0.0,
380  0.0, # mean anomaly of periastron
381  delta_f,
382  f_min,
383  f_max + delta_f,
384  100., # reference frequency (Hz)
385  None, # LAL dictionary containing accessory parameters
386  lalsim.GetApproximantFromString("IMRPhenomD")
387  )
388  assert hp.data.length > 0, "huh!? h+ has zero length!"
389 
390  return hp.data.data[:len(farr)]
391 
392 def fn(farr, h, n, psd):
393  df = farr[1] - farr[0]
394  return 4 * numpy.sum(numpy.abs(h)**2 * farr**n * df / psd(farr))
395 
396 def moment(farr, h, n, psd):
397  return fn(farr, h, n, psd) / fn(farr, h, 0, psd)
398 
399 def bandwidth(m1, m2, s1, s2, f_min, f_max, delta_f, psd):
400  h = hplus_of_f(m1, m2, s1, s2, f_min, f_max, delta_f)
401  farr = numpy.linspace(0, f_max, f_max / delta_f + delta_f)
402  return (moment(farr, h, 2, psd) - moment(farr, h, 1, psd)**2)**.5
def imr_time
Definition: chirptime.py:126