19 The python module to implement SVD decomposed FIR filtering
23 STATUS: reviewed with actions
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 +-----------------------------------------------------+------------------------------------------+------------+
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
63 from lal
import LIGOTimeGPS
64 import lalsimulation
as lalsim
67 from gstlal
import spawaveform
70 from gstlal
import chirptime
71 from gstlal
import reference_psd
72 from gstlal
import templates
80 __author__ =
"Kipp Cannon <kipp.cannon@ligo.org>, Chad Hanna <chad.hanna@ligo.org>, Drew Keppel <drew.keppel@ligo.org>"
86 if int(os.environ[
"GSTLAL_FIR_WHITEN"]):
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)
102 def create_FIR_whitener_kernel(length, duration, sample_rate, psd):
109 fwdplan_kernel = lal.CreateForwardCOMPLEX16FFTPlan(length, 1)
110 kernel_tseries = lal.CreateCOMPLEX16TimeSeries(
111 name =
"timeseries of whitening kernel",
112 epoch = LIGOTimeGPS(0.),
114 deltaT = 1.0 / sample_rate,
116 sampleUnits = lal.Unit(
"strain")
118 kernel_fseries = lal.CreateCOMPLEX16FrequencySeries(
119 name =
"freqseries of whitening kernel",
120 epoch = LIGOTimeGPS(0),
122 deltaF = 1.0 / duration,
124 sampleUnits = lal.Unit(
"strain s")
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]
138 if len(kernel) < length:
139 kernel = numpy.append(kernel, numpy.zeros(length - len(kernel)))
141 kernel = kernel[:length]
143 kernel_tseries.data.data = kernel
149 lal.COMPLEX16TimeFreqFFT(kernel_fseries, kernel_tseries, fwdplan_kernel)
151 return kernel_fseries
153 def taperzero_fseries(fseries, minfs = (35.0, 40.0), maxfs = (1800., 2048.)):
155 A function to taper the psd to infinity for given min/max frequencies
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.
162 :returns: A tapered psd
170 data = fseries.data.data
171 norm_before = numpy.dot(data.conj(), data).real
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
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
194 fseries.data.data = data * math.sqrt(norm_before / numpy.dot(data.conj(), data).real)
203 def tukeywindow(data, samps = 200.):
204 assert (len(data) >= 2 * samps)
205 tp = float(samps) / len(data)
206 return lal.CreateTukeyREAL8Window(len(data), tp).data.data
209 def generate_template(template_bank_row, approximant, sample_rate, duration, f_low, f_high, amporder = 0, order = 7, fwdplan = None, fworkspace = None):
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
216 if approximant
not in templates.gstlal_approximants:
217 raise ValueError(
"Unsupported approximant given %s" % approximant)
218 assert f_high <= sample_rate // 2
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))
246 hplus, hcross = lalsim.SimInspiralFD(**parameters)
247 assert len(hplus.data.data) == int(round(f_high * duration)) +1
250 if f_high < sample_rate / 2:
251 fseries = lal.CreateCOMPLEX16FrequencySeries(
255 deltaF = hplus.deltaF,
256 length = int(round(sample_rate * duration))//2 +1,
257 sampleUnits = hplus.sampleUnits
259 fseries.data.data = numpy.zeros(fseries.data.length)
260 fseries.data.data[:hplus.data.length] = hplus.data.data[:]
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"
269 epoch_index = -int(epoch_time*sample_rate_max) - 1
272 target_index = len(data)-1 - int(sample_rate_max * max_ringtime)
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)
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
283 return data, target_index
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"
290 epoch_index = -int(epoch_time*sample_rate_max) - 1
294 target_index = int(sample_rate_max * max_shift_time)
295 data = numpy.roll(data, target_index-epoch_index)
296 return data, target_index
299 def compute_autocorrelation_mask( autocorrelation ):
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
306 return numpy.ones( autocorrelation.shape, dtype=
"int" )
309 def movingmedian(interval, window_size):
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])
315 tmp[window_size : len(interval) - window_size] = pandas.rolling_median(tmp, 2 * window_size)[2 * window_size - 1 : -1]
317 interval = list(interval)
318 tmp = numpy.copy(interval)
322 for i
in range(window_size, len(interval)-window_size):
324 A = interval[i-window_size:i+window_size]
325 ix = numpy.argsort(A)
326 As = list(numpy.array(A)[ix])
328 newdata = interval[i+window_size-1]
330 bisect.insort(As, newdata)
332 tmp[i] = As[len(As)//2]
334 tmp[i] = (As[len(As)//2-1] + As[len(As)//2]) / 2.
336 del As[bisect.bisect_left(As, prev)]
340 def movingaverage(interval, window_size):
341 window = lal.CreateTukeyREAL8Window(window_size, 0.5).data.data
342 return numpy.convolve(interval, window,
'same')
345 def condition_psd(psd, newdeltaF, minfs = (35.0, 40.0), maxfs = (1800., 2048.), smoothing_frequency = 4.):
347 A function to condition the psd that will be used to whiten waveforms
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.
354 returns a conditioned psd
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]
368 psd = reference_psd.interpolate_psd(psd, newdeltaF)
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
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
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
400 psd.data.data = psddata
406 horizon_after = horizon_distance(psd, 8.0)[0]
408 psddata = psd.data.data
409 psd.data.data = psddata * (horizon_after / horizon_before)**2
419 def __init__(self, template_table, approximant, psd, f_low, time_slices, autocorrelation_length = None, fhigh = None):
427 self.
duration = max(time_slices[
"end"])
430 if self.
fhigh is None:
434 raise ValueError(
"template list is empty")
436 raise ValueError(
"f_low must be >= 0. %s" % repr(self.
f_low))
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)
466 self.
tseries = lal.CreateCOMPLEX16TimeSeries(
468 epoch = LIGOTimeGPS(0.),
472 sampleUnits = lal.Unit(
"strain")
474 self.
fworkspace = lal.CreateCOMPLEX16FrequencySeries(
476 epoch = LIGOTimeGPS(0),
480 sampleUnits = lal.Unit(
"strain s")
484 if approximant
in templates.gstlal_IMR_approximants:
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])
499 def make_whitened_template(self, template_table_row):
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:]
518 if self.
psd is not None:
519 lal.WhitenCOMPLEX16FrequencySeries(fseries, self.
psd)
529 autocorrelation =
None
537 data = self.tseries.data.data
538 epoch_time = fseries.epoch.gpsSeconds + fseries.epoch.gpsNanoSeconds*1.e-9
549 if self.
approximant in templates.gstlal_IMR_approximants:
552 template_table_row.end = LIGOTimeGPS(float(target_index-(len(data) - 1.))/self.
sample_rate_max)
556 data *= tukeywindow(data, samps = 32)
558 template_table_row.end = LIGOTimeGPS(float(target_index)/self.
sample_rate_max)
560 data *= tukeywindow(data, samps = 32)
569 norm = abs(numpy.dot(data, numpy.conj(data)))
570 data *= cmath.sqrt(2 / norm)
602 return data, autocorrelation, sigmasq
605 def generate_templates(template_table, approximant, psd, f_low, time_slices, autocorrelation_length = None, fhigh = None, verbose = False):
607 workspace =
templates_workspace(template_table, approximant, psd, f_low, time_slices, autocorrelation_length = autocorrelation_length, fhigh = fhigh)
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 )
616 autocorrelation_bank =
None
617 autocorrelation_mask =
None
620 template_bank = [numpy.zeros((2 * len(template_table), int(round(rate*(end-begin)))), dtype =
"double")
for rate,begin,end
in time_slices]
627 for i, row
in enumerate(template_table):
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)
631 template, autocorrelation, this_sigmasq = workspace.make_whitened_template(row)
633 sigmasq.append(this_sigmasq)
635 if autocorrelation
is not None:
636 autocorrelation_bank[i, ::-1] = numpy.concatenate((autocorrelation[-(autocorrelation_length // 2):], autocorrelation[:(autocorrelation_length // 2 + 1)]))
643 for j, time_slice
in enumerate(time_slices):
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
657 assert stride * time_slice[
'rate'] == workspace.sample_rate_max
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)
671 return template_bank, autocorrelation_bank, autocorrelation_mask, sigmasq, workspace
674 def decompose_templates(template_bank, tolerance, identity = False):
679 chifacs = (template_bank * template_bank).sum(1)
689 return template_bank,
None,
None, chifacs
695 tolerance = 1 - (1 - tolerance) / chifacs.max()
701 U, s, Vh = spawaveform.svd(template_bank.T,mod=
True,inplace=
True)
707 residual = numpy.sqrt((s * s).cumsum() / numpy.dot(s, s))
709 n = max(min(residual.searchsorted(tolerance) + 1, len(s)), 6)
716 Vh = numpy.dot(numpy.diag(s), Vh)[:n,:]
727 V2 = (Vh * Vh).sum(0)
728 for idx,v2
in enumerate(V2):
729 Vh[:, idx] *= numpy.sqrt(chifacs[idx] / v2)
735 return U.T, s, Vh, chifacs
def overestimate_j_from_chi
def normalized_autocorrelation