コード例 #1
0
def shift_waveform_phase_time(hp,
                              hc,
                              t_shift,
                              ph_shift,
                              trim_leading=False,
                              trim_trailing=True,
                              verbose=False):
    """
    Input:  hp, hc, where h = hp(t) + i hx(t) = Amp(t) * exp(-i * Phi(t))
    Output: hp, hc, where h = Amp(t - t_c) * exp( -i * [Phi(t - t_c) + phi_c] )
    """
    hpnew = TimeSeries(hp,
                       epoch=hp._epoch,
                       delta_t=hp.delta_t,
                       dtype=hp.dtype,
                       copy=True)
    hcnew = TimeSeries(hc,
                       epoch=hc._epoch,
                       delta_t=hc.delta_t,
                       dtype=hc.dtype,
                       copy=True)
    # First apply phase shift
    if ph_shift != 0.:
        amplitude = amplitude_from_polarizations(hpnew, hcnew)
        phase = phase_from_polarizations(hpnew, hcnew)
        if verbose:
            print(("shifting by %f radians" % ph_shift))
        phase = phase + ph_shift
        hpnew = TimeSeries(amplitude * np.cos(phase + np.pi),
                           epoch=hpnew._epoch,
                           delta_t=hpnew.delta_t,
                           dtype=hpnew.dtype)
        hcnew = TimeSeries(amplitude * np.sin(phase + np.pi),
                           epoch=hcnew._epoch,
                           delta_t=hcnew.delta_t,
                           dtype=hcnew.dtype)
    # Now apply time shift
    if t_shift != 0:
        id_shift = int(np.round(np.abs(t_shift) / hpnew.delta_t))
        if verbose:
            print(("shifting by %d (%f)" % (id_shift, t_shift)))
        if t_shift > 0:
            hpnew.append_zeros(id_shift)
            hcnew.append_zeros(id_shift)
        else:
            hpnew.prepend_zeros(id_shift)
            hcnew.prepend_zeros(id_shift)
        hpnew.roll(id_shift * np.sign(t_shift))
        hcnew.roll(id_shift * np.sign(t_shift))
    if trim_trailing:
        hpnew = trim_trailing_zeros(hpnew)
        hcnew = trim_trailing_zeros(hcnew)
    if trim_leading:
        hpnew = trim_leading_zeros(hpnew)
        hcnew = trim_leading_zeros(hcnew)
    # RETURN
    return hpnew, hcnew
コード例 #2
0
def align_waveforms_optimally(hplus1,
                              hcross1,
                              hplus2,
                              hcross2,
                              psd='aLIGOZeroDetHighPower',
                              low_frequency_cutoff=None,
                              high_frequency_cutoff=None,
                              tsign=1,
                              phsign=-1,
                              verify=True,
                              phase_tolerance=1e-3,
                              overlap_tolerance=1e-3,
                              trim_leading=False,
                              trim_trailing=False,
                              verbose=False):
    """
    Align waveforms such that their inner product (noise weighted) is optimal
    without requiring any phase or time shift.

    The appropriate time and phase shifts are determined iteratively and applied
    to the second set of (hplus, hcross) vectors.
    """
    #############################################################################
    # First copy over data into local memory, ensure lengths of time and
    # frequency domain vectors are consistent, and compute the maximized overlap
    #
    # 1) Cast into time-series
    h_plus1 = TimeSeries(hplus1,
                         epoch=hplus1._epoch,
                         delta_t=hplus1.delta_t,
                         dtype=hplus1.dtype,
                         copy=True)
    h_cross1 = TimeSeries(hcross1,
                          epoch=hplus1._epoch,
                          delta_t=hplus1.delta_t,
                          dtype=hplus1.dtype,
                          copy=True)
    h_plus2 = TimeSeries(hplus2,
                         epoch=hplus2._epoch,
                         delta_t=hplus2.delta_t,
                         dtype=hplus2.dtype,
                         copy=True)
    h_cross2 = TimeSeries(hcross2,
                          epoch=hplus2._epoch,
                          delta_t=hplus2.delta_t,
                          dtype=hplus2.dtype,
                          copy=True)
    #
    # 2) Ensure both input hplus vectors are equal in length
    if len(hplus2) > len(hplus1):
        h_plus1.append_zeros(len(hplus2) - len(hplus1))
        h_cross1.append_zeros(len(hplus2) - len(hplus1))
    elif len(hplus2) < len(hplus1):
        h_plus2.append_zeros(len(hplus1) - len(hplus2))
        h_cross2.append_zeros(len(hplus1) - len(hplus2))
    #
    # 3) Set the upper frequency cutoff to Nyquist if not set by User
    if high_frequency_cutoff == None:
        high_frequency_cutoff = 1. / h_plus1.delta_t / 2.
    #
    # 4) Compute LIGO noise psd
    if psd == None:
        raise IOError("Need compatible psd [or name] as input!")
    elif type(psd) == str:
        htilde = make_frequency_series(h_plus1)
        psd_name = psd
        psd = from_string(psd_name, len(htilde), htilde.delta_f,
                          low_frequency_cutoff)
    ##
    # 5) Calculate Overlap (maximized) before alignment
    m = match(h_plus1,
              h_plus2,
              psd=psd,
              low_frequency_cutoff=low_frequency_cutoff,
              high_frequency_cutoff=high_frequency_cutoff)
    optimal_overlap = m[0]  # FIXME
    if verbose:
        print(("Overlap BEFORE ALIGNMENT:",
               overlap_cplx(h_plus1,
                            h_plus2,
                            psd=psd,
                            low_frequency_cutoff=low_frequency_cutoff,
                            high_frequency_cutoff=high_frequency_cutoff,
                            normalized=True)))
        print(("Match BEFORE ALIGNMENT:", m))
    #############################################################################
    # Iterate to obtain the correct phase and time shifts, using which we
    # align the two waveforms such that their unmaximized and maximized overlaps
    # agree.

    #
    # 1) Initialize phase/time offset counters
    t_shift_counter = 0
    ph_shift_counter = 0
    #
    # 2) Initialize initial garbage values to enter the while loop
    idx = 0
    ph_shift = t_shift = 1e9
    olap = 0 + 0j
    #
    # 3) Iteration begins
    # >>>>>>
    while np.abs(ph_shift) > phase_tolerance or \
            np.abs(t_shift) > h_plus1.delta_t or \
            np.abs(np.abs(olap.real) - optimal_overlap) > overlap_tolerance:
        if idx == 0:
            hp2, hc2 = h_plus2, h_cross2
        #
        # 1) Determine the phase and time shifts for optimal match
        #    by comparing hplus1/hcross1 with hp2/hc2 which is phase/time shifted
        #    in previous iteration
        snr, corr, snr_norm = matched_filter_core(h_plus1, hp2, psd,
                                                  low_frequency_cutoff,
                                                  high_frequency_cutoff, None)
        max_snr, max_id = snr.abs_max_loc()

        if max_id != 0:
            t_shift = snr.delta_t * (len(snr) - max_id)
        else:
            t_shift = snr.delta_t * max_id

        ph_shift = np.angle(snr[max_id])

        #
        # 2) Add them to running time/phase offset counter
        t_shift_counter += t_shift
        ph_shift_counter += ph_shift
        #
        if verbose:
            print((" >> Iteration %d\n" % (idx + 1)))
            print(("max_id = %d, id_shift = %d" %
                   (max_id, int(t_shift / snr.delta_t))))
            print(("t_shift = %f,\n ph_shift = %f" % (t_shift, ph_shift)))
        #
        ####
        # 3) Shift the second hp/hc pair (ORIGINAL) by cumulative phase/time offset
        hp2, hc2 = shift_waveform_phase_time(h_plus2,
                                             h_cross2,
                                             tsign * t_shift_counter,
                                             phsign * ph_shift_counter,
                                             verbose=verbose)
        #
        ###
        # 4) As time shifting can change array lengths, equalize again, compute psd
        ##
        if len(h_plus1) > len(hp2):
            hp2.append_zeros(len(h_plus1) - len(hp2))
            htilde = make_frequency_series(h_plus1)
            psd = from_string(psd_name, len(htilde), htilde.delta_f,
                              low_frequency_cutoff)
        elif len(h_plus1) < len(hp2):
            h_plus1.append_zeros(len(hp2) - len(h_plus1))
            htilde = make_frequency_series(h_plus1)
            psd = from_string(psd_name, len(htilde), htilde.delta_f,
                              low_frequency_cutoff)
        #
        # 5) Compute UNMAXIMIZED overlap.
        olap = overlap_cplx(h_plus1,
                            hp2,
                            psd=psd,
                            low_frequency_cutoff=low_frequency_cutoff,
                            high_frequency_cutoff=high_frequency_cutoff,
                            normalized=True)
        if verbose:
            print(("Overlap AFTER ALIGNMENT = ", olap))
            print(("Optimal Overlap = ", optimal_overlap))
        #
        idx += 1
        if verbose:
            print("\n")
    # >>>>>>
    # 3) Iteration ended.

    #############################################################################
    # Verify the alignment
    ###
    if verify:
        #
        print("Verifying time alignment...")
        #
        # 1) Determine the phase and time shifts for optimal match
        snr, corr, snr_norm = matched_filter_core(h_plus1, hp2, psd,
                                                  low_frequency_cutoff,
                                                  high_frequency_cutoff, None)
        max_snr, max_id = snr.abs_max_loc()
        if verbose:
            print(
                ("Post-Alignment Index of MAX SNR (should be 0 or 1 or %d): %d"
                 % (len(snr) - 1, max_id)))
            print(("Length of whole SNR time-series: ", len(snr)))
        #
        # 2) Test if current time shift is within tolerance
        if max_id != 0 and max_id != 1 and \
                max_id != (len(snr)-1) and max_id != (len(snr)-2):
            raise RuntimeError("Warning: ALIGNMENT NOT CORRECT (see above)")
        else:
            print("Alignment in time correct..")
        #
        # 3) Test if current phase shift is within tolerance
        print("Verifying phase alignment...")
        ph_shift = np.angle(snr[max_id])
        if np.abs(ph_shift) > phase_tolerance:
            if verbose:
                print(("dphi, dphi+pi, dphi-pi: ", ph_shift, ph_shift + np.pi,
                       ph_shift - np.pi))
                print(
                    ("dphi/pi, dphi*pi: ", ph_shift / np.pi, ph_shift * np.pi))
            raise RuntimeError(
                "Warning: Phasing alignment possibly incorrect.")
        else:
            if verbose:
                print(("Post-Alignmend Phase shift (should be < %.2e): %.2e" %
                       (phase_tolerance, np.abs(ph_shift))))
            print(("Alignment in phasing correct.. (within tol %.2e)" %
                   phase_tolerance))
        #

    #############################################################################
    # TRIM the output arrays and return
    if trim_trailing:
        hp2 = trim_trailing_zeros(hp2)
        hc2 = trim_trailing_zeros(hc2)
    if trim_leading:
        hp2 = trim_leading_zeros(hp2)
        hc2 = trim_leading_zeros(hc2)
    #
    return hplus1, hcross1, hp2, hc2
コード例 #3
0
def align_waveforms_suboptimally(hplus1,
                                 hcross1,
                                 hplus2,
                                 hcross2,
                                 psd='aLIGOZeroDetHighPower',
                                 low_frequency_cutoff=None,
                                 high_frequency_cutoff=None,
                                 tsign=1,
                                 phsign=1,
                                 verify=True,
                                 trim_leading=False,
                                 trim_trailing=False,
                                 verbose=False):
    # Cast into time-series
    h_plus1 = TimeSeries(hplus1,
                         epoch=hplus1._epoch,
                         delta_t=hplus1.delta_t,
                         dtype=hplus1.dtype)
    h_cross1 = TimeSeries(hcross1,
                          epoch=hplus1._epoch,
                          delta_t=hplus1.delta_t,
                          dtype=hplus1.dtype)
    h_plus2 = TimeSeries(hplus2,
                         epoch=hplus2._epoch,
                         delta_t=hplus2.delta_t,
                         dtype=hplus2.dtype)
    h_cross2 = TimeSeries(hcross2,
                          epoch=hplus2._epoch,
                          delta_t=hplus2.delta_t,
                          dtype=hplus2.dtype)
    #
    # Ensure both input hplus vectors are equal in length
    if len(hplus2) > len(hplus1):
        h_plus1.append_zeros(len(hplus2) - len(hplus1))
        h_cross1.append_zeros(len(hplus2) - len(hplus1))
    elif len(hplus2) < len(hplus1):
        h_plus2.append_zeros(len(hplus1) - len(hplus2))
        h_cross2.append_zeros(len(hplus1) - len(hplus2))
    #
    htilde = make_frequency_series(h_plus1)
    stilde = make_frequency_series(h_plus2)
    #
    if high_frequency_cutoff == None:
        high_frequency_cutoff = 1. / h_plus1.delta_t / 2.
    #
    if psd == None:
        raise IOError("Need compatible psd [or name] as input!")
    elif type(psd) == str:
        psd_name = psd
        psd = from_string(psd_name, len(htilde), htilde.delta_f,
                          low_frequency_cutoff)
    #
    # Determine the phase and time shifts for optimal match
    snr, corr, snr_norm = matched_filter_core(
        htilde,
        stilde,
        # h_plus1, h_plus2,
        psd,
        low_frequency_cutoff,
        high_frequency_cutoff,
        None)
    max_snr, max_id = snr.abs_max_loc()

    if max_id != 0:
        t_shift = snr.delta_t * (len(snr) - max_id)
    else:
        t_shift = snr.delta_t * max_id

    ph_shift = np.angle(snr[max_id]) - 0.24850315030 - 0.0465881735639
    #
    if verbose:
        print(("max_id = %d, id_shift = %d" %
               (max_id, int(t_shift / snr.delta_t))))
        print(("t_shift = %f,\n ph_shift = %f" % (t_shift, ph_shift)))
    #
    # print(OVERLAPS
    if verbose:
        print(("Overlap BEFORE ALIGNMENT:",
               overlap_cplx(h_plus1,
                            h_plus2,
                            psd=psd,
                            low_frequency_cutoff=low_frequency_cutoff,
                            high_frequency_cutoff=high_frequency_cutoff,
                            normalized=True)))
        print(("Match BEFORE ALIGNMENT:",
               match(h_plus1,
                     h_plus2,
                     psd=psd,
                     low_frequency_cutoff=low_frequency_cutoff,
                     high_frequency_cutoff=high_frequency_cutoff)))

    # Shift whichever needs to be shifted to future time.
    # Shifting back in time is tricky.
    if t_shift >= 0:
        hp2, hc2 = shift_waveform_phase_time(h_plus2,
                                             h_cross2,
                                             tsign * t_shift,
                                             phsign * ph_shift,
                                             verbose=verbose)
    else:
        hp2, hc2 = shift_waveform_phase_time(h_plus2,
                                             h_cross2,
                                             tsign * t_shift,
                                             phsign * ph_shift,
                                             verbose=verbose)
    #
    # Ensure both input hplus vectors are equal in length
    if len(h_plus1) > len(hp2):
        hp2.append_zeros(len(h_plus1) - len(hp2))
    elif len(h_plus1) < len(hp2):
        h_plus1.append_zeros(len(hp2) - len(h_plus1))

    if verbose:
        htilde = make_frequency_series(h_plus1)
        psd = from_string(psd_name, len(htilde), htilde.delta_f,
                          low_frequency_cutoff)
        print(("Overlap AFTER ALIGNMENT:",
               overlap_cplx(h_plus1,
                            hp2,
                            psd=psd,
                            low_frequency_cutoff=low_frequency_cutoff,
                            high_frequency_cutoff=high_frequency_cutoff,
                            normalized=True)))
        print(("Match AFTER ALIGNMENT:",
               match(h_plus1,
                     hp2,
                     psd=psd,
                     low_frequency_cutoff=low_frequency_cutoff,
                     high_frequency_cutoff=high_frequency_cutoff)))
    if verify:
        #
        print("Verifying time alignment...")
        # Determine the phase and time shifts for optimal match
        snr, corr, snr_norm = matched_filter_core(  # htilde, stilde,
            h_plus1, hp2, psd, low_frequency_cutoff, high_frequency_cutoff,
            None)
        max_snr, max_id = snr.abs_max_loc()
        print(("Post-Alignment Index of MAX SNR (should be 0 or 1 or %d): %d" %
               (len(snr) - 1, max_id)))
        print(("Length of whole SNR time-series: ", len(snr)))
        if max_id != 0 and max_id != 1 and max_id != (
                len(snr) - 1) and max_id != (len(snr) - 2):
            # raise RuntimeError( "Warning: ALIGNMENT NOT CORRECT (see above)" )
            print("Warning: ALIGNMENT NOT CORRECT (see above)")
        else:
            print("Alignment in time correct..")
        #
        print("Verifying phase alignment...")
        ph_shift = np.angle(snr[max_id])
        if ph_shift != 0:
            print("Warning: Phasing alignment possibly incorrect.")
            print(("dphi, dphi+pi, dphi-pi: ", ph_shift, ph_shift + np.pi,
                   ph_shift - np.pi))
            print(("dphi/pi, dphi*pi: ", ph_shift / np.pi, ph_shift * np.pi))
        #

    #
    if trim_trailing:
        hp1 = trim_trailing_zeros(hp1)
        hc1 = trim_trailing_zeros(hc1)
        hp2 = trim_trailing_zeros(hp2)
        hc2 = trim_trailing_zeros(hc2)
    if trim_leading:
        hp1 = trim_leading_zeros(hp1)
        hc1 = trim_leading_zeros(hc1)
        hp2 = trim_leading_zeros(hp2)
        hc2 = trim_leading_zeros(hc2)
    #
    return hplus1, hcross1, hp2, hc2