Exemple #1
0
    def match(self):
        match_result = []
        injtau0 = conversions.tau0_from_mass1_mass2(0.1,
                                                    0.1,
                                                    f_lower=self.f_lower)
        for i in range(self.inj_num):
            print('i is %s' % i)
            hpinj, _ = get_fd_waveform(approximant="TaylorF2e",
                                       mass1=0.1,
                                       mass2=0.1,
                                       eccentricity=self.injecc[i],
                                       long_asc_nodes=self.injection['pol'][i],
                                       inclination=self.injection['inc'][i],
                                       delta_f=self.delta_f,
                                       f_lower=self.f_lower,
                                       f_final=self.f_upper)
            # scan the template bank to find the maximum match
            index = np.where(np.abs(injtau0 - self.bank_tau0) < 3)
            max_match, max_m1, max_m2 = None, None, None
            for k in index[0]:
                hpbank, __ = get_fd_waveform(approximant="TaylorF2",
                                             mass1=self.bank_m1[k],
                                             mass2=self.bank_m2[k],
                                             phase_order=6,
                                             delta_f=self.delta_f,
                                             f_lower=self.f_lower,
                                             f_final=self.f_upper)
                cache_match, _ = match(hpinj,
                                       hpbank,
                                       psd=self.psd,
                                       low_frequency_cutoff=self.f_lower,
                                       high_frequency_cutoff=self.f_upper)
                print('ecc=%f,m1=%f,m2=%f,match=%f' %
                      (self.injecc[i], self.bank_m1[k], self.bank_m2[k],
                       cache_match))
                if max_match == None:
                    max_match = cache_match
                    max_m1 = self.bank_m1[k]
                    max_m2 = self.bank_m2[k]
                elif cache_match > max_match:
                    max_match = cache_match
                    max_m1 = self.bank_m1[k]
                    max_m2 = self.bank_m2[k]
            match_result.append([
                0.1, 0.1, self.injecc[i], self.injection['pol'][i],
                self.injection['inc'][i], max_match, max_m1, max_m2
            ])

        np.savetxt(
            'result' + str(sys.argv[1]) + '.txt',
            match_result,
            fmt='%f',
            header='injm1  injm2  injecc  injpol injinc maxmatch  maxm1  maxm2'
        )
        return match_result
Exemple #2
0
    def test_spintaylorf2GPU(self):
    
        print(type(self.context))
        if isinstance(self.context, CPUScheme):
            return
            
        fl = 25
        delta_f = 1.0 / 256

        for m1 in [3, 5, 15]:
               for m2 in [1., 2., 3.]:
                   for s1 in [0.001, 1.0, 10]:
                       for s1Ctheta in [-1.,0.,0.5,1.]:
                           for s1phi in [0,2.09,4.18]:
                               for inclination in [0.2,1.2]:
                                   s1x = s1 * sqrt(1-s1Ctheta**2) * cos(s1phi)
                                   s1y = s1 * sqrt(1-s1Ctheta**2) * sin(s1phi)
                                   s1z = s1 * s1Ctheta
                                   # Generate SpinTaylorF2 from lalsimulation
                                   hpLAL,hcLAL = get_fd_waveform( mass1=m1, mass2=m2, spin1x=s1x, spin1y=s1y,spin1z=s1z, delta_f=delta_f, f_lower=fl,approximant="SpinTaylorF2", amplitude_order=0, phase_order=7, inclination=inclination )

                                   #Generate SpinTaylorF2 from SpinTaylorF2.py
                                   with self.context:
                                        hp,hc = get_fd_waveform( mass1=m1, mass2=m2, spin1x=s1x, spin1y=s1y,spin1z=s1z, delta_f=delta_f, f_lower=fl,approximant="SpinTaylorF2", amplitude_order=0, phase_order=7, inclination=inclination )

                                   o =  overlap(hpLAL, hp)
                                   self.assertAlmostEqual(1.0, o, places=4)
                                   o =  overlap(hcLAL, hc)
                                   self.assertAlmostEqual(1.0, o, places=4)

                                   ampPLAL=numpy.abs(hpLAL.data)
                                   ampP=numpy.abs(hp.data)
                                   phasePLAL=numpy.unwrap(numpy.angle(hpLAL.data))
                                   phaseP=numpy.unwrap(numpy.angle(hp.data))
                                   ampCLAL=numpy.abs(hcLAL.data)
                                   ampC=numpy.abs(hc.data)
                                   phaseCLAL=numpy.unwrap(numpy.angle(hcLAL.data))
                                   phaseC=numpy.unwrap(numpy.angle(hc.data))
                                   indexampP=numpy.where( ampPLAL!= 0)
                                   indexphaseP=numpy.where( phasePLAL!= 0)
                                   indexampC=numpy.where( ampCLAL!= 0)
                                   indexphaseC=numpy.where( phaseCLAL!= 0)
                                   AmpDiffP = max(abs ( (ampP[indexampP]-ampPLAL[indexampP]) / ampPLAL[indexampP] ) )
                                   PhaseDiffP = max(abs ( (phaseP[indexphaseP] - phasePLAL[indexphaseP]) / phasePLAL[indexphaseP] ) )
                                   AmpDiffC = max(abs ( (ampC[indexampP]-ampCLAL[indexampP]) / ampCLAL[indexampP] ) )
                                   PhaseDiffC = max(abs ( (phaseC[indexphaseP] - phaseCLAL[indexphaseP]) / phaseCLAL[indexphaseP] ) )
                                   self.assertTrue(AmpDiffP < 0.00001)
                                   self.assertTrue(PhaseDiffP < 0.00001)
                                   self.assertTrue(AmpDiffC < 0.00001)
                                   self.assertTrue(PhaseDiffC < 0.00001)
                                   print("..checked m1: %s m2:: %s s1x: %s s1y: %s s1z: %s Inclination: %s" % (m1, m2, s1x, s1y, s1z, inclination))
def calc_reach_bandwidth(mass1, mass2, approx, power_spec, fmin, thresh=8.):
    fmax = power_spec.sample_frequencies[-1]
    df = power_spec.delta_f
    hpf, hcf = waveform.get_fd_waveform(approximant=approx,
                                        mass1=mass1,
                                        mass2=mass2,
                                        f_lower=fmin,
                                        f_final=fmax,
                                        delta_f=df)
    ss = float(
        waveform.sigmasq(hpf,
                         power_spec,
                         low_frequency_cutoff=fmin,
                         high_frequency_cutoff=hpf.sample_frequencies[-1]))
    hpf *= hpf.sample_frequencies**(0.5)
    ssf = float(
        waveform.sigmasq(hpf,
                         power_spec,
                         low_frequency_cutoff=fmin,
                         high_frequency_cutoff=hpf.sample_frequencies[-1]))
    hpf *= hpf.sample_frequencies**(0.5)
    ssf2 = float(
        waveform.sigmasq(hpf,
                         power_spec,
                         low_frequency_cutoff=fmin,
                         high_frequency_cutoff=hpf.sample_frequencies[-1]))
    max_dist = numpy.sqrt(ss) / thresh
    meanf = ssf / ss
    sigf = (ssf2 / ss - meanf**2)**(0.5)
    return max_dist, meanf, sigf
Exemple #4
0
    def test_spatmplt(self):
        fl = 25
        delta_f = 1.0 / 256

        for m1 in [1, 1.4, 20]:
            for m2 in [1.4, 20]:
                for s1 in  [-2, -1, -0.5, 0, 0.5, 1, 2]:
                    for s2 in [-2, -1, -0.5, 0, 0.5, 1, 2]:
                        # Generate TaylorF2 from lalsimulation, restricting to the capabilities of spatmplt
                        hpr,_ = get_fd_waveform( mass1=m1, mass2=m2, spin1z=s1, spin2z=s2, 
                                                 delta_f=delta_f, f_lower=fl,
                                                 approximant="TaylorF2", amplitude_order=0,
                                                 spin_order=-1, phase_order=-1)
                        hpr=hpr.astype(complex64)

                        with self.context:
                            # Generate the spatmplt waveform
                            out = zeros(len(hpr), dtype=complex64)
                            hp = get_waveform_filter(out, mass1=m1, mass2=m2, spin1z=s1, spin2z=s2,
                                                     delta_f=delta_f, f_lower=fl, approximant="SPAtmplt", 
                                                     amplitude_order=0, spin_order=-1, phase_order=-1)

                            # Check the diff is sane
                            mag = abs(hpr).sum()
                            diff = abs(hp - hpr).sum() / mag
                            self.assertTrue(diff < 0.01)

                            # Point to point overlap (no phase or time maximization)
                            o =  overlap(hp, hpr)
                            self.assertAlmostEqual(1.0, o, places=4)

                            print("checked m1: %s m2:: %s s1z: %s s2z: %s] overlap = %s, diff = %s" % (m1, m2, s1, s2, o, diff))
Exemple #5
0
def premerger_taylorf2(**p):
    """ Generate time-shifted TaylorF2"""
    from pycbc.waveform import get_fd_waveform
    from pycbc.waveform.spa_tmplt import spa_length_in_time
    from pycbc.waveform.utils import fd_taper

    p.pop('approximant')
    hp, hc = get_fd_waveform(approximant="TaylorF2", **p)

    removed = spa_length_in_time(mass1=p['mass1'],
                                 mass2=p['mass2'],
                                 f_lower=p['f_final'],
                                 phase_order=-1)

    hp = hp.cyclic_time_shift(removed)
    hp.start_time += removed

    hc = hc.cyclic_time_shift(removed)
    hc.start_time += removed

    logging.info("PreTaylorF2, m1=%.1f, m2=%.1f, fmax=%.1f, timeshift=%.1f",
                 p['mass1'], p['mass2'], p['f_final'], removed)
    kmin = int(p['f_lower'] / p['delta_f'])
    hp[0:kmin] = 0
    hc[0:kmin] = 0

    if 'final_taper' in p:
        taper_size = p['final_taper']
        hp = fd_taper(hp, p['f_final'] - taper_size, p['f_final'], side='right')
        hc = fd_taper(hc, p['f_final'] - taper_size, p['f_final'], side='right')

    hp.time_offset = removed
    hc.time_offset = removed

    return hp, hc
Exemple #6
0
    def next(self):
        nseries = []
        stats = []
        for i in range(self.batch):
            stat = {}
            n = self.noise.next()
            p = self.param.draw()
            hp, _ = get_fd_waveform(p, delta_f=n.delta_f,
                                    f_lower=self.noise.flow, **self.param.static)
            hp.resize(len(n))
            sg = sigma(hp, psd=self.noise.psd, low_frequency_cutoff=self.noise.flow)
            n += hp.cyclic_time_shift(p.tc) / sg * p.snr

            # Collect some standard stats we might want
            msnr = matched_filter(hp, n, psd=self.noise.psd,
                                  low_frequency_cutoff=self.noise.flow)
            msnr = msnr.time_slice(p.tc - 1, p.tc + 1)       
            
            params = {k: p[k] for k in p.dtype.names}
            idx = msnr.abs_arg_max()
            csnr = msnr[idx]
            params['csnr'] = csnr
            params['rsnr'] = csnr.real
            params['isnr'] = csnr.imag
            params['snr'] = abs(csnr)
            params['time'] = float(msnr.start_time + idx * msnr.delta_t)

            nseries.append(n)
            stats.append(params)

        self.current_params = stats
        return nseries, self.current_params
Exemple #7
0
    def waveform(self,
                 m1=2.,
                 m2=1.,
                 chi1=0.,
                 kappa=1.,
                 thetaJ=0.05,
                 psiJ=0.05,
                 alpha0=0.,
                 phi0=0.,
                 tC=0.):

        template_params = template(m1, m2, chi1, kappa, thetaJ, psiJ, alpha0,
                                   phi0, self._finj)
        hp, hx = get_fd_waveform(template_params,
                                 approximant=self._approximant,
                                 delta_f=self._deltaf,
                                 f_lower=self._finj,
                                 phase_order=self._phaseO,
                                 spin_order=self._spinO,
                                 sideband=None,
                                 amplitude_order=self._ampO,
                                 **(self._kwargs))
        #print('time elapsed=%f'%t.elapsed)

        sin2Y, cos2Y = sin(2. * template_params.pol), cos(2. *
                                                          template_params.pol)
        wave = pycbc.DYN_RANGE_FAC * (hp * cos2Y + hx * sin2Y)
        wave.resize(self._nsamples)
        shift = FrequencySeries(exp(2. * pi * (0. + 1.j) * tC * self._deltaf *
                                    np.arange(len(wave), dtype=np.complex128)),
                                delta_f=self._deltaf,
                                copy=False)

        return wave * shift
Exemple #8
0
def get_waveform(approximant, phase_order, amplitude_order, template_params,
                 start_frequency, sample_rate, length, filter_rate):

    if approximant in td_approximants():
        hplus, hcross = get_td_waveform(template_params,
                                        approximant=approximant,
                                        phase_order=phase_order,
                                        delta_t=1.0 / sample_rate,
                                        f_lower=start_frequency,
                                        amplitude_order=amplitude_order)
        hvec = generate_detector_strain(template_params, hplus, hcross)

        if filter_rate != sample_rate:
            delta_t = 1.0 / filter_rate
            hvec = resample_to_delta_t(hvec, delta_t)

    elif approximant in fd_approximants():
        delta_f = filter_rate / length
        if hasattr(template_params, "spin1z") and hasattr(
                template_params, "spin2z"):
            if template_params.spin1z <= -0.9 or template_params.spin1z >= 0.9:
                template_params.spin1z *= 0.99999999
            if template_params.spin2z <= -0.9 or template_params.spin2z >= 0.9:
                template_params.spin2z *= 0.99999999
        if True:
            print("\n spin1z = %f, spin2z = %f, chi = %f" %
                  (template_params.spin1z, template_params.spin2z,
                   lalsimulation.SimIMRPhenomBComputeChi(
                       template_params.mass1 * lal.LAL_MSUN_SI,
                       template_params.mass2 * lal.LAL_MSUN_SI,
                       template_params.spin1z, template_params.spin2z)),
                  file=sys.stderr)
            print("spin1x = %f, spin1y = %f" %
                  (template_params.spin1x, template_params.spin1y),
                  file=sys.stderr)
            print("spin2x = %f, spin2y = %f" %
                  (template_params.spin2x, template_params.spin2y),
                  file=sys.stderr)
            print("m1 = %f, m2 = %f" %
                  (template_params.mass1, template_params.mass2),
                  file=sys.stderr)
        hvec = get_fd_waveform(template_params,
                               approximant=approximant,
                               phase_order=phase_order,
                               delta_f=delta_f,
                               f_lower=start_frequency,
                               amplitude_order=amplitude_order)[0]
        if True:
            print("filter_N = %d in get waveform" % filter_N,
                  "\n type(hvec) in get_waveform:",
                  type(hvec),
                  file=sys.stderr)
            print(hvec, file=sys.stderr)
            print(hvec[0], file=sys.stderr)
            print(hvec[1], file=sys.stderr)
            print(isinstance(hvec, FrequencySeries), file=sys.stderr)
    htilde = make_padded_frequency_series(hvec, filter_N)

    return htilde
Exemple #9
0
def reverse_chirp_fd(newparam=0.0, **kwds):
    from pycbc.waveform import get_fd_waveform

    if 'approximant' in kwds:
        kwds.pop("approximant")
    hp, hc = get_fd_waveform(approximant="IMRPhenomD", **kwds)

    return hp.conj(), hc.conj() + newparam
def get_waveform(m1, m2, d=1):
    sptilde, sctilde = waveform.get_fd_waveform(approximant="IMRPhenomD",
                                                mass1=m1,
                                                mass2=m2,
                                                delta_f=df,
                                                f_lower=fl,
                                                f_final=fh,
                                                distance=d)
    return sptilde
Exemple #11
0
def GenTemplate(mass1, mass2, apx, ecc, lan, inc, f_low=30., freq_step=4):
    hptilde, hctilde = get_fd_waveform(approximant=apx,
                                       mass1=mass1,
                                       mass2=mass2,
                                       eccentricity=ecc,
                                       long_asc_nodes=lan,
                                       inclination=inc,
                                       f_lower=f_low,
                                       delta_f=1.0 / freq_step)
    return hptilde
Exemple #12
0
    def __init__(self,
                 variable_params,
                 data,
                 low_frequency_cutoff,
                 sample_rate=32768,
                 polarization_samples=None,
                 **kwargs):

        variable_params, kwargs = self.setup_distance_marginalization(
            variable_params, marginalize_phase=True, **kwargs)
        super(SingleTemplate, self).__init__(variable_params, data,
                                             low_frequency_cutoff, **kwargs)

        # Generate template waveforms
        df = data[self.detectors[0]].delta_f
        p = self.static_params.copy()
        if 'distance' in p:
            _ = p.pop('distance')
        if 'inclination' in p:
            _ = p.pop('inclination')
        hp, _ = get_fd_waveform(delta_f=df, distance=1, inclination=0, **p)

        # Extend template to high sample rate
        flen = int(int(sample_rate) / df) / 2 + 1
        hp.resize(flen)
        #polarization array to marginalize over if num_samples given
        self.pflag = 0
        if polarization_samples is not None:
            self.polarization = numpy.linspace(0, 2 * numpy.pi,
                                               int(polarization_samples))
            self.pflag = 1

        # Calculate high sample rate SNR time series
        self.sh = {}
        self.hh = {}
        self.det = {}
        for ifo in self.data:
            flow = self.kmin[ifo] * df
            fhigh = self.kmax[ifo] * df
            # Extend data to high sample rate
            self.data[ifo].resize(flen)
            self.det[ifo] = Detector(ifo)
            snr, _, _ = pyfilter.matched_filter_core(
                hp,
                self.data[ifo],
                psd=self.psds[ifo],
                low_frequency_cutoff=flow,
                high_frequency_cutoff=fhigh)

            self.sh[ifo] = 4 * df * snr
            self.hh[ifo] = pyfilter.sigmasq(hp,
                                            psd=self.psds[ifo],
                                            low_frequency_cutoff=flow,
                                            high_frequency_cutoff=fhigh)
        self.time = None
Exemple #13
0
    def __init__(self,
                 data,
                 psds,
                 low_frequency_cutoff=None,
                 high_frequency_cutoff=None,
                 sample_rate=32768,
                 **kwargs):

        super(SingleTemplate, self).__init__(data=data, **kwargs)

        if low_frequency_cutoff is not None:
            low_frequency_cutoff = float(low_frequency_cutoff)

        if high_frequency_cutoff is not None:
            high_frequency_cutoff = float(high_frequency_cutoff)

        # Generate template waveforms
        df = data[tuple(data.keys())[0]].delta_f
        p = self.static_params.copy()
        if 'distance' in p:
            p.pop('distance')
        if 'inclination' in p:
            p.pop('inclination')

        hp, _ = get_fd_waveform(delta_f=df, distance=1, inclination=0, **p)

        if high_frequency_cutoff is None:
            high_frequency_cutoff = len(data[tuple(data.keys())[0]] - 1) * df

        # Extend data and template to high sample rate
        flen = int(sample_rate / df) / 2 + 1
        hp.resize(flen)
        for ifo in data:
            data[ifo].resize(flen)

        # Calculate high sample rate SNR time series
        self.sh = {}
        self.hh = {}
        self.det = {}
        for ifo in data:
            self.det[ifo] = Detector(ifo)
            snr, _, _ = pyfilter.matched_filter_core(
                hp,
                data[ifo],
                psd=psds[ifo],
                low_frequency_cutoff=low_frequency_cutoff,
                high_frequency_cutoff=high_frequency_cutoff)

            self.sh[ifo] = 4 * df * snr
            self.hh[ifo] = -0.5 * pyfilter.sigmasq(
                hp,
                psd=psds[ifo],
                low_frequency_cutoff=low_frequency_cutoff,
                high_frequency_cutoff=high_frequency_cutoff)
        self.time = None
Exemple #14
0
def get_waveform(p, **kwds):
    """ Given the input parameters get me the waveform, whether it is TD or
        FD
    """
    params = copy.copy(p.__dict__)
    params.update(kwds)

    if params['approximant'] in td_approximants():
        return get_td_waveform(**params)
    else:
        return get_fd_waveform(**params)
Exemple #15
0
def get_waveform(p, **kwds):
    """ Given the input parameters get me the waveform, whether it is TD or
        FD
    """
    params = copy.copy(p.__dict__)
    params.update(kwds)

    if params['approximant'] in td_approximants():
        return get_td_waveform(**params)
    else:
        return get_fd_waveform(**params)
Exemple #16
0
    def setUp(self, *args):
        self.context = _context
        self.scheme = _scheme
        self.tolerance = 1e-6
        xr = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        xi = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        self.x = Array(xr + xi * 1.0j, dtype=complex64)
        self.z = zeros(2**20, dtype=float32)
        for i in range(0, 4):
            trusted_accum(self.z, self.x)

        m = Merger("GW170814")

        ifos = ['H1', 'L1', 'V1']
        data = {}
        psd = {}
        for ifo in ifos:
            # Read in and condition the data and measure PSD
            ts = m.strain(ifo).highpass_fir(15, 512)
            data[ifo] = resample_to_delta_t(ts, 1.0 / 2048).crop(2, 2)
            p = data[ifo].psd(2)
            p = interpolate(p, data[ifo].delta_f)
            p = inverse_spectrum_truncation(p,
                                            int(2 * data[ifo].sample_rate),
                                            low_frequency_cutoff=15.0)
            psd[ifo] = p
        hp, _ = get_fd_waveform(approximant="IMRPhenomD",
                                mass1=31.36,
                                mass2=31.36,
                                f_lower=20.0,
                                delta_f=data[ifo].delta_f)
        hp.resize(len(psd[ifo]))

        # For each ifo use this template to calculate the SNR time series
        snr = {}
        snr_unnorm = {}
        norm = {}
        corr = {}
        for ifo in ifos:
            snr_unnorm[ifo], corr[ifo], norm[ifo] = \
                matched_filter_core(hp, data[ifo], psd=psd[ifo],
                                    low_frequency_cutoff=20)
            snr[ifo] = snr_unnorm[ifo] * norm[ifo]

        self.snr = snr
        self.snr_unnorm = snr_unnorm
        self.norm = norm
        self.corr = corr
        self.hp = hp
        self.data = data
        self.psd = psd
        self.ifos = ifos
    def __init__(self, data, psds,
                 low_frequency_cutoff=None,
                 high_frequency_cutoff=None,
                 sample_rate=32768,
                 **kwargs):

        super(SingleTemplate, self).__init__(data=data, **kwargs)

        if low_frequency_cutoff is not None:
            low_frequency_cutoff = float(low_frequency_cutoff)

        if high_frequency_cutoff is not None:
            high_frequency_cutoff = float(high_frequency_cutoff)

        # Generate template waveforms
        df = data[data.keys()[0]].delta_f
        p = self.static_params.copy()
        if 'distance' in p:
            p.pop('distance')
        if 'inclination' in p:
            p.pop('inclination')

        hp, _ = get_fd_waveform(delta_f=df, distance=1, inclination=0, **p)

        if high_frequency_cutoff is None:
            high_frequency_cutoff = len(data[data.keys()[0]]-1) * df

        # Extend data and template to high sample rate
        flen = int(sample_rate / df) / 2 + 1
        hp.resize(flen)
        for ifo in data:
            data[ifo].resize(flen)

        # Calculate high sample rate SNR time series
        self.sh = {}
        self.hh = {}
        self.det = {}
        for ifo in data:
            self.det[ifo] = Detector(ifo)
            snr, _, _ = pyfilter.matched_filter_core(
                hp, data[ifo],
                psd=psds[ifo],
                low_frequency_cutoff=low_frequency_cutoff,
                high_frequency_cutoff=high_frequency_cutoff)

            self.sh[ifo] = 4 * df * snr
            self.hh[ifo] = -0.5 * pyfilter.sigmasq(
                hp, psd=psds[ifo],
                low_frequency_cutoff=low_frequency_cutoff,
                high_frequency_cutoff=high_frequency_cutoff)
        self.time = None
Exemple #18
0
 def test_generation(self):
     with self.context:
         for waveform in td_approximants():
             if waveform in failing_wfs:
                 continue
             print(waveform)
             hc,hp = get_td_waveform(approximant=waveform,mass1=20,mass2=20,delta_t=1.0/4096,f_lower=40)
             self.assertTrue(len(hc)> 0)
         for waveform in fd_approximants():
             if waveform in failing_wfs:
                 continue
             print(waveform)
             htilde, g = get_fd_waveform(approximant=waveform,mass1=20,mass2=20,delta_f=1.0/256,f_lower=40)
             self.assertTrue(len(htilde)> 0)
Exemple #19
0
    def setUp(self,*args):
        self.context = _context
        self.scheme = _scheme
        self.tolerance = 1e-6
        xr = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        xi = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        self.x = Array(xr + xi * 1.0j, dtype=complex64)
        self.z = zeros(2**20, dtype=float32)
        for i in range(0, 4):
            trusted_accum(self.z, self.x)

        m = Merger("GW170814")

        ifos = ['H1', 'L1', 'V1']
        data = {}
        psd = {}
        for ifo in ifos:
            # Read in and condition the data and measure PSD
            ts = m.strain(ifo).highpass_fir(15, 512)
            data[ifo] = resample_to_delta_t(ts, 1.0/2048).crop(2, 2)
            p = data[ifo].psd(2)
            p = interpolate(p, data[ifo].delta_f)
            p = inverse_spectrum_truncation(p, 2 * data[ifo].sample_rate,
                                            low_frequency_cutoff=15.0)
            psd[ifo] = p
        hp, _ = get_fd_waveform(approximant="IMRPhenomD",
                                 mass1=31.36, mass2=31.36,
                                 f_lower=20.0, delta_f=data[ifo].delta_f)
        hp.resize(len(psd[ifo]))

        # For each ifo use this template to calculate the SNR time series
        snr = {}
        snr_unnorm = {}
        norm = {}
        corr = {}
        for ifo in ifos:
            snr_unnorm[ifo], corr[ifo], norm[ifo] = \
                matched_filter_core(hp, data[ifo], psd=psd[ifo],
                                    low_frequency_cutoff=20)
            snr[ifo] = snr_unnorm[ifo] * norm[ifo]

        self.snr = snr
        self.snr_unnorm = snr_unnorm
        self.norm = norm
        self.corr = corr
        self.hp = hp
        self.data = data
        self.psd = psd
        self.ifos = ifos
Exemple #20
0
    def test_spatmplt(self):
        fl = 25
        delta_f = 1.0 / 256

        for m1 in [1, 1.4, 20]:
            for m2 in [1.4, 20]:
                for s1 in [-2, -1, -0.5, 0, 0.5, 1, 2]:
                    for s2 in [-2, -1, -0.5, 0, 0.5, 1, 2]:
                        # Generate TaylorF2 from lalsimulation, restricting to the capabilities of spatmplt
                        hpr, _ = get_fd_waveform(mass1=m1,
                                                 mass2=m2,
                                                 spin1z=s1,
                                                 spin2z=s2,
                                                 delta_f=delta_f,
                                                 f_lower=fl,
                                                 approximant="TaylorF2",
                                                 amplitude_order=0,
                                                 spin_order=-1,
                                                 phase_order=-1)
                        hpr = hpr.astype(complex64)

                        with self.context:
                            # Generate the spatmplt waveform
                            out = zeros(len(hpr), dtype=complex64)
                            hp = get_waveform_filter(out,
                                                     mass1=m1,
                                                     mass2=m2,
                                                     spin1z=s1,
                                                     spin2z=s2,
                                                     delta_f=delta_f,
                                                     f_lower=fl,
                                                     approximant="SPAtmplt",
                                                     amplitude_order=0,
                                                     spin_order=-1,
                                                     phase_order=-1)

                            # Check the diff is sane
                            mag = abs(hpr).sum()
                            diff = abs(hp - hpr).sum() / mag
                            self.assertTrue(diff < 0.01)

                            # Point to point overlap (no phase or time maximization)
                            o = overlap(hp, hpr)
                            self.assertAlmostEqual(1.0, o, places=4)

                            print(
                                "checked m1: %s m2:: %s s1z: %s s2z: %s] overlap = %s, diff = %s"
                                % (m1, m2, s1, s2, o, diff))
Exemple #21
0
def get_waveform(approximant, order, template_params, start_frequency, sample_rate, length):

    if approximant in fd_approximants():
        delta_f = float(sample_rate) / length
        hvec = get_fd_waveform(template_params, approximant=approximant,
                               phase_order=order, delta_f=delta_f,
                               f_lower=start_frequency, amplitude_order=order)     

    if approximant in td_approximants():
        hplus,hcross = get_td_waveform(template_params, approximant=approximant,
                                   phase_order=order, delta_t=1.0 / sample_rate,
                                   f_lower=start_frequency, amplitude_order=order) 
        hvec = hplus

    htilde = make_padded_frequency_series(hvec,filter_N)

    return htilde
Exemple #22
0
def get_waveform(wf_params, start_frequency, sample_rate, length,
                 filter_rate, sky_max_template=False):
    delta_f = filter_rate / float(length)
    if wf_params.approximant in fd_approximants():
        hp, hc = get_fd_waveform(wf_params, delta_f=delta_f,
                                 f_lower=start_frequency)

    elif wf_params.approximant in td_approximants():
        hp, hc = get_td_waveform(wf_params, delta_t=1./sample_rate,
                                 f_lower=start_frequency)

    if not sky_max_template:
        hvec = generate_detector_strain(wf_params, hp, hc)
        return make_padded_frequency_series(hvec, length, delta_f=delta_f)
    else:
        return make_padded_frequency_series(hp, length, delta_f=delta_f), \
            make_padded_frequency_series(hc, length, delta_f=delta_f)
Exemple #23
0
def get_waveform(wf_params, start_frequency, sample_rate, length,
                 filter_rate, sky_max_template=False):
    delta_f = filter_rate / float(length)
    if wf_params.approximant in fd_approximants():
        hp, hc = get_fd_waveform(wf_params, delta_f=delta_f,
                                 f_lower=start_frequency)

    elif wf_params.approximant in td_approximants():
        hp, hc = get_td_waveform(wf_params, delta_t=1./sample_rate,
                                 f_lower=start_frequency)

    if not sky_max_template:
        hvec = generate_detector_strain(wf_params, hp, hc)
        return make_padded_frequency_series(hvec, length, delta_f=delta_f)
    else:
        return make_padded_frequency_series(hp, length, delta_f=delta_f), \
            make_padded_frequency_series(hc, length, delta_f=delta_f)
    def __init__(self,
                 variable_params,
                 data,
                 low_frequency_cutoff,
                 sample_rate=32768,
                 **kwargs):
        super(SingleTemplate, self).__init__(variable_params, data,
                                             low_frequency_cutoff, **kwargs)

        # Generate template waveforms
        df = data[self.detectors[0]].delta_f
        p = self.static_params.copy()
        if 'distance' in p:
            _ = p.pop('distance')
        if 'inclination' in p:
            _ = p.pop('inclination')
        hp, _ = get_fd_waveform(delta_f=df, distance=1, inclination=0, **p)

        # Extend template to high sample rate
        flen = int(int(sample_rate) / df) / 2 + 1
        hp.resize(flen)

        # Calculate high sample rate SNR time series
        self.sh = {}
        self.hh = {}
        self.det = {}
        for ifo in self.data:
            flow = self.kmin[ifo] * df
            fhigh = self.kmax[ifo] * df
            # Extend data to high sample rate
            self.data[ifo].resize(flen)
            self.det[ifo] = Detector(ifo)
            snr, _, _ = pyfilter.matched_filter_core(
                hp,
                self.data[ifo],
                psd=self.psds[ifo],
                low_frequency_cutoff=flow,
                high_frequency_cutoff=fhigh)

            self.sh[ifo] = 4 * df * snr
            self.hh[ifo] = -0.5 * pyfilter.sigmasq(hp,
                                                   psd=self.psds[ifo],
                                                   low_frequency_cutoff=flow,
                                                   high_frequency_cutoff=fhigh)
        self.time = None
Exemple #25
0
def get_waveform(approximant, phase_order, amplitude_order, template_params, start_frequency, sample_rate, length):

    if approximant in td_approximants():
        hplus,hcross = get_td_waveform(template_params, approximant=approximant,
                                   phase_order=phase_order, delta_t=1.0 / sample_rate,
                                   f_lower=start_frequency, amplitude_order=amplitude_order) 
        hvec = generate_detector_strain(template_params, hplus, hcross)

    elif approximant in fd_approximants():
        delta_f = sample_rate / length
        hvec = get_fd_waveform(template_params, approximant=approximant,
                               phase_order=phase_order, delta_f=delta_f,
                               f_lower=start_frequency, amplitude_order=amplitude_order)     


    htilde = make_padded_frequency_series(hvec,filter_N)

    return htilde
Exemple #26
0
 def test_generation(self):
     with self.context:
         for waveform in good_waveforms:
             print(waveform)
             hc, hp = get_td_waveform(approximant=waveform,
                                      mass1=20,
                                      mass2=20,
                                      delta_t=1.0 / 4096,
                                      f_lower=40)
             self.assertTrue(len(hc) > 0)
         for waveform in good_waveforms:
             print(waveform)
             htilde, g = get_fd_waveform(approximant=waveform,
                                         mass1=20,
                                         mass2=20,
                                         delta_f=1.0 / 256,
                                         f_lower=40)
             self.assertTrue(len(htilde) > 0)
Exemple #27
0
def get_waveform(approximant, phase_order, amplitude_order, template_params, start_frequency, sample_rate, length):

    if approximant in td_approximants():
        hplus,hcross = get_td_waveform(template_params, approximant=approximant,
                                   phase_order=phase_order, delta_t=1.0 / sample_rate,
                                   f_lower=start_frequency, amplitude_order=amplitude_order)
        hvec = generate_detector_strain(template_params, hplus, hcross)

    elif approximant in fd_approximants():
        delta_f = sample_rate / length
        hvec = get_fd_waveform(template_params, approximant=approximant,
                               phase_order=phase_order, delta_f=delta_f,
                               f_lower=start_frequency, amplitude_order=amplitude_order)


    htilde = make_padded_frequency_series(hvec,filter_N)

    return htilde
Exemple #28
0
def generate_template(**options):

    incl, psi0, spin1 = coords.to_lal_coords(options['M1'], options['M2'], \
                        options['CHI1'], options['KAPPA'], options['THETAJ'], \
                        options['PSIJ'], options['ALPHA0'], options['F_INJ'])

    # FIXME: Number of samples of the waveform.
    nsamples = int((options['F_MAX']) / options['DEL_F']) + 1

    hpluss, hcross = get_fd_waveform(
        approximant=options['APPROX'],  #Input
        mass1=options['M1'],  #Input
        mass2=options['M2'],  #Input
        delta_f=options['DEL_F'],  #Input
        f_lower=options['F_MIN'],  #Input
        f_final=options['F_MAX'],  #Input, can be turned off.
        distance=400.0,  #Default
        inclination=incl,  #to_lal_coords
        coa_phase=options['PHI0'],  #Input
        spin1x=spin1[0],  #to_lal_coords
        spin1y=spin1[1],  #to_lal_coords
        spin1z=spin1[2],  #to_lal_coords
        spin2x=0.0,  #Default
        spin2y=0.0,  #Default
        spin2z=0.0,  #Default
        phase_order=7,  #Default
        spin_order=6,  #Default
        amplitude_order=0,  #Default
        sideband=options['BAND']  #Input
    )

    #--------------------------------------------------
    # NOTE: We're only plotting the hpluss strain here.
    #--------------------------------------------------

    # sin2Y, cos2Y = np.sin(2.*psi0), np.cos(2.*psi0)

    # hp   = pycbc.DYN_RANGE_FAC*hpluss
    # hc   = pycbc.DYN_RANGE_FAC*hcross

    # waveform =  hp*cos2Y + hc*sin2Y
    # waveform.resize(nsamples)

    return hpluss
 def FUNC(x):
     # Substitute the right parameter
     deriv_param = param_list['deriv_param']
     param_list[deriv_param] = x
     # Compute the waveform
     if approximant in td_approximants():
         test_hp, test_hc = get_td_waveform(
             approximant=approximant,
             mass1=param_list['mass1'],
             mass2=param_list['mass2'],
             spin1x=param_list['spin1x'],
             spin1y=param_list['spin1y'],
             spin1z=param_list['spin1z'],
             spin2x=param_list['spin2x'],
             spin2y=param_list['spin2y'],
             spin2z=param_list['spin2z'],
             distance=param_list['distance'],
             inclination=param_list['inclination'],
             coa_phase=param_list['coa_phase'],
             f_lower=f_lower,
             delta_t=delta_t)
         test_wav = generate_detector_strain(param_list, test_hp, test_hc)
         test_wav = extend_waveform_TimeSeries(test_wav, N)
     elif approximant in fd_approximants():
         test_hp, test_hc = get_fd_waveform(
             approximant=approximant,
             mass1=param_list['mass1'],
             mass2=param_list['mass2'],
             spin1x=param_list['spin1x'],
             spin1y=param_list['spin1y'],
             spin1z=param_list['spin1z'],
             spin2x=param_list['spin2x'],
             spin2y=param_list['spin2y'],
             spin2z=param_list['spin2z'],
             distance=param_list['distance'],
             inclination=param_list['inclination'],
             coa_phase=param_list['coa_phase'],
             f_lower=f_lower,
             delta_f=delta_f)
         test_wav = generate_detector_strain(param_list, test_hp, test_hc)
         test_wav = extend_waveform_FrequencySeries(test_wav, n)
     # Return waveform
     return np.array(test_wav.data)
Exemple #30
0
def generate_analytic_waveform(mass_rat,
                               eccentricity,
                               approximant='TaylorF2Ecc',
                               total_m=50,
                               f_lower=20.,
                               delta_f=0.1):
    mass1, mass2 = q_to_masses(mass_rat, total_m)
    hp, hc = hp, hc = get_fd_waveform(mass1=mass1,
                                      mass2=mass2,
                                      delta_f=delta_f,
                                      f_lower=f_lower,
                                      approximant=approximant,
                                      eccentricity=eccentricity)
    hs = hp + hc * 1j
    amp = amplitude_from_frequencyseries(
        types.FrequencySeries(hs, delta_f=delta_f))
    phase = phase_from_frequencyseries(
        types.FrequencySeries(hs, delta_f=delta_f))
    return hp.sample_frequencies.data, np.real(hp.data), np.real(
        hc.data), np.imag(hp.data), np.imag(hc.data), amp.data, phase.data
Exemple #31
0
def fd(taper_start=None, taper_end=None, **kwds):
    from pycbc.waveform import get_fd_waveform
    from pycbc.waveform.utils import fd_taper

    flow = kwds['f_lower']
    fhigh = kwds['f_final']

    if 'approximant' in kwds:
        kwds.pop("approximant")
    hp, hc = get_fd_waveform(approximant="TaylorF2", **kwds)

    if taper_start:
        hp = fd_taper(hp, flow, flow + taper_start, side='left')
        hc = fd_taper(hc, flow, flow + taper_start, side='left')

    if taper_end:
        hp = fd_taper(hp, fhigh - taper_end, fhigh, side='right')
        hc = fd_taper(hc, fhigh - taper_end, fhigh, side='right')

    return hp, hc
Exemple #32
0
def nonlinear_tidal_spa(**kwds):
    """Generates a frequency-domain waveform that implements the
    TaylorF2+NL tide model described in https://arxiv.org/abs/1808.07013
    """

    from pycbc import waveform
    from pycbc.types import Array

    # We start with the standard TaylorF2 based waveform
    kwds.pop('approximant')
    hp, hc = waveform.get_fd_waveform(approximant="TaylorF2", **kwds)

    # Add the phasing difference from the nonlinear tides
    f = numpy.arange(len(hp)) * hp.delta_f
    pd = Array(numpy.exp(-1.0j * nltides_fourier_phase_difference(
        f, hp.delta_f, kwds['f0'], kwds['amplitude'], kwds['n'], kwds['mass1'],
        kwds['mass2'])),
               dtype=hp.dtype)
    hp *= pd
    hc *= pd
    return hp, hc
def compute_SNR_1Mpc(arg):
    '''Return the one-detector SNR an event of given parameters would 
    have, given the PSD and assuming D=1Mpc, optimal orientation and
    that the template is identical to the signal.
    '''
    approximant, p_dict = arg
    m1 = m1_of_Mchirp_q(p_dict['M_chirp'], p_dict['q'])
    m2 = m2_of_Mchirp_q(p_dict['M_chirp'], p_dict['q'])
    H = np.array(
        waveform.get_fd_waveform(
            mass1=m1,
            mass2=m2,
            spin1z=p_dict['chi_eff'],
            spin2z=p_dict['chi_eff'],  # Force chi1 == chi2 == chi_eff
            approximant=approximant,
            f_lower=f_lower,
            f_final=fs / 2,
            delta_f=df)[0])
    SNR_1Mpc = {}
    for psd in PSDs:
        SNR_1Mpc[psd] = sqrt((4 * abs(H[imin:imax])**2 / PSD[psd] * df).sum())
    return SNR_1Mpc
def find_pycbc_SNR(M1, M2, dist, alpha, delta, iota):
    SNRs_for_RUN = {}
    M1 = M1 / Msun
    M2 = M2 / Msun
    # print "m1: {}, m2: {}, r: {}".format(M1, M2, dist)
    # Making an SNR dictionary for SNR arrays corresponding to diff RUNs
    SNRs_for_RUN = {}
    # For each RUN like "O1"
    for RUN in for_run.keys():
        Dist = dist[RUN] / Mpc
        # We get an array of SNRs of the size of M1
        SNRs_for_RUN[RUN] = np.zeros(len(M1))
        # Calculation for each binary
        for i in range(len(M1)):
            if i == 2:
                start_t = time.time()
            # Strain calculation only for (+) polarization
            sptilde, _ = get_fd_waveform(approximant="IMRPhenomD",
                                         mass1=M1[i],
                                         mass2=M2[i],
                                         distance=Dist[i],
                                         inclination=iota[i],
                                         delta_f=df,
                                         f_lower=freq[0],
                                         f_final=freq[-1])
            sptilde.resize(len(PSD_for_det['O1_L1']))
            # root of sum of sigma squares in individual detectors
            for det in for_run[RUN]:
                # SNR in each detector
                SNRs_for_RUN[RUN][i] += mf.sigmasq(
                    sptilde,
                    psd=PSD_for_det[detector[det]],
                    low_frequency_cutoff=freq[0])
            if i == 2:
                print "For {} run, expected time: {} min".format(
                    RUN, (time.time() - start_t) * len(M1) / 60.)
        # taking root to get values of SNR
        SNRs_for_RUN[RUN] = np.sqrt(SNRs_for_RUN[RUN])
    return SNRs_for_RUN
Exemple #35
0
def nonlinear_tidal_spa(**kwds):
    """Generates a frequency-domain waveform that implements the
    TaylorF2+NL tide model described in https://arxiv.org/abs/1808.07013
    """

    from pycbc import waveform
    from pycbc.types import Array

    # We start with the standard TaylorF2 based waveform
    kwds.pop('approximant')
    hp, hc = waveform.get_fd_waveform(approximant="TaylorF2", **kwds)

    # Add the phasing difference from the nonlinear tides
    f = numpy.arange(len(hp)) * hp.delta_f
    pd =  Array(numpy.exp(-1.0j * nltides_fourier_phase_difference(f,
               hp.delta_f,
               kwds['f0'], kwds['amplitude'], kwds['n'],
               kwds['mass1'], kwds['mass2'])),
               dtype=hp.dtype)
    hp *= pd
    hc *= pd
    return hp, hc
Exemple #36
0
def get_waveform(wav, f_min, dt, N):
    """This function will generate the waveform corresponding to the point taken as input"""
    #{{{
    m1 = wav.mass1
    m2 = wav.mass2

    s1x = wav.spin1x
    s1y = wav.spin1y
    s1z = wav.spin1z
    s2x = wav.spin2x
    s2y = wav.spin2y
    s2z = wav.spin2z

    inc = wav.inclination
    psi = wav.polarization
    theta = wav.latitude
    phi = wav.longitude

    df = 1. / (dt * N)
    f_max = min(1. / (2. * dt), 0.15 / ((m1 + m2) * qm.QM_MTSUN_SI))

    htild = get_fd_waveform(approximant="IMRPhenomC",
                            mass1=m1,
                            mass2=m2,
                            spin1z=s1z,
                            spin2z=s2z,
                            f_lower=f_min,
                            f_final=f_max,
                            delta_f=df)

    htilde = FrequencySeries(htild, delta_f=df, dtype=complex128, copy=True)
    href_padded = FrequencySeries(zeros(N / 2 + 1),
                                  delta_f=df,
                                  dtype=complex128,
                                  copy=True)
    href_padded[0:len(htilde)] = htilde

    return href_padded
Exemple #37
0
    def next(self):
        images = []
        targets = []
        for i in range(self.batch):
            n = self.noise.next()
            p = self.param.draw()
            hp, _ = get_fd_waveform(p, delta_f=n.delta_f,
                                    f_lower=self.noise.flow, **self.param.static)
            hp.resize(len(n))
            sg = sigma(hp, psd=self.noise.psd, low_frequency_cutoff=self.noise.flow)
            n += hp.cyclic_time_shift(p.tc) / sg * p.snr
            
            msnr = matched_filter(hp, n, psd=self.noise.psd,
                                  low_frequency_cutoff=self.noise.flow)
            snr = abs(msnr.crop(self.whitening_truncation,
                                self.whitening_truncation)).max()

            n = n.to_timeseries()
            w = n.whiten(self.whitening_truncation, self.whitening_truncation)

            dt = self.duration / float(self.image_dim[0])
            fhigh = self.noise.sample_rate * 0.3
            t, f, p = w.qtransform(dt, logfsteps=self.image_dim[1],
                                       frange=(self.noise.flow, fhigh),
                                       qrange=(self.q, self.q),
                                       return_complex=True)

            kmin = int((w.duration / 2 - self.duration / 2) / dt)
            kmax = kmin + int(self.duration / dt)
            p = p[:, kmin:kmax].transpose()
            
            amp = numpy.abs(p)
            p = numpy.stack([p.real, p.imag, amp], axis=2)
            images.append(p)
            targets.append(snr)
        
        return numpy.stack(images, axis=0), numpy.array(targets)
Exemple #38
0
# accurately calibrated, and swamps smaller noises at higher frequencies.

# For this example, we want to calculate the SNR over a 4 second segment, so
# we calculate a Power Spectral Density with a 4 second FFT length (using all
# of the data), then :meth:`~TimeSeries.crop` the data:

psd = high.psd(4, 2)
zoom = high.crop(1126259460, 1126259464)

# In order to calculate signal-to-noise ratio, we need a signal model
# against which to compare our data.
# For this we import :func:`~pycbc.waveform.get_fd_waveform` and generate a
# template `~pycbc.types.frequencyseries.FrequencySeries`:

from pycbc.waveform import get_fd_waveform
hp, _ = get_fd_waveform(approximant="IMRPhenomD", mass1=40, mass2=32,
                        f_lower=20, f_final=2048, delta_f=psd.df.value)

# At this point we are ready to calculate the SNR, so we import the
# :func:`~pycbc.filter.matched_filter` method, and pass it our template,
# the data, and the PSD, using the :meth:`~TimeSeries.to_pycbc` methods of
# the `TimeSeries` and `~gwpy.frequencyseries.FrequencySeries` objects:

import numpy
from pycbc.filter import matched_filter
snr = matched_filter(hp, zoom.to_pycbc(), psd=psd.to_pycbc(),
                     low_frequency_cutoff=15)
snrts = TimeSeries.from_pycbc(snr).abs()

# We can plot the SNR `TimeSeries` around the region of interest:
plot = snrts.plot()
ax = plot.gca()
Exemple #39
0
# the Gibb's phenomenon. (http://en.wikipedia.org/wiki/Gibbs_phenomenon)

import pylab
from pycbc import types, fft, waveform

# Get a time domain waveform
hp, hc = waveform.get_td_waveform(approximant="EOBNRv2",
                                  mass1=6,
                                  mass2=6,
                                  delta_t=1.0 / 4096,
                                  f_lower=40)

# Get a frequency domain waveform
sptilde, sctilde = waveform.get_fd_waveform(approximant="TaylorF2",
                                            mass1=6,
                                            mass2=6,
                                            delta_f=1.0 / 4,
                                            f_lower=40)

# FFT it to the time-domain
tlen = 1.0 / hp.delta_t / sptilde.delta_f
sptilde.resize(tlen / 2 + 1)
sp = types.TimeSeries(types.zeros(tlen), delta_t=hp.delta_t)
fft.ifft(sptilde, sp)

pylab.plot(sp.sample_times, sp, label="TaylorF2 (IFFT)")
pylab.plot(hp.sample_times, hp, label="EOBNRv2")

pylab.ylabel('Strain')
pylab.xlabel('Time (s)')
pylab.legend()
Exemple #40
0
from pycbc.waveform import get_fd_waveform 
from pycbc.psd import welch, interpolate
import urllib

# Read data and remove low frequency content
fname = 'H-H1_LOSC_4_V2-1126259446-32.gwf'
url = "https://losc.ligo.org/s/events/GW150914/" + fname
urllib.urlretrieve(url, filename=fname)
h1 = read_frame('H-H1_LOSC_4_V2-1126259446-32.gwf', 'H1:LOSC-STRAIN')
h1 = highpass_fir(h1, 15, 8)

# Calculate the noise spectrum
psd = interpolate(welch(h1), 1.0 / 32)

# Generate a template to filter with
hp, hc = get_fd_waveform(approximant="IMRPhenomD", mass1=40, mass2=32, 
                         f_lower=20, delta_f=1.0/32)
hp.resize(len(h1) / 2 + 1)

# Calculate the complex (two-phase SNR)
snr = matched_filter(hp, h1, psd=psd, low_frequency_cutoff=20.0)

# Remove regions corrupted by filter wraparound 
snr = snr[len(snr) / 4: len(snr) * 3 / 4]

import pylab
pylab.plot(snr.sample_times, abs(snr))
pylab.ylabel('signal-to-noise')
pylab.xlabel('GPS Time (s)')
pylab.show()

Exemple #41
0
def get_chirp_time_region(trigger_params,
                          psd,
                          miss_match,
                          f_lower=30.,
                          f_max=2048.,
                          f_ref=30.):
    central_param = copy.deepcopy(trigger_params)
    # if central_param['approximant'] == 'SPAtmplt':
    central_param['approximant'] == 'TaylorF2RedSpin'
    # if not ('tau0' and 'tau3' in central_param):
    #     t0, t3 = pnu.mass1_mass2_to_tau0_tau3(central_param['mass1'], central_param['mass2'], f_ref)
    # else:
    #     t0 = central_param['tau0']
    #     t3 = central_param['tau3']
    # for tau0 boundary
    newt0, newt3 = temp_tau0_tau3_with_valid_dtau0(central_param['tau0'],
                                                   central_param['tau3'],
                                                   f_ref)
    temp_param0 = temp_param_from_central_param(central_param, newt0, newt3,
                                                f_ref)
    # for tau3 boundary
    newt0, newt3 = temp_tau0_tau3_with_valid_dtau3(central_param['tau0'],
                                                   central_param['tau3'],
                                                   f_ref)
    temp_param3 = temp_param_from_central_param(central_param, newt0, newt3,
                                                f_ref)

    tlen = pnu.nearest_larger_binary_number(
        max([central_param['tau0'], temp_param0['tau0'], temp_param3['tau0']]))
    df = 1.0 / tlen
    flen = int(f_max / df) + 1

    # hp = pt.zeros(flen, dtype=pt.complex64)
    # hp0 = pt.zeros(flen, dtype=pt.complex64)
    # hp3 = pt.zeros(flen, dtype=pt.complex64)

    # print central_param['approximant']

    # if central_param['approximant'] == 'SPAtmplt':
    #     central_param['approximant'] == 'TaylorF2RedSpin'
    # hp = pw.get_waveform_filter(hp, central_param, delta_f=df, f_lower=f_lower, f_ref=f_ref, f_final=f_max)
    # hp0 = pw.get_waveform_filter(hp0, temp_param0, delta_f=df, f_lower=f_lower, f_ref=f_ref, f_final=f_max)
    # hp3 = pw.get_waveform_filter(hp3, temp_param3, delta_f=df, f_lower=f_lower, f_ref=f_ref, f_final=f_max)
    # else:
    hp, hc = pw.get_fd_waveform(central_param,
                                delta_f=df,
                                f_lower=f_lower,
                                f_ref=f_ref,
                                f_final=f_max)
    hp0, hc0 = pw.get_fd_waveform(temp_param0,
                                  delta_f=df,
                                  f_lower=f_lower,
                                  f_ref=f_ref,
                                  f_final=f_max)
    hp3, hc3 = pw.get_fd_waveform(temp_param3,
                                  delta_f=df,
                                  f_lower=f_lower,
                                  f_ref=f_ref,
                                  f_final=f_max)

    # FIXME: currently will using aLIGOZeroDetHighPower
    # FIXME: add how to make sure, psd numerical problems of psd
    if psd is not None:
        ipsd = pp.interpolate(psd, df)
    else:
        ipsd = None
        # ipsd = pp.aLIGOZeroDetHighPower(flen, df, f_lower)
        # ipsd = pp.interpolate(ipsd, df)
        # ipsd.data[-1] = 2.0*ipsd.data[-2]
        # ipsd = ipsd.astype(hp.dtype)

    mat0, _ = pf.match(hp, hp0, ipsd, f_lower, f_max)
    mat3, _ = pf.match(hp, hp3, ipsd, f_lower, f_max)
    # print mat0, mat3, miss_match
    #     print central_param['tau0'], central_param['tau3']
    #     print temp_param0['tau0'], temp_param0['tau3']
    #     print temp_param3['tau0'], temp_param3['tau3']
    #     print float(temp_param0['tau0'])-float(central_param['tau0'])
    #     print temp_param3['tau3']-central_param['tau3']
    dtau0_range = miss_match * (temp_param0['tau0'] -
                                central_param['tau0']) / (1.0 - mat0)
    dtau3_range = miss_match * (temp_param3['tau3'] -
                                central_param['tau3']) / (1.0 - mat3)
    #     print dtau0_range, dtau3_range
    return dtau0_range, dtau3_range
        hplus_approx = wfutils.taper_timeseries(hplus_approx, "TAPER_STARTEND")
        hcross_approx = wfutils.taper_timeseries(hcross_approx, "TAPER_STARTEND")

        approx_freqs = wfutils.frequency_from_polarizations(hplus_approx, hcross_approx)

    # elif approx == 'IMRPhenomPv2' or approx == 'IMRPhenomP':
    elif approx in fd_approximants():

        Hplus_approx, Hcross_approx = get_fd_waveform(
            approximant=approx,
            distance=distance,
            mass1=mass1,
            mass2=mass2,
            spin1x=simulations.simulations[0]["spin1x"],
            spin2x=simulations.simulations[0]["spin2x"],
            spin1y=simulations.simulations[0]["spin1y"],
            spin2y=simulations.simulations[0]["spin2y"],
            spin1z=simulations.simulations[0]["spin1z"],
            spin2z=simulations.simulations[0]["spin2z"],
            inclination=inc,
            f_lower=10,  # f_low_approx * min(masses)/mass,
            delta_f=delta_f,
        )

        tlen = int(1.0 / delta_t / Hplus_approx.delta_f)
        Hplus_approx.resize(tlen / 2 + 1)
        delta_f = 1 / (tlen * delta_t)
        hplus_approx = Hplus_approx.to_timeseries()

        Hcross_approx.resize(tlen / 2 + 1)
        hcross_approx = Hcross_approx.to_timeseries()