Пример #1
0
 def simulated_signals(noise):  
   global next_val,signal_gw
   apx=['TaylorT1','TaylorT2','EOBNRv2','SEOBNRv1','SEOBNRv2']
   with open('gdrive/My Drive/GW data/labels_5_noise.csv', 'a', newline='') as file:
     for a in tqdm(range(len(apx))):
       check=np.zeros(noise.shape[1])
       k=0
       for m1 in range(5,16,5):
         for m2 in range(5,16,5):
           for d in range(50,501,100):
             for fl in [60,120]:
               if (m1+m2+d+fl) not in check:
                 check[k]=m1+m2+d+fl
                 hp,hc = get_td_waveform(approximant=apx[a],
                                   mass1=m1,mass2=m2,
                                   delta_t=1.0/4096,
                                   f_lower=fl,f_final=50, 
                                   distance=d)
                   
                 if len(hp)<=noise.shape[1]:
                   signal_gw[next_val:next_val+noise.shape[0],:]=np.copy(noise)
                   pos=np.random.randint(0,noise.shape[1]-len(hp))
                   signal_gw[next_val:next_val+noise.shape[0],pos:pos+len(hp)]+=hp
                   writer = csv.writer(file)
                   for i in range(noise.shape[0]):
                     col=np.zeros(27)
                     col[m1//5-1],col[2+m2//4],col[5+d//50],col[10+fl//60],col[13],col[26]=1,1,1,1,1,1
                     writer.writerow(col)
                   k=k+1
                   next_val+=(noise.shape[0])
Пример #2
0
def generate_signal(param_set):
    hp, hc = get_td_waveform(
        approximant=
        'SEOBNRv4',  #This approximant is only appropriate for BBH mergers
        mass1=param_set['m1'],
        mass2=param_set['m2'],
        spin1z=param_set['x1'],
        spin2z=param_set['x2'],
        inclination_range=param_set['inc'],
        coa_phase=param_set['coa'],
        distance=param_set['dist'],
        delta_t=1.0 / param_set['f'],
        f_lower=30)

    time = 100000000

    det_h1 = Detector('H1')
    det_l1 = Detector('L1')
    det_v1 = Detector('V1')

    hp = fade_on(hp, 0.25)
    hc = fade_on(hc, 0.25)

    sig_h1 = det_h1.project_wave(hp, hc, param_set['ra'], param_set['dec'],
                                 param_set['pol'])
    sig_l1 = det_l1.project_wave(hp, hc, param_set['ra'], param_set['dec'],
                                 param_set['pol'])
    sig_v1 = det_v1.project_wave(hp, hc, param_set['ra'], param_set['dec'],
                                 param_set['pol'])

    return {'H1': sig_h1, 'L1': sig_l1, 'V1': sig_v1}
Пример #3
0
def get_cbc(f_lower, delta_t, mass1=38.9, mass2=32.8):

    filename = 'waveforms/cbc_%.1f_%.1f.dat' % (mass1, mass2)
    if not os.path.isfile(filename):
        try:
            from pycbc.waveform import get_td_waveform
        except:
            print("Waveform not found and no pycbc installed...")
            exit(0)
        hp, hc = get_td_waveform(approximant="SEOBNRv2",
                                 mass1=mass1,
                                 mass2=mass2,
                                 f_lower=f_lower,
                                 delta_t=delta_t,
                                 distance=1)
        tt = hp.sample_times
        t0 = tt[0]

        f = open(filename, "w+")
        for i in xrange(len(tt)):
            f.write("%.15e %.15e %.15e\n" % (tt[i] - t0, hp[i], hc[i]))
        f.close()

    data_out = np.loadtxt(filename)
    tt, hp, hc = data_out[:, 0], data_out[:, 1], data_out[:, 2]
    dt = tt[1] - tt[0]
    if dt != delta_t:
        raise ValueError("Waveform delta t (%.0f) different from "
                         "requested(%.0f)" % (dt, delta_t))

    return tt, hp, hc
Пример #4
0
    def create_dataset(filename, samples):

        file = h5py.File(filename, "w")
        for i in range(samples):
            print(i)
            m1, m2, SNR, merger_time = GWsynthesizer.sample()
            hp, hc = get_td_waveform(approximant='SEOBNRv4_opt',
                                     mass1=m1,
                                     mass2=m2,
                                     delta_t=delta_t,
                                     f_lower=25,
                                     distance=100)
            noise = generate_noise(time_duration, delta_f, delta_t, f_min)

            scaled_template, amplitude = GWsynthesizer.scale(hp, noise, SNR)
            injected_waveform = GWsynthesizer.inject(merger_time, noise,
                                                     scaled_template)
            injected_waveform = np.array(injected_waveform)

            dset = file.create_dataset('sample_' + str(i),
                                       data=injected_waveform)

            dset.attrs['m1'] = m1
            dset.attrs['m2'] = m2
            dset.attrs['SNR'] = SNR
            dset.attrs['amplitude'] = amplitude
            dset.attrs['merger_time'] = merger_time

        return file
Пример #5
0
def gen_pycbc_waveform(mass1, mass2, approximant, delta_t=1./8192, f_lower=30, distance=1, t1=None, t2=None, *args, **kwargs):
    q = mass1/mass2
    mtot = mass1 + mass2
    hp, hc = waveform.get_td_waveform(approximant=approximant,
                             mass1=mass1,
                             mass2=mass2,
                             delta_t=delta_t,
                             f_lower=f_lower,
                             distance=distance)
    times = phenom.StoM(hp.sample_times.numpy(), mtot)
    ylm = np.abs(lal.SpinWeightedSphericalHarmonic(0,0,-2,2,2))
    amp_scale = utils.td_amp_scale(mtot, distance) * ylm
    hp_array = hp.numpy() / amp_scale
    hc_array = hc.numpy() / amp_scale

    h_array = hp_array - 1.j*hc_array

    if t1 is None:
        t1 = times[0]
    if t2 is None:
        t2 = times[-1]

    mask = (times >= t1) & (times <= t2)

    times = times[mask]
    h_array = h_array[mask]

    return times, h_array
Пример #6
0
def generate_TD_waveform(mass_rat,
                         eccentricity,
                         s1z,
                         s2z,
                         approximant='TaylorT1',
                         total_m=50,
                         f_lower=20.,
                         delta_t=1. / 1024):
    nonspinning_models = [
        'TaylorT1', 'TaylorT2', 'TaylorEt', 'TaylorT3', 'TaylorT4', 'EOBNRv2',
        'EOBNRv2HM', 'EOBNRv2_ROM', 'EOBNRv2HM_ROM', 'SEOBNRv1',
        'SEOBNRv1_ROM_DoubleSpin', 'SEOBNRv1_ROM_EffectiveSpin',
        'TEOBResum_ROM', 'PhenSpinTaylor', 'PhenSpinTaylorRD', 'IMRPhenomA',
        'EccentricTD', 'NRSur7dq2'
    ]
    if approximant in nonspinning_models:
        s1z = 0
        s2z = 0
    mass1, mass2 = q_to_masses(mass_rat, total_m)
    hp, hc = hp, hc = get_td_waveform(mass1=mass1,
                                      mass2=mass2,
                                      spin1z=s1z,
                                      spin2z=s2z,
                                      delta_t=delta_t,
                                      f_lower=f_lower,
                                      approximant=approximant,
                                      eccentricity=eccentricity)
    hs = hp + hc * 1j
    amp = abs(hs)
    phase = np.unwrap(np.angle(hs))
    return hp.sample_times.data, np.real(hp.data), np.real(hc.data), np.imag(
        hp.data), np.imag(hc.data), amp, phase
Пример #7
0
def GetFittingFactor(comp_mass1, comp_mass2, waveform0, tp_apx, tp_m1, tp_m2, tp_ecc, tp_lan, tp_inc, radius, f_low=30):
    waveform0_mchirp = pycbc.conversions.mchirp_from_mass1_mass2(comp_mass1, comp_mass2)
    matches = []
    for k in range(0, len(tp_m1)):
        template_m1 = tp_m1[k]
        template_m2 = tp_m2[k]
        template_mchirp = pycbc.conversions.mchirp_from_mass1_mass2(template_m1, template_m2)
        diff = abs(waveform0_mchirp - template_mchirp)
        percentage_diff = diff/waveform0_mchirp
        if (percentage_diff > radius):
            matches.append(0.)
        else: 
            hp, hc = get_td_waveform(approximant = 'EccentricTD',
                                    mass1 = tp_m1[k],
                                    mass2 = tp_m2[k],
                                    eccentricity = tp_ecc[k],
                                    long_asc_nodes = tp_lan[k],
                                    inclination = tp_inc[k],
                                    f_lower = f_low,
                                    delta_t = waveform0.delta_t)
            this_match = GetMatch(waveform0, hp)
            matches.append(this_match)
            print ('Found a nontrivial match: at template %d:  %s' % (k, this_match))
    matches = np.asarray(matches)
    fitting_factor = np.amax(matches)
    return fitting_factor
Пример #8
0
    def make_strain_from_inj_object(self,
                                    inj,
                                    delta_t,
                                    detector_name,
                                    f_lower=None,
                                    distance_scale=1):
        """Make a h(t) strain time-series from an injection object as read from
        a sim_inspiral table, for example.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t).
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is 
            no scaling. 

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        detector = Detector(detector_name)
        if f_lower is None:
            f_l = inj.f_lower
        else:
            f_l = f_lower

        name, phase_order = legacy_approximant_name(inj.waveform)

        # compute the waveform time series
        hp, hc = get_td_waveform(inj,
                                 approximant=name,
                                 delta_t=delta_t,
                                 phase_order=phase_order,
                                 f_lower=f_l,
                                 distance=inj.distance,
                                 **self.extra_args)
        hp /= distance_scale
        hc /= distance_scale

        hp._epoch += inj.get_time_geocent()
        hc._epoch += inj.get_time_geocent()

        # taper the polarizations
        hp_tapered = wfutils.taper_timeseries(hp, inj.taper)
        hc_tapered = wfutils.taper_timeseries(hc, inj.taper)

        # compute the detector response and add it to the strain
        signal = detector.project_wave(hp_tapered, hc_tapered, inj.longitude,
                                       inj.latitude, inj.polarization)

        return signal
Пример #9
0
def generate_waveform(static_arguments, waveform_params):

    if static_arguments["approximant"] not in td_approximants():
        print("Invalid waveform approximant. Please input"
              "a valid PyCBC time-series approximant.")
        quit()

    sample_length = int(static_arguments["sample_length"] *
                        static_arguments["target_sampling_rate"])

    # Collect all the required parameters for the simulation from the given
    # static and variable parameters
    simulation_parameters = dict(approximant=static_arguments['approximant'],
                                 coa_phase=waveform_params['coa_phase'],
                                 delta_f=static_arguments['delta_f'],
                                 delta_t=static_arguments['delta_t'],
                                 distance=static_arguments['distance'],
                                 f_lower=static_arguments['f_lower'],
                                 inclination=waveform_params['inclination'],
                                 mass1=waveform_params['mass1'],
                                 mass2=waveform_params['mass2'],
                                 spin1z=waveform_params['spin1z'],
                                 spin2z=waveform_params['spin2z'],
                                 ra=waveform_params['ra'],
                                 dec=waveform_params['dec'])

    # Perform the actual simulation with the given parameters
    h_plus, h_cross = get_td_waveform(**simulation_parameters)

    start_time = np.copy(float(h_plus.start_time))

    return h_plus, simulation_parameters, h_plus.sample_times, start_time
Пример #10
0
def generate_data(batch_size, sample_rate, mass_range):
    '''
    Function for generating synthetic gravitational waveforms
    for binary mergers of equal masses over a range of masses determined by batch_size and mass_range
    as well as positive class labels. The waveforms are clipped/padded to be 256 steps in length.
    Param: batch_size - Integer number of waveforms to produce
    Param: sample_rate (Hz) - Integer number of measurements per second
    Param: mass_range (solar masses) - List of form [lower_bound, upper_bound] for mass range
    Param: data - list containing generated waveforms as numpy arrays
    '''
    data = []
    mass_step = (mass_range[1] - mass_range[0]) / batch_size
    masses = np.arange(mass_range[0], mass_range[1], mass_step)
    for mass in masses:
        #Generating waveform
        wave, _ = get_td_waveform(approximant='IMRPhenomD',
                                  mass1=mass,
                                  mass2=mass,
                                  delta_t=1.0 / sample_rate,
                                  f_lower=25)
        #Cropping/padding to get waveforms of length 256
        if len(wave) > 256:
            wave = wave[len(wave) - 256:]
        else:
            wave = np.concatenate([np.zeros(256 - len(wave)), wave])
        #Normalizing waveform
        wave = wave / max(np.correlate(wave, wave, mode="full"))**0.5
        #Saving waveform as numpy array
        data.append(np.asarray(wave))
    labels = np.ones(len(data))
    return np.asarray(data), labels
Пример #11
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
def genDesignMatrix(m1Range,
                    m2Range,
                    spzRange,
                    del_tRange,
                    f_lowRange,
                    strict=False):
    try:
        if len(del_t) not in [1, 3] or len(f_low) not in [1, 3]:
            raise Exception('Syntax for arguments in genDesignMatrix()')
    except Exception:
        print 'del_t and f_low could either have a single value or a range, \
			in range specify min, max and increment'

    EPSILON = myconstants.epsilon
    if len(del_tRange) == 1:
        del_tRange.append(del_tRange[0] + EPSILON)
        del_tRange.append(EPSILON)
    if len(f_lowRange) == 1:
        f_lowRange.append(f_lowRange[0] + EPSILON)
        f_lowRange.append(EPSILON)

    designMatrix = dict()
    designMatrix['amplitude'] = list()
    designMatrix['m1'] = list()
    designMatrix['m2'] = list()
    designMatrix['spz'] = list()
    designMatrix['del_t'] = list()
    designMatrix['f_low'] = list()
    # Size of the matrix is six because of,
    # m1, m2, spz, del_t, f_low and the amplitude (during coalescence)
    del_tRange = frange(del_tRange[0], del_tRange[1], del_tRange[2])
    f_lowRange = frange(f_lowRange[0], f_lowRange[1], f_lowRange[2])

    print '\nComputation START'
    loop = 1
    for m1 in xrange(m1Range[0], m1Range[1], m1Range[2]):
        for m2 in xrange(m2Range[0], m2Range[1], m2Range[2]):
            if strict == True:
                if m1 < m2:
                    continue
            for spz in frange(spzRange[0], spzRange[1], spzRange[2]):
                for del_t in del_tRange:
                    for f_low in f_lowRange:
                        for apx in ['SEOBNRv2']:
                            print 'Entered loop: ' + str(loop)
                            loop += 1
                            hp, hc = get_td_waveform(approximant=apx, \
                             mass1 = m1, \
                             mass2 = m2, \
                             spin1z = spz, \
                             delta_t = del_t,\
                             f_lower = f_low)
                            designMatrix['amplitude'].append(max(hp))
                            designMatrix['m1'].append(m1)
                            designMatrix['m2'].append(m2)
                            designMatrix['spz'].append(spz)
                            designMatrix['del_t'].append(del_t)
                            designMatrix['f_low'].append(f_low)
    return designMatrix
Пример #13
0
    def compute_hphc_td(self, t):

        hp, hc = get_td_waveform(**self.source_parameters)
        tm = hp.sample_times.numpy() + self.source_parameters['tc']
        hp, hc = self.source2SSB(hp, hc)
        self._interp_hphc(tm, hp, hc, t, kind="spline")

        return (self.hp, self.hc)
Пример #14
0
  def mixed_signals_BHBNSB(noise):
    global next_val,signal_gw
    #apx=
    with open('gdrive/My Drive/GW data/labels_mixed.csv', 'a', newline='') as file:
      for aab in ['TaylorT1', 'TaylorT2', 'EOBNRv2', 'SEOBNRv2']:
        print(aab)
        check=np.zeros(noise.shape[1])
        k=0
        for m1 in tqdm(range(5,16,5)):
          for m2 in range(5,16,5):
            for d in (range(50,501,100)):
              for fl in [60,120]:
                if (m1+m2+d+fl) not in check:
                  check[k]=m1+m2+d+fl
                  hp,hc = get_td_waveform(approximant=aab,
                                    mass1=m1,mass2=m2,
                                    delta_t=1.0/4096,
                                    f_lower=fl,f_final=50, 
                                    distance=d)
                  
                  if len(hp)<=16384:
                    t=np.linspace(0,.3,np.random.randint(16384))
                    y2=np.zeros(len(t))          
                    r=.3
                    for j in range(3,8):
                      for i in range(len(t)):
                        aa=t[i]-0.0295-j*0.0295-(j*(j+1)/2)*r*0.0295
                        y2[i]+=1.5*10e-21*(-1)**j*(1.5*10e-21*.5/(3+j))*np.exp(-(aa**2)/(2*.006**2))*np.cos(2*np.pi*250*aa)

                      wave=['helix2','whistle','wandering_line','violin_mode','Tomte','koi_fish','scratchy','scattered_light','repeating_blip','power_line','paired_dove','low_freq_burst','light_modulation']
                      for wave_name in wave: 
                        loc='gdrive/My Drive/GW data/Glitches/'+wave_name+'.wav'
                        rate,data=s.read(loc)
                        for c2 in [5,7]:
                          b, a = signal.butter(7, .9, btype='lowpass', analog=False)
                          low_passed = signal.filtfilt(b, a, data)
                          z = 10e-28*signal.medfilt(low_passed,c2)
                          sig=np.zeros(8820)
                          jj=0
                          for ii in range(0,len(z),5):
                            sig[jj]=z[ii]
                            jj+=1

                          signal_gw[next_val:next_val+noise.shape[0],:]=np.copy(noise[:,::2])
                          pos=np.random.randint(0,signal_gw.shape[1]-int(np.ceil(len(hp)/2)))
                          signal_gw[next_val:next_val+noise.shape[0] ,pos:pos+int(np.ceil(len(hp)/2))]+=hp[::2]
                          pos=np.random.randint(0,signal_gw.shape[1]-int(np.ceil(len(sig)/2)))
                          signal_gw[next_val:next_val+noise.shape[0], pos:pos+int(np.ceil(len(sig)/2))]+=sig[::2]
                          pos=np.random.randint(0,signal_gw.shape[1]-int(np.floor(len(y2)/2)))
                          signal_gw[next_val:next_val+noise.shape[0] ,pos:pos+int(np.ceil(len(y2)/2))]+=y2[::2]
                          writer = csv.writer(file)
                          for i in range(noise.shape[0]):
                            col=np.zeros(27)
                            col[m1//5-1],col[2+m2//4],col[5+d//50],col[10+fl//60],col[13],col[18],col[26]=1,1,1,1,1,1,1
                            writer.writerow(col)  
                          k=k+1
                          next_val+=(noise.shape[0])
Пример #15
0
def computeHPHC(argList):
    for apx in ['SEOBNRv2']:
        hp, hc = get_td_waveform(approximant=apx, \
         mass1 = argList[0], \
         mass2 = argList[1], \
         spin1z = argList[2], \
         delta_t = argList[3],\
         f_lower = argList[4])
    return hp, hc
Пример #16
0
    def make_strain_from_inj_object(self, inj, delta_t, detector_name, f_lower=None, distance_scale=1):
        """Make a h(t) strain time-series from an injection object as read from
        a sim_inspiral table, for example.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t).
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is 
            no scaling. 

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        detector = Detector(detector_name)
        if f_lower is None:
            f_l = inj.f_lower
        else:
            f_l = f_lower

        name, phase_order = legacy_approximant_name(inj.waveform)

        # compute the waveform time series
        hp, hc = get_td_waveform(
            inj,
            approximant=name,
            delta_t=delta_t,
            phase_order=phase_order,
            f_lower=f_l,
            distance=inj.distance,
            **self.extra_args
        )
        hp /= distance_scale
        hc /= distance_scale

        hp._epoch += inj.get_time_geocent()
        hc._epoch += inj.get_time_geocent()

        # taper the polarizations
        hp_tapered = wfutils.taper_timeseries(hp, inj.taper)
        hc_tapered = wfutils.taper_timeseries(hc, inj.taper)

        # compute the detector response and add it to the strain
        signal = detector.project_wave(hp_tapered, hc_tapered, inj.longitude, inj.latitude, inj.polarization)

        return signal
Пример #17
0
def reverse_chirp_td(**kwds):
    import numpy
    from pycbc.waveform import get_td_waveform

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

    return (hp.to_frequencyseries().conj().to_timeseries(),
            hp.to_frequencyseries().conj().to_timeseries())
def computeHPHC(argList):
    for apx in ['SEOBNRv2']:
        hp, hc = get_td_waveform(approximant=apx, \
         mass1 = argList[0], \
         mass2 = argList[1], \
         spin1z = argList[2], \
         delta_t = argList[3],\
         f_lower = argList[4])
        plt.plot(hp.sample_times, hp, label=apx)
    return hp, hc
Пример #19
0
    def make_strain_from_inj_object(self, inj, delta_t, detector_name,
                                    f_lower=None, distance_scale=1):
        """Make a h(t) strain time-series from an injection object.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t). Can be any
            object which has waveform parameters as attributes, such as an
            element in a ``WaveformArray``.
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is
            no scaling.

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        detector = Detector(detector_name)
        if f_lower is None:
            f_l = inj.f_lower
        else:
            f_l = f_lower

        # compute the waveform time series
        hp, hc = get_td_waveform(inj, delta_t=delta_t, f_lower=f_l,
                                 **self.extra_args)

        hp /= distance_scale
        hc /= distance_scale

        hp._epoch += inj.tc
        hc._epoch += inj.tc

        # taper the polarizations
        try:
            hp_tapered = wfutils.taper_timeseries(hp, inj.taper)
            hc_tapered = wfutils.taper_timeseries(hc, inj.taper)
        except AttributeError:
            hp_tapered = hp
            hc_tapered = hc

        # compute the detector response and add it to the strain
        signal = detector.project_wave(hp_tapered, hc_tapered,
                             inj.ra, inj.dec, inj.polarization)

        return signal
Пример #20
0
    def make_strain_from_inj_object(self, inj, delta_t, detector_name,
                                    f_lower=None, distance_scale=1):
        """Make a h(t) strain time-series from an injection object.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t). Can be any
            object which has waveform parameters as attributes, such as an
            element in a ``WaveformArray``.
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is
            no scaling.

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        detector = Detector(detector_name)
        if f_lower is None:
            f_l = inj.f_lower
        else:
            f_l = f_lower

        # compute the waveform time series
        hp, hc = get_td_waveform(inj, delta_t=delta_t, f_lower=f_l,
                                 **self.extra_args)

        hp /= distance_scale
        hc /= distance_scale

        hp._epoch += inj.tc
        hc._epoch += inj.tc

        # taper the polarizations
        try:
            hp_tapered = wfutils.taper_timeseries(hp, inj.taper)
            hc_tapered = wfutils.taper_timeseries(hc, inj.taper)
        except AttributeError:
            hp_tapered = hp
            hc_tapered = hc

        # compute the detector response and add it to the strain
        signal = detector.project_wave(hp_tapered, hc_tapered,
                             inj.ra, inj.dec, inj.polarization)

        return signal
Пример #21
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)
Пример #22
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)
Пример #23
0
def generate_GWChirp():

    #returns + polarization of the gw chirp

    mass = 10
    hp, hc = get_td_waveform(approximant='SEOBNRv4_opt',
                             mass1=mass,
                             mass2=mass,
                             delta_t=1 / 4096,
                             f_lower=20)
    return hp
Пример #24
0
def gen_pol(ms, apx, d_t, f_low):
    ''' Generates the plus and cross polarizations of a gravitational wave

        INPUT:    ms: two-dimentional tuple. Masses of the merger
                  apx: Waveform approximant
                  d_t: sampling rate of the signal
                  f_low: starting frequency of the signal
    '''

    hp, hc = get_td_waveform(mass1=ms[0], mass2=ms[1], approximant=apx, delta_t=d_t, f_lower=f_low)

    return hp, hc
Пример #25
0
def get_wf_pols(file, mtotal, inclination=0.0, delta_t=1./1024, f_lower=30,
        distance=100):
    """
    Generate the NR_hdf5_pycbc waveform from the HDF5 file <file> with specified
    params
    """

    f = h5py.File(file, 'r')


    # Metadata parameters:

    params = {}
    params['mtotal'] = mtotal

    params['eta'] = f.attrs['eta']

    params['mass1'] = pnutils.mtotal_eta_to_mass1_mass2(params['mtotal'], params['eta'])[0]
    params['mass2'] = pnutils.mtotal_eta_to_mass1_mass2(params['mtotal'], params['eta'])[1]

    params['spin1x'] = f.attrs['spin1x']
    params['spin1y'] = f.attrs['spin1y']
    params['spin1z'] = f.attrs['spin1z']
    params['spin2x'] = f.attrs['spin2x']
    params['spin2y'] = f.attrs['spin2y']
    params['spin2z'] = f.attrs['spin2z']

    params['coa_phase'] = f.attrs['coa_phase']

    f.close()

    hp, hc = get_td_waveform(approximant='NR_hdf5_pycbc', 
                                     numrel_data=file,
                                     mass1=params['mass1'],
                                     mass2=params['mass2'],
                                     spin1x=params['spin1x'],
                                     spin1y=params['spin1y'],
                                     spin1z=params['spin1z'],
                                     spin2x=params['spin2x'],
                                     spin2y=params['spin2y'],
                                     spin2z=params['spin2z'],
                                     delta_t=delta_t,
                                     f_lower=f_lower,
                                     inclination=inclination,
                                     coa_phase=params['coa_phase'],
                                     distance=distance)


    hp_tapered = wfutils.taper_timeseries(hp, 'TAPER_START')
    hc_tapered = wfutils.taper_timeseries(hc, 'TAPER_START')

    return hp_tapered, hc_tapered
Пример #26
0
    def waveform(self,
                 p,
                 time_range,
                 distance=1.0,
                 coa_phase=0,
                 t0=0,
                 f_ref=100):
        """
        Generate a single waveform from the catalogue.
        """

        delta_t = (time_range[1] - time_range[0]) / time_range[2]
        mass1, mass2 = self.components_from_total(self.total_mass,
                                                  p['mass ratio'])

        for par in self.parameters:
            if not par.replace("_", " ") in p: p[par.replace("_", " ")] = 0

        hp, hx = get_td_waveform(approximant=self.approximant,
                                 mass1=mass1,
                                 mass2=mass2,
                                 spin1x=p['spin 1x'],
                                 spin1y=p['spin 1y'],
                                 spin1z=p['spin 1z'],
                                 spin2x=p['spin 2x'],
                                 spin2y=p['spin 2y'],
                                 spin2z=p['spin 2z'],
                                 distance=distance,
                                 delta_t=delta_t,
                                 coa_phase=coa_phase,
                                 f_ref=f_ref,
                                 f_lower=self.fmin)

        hp = Timeseries(hp)
        hx = Timeseries(hx)

        # Recenter the waveforms on the maximum strain
        hp.times -= hp.times[np.argmax(np.abs(hp.data - 1j * hx.data))]
        hx.times -= hx.times[np.argmax(np.abs(hp.data - 1j * hx.data))]

        # Recenter the waveforms now to some arbitrary time
        hp.times -= t0
        hx.times -= t0

        tix = (time_range[0] < hp.times) & (hp.times < time_range[1])

        hp.times = hp.times[tix]
        hx.times = hx.times[tix]
        hp.data = hp.data[tix]
        hx.data = hx.data[tix]

        return hp, hx
Пример #27
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)
Пример #28
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
Пример #29
0
    def make_strain_from_inj_object(self,
                                    inj,
                                    delta_t,
                                    detector_name,
                                    f_lower=None,
                                    distance_scale=1):
        """Make a h(t) strain time-series from an injection object as read from
        a sim_inspiral table, for example.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t).
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is
            no scaling.

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        f_l = inj.f_lower if f_lower is None else f_lower

        name, phase_order = legacy_approximant_name(inj.waveform)

        # compute the waveform time series
        hp, hc = get_td_waveform(inj,
                                 approximant=name,
                                 delta_t=delta_t,
                                 phase_order=phase_order,
                                 f_lower=f_l,
                                 distance=inj.distance,
                                 **self.extra_args)
        return projector(detector_name,
                         inj,
                         hp,
                         hc,
                         distance_scale=distance_scale)
Пример #30
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)
Пример #31
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)
Пример #32
0
    def make_strain_from_inj_object(self,
                                    inj,
                                    delta_t,
                                    detector_name,
                                    f_lower=None,
                                    distance_scale=1):
        """Make a h(t) strain time-series from an injection object.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t). Can be any
            object which has waveform parameters as attributes, such as an
            element in a ``WaveformArray``.
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is
            no scaling.

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        if f_lower is None:
            f_l = inj.f_lower
        else:
            f_l = f_lower

        # compute the waveform time series
        hp, hc = get_td_waveform(inj,
                                 delta_t=delta_t,
                                 f_lower=f_l,
                                 **self.extra_args)
        return projector(detector_name,
                         inj,
                         hp,
                         hc,
                         distance_scale=distance_scale)
Пример #33
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
Пример #34
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
Пример #35
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)
Пример #36
0
 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)
Пример #37
0
def gen_waveform(iota, phi, numrel_data):
    print "I am in gen_waveform()!"

    ## FIXME(Gonghan): It seems that this variable is never used.
    global wavelabel
    wavelabel = os.path.join(savepath,
                             numrel_data.split('/')[-1].replace(".h5", ""))

    f = h5py.File(numrel_data, 'r')

    global hp, hc
    hp, hc = get_td_waveform(approximant='NR_hdf5',
                             numrel_data=numrel_data,
                             mass1=f.attrs['mass1'] * mass,
                             mass2=f.attrs['mass2'] * mass,
                             spin1z=f.attrs['spin1z'],
                             spin2z=f.attrs['spin2z'],
                             delta_t=1.0 / sample_frequency,
                             f_lower=30.,
                             inclination=iota,
                             coa_phase=phi,
                             distance=1000)

    print "in gen_waveform, have got hp, hc. iota: {}, phi: {}".format(
        iota, phi)
    print "hp:", hp
    print "hc:", hc
    f.close()

    # Taper waveform for smooth FFTs
    hp = taper_timeseries(hp, tapermethod="TAPER_START")
    hc = taper_timeseries(hc, tapermethod="TAPER_START")

    global amp, foft
    amp = wfutils.amplitude_from_polarizations(hp, hc)
    foft = wfutils.frequency_from_polarizations(hp, hc)

    # Shift time origin to merger
    global sample_times

    ## FIXME(Gonghan): Not sure how we want to define zero time.
    sample_times = amp.sample_times - amp.sample_times[np.argmax(amp)]
Пример #38
0
from pycbc.waveform import get_td_waveform
from pycbc.filter import match
from pycbc.psd import aLIGOZeroDetHighPower

f_low = 30
sample_rate = 4096

# Generate the two waveforms to compare
hp, hc = get_td_waveform(approximant="EOBNRv2",
                         mass1=10,
                         mass2=10,
                         f_lower=f_low,
                         delta_t=1.0/sample_rate)

sp, sc = get_td_waveform(approximant="TaylorT4",
                         mass1=10,
                         mass2=10,
                         f_lower=f_low,
                         delta_t=1.0/sample_rate)

# Resize the waveforms to the same length
tlen = max(len(sp), len(hp))
sp.resize(tlen)
hp.resize(tlen)

# Generate the aLIGO ZDHP PSD
delta_f = 1.0 / sp.duration
flen = tlen/2 + 1
psd = aLIGOZeroDetHighPower(flen, delta_f, f_low)

# Note: This takes a while the first time as an FFT plan is generated
Пример #39
0
    hcross_NR = wfutils.taper_timeseries(hcross_NR, "TAPER_STARTEND")

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    # APPROXIMANT

    # if approx == 'SEOBNRv2':
    if approx in td_approximants():

        hplus_approx, hcross_approx = get_td_waveform(
            approximant=approx,
            distance=distance,
            mass1=mass1,
            mass2=mass2,
            spin1x=0.0,
            spin2x=0.0,
            spin1y=0.0,
            spin2y=0.0,
            spin1z=simulations.simulations[0]["spin1z"],
            spin2z=simulations.simulations[0]["spin2z"],
            inclination=inc,
            f_lower=f_low_approx * min(masses) / mass,
            delta_t=delta_t,
        )

        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():
Пример #40
0
ra = 1.7
dec = 1.7
pol = 0.2
inc = 0
time = 1000000000

# We can calcualate the antenna pattern for Hanford at
# the specific sky location
d = Detector("H1")

# We get back the fp and fc antenna pattern weights.
fp, fc = d.antenna_pattern(ra, dec, pol, time)
print("fp={}, fc={}".format(fp, fc))

# These factors allow us to project a signal into what the detector would
# observe

## Generate a waveform
hp, hc = get_td_waveform(approximant="IMRPhenomD", mass1=10, mass2=10,
                         f_lower=30, delta_t=1.0/4096, inclination=inc,
                         distance=400)

## Apply the factors to get the detector frame strain
ht = fp * hp + fc * hc


# The projection process can also take into account the rotation of the
# earth using the project wave function.
hp.start_time = hc.start_time = time
ht = d.project_wave(hp, hc, ra, dec, pol)
Пример #41
0
params['spin2x'] = f.attrs['spin2x']
params['spin2y'] = f.attrs['spin2y']
params['spin2z'] = f.attrs['spin2z']

params['coa_phase'] = f.attrs['coa_phase']

f.close()

hp, hc = get_td_waveform(approximant='NR_hdf5_pycbc', 
                                 numrel_data=file,
                                 mass1=params['mass1'],
                                 mass2=params['mass2'],
                                 spin1x=params['spin1x'],
                                 spin1y=params['spin1y'],
                                 spin1z=params['spin1z'],
                                 spin2x=params['spin2x'],
                                 spin2y=params['spin2y'],
                                 spin2z=params['spin2z'],
                                 delta_t=deltaT,
                                 f_lower=f_lower,
                                 inclination=float(sys.argv[2]),
                                 coa_phase=params['coa_phase'],
                                 distance=100)


hp_tapered = wfutils.taper_timeseries(hp, 'TAPER_START')
hc_tapered = wfutils.taper_timeseries(hc, 'TAPER_START')

hp_tapered.data[:] /= pycbc.filter.sigma(hp_tapered)
hc_tapered.data[:] /= pycbc.filter.sigma(hc_tapered)
    spin_magnitudes.append((simulation['a1'], simulation['a2']))
    spin_angles.append((simulation['th1L'], simulation['th2L']))

    mass1, mass2 = component_masses(total_mass, mass_ratios[s])

    spin1z = cartesian_spins(simulation['a1'], simulation['th1L'])
    spin2z = cartesian_spins(simulation['a2'], simulation['th2L'])

    effective_spins[s] = spawaveform.computechi(mass1, mass2, spin1z, spin2z)


    print "Generating EOBNR"
    hplus_EOBNR, _ = get_td_waveform(approximant="SEOBNRv2",
            distance=distance,
            mass1=mass1,
            mass2=mass2,
            spin1z=spin1z,
            spin2z=spin2z,
            f_lower=f_low,
            delta_t=SI_deltaT)

    # divide out the spherical harmonic (2,2) amplitude (this is just for nice
    # plots / sanity - it does not affect match)
    sY22 = lal.SpinWeightedSphericalHarmonic(0,0,-2,2,2)
    hplus_EOBNR.data /= np.real(sY22)

    # (1-sided) Planck window for smooth FFT
    hplus_EOBNR.data = bwave.window_wave(hplus_EOBNR.data)

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #
    # Match Calculation
Пример #43
0
# Plot a time domain and fourier domain waveform together in the time domain.
# Note that without special cleanup the Fourier domain waveform will exhibit
# 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 = int(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()
pylab.show()
Пример #44
0
# --- Generate the polarisations
hplus_NR, hcross_NR = nrbu.get_wf_pols(
       simulations.simulations[sim_number]['wavefile'], mass, inclination=inc,
       delta_t=delta_t, f_lower=30.0001, distance=distance)


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# APPROXIMANT 
hplus_approx, hcross_approx = get_td_waveform(approximant=approx,
        distance=distance,
        mass1=mass1,
        mass2=mass2,
        spin1x=0.0,
        spin2x=0.0,
        spin1y=0.0,
        spin2y=0.0,
        spin1z=simulations.simulations[sim_number]['spin1z'],
        spin2z=simulations.simulations[sim_number]['spin2z'],
        inclination=inc,
        f_lower=f_low_approx,
        delta_t=delta_t)

hplus_approx = wfutils.taper_timeseries(hplus_approx, 'TAPER_START')
hcross_approx = wfutils.taper_timeseries(hcross_approx, 'TAPER_START')



# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# MATCH CALCULATION 
Пример #45
0
import pylab
from pycbc.waveform import get_td_waveform

for apx in ['SEOBNRv2', 'IMRPhenomC']:
    hp, hc = get_td_waveform(approximant=apx,
                                 mass1=10,
                                 mass2=10,
                                 spin1z=0.9,
                                 delta_t=1.0/4096,
                                 f_lower=40)

    pylab.plot(hp.sample_times, hp, label=apx)

pylab.ylabel('Strain')
pylab.xlabel('Time (s)')
pylab.legend()
pylab.show()
Пример #46
0
    def apply(self, strain, detector_name, f_lower=None, distance_scale=1,
              simulation_ids=None):
        """Add injections (as seen by a particular detector) to a time series.

        Parameters
        ----------
        strain : TimeSeries
            Time series to inject signals into, of type float32 or float64.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is 
            no scaling. 
        simulation_ids: iterable, optional
            If given, only inject signals with the given simulation IDs.

        Returns
        -------
        None

        Raises
        ------
        TypeError
            For invalid types of `strain`.
        """

        if not strain.dtype in (float32, float64):
            raise TypeError("Strain dtype must be float32 or float64, not " \
                    + str(strain.dtype))

        lalstrain = strain.lal()    
        detector = Detector(detector_name)
        earth_travel_time = lal.REARTH_SI / lal.C_SI
        t0 = float(strain.start_time) - earth_travel_time
        t1 = float(strain.end_time) + earth_travel_time

        # pick lalsimulation injection function
        add_injection = injection_func_map[strain.dtype]

        injections = self.table
        if simulation_ids:
            injections = [inj for inj in injections \
                          if inj.simulation_id in simulation_ids]

        for inj in injections:
            if f_lower is None:
                f_l = inj.f_lower
            else:
                f_l = f_lower

            if inj.numrel_data != None and inj.numrel_data != "":
                # performing NR waveform injection
                # reading Hp and Hc from the frame files
                swigrow = self.getswigrow(inj)
                import lalinspiral
                Hp, Hc = lalinspiral.NRInjectionFromSimInspiral(swigrow,
                                                                strain.delta_t)
                # converting to pycbc timeseries
                hp = TimeSeries(Hp.data.data[:], delta_t=Hp.deltaT,
                                epoch=Hp.epoch)
                hc = TimeSeries(Hc.data.data[:], delta_t=Hc.deltaT,
                                epoch=Hc.epoch)
                hp /= distance_scale
                hc /= distance_scale
                end_time = float(hp.get_end_time())
                start_time = float(hp.get_start_time())
                if end_time < t0 or start_time > t1:
                    continue
            else:
                # roughly estimate if the injection may overlap with the segment
                end_time = inj.get_time_geocent()
                inj_length = sim.SimInspiralTaylorLength(
                    strain.delta_t, inj.mass1 * lal.MSUN_SI,
                    inj.mass2 * lal.MSUN_SI, f_l, 0)
                start_time = end_time - 2 * inj_length
                if end_time < t0 or start_time > t1:
                   continue
                   
                name, phase_order = legacy_approximant_name(inj.waveform)

                # compute the waveform time series
                hp, hc = get_td_waveform(
                    inj, approximant=name, delta_t=strain.delta_t,
                    phase_order=phase_order,
                    f_lower=f_l, distance=inj.distance * distance_scale,
                    **self.extra_args)

                hp._epoch += float(end_time)
                hc._epoch += float(end_time)
                if float(hp.start_time) > t1:
                   continue

            # compute the detector response, taper it if requested
            # and add it to the strain
            signal = detector.project_wave(
                    hp, hc, inj.longitude, inj.latitude, inj.polarization)
            # the taper_timeseries function converts to a LAL TimeSeries
            signal = signal.astype(strain.dtype)
            signal_lal = wfutils.taper_timeseries(signal, inj.taper, return_lal=True)
            add_injection(lalstrain, signal_lal, None)

        strain.data[:] = lalstrain.data.data[:]
Пример #47
0
import pylab
from pycbc import waveform

for apx in ["EOBNRv2", "TaylorT4", "IMRPhenomB"]:
    hp, hc = waveform.get_td_waveform(approximant=apx, mass1=10, mass2=10, delta_t=1.0 / 4096, f_lower=40)

    hp, hc = hp.trim_zeros(), hc.trim_zeros()
    amp = waveform.utils.amplitude_from_polarizations(hp, hc)
    phase = waveform.utils.phase_from_polarizations(hp, hc)

    pylab.plot(phase, amp, label=apx)

pylab.ylabel("GW Strain Amplitude")
pylab.xlabel("GW Phase (radians)")
pylab.legend(loc="upper left")
pylab.show()
Пример #48
0
import pylab
from pycbc.waveform import get_td_waveform
from pycbc.detector import Detector

apx = 'SEOBNRv4'
# NOTE: Inclination runs from 0 to pi, with poles at 0 and pi
#       coa_phase runs from 0 to 2 pi.
hp, hc = get_td_waveform(approximant=apx,
                         mass1=10,
                         mass2=10,
                         spin1z=0.9,
                         spin2z=0.4,
                         inclination=1.23,
                         coa_phase=2.45,
                         delta_t=1.0/4096,
                         f_lower=40)

det_h1 = Detector('H1')
det_l1 = Detector('L1')
det_v1 = Detector('V1')

# Choose a GPS end time, sky location, and polarization phase for the merger
# NOTE: Right ascension and polarization phase runs from 0 to 2pi
#       Declination runs from pi/2. to -pi/2 with the poles at pi/2. and -pi/2.
end_time = 1192529720
declination = 0.65
right_ascension = 4.67
polarization = 2.34
hp.start_time += end_time
hc.start_time += end_time
    # Parse trigger files into SNR, time, and frequency for Omicron triggers
    for file in file_list:
        omicron_xml = utils.load_filename(file, contenthandler=DefaultContentHandler)
        snglburst_table = table.get_table(omicron_xml, lsctables.SnglBurstTable.tableName)

        for row in snglburst_table:
            if (row.snr > args.omicron_snr_thresh and 
                    omicron_start_time < row.peak_time < omicron_end_time):
                omicron_times.append(row.peak_time + row.peak_time_ns * 10**(-9))
                omicron_snr.append(row.snr)
                omicron_freq.append(row.peak_frequency)


# Generate inspiral waveform and calculate f(t) to plot on top of Omicron triggers
hp, hc = get_td_waveform(approximant='SEOBNRv2', mass1=m1, mass2=m2,
                 spin1x=0, spin1y=0, spin1z=s1z,
                 spin2x=0, spin2y=0, spin2z=s2z,
                 delta_t=(1./32768.), f_lower=30)


f = frequency_from_polarizations(hp, hc)
amp = amplitude_from_polarizations(hp, hc)
stop_idx = amp.abs_max_loc()[1]

f = f[:stop_idx]

freq = np.array(f.data)
times = np.array(f.sample_times) + cbc_end_time

logging.info('Plotting')

plt.figure(0)
Пример #50
0
    def make_strain_from_inj_object(self, inj, delta_t, detector_name,
                                    f_lower=None, distance_scale=1):
        """Make a h(t) strain time-series from an injection object as read from
        a sim_inspiral table, for example.

        Parameters
        -----------
        inj : injection object
            The injection object to turn into a strain h(t).
        delta_t : float
            Sample rate to make injection at.
        detector_name : string
            Name of the detector used for projecting injections.
        f_lower : {None, float}, optional
            Low-frequency cutoff for injected signals. If None, use value
            provided by each injection.
        distance_scale: {1, float}, optional
            Factor to scale the distance of an injection with. The default is 
            no scaling. 

        Returns
        --------
        signal : float
            h(t) corresponding to the injection.
        """
        detector = Detector(detector_name)
        if f_lower is None:
            f_l = inj.f_lower
        else:
            f_l = f_lower

        # FIXME: Old NR interface will soon be removed. Do not use!
        if inj.numrel_data != None and inj.numrel_data != "":
            # performing NR waveform injection
            # reading Hp and Hc from the frame files
            swigrow = self.getswigrow(inj)
            import lalinspiral
            Hp, Hc = lalinspiral.NRInjectionFromSimInspiral(swigrow, delta_t)
            # converting to pycbc timeseries
            hp = TimeSeries(Hp.data.data[:], delta_t=Hp.deltaT,
                            epoch=Hp.epoch)
            hc = TimeSeries(Hc.data.data[:], delta_t=Hc.deltaT,
                            epoch=Hc.epoch)
            hp /= distance_scale
            hc /= distance_scale
        else:
            name, phase_order = legacy_approximant_name(inj.waveform)

            # compute the waveform time series
            hp, hc = get_td_waveform(
                inj, approximant=name, delta_t=delta_t,
                phase_order=phase_order,
                f_lower=f_l, distance=inj.distance,
                **self.extra_args)
            hp /= distance_scale
            hc /= distance_scale

            hp._epoch += inj.get_time_geocent()
            hc._epoch += inj.get_time_geocent()

        # taper the polarizations
        hp_tapered = wfutils.taper_timeseries(hp, inj.taper)
        hc_tapered = wfutils.taper_timeseries(hc, inj.taper)

        # compute the detector response and add it to the strain
        signal = detector.project_wave(hp_tapered, hc_tapered,
                             inj.longitude, inj.latitude, inj.polarization)

        return signal
Пример #51
0
import pylab
from pycbc import waveform

for phase_order in [2, 3, 4, 5, 6, 7]:
    hp, hc = waveform.get_td_waveform(approximant='SpinTaylorT4',
                                 mass1=10, mass2=10,
                                 phase_order=phase_order,
                                 delta_t=1.0/4096,
                                 f_lower=100)
                                 
    hp, hc = hp.trim_zeros(), hc.trim_zeros()
    amp = waveform.utils.amplitude_from_polarizations(hp, hc)
    f = waveform.utils.frequency_from_polarizations(hp, hc)
    
    pylab.plot(f.sample_times, f, label="PN Order = %s" % phase_order)
    
pylab.ylabel('Frequency (Hz)')
pylab.xlabel('Time (s)')
pylab.legend(loc='upper left')
pylab.show()
Пример #52
0
def get_td_waveform_resp(params):
    """
    Generate time domain data of gw detector response

    This function will produce data of a gw detector response based on a
    numerical relativity waveform.

    Parameters
    ----------
    params: object
        The fields of this object correspond to the kwargs of the
        `pycbc.waveform.get_td_waveform()` method and the positional
        arguments of `pycbc.detector.Detector.antenna_pattern()`. For the later
        the fields should be supplied as `params.ra`, `.dec`, `.polarization`
        and `.geocentric_end_time`

    Returns
    -------
    h_plus: pycbc.Types.TimeSeries
    h_cross: pycbc.Types.TimeSeries
    pats: dictionary
        Dictionary containing 'H1' and 'L1' keys. Each key maps to an object
        of containing the field `.f_plus` and `.f_cross` corresponding to
        the plus and cross antenna patterns for the two ifos 'H1' and 'L1'.
    """

    # # construct waveform string that can be parsed by lalsimulation
    waveform_string = params.approximant
    if not pn_orders[params.order] == -1:
        waveform_string += params.order
    name, phase_order = legacy_approximant_name(waveform_string)

    # Populate additional fields of params object
    params.mchirp, params.eta = pnutils.mass1_mass2_to_mchirp_eta(
        params.mass1, params.mass2)
    params.waveform           = waveform_string
    params.approximant        = name
    params.phase_order        = phase_order

    # generate waveform
    h_plus, h_cross = get_td_waveform(params)

    # Generate antenna patterns for all ifos
    pats = {}
    for ifo in params.instruments:

        # get Detector instance for IFO
        det = Detector(ifo)

        # get antenna pattern
        f_plus, f_cross = det.antenna_pattern(
            params.ra,
            params.dec,
            params.polarization,
            params.geocentric_end_time)

        # Populate antenna patterns with new pattern
        pat         = type('AntennaPattern', (object,), {})
        pat.f_plus  = f_plus
        pat.f_cross = f_cross
        pats[ifo]   = pat

    return h_plus, h_cross, pats