Esempio n. 1
0
 def time_delay_from_earth_center(self, right_ascension, declination,
                                  t_gps):
     """Return the time delay from the earth center
     """
     return lal.TimeDelayFromEarthCenter(self.location,
                                         float(right_ascension),
                                         float(declination), float(t_gps))
Esempio n. 2
0
def delay_and_amplitude_correct(event, ra, dec):
    # retrieve station metadata

    detector = lal.cached_detector_by_prefix[event.ifo]

    # delay-correct the event to the geocentre

    delay = lal.TimeDelayFromEarthCenter(detector.location, ra, dec,
                                         event.peak)
    event.peak -= delay
    event.period = event.period.shift(-delay)
    try:
        event.ms_peak -= delay
    except AttributeError:
        pass
    try:
        event.ms_period = event.ms_period.shift(-delay)
    except AttributeError:
        pass

    # amplitude-correct the event using the polarization-averaged
    # antenna response

    fp, fc = lal.ComputeDetAMResponse(
        detector.response, ra, dec, 0,
        lal.GreenwichMeanSiderealTime(event.peak))
    mean_response = math.sqrt(fp**2 + fc**2)
    event.amplitude /= mean_response
    event.ms_hrss /= mean_response

    # done

    return event
Esempio n. 3
0
def make_bbh(hp, hc, fs, ra, dec, psi, det):
    """
    turns hplus and hcross into a detector output
    applies antenna response and
    and applies correct time delays to each detector
    """

    # make basic time vector
    tvec = np.arange(len(hp)) / float(fs)

    # compute antenna response and apply
    Fp, Fc, _, _ = antenna.response(0.0, ra, dec, 0, psi, 'radians', det)
    ht = hp * Fp + hc * Fc  # overwrite the timeseries vector to reuse it

    # compute time delays relative to Earth centre
    frDetector = lalsimulation.DetectorPrefixToLALDetector(det)
    tdelay = lal.TimeDelayFromEarthCenter(frDetector.location, ra, dec, 0.0)
    print '{}: computed {} Earth centre time delay = {}'.format(
        time.asctime(), det, tdelay)
    # interpolate to get time shifted signal
    ht_tck = interpolate.splrep(tvec, ht, s=0)
    hp_tck = interpolate.splrep(tvec, hp, s=0)
    hc_tck = interpolate.splrep(tvec, hc, s=0)
    tnew = tvec + tdelay
    new_ht = interpolate.splev(tnew, ht_tck, der=0, ext=1)
    new_hp = interpolate.splev(tnew, hp_tck, der=0, ext=1)
    new_hc = interpolate.splev(tnew, hc_tck, der=0, ext=1)

    return new_ht, new_hp, new_hc
Esempio n. 4
0
def make_bbh(hp, hc, fs, ra, dec, psi, det):
    """ Turns hplus and hcross into a detector output
    applies antenna response and
    and applies correct time delays to each detector

    Parameters
    ----------
    hp:
        h-plus version of GW waveform
    hc:
        h-cross version of GW waveform
    fs:
        sampling frequency
    ra:
        right ascension
    dec:
        declination
    psi:
        polarization angle        
    det:
        detector

    Returns
    -------
    ht:
        combined h-plus and h-cross version of waveform
    hp:
        h-plus version of GW waveform 
    hc:
        h-cross version of GW waveform
    """
    # make basic time vector
    tvec = np.arange(len(hp)) / float(fs)

    # compute antenna response and apply
    Fp, Fc, _, _ = antenna.response(float(event_time), ra, dec, 0, psi,
                                    'radians', det)
    ht = hp * Fp + hc * Fc  # overwrite the timeseries vector to reuse it

    # compute time delays relative to Earth centre
    frDetector = lalsimulation.DetectorPrefixToLALDetector(det)
    tdelay = lal.TimeDelayFromEarthCenter(frDetector.location, ra, dec,
                                          float(event_time))
    if verb:
        print '{}: computed {} Earth centre time delay = {}'.format(
            time.asctime(), det, tdelay)

    # interpolate to get time shifted signal
    ht_tck = interpolate.splrep(tvec, ht, s=0)
    hp_tck = interpolate.splrep(tvec, hp, s=0)
    hc_tck = interpolate.splrep(tvec, hc, s=0)
    if gw_tmp: tnew = tvec - tdelay
    else:
        tnew = tvec - tdelay  # + (np.random.uniform(low=-0.037370920181274414,high=0.0055866241455078125))
    new_ht = interpolate.splev(tnew, ht_tck, der=0, ext=1)
    new_hp = interpolate.splev(tnew, hp_tck, der=0, ext=1)
    new_hc = interpolate.splev(tnew, hc_tck, der=0, ext=1)

    return ht, hp, hc
def compute_arrival_time_at_detector(det, RA, DEC, tref):
    """
    Function to compute the time of arrival at a detector
    from the time of arrival at the geocenter.

    'det' is a detector prefix string (e.g. 'H1')
    'RA' and 'DEC' are right ascension and declination (in radians)
    'tref' is the reference time at the geocenter.  It can be either a float (in which case the return is a float) or a GPSTime object (in which case it returns a GPSTime)
    """
    detector = lalsim.DetectorPrefixToLALDetector(det)
    # if tref is a float or a GPSTime object,
    # it shoud be automagically converted in the appropriate way
    return tref + lal.TimeDelayFromEarthCenter(detector.location, RA, DEC, tref)
Esempio n. 6
0
    def time_delay_from_earth_center(self, skypoints, time=None):
        """ Returns the time delay from the earth center
            skypoints: Skypoint object or list of Skypoint objects (in the same coordinate system)

            This function uses LALTimeDelayFromEarthCenter() that takes equatorial 
            coordinates (RA and dec) and a reference GPS time to define the sky location.

            If the skypoints are given in the equatorial coordinate system, 
            the time delays are computed at the provided time if not None, otherwise
            it is computed at the reference time of the coordinate system of 
            the skypoints.

            If the skypoints are given in the geographic coordinate system,
            they are mapped to fiducial equatorial coordinate system with 
            GMST = 0 hr (REFDATE_GMST_ZERO).

        """

        if not isinstance(skypoints, list):
            skypoints = [skypoints]

        delays = []
        for p in skypoints:

            assert p.coordsystem.is_valid(), "Unsupported coordinate system"

            # TimeDelayFromEarthCenter() requires equatorial coordinates.
            # We transform the points with Earth-fixed coordsystem ('geographic')
            # to the fiducial equatorial coordinates system with GMST = 0 hr.

            if p.coordsystem.name == 'geographic':
                p = p.transformed_to(FIDUCIAL_EQUATORIAL_COORDSYS_GMST_ZERO)
                assert time is None, \
                    'time cannot be forced for skypoints in the geographic coordinate system'
                time = p.coordsystem.ref_time
            else:
                time = time if time is not None else p.coordsystem.ref_time

            # TimeDelayFromEarthCenter() takes equatorial coordinates (RA and dec)
            # and a GPS reference time to define a sky location

            delays.append(lal.TimeDelayFromEarthCenter(self.location, \
                                    *p.coords(fmt='lonlat',unit='radians'), time))

        return numpy.squeeze(numpy.array(delays))
fig_list = {}
indx = 0
t_ref = wfP.P.tref   # This SHOULD NOT BE USED, if you want to time-align your signal
if opts.t_ref:
    t_ref = float(opts.t_ref)
else:
    print(" Warning: no reference time, it will be very difficult to time-align your signals ")
for ifo in ['H1', 'L1', 'V1']:
    indx += 1
    fig_list[ifo] = indx
    plt.figure(indx)
    wfP.P.detector = ifo
    data_dict_T[ifo] = wfP.real_hoft(no_memory=opts.no_memory,hybrid_use=opts.hybrid_use,hybrid_method=opts.hybrid_method)
    tvals = data_dict_T[ifo].deltaT*np.arange(data_dict_T[ifo].data.length) + float(data_dict_T[ifo].epoch)
    det = lalsim.DetectorPrefixToLALDetector(ifo)
    print(ifo, " T_peak =", P.tref + lal.TimeDelayFromEarthCenter(det.location, P.phi, P.theta, P.tref) - t_ref)
    if opts.verbose:
        plt.plot(tvals - wfP.P.tref, data_dict_T[ifo].data.data)

    np.savetxt(ifo+"_nr_"+group+"_"+str(param)+"_event_"+str(opts.event)+".dat", np.array([tvals -t_ref, data_dict_T[ifo].data.data]).T)

if opts.verbose and not opts.save_plots:
    plt.show()
if opts.save_plots:
    for ifo in  fig_list:
        plt.figure(fig_list[ifo])
        plt.savefig("response-"+str(ifo)+group+"_"+str(param)+fig_extension)
        


    signal_models = [timing.SignalModel(_) for _ in W]

    # Get SNR=1 horizon distances for each detector.
    horizons = np.asarray([
        signal_model.get_horizon_distance() for signal_model in signal_models
    ])

    # Get antenna factors for each detector.
    Fplus, Fcross = np.asarray([
        lal.ComputeDetAMResponse(response, ra, dec, psi, gmst)
        for response in responses
    ]).T

    # Compute TOAs at each detector.
    toas = np.asarray([
        lal.TimeDelayFromEarthCenter(location, ra, dec, epoch)
        for location in locations
    ])

    # Compute SNR in each detector.
    snrs = (0.5 * (1 + u2) * Fplus + 1j * u * Fcross) * horizons / DL

    abs_snrs = np.abs(snrs)
    arg_snrs = np.angle(snrs)

    if opts.measurement_error == 'zero-noise':
        pass
    elif opts.measurement_error == 'from-truth':
        # If user asked, apply noise to amplitudes /before/ adding noise to
        # TOAs and phases.
    signal_models = [
        timing.SignalModel(m1, m2, psds[ifo], f_low,
        approximant, amplitude_order, phase_order)
        for ifo in opts.detector]

    # Get SNR=1 horizon distances for each detector.
    horizons = np.asarray([signal_model.get_horizon_distance()
        for signal_model in signal_models])

    # Get antenna factors for each detector.
    Fplus, Fcross = np.asarray([
        lal.ComputeDetAMResponse(response, ra, dec, psi, gmst)
        for response in responses]).T

    # Compute TOAs at each detector.
    toas = np.asarray([lal.TimeDelayFromEarthCenter(location, ra, dec,
        epoch) for location in locations])

    # Compute SNR in each detector.
    snrs = (0.5 * (1 + u2) * Fplus + 1j * u * Fcross) * horizons / DL

    abs_snrs = np.abs(snrs)
    arg_snrs = np.angle(snrs)

    if opts.measurement_error == 'zero-noise':
        pass
    elif opts.measurement_error == 'from-truth':
        # If user asked, apply noise to amplitudes /before/ adding noise to TOAs and phases.

        # Add noise to SNR estimates.
        abs_snrs += np.random.randn(len(abs_snrs))
def simulate_snr(ra,
                 dec,
                 psi,
                 inc,
                 distance,
                 epoch,
                 gmst,
                 H,
                 S,
                 response,
                 location,
                 measurement_error='zero-noise'):
    from scipy.interpolate import interp1d

    from ..bayestar import filter
    from ..bayestar.interpolation import interpolate_max

    duration = 0.1

    # Calculate whitened template autocorrelation sequence.
    HS = filter.signal_psd_series(H, S)
    n = len(HS.data.data)
    acor, sample_rate = filter.autocorrelation(HS, duration)

    # Calculate time, amplitude, and phase.
    u = np.cos(inc)
    u2 = np.square(u)
    signal_model = filter.SignalModel(HS)
    horizon = signal_model.get_horizon_distance()
    Fplus, Fcross = lal.ComputeDetAMResponse(response, ra, dec, psi, gmst)
    toa = lal.TimeDelayFromEarthCenter(location, ra, dec, epoch)
    z = (0.5 * (1 + u2) * Fplus + 1j * u * Fcross) * horizon / distance

    # Calculate complex autocorrelation sequence.
    snr_series = z * np.concatenate((acor[:0:-1].conj(), acor))

    # If requested, add noise.
    if measurement_error == 'gaussian-noise':
        sigmasq = 4 * np.sum(HS.deltaF * np.abs(HS.data.data))
        amp = 4 * n * HS.deltaF**0.5 * np.sqrt(HS.data.data / sigmasq)
        N = lal.CreateCOMPLEX16FrequencySeries('', HS.epoch, HS.f0, HS.deltaF,
                                               HS.sampleUnits, n)
        N.data.data = amp * (np.random.randn(n) + 1j * np.random.randn(n))
        noise_term, sample_rate_2 = filter.autocorrelation(N,
                                                           2 * duration -
                                                           1 / sample_rate,
                                                           normalize=False)
        assert sample_rate == sample_rate_2
        snr_series += noise_term

    # Shift SNR series to the nearest sample.
    int_samples, frac_samples = divmod(
        (1e-9 * epoch.gpsNanoSeconds + toa) * sample_rate, 1)
    if frac_samples > 0.5:
        int_samples += 1
        frac_samples -= 1
    epoch = lal.LIGOTimeGPS(epoch.gpsSeconds, 0)
    n = len(acor) - 1
    mprime = np.arange(-n, n + 1)
    m = mprime + frac_samples
    re, im = (interp1d(m, x, kind='cubic', bounds_error=False,
                       fill_value=0)(mprime)
              for x in (snr_series.real, snr_series.imag))
    snr_series = re + 1j * im

    # Find the trigger values.
    i_nearest = np.argmax(np.abs(
        snr_series[n - n // 2:n + n // 2 + 1])) + n - n // 2
    i_interp, z_interp = interpolate_max(i_nearest,
                                         snr_series,
                                         n // 2,
                                         method='lanczos')
    toa = epoch + (int_samples + i_interp - n) / sample_rate
    snr = np.abs(z_interp)
    phase = np.angle(z_interp)

    # Shift and truncate the SNR time series.
    epoch += (int_samples + i_nearest - n - n // 2) / sample_rate
    snr_series = snr_series[(i_nearest - n // 2):(i_nearest + n // 2 + 1)]
    tseries = lal.CreateCOMPLEX8TimeSeries('snr', epoch, 0, 1 / sample_rate,
                                           lal.DimensionlessUnit,
                                           len(snr_series))
    tseries.data.data = snr_series
    return horizon, snr, phase, toa, tseries
Esempio n. 11
0
 def time_delay_from_earth_center(self, RA, dec, time_gps):
     """ Returns the time delay from the earth center
     """
     return lal.TimeDelayFromEarthCenter(self.location, float(RA),
                                         float(dec), float(time_gps))