def compare_splines(filename1, filename2, key):
    spline1 = romspline.ReducedOrderSpline()
    spline1.read(filename1, group=key)
    spline2 = romspline.ReducedOrderSpline()
    spline2.read(filename2, group=key)
    x_min = np.max([spline1.X[0], spline2.X[0]])
    x_max = np.min([spline1.X[-1], spline2.X[-1]])
    x = np.arange(x_min, x_max, np.abs(spline1.X[1] - spline1.X[0]))
    diff = np.max(np.abs(spline1(x) - spline2(x)))
    return diff
예제 #2
0
def time_grid_for_longest_waveform(Mtot, f_min, outfile, deg=3, abstol=5e-5):
    # Note: This function is no longer used
    # 1) this is very slow for long waveforms (O(day))
    # 2) Ben wants the data to start exactly at f_min.
    #
    # positive aligned spins and equal mass-ratio increase the length of the waveform in time
    # high lambda also makes the wf shorter, so use lambda ~ 0 here.
    
    m1, m2 = Mtot/2.0, Mtot/2.0
    s1z, s2z = +0.9, +0.9 # this is more than we want to cover in spin
    lambda1, lambda2, = 0.1, 0.1
    t, hp, hc = spin_tidal_eob(m1, m2, s1z, s2z, lambda1, lambda2,
                        f_min,
                        distance=1.0, inclination=0.0, delta_t=1.0/16384.0,
                        approximant='TEOBv4', verbose=False)
    # post-process TD data
    h = hp - 1j * hc
    amp = np.abs(h)
    phi = np.unwrap(np.angle(h))
    
    # use a phase romspline for a common grid for amplitude and phase
    spline_phi = romspline.ReducedOrderSpline(t, phi, verbose=True, deg=deg,
                                              tol=abstol, rel=False)

    print 'Generation of phase romspline finished.'
    print 'Size of romspline', spline_phi.size
    print 'Compression factor of romspline', spline_phi.compression
    print 'Resulting spline points in time', spline_phi.X

    phiI = ip.InterpolatedUnivariateSpline(t, phi)
    ampI = ip.InterpolatedUnivariateSpline(t, amp)

    #np.save('./time_grid_debug.npy', [t, hp, hc, amp, phi, spline_phi.X])
    np.save(outfile, spline_phi.X)
예제 #3
0
def spline_amp_phase_from_sxs(sxs_format_waveform, metadata, modes,
                              extrapolation_order="Extrapolated_N2",
                              truncation_time=None):
    """Returns spline amplitude and phase for an SXS-format waveform, for a
    list of Ylm modes. If modes='all', return all modes for l=2 through l=8,
    inclusive."""
    modes, times, amps, phases, start_time, peak_time, l_max \
        = amp_phase_from_sxs(sxs_format_waveform, metadata, modes,
                             extrapolation_order, truncation_time)
    spline_amps = []
    spline_phases = []
    for i, mode in enumerate(modes):
        log("Computing spline for amplitude of mode " + str(mode))
        spline_amps.append(romspline.ReducedOrderSpline(times[i], amps[i]))
        log("Computing spline for phase of mode " + str(mode))
        spline_phases.append(romspline.ReducedOrderSpline(times[i], phases[i]))
    return modes, times, spline_amps, spline_phases, start_time, peak_time, \
        l_max
예제 #4
0
def spline_horizon_quantity(sxs_horizon_quantity, start_time, peak_time):
    """Prepares sxs_horizon_quantity by passing it to
    prepare_horizon_quantity() and then returns a spline of the result."""
    times_AH, quantity_AH = prepare_horizon_quantity(sxs_horizon_quantity,
                                                     start_time, peak_time)
    spline_AH_list = []
    for i in range(0, len(sxs_horizon_quantity[0]) - 1):
        spline_AH_list.append(
            romspline.ReducedOrderSpline(times_AH, quantity_AH[i]))
    return np.array(spline_AH_list)
예제 #5
0
def insert_derived_spline(spline_dictionary, spline_keys, derived_quantity):
    """Inserts a spline into a dictionary of horizon splines for a quantity
    derived from Horizons.h5. Note: spline_keys is a vector of key names
    (should be length 1 for scalars, length 3 for vectors), where each key is
    the name of a group that will be written in the LVC file, such as
    Omega-vs-time or LNhatx-vs-time; and derived_quantity is the quantity to
    be splined. The derived_quantity should be computed using
    erived_horizon_quantities_from_sxs()."""
    # N.B. times already shifted, truncated to remove junk by
    # derived_horizon_quantities_from_sxs()
    log("Computing " + str(spline_keys))
    times_AH = derived_quantity[:, 0]
    quantity_AH = derived_quantity[:, 1:]
    spline_AH_list = []
    for a in range(0, len(derived_quantity[0]) - 1):
        spline_AH_list.append(romspline.ReducedOrderSpline(
            times_AH, quantity_AH[:, a]))
    spline = np.array(spline_AH_list)
    for i, spline_key in enumerate(spline_keys):
        spline_dictionary[spline_key] = spline[i]
예제 #6
0
                            strainVal1, strainVal2).data
                        # for m<0
                        strainAmp2 = wfutils.amplitude_from_polarizations(
                            strainVal1, strain2neg).data
                        strainPhase2 = wfutils.phase_from_polarizations(
                            strainVal1, strain2neg).data
                    else:
                        print "dataFormat is incorrect or is not specified. Edit the metadata file and try again."

                    print '    key = %s' % (key)
                    print '        fitting spline...'

                    try:
                        # when a mode has nothing but zeros for strain, we don't want to add it to the .h5
                        sAmpH = romSpline.ReducedOrderSpline(times,
                                                             strainAmp,
                                                             rel=True,
                                                             verbose=False)
                        sPhaseH = romSpline.ReducedOrderSpline(times,
                                                               strainPhase,
                                                               rel=True,
                                                               verbose=False)

                        grAmp = fd.create_group('amp_' + ell + '_' + em)
                        grPhase = fd.create_group('phase_' + ell + '_' + em)

                        sAmpH.write(grAmp)
                        sPhaseH.write(grPhase)

                        # also creates m<0 mode for the given m>0 mode by using the complex conjugate
                        # (only works for 2,2 I think, hence if statement)
                        if (ell == '2' and em == '2'):
예제 #7
0
def compare_splines(lvc_filename,
                    rhOverM,
                    horizons,
                    key,
                    extrap_order="Extrapolated_N2"):
    spline = romspline.ReducedOrderSpline()
    spline.read(lvc_filename, group=key)

    lvc_file = h5py.File(lvc_filename, 'r')
    start_time = lvc_file.attrs["NR_start_time"]
    peak_time = lvc_file.attrs["NR_peak_time"]

    key_split = key.split('_')
    if (key_split[0] == "amp"):
        sxs_key = "Y_" + key_split[1] + "_" + key_split[2] + ".dat"
        hlm = rhOverM[extrap_order + ".dir"][sxs_key]
        times_raw = hlm[:, 0]
        start_h = np.abs(times_raw - start_time).argmin() + 1
        h = hlm[start_h:, 1] + 1j * hlm[start_h:, 2]
        sxs_values = np.abs(h)
        sxs_times = hlm[start_h:, 0] - peak_time
    elif (key_split[0] == "phase"):
        sxs_key = "Y_" + key_split[1] + "_" + key_split[2] + ".dat"
        hlm = rhOverM[extrap_order + ".dir"][sxs_key]
        times_raw = hlm[:, 0]
        start_h = np.abs(times_raw - start_time).argmin() + 1
        h = hlm[start_h:, 1] + 1j * hlm[start_h:, 2]
        sxs_values = np.unwrap(np.angle(h))
        sxs_times = hlm[start_h:, 0] - peak_time
    else:
        if "remnant" in key:
            ah_key = "AhC.dir"
        elif "2" in key:
            ah_key = "AhB.dir"
        elif "1" in key:
            ah_key = "AhA.dir"

        if "mass" in key:
            quantity_key = "ChristodoulouMass"
            component_key = 1
        elif "spin" in key:
            quantity_key = "chiInertial"
            if 'x' in key:
                component_key = 1
            elif 'y' in key:
                component_key = 2
            elif 'z' in key:
                component_key = 3
        elif "position" in key:
            quantity_key = "CoordCenterInertial"
            if 'x' in key:
                component_key = 1
            elif 'y' in key:
                component_key = 2
            elif 'z' in key:
                component_key = 3
        quantity = horizons[ah_key][quantity_key + ".dat"]
        times_raw_ah = quantity[:, 0]
        start_ah = np.argmin(np.abs(times_raw_ah - start_time))
        sxs_values = quantity[start_ah:, component_key]
        sxs_times = quantity[start_ah:, 0] - peak_time

    # Linf norm of difference
    diff = np.max(np.abs(spline(sxs_times) - sxs_values))
    lvc_file.close()
    return diff
예제 #8
0
 def write_spline(output_location, domain_data, feature_data):
     # Create romspline object of multipole data
     spline = romspline.ReducedOrderSpline(domain_data,
                                           feature_data,
                                           verbose=False)
     spline.write(output_location)
def compress_modes_to_splines(hLM,
                              total_mass,
                              to_amp_phase=True,
                              to_modes=False,
                              tol_one=1e-5,
                              tol_two=1e-5,
                              func_one=np.array,
                              subsamp_fac_one_low=4,
                              subsamp_fac_one_high=2,
                              func_two=np.log,
                              subsamp_fac_two_low=4,
                              subsamp_fac_two_high=1,
                              verbose=False):
    """
Compresses modes provided in hLM according to total mass,
by either first converting to amplitude and phase OR using
the modes directly.
Users can subsample the time-series and apply a function to
them before using romspline compression. These functions can
decrease run time drastically.

[DEFAULTS are sensible for raw modes.]
    """
    # {{{
    #################################
    t_arr = TimeSeries(hLM.tdata.data * total_mass * lal.MTSUN_SI,
                       delta_t=hLM.mode.deltaT)
    h_real = TimeSeries(hLM.mode.data.data.real, delta_t=hLM.mode.deltaT)
    h_imag = TimeSeries(hLM.mode.data.data.imag, delta_t=hLM.mode.deltaT)
    ampLM = amplitude_from_polarizations(h_real, h_imag)
    val, idx = ampLM.abs_max_loc()
    #################################
    if to_amp_phase and not to_modes:
        if verbose:
            print("Converting to amplitude and phase")
        #################################
        if verbose:
            __t0 = time.time()
        phsLM = phase_from_polarizations(h_real, h_imag) + np.pi
        phsLM_min = phsLM.min()
        #################
        t_amp_subsampled = np.append(
            t_arr.data[0:idx - 500:subsamp_fac_one_low],
            t_arr.data[idx - 500:-1:subsamp_fac_one_high])
        amp_subsampled = np.append(
            ampLM.data[0:idx - 500:subsamp_fac_one_low],
            ampLM.data[idx - 500:-1:subsamp_fac_one_high])
        funcamp = func_one(amp_subsampled)
        #
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
            __t0 = time.time()
            print("RomSpline compressing amplitude")

        funcamp_subsampled_spline = romspline.ReducedOrderSpline(
            t_amp_subsampled, funcamp, tol=tol_one)
        #################
        t_phs_subsampled = np.append(
            t_arr.data[0:idx - 500:subsamp_fac_two_low],
            t_arr.data[idx - 500:-1:subsamp_fac_two_high])
        phs_subsampled = np.append(
            phsLM.data[0:idx - 500:subsamp_fac_two_low],
            phsLM.data[idx - 500:-1:subsamp_fac_two_high])
        funcphs = func_two(phs_subsampled - phsLM_min)
        #
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
            __t0 = time.time()
            print("RomSpline compressing phase")
        #
        funcphs_subsampled_spline = romspline.ReducedOrderSpline(
            t_phs_subsampled, funcphs, tol=tol_two)
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
        ################
        return funcamp_subsampled_spline, funcphs_subsampled_spline, phsLM_min,\
            t_arr.min(), t_arr.max()
        #################################
    elif to_modes and not to_amp_phase:
        if verbose:
            print("Using mode real/imaginary parts directly")
        #################################
        if verbose:
            __t0 = time.time()
        t_h_real_subsampled = np.append(
            t_arr.data[0:idx - 500:subsamp_fac_one_low],
            t_arr.data[idx - 500:-1:subsamp_fac_one_high])
        h_real_subsampled = np.append(
            h_real.data[0:idx - 500:subsamp_fac_one_low],
            h_real.data[idx - 500:-1:subsamp_fac_one_high])
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
            __t0 = time.time()
            print("RomSpline compressing real part of mode")
        func_hreal_subsampled_spline = romspline.ReducedOrderSpline(
            t_h_real_subsampled, h_real_subsampled, tol=tol_one)
        #
        t_h_imag_subsampled = np.append(
            t_arr.data[0:idx - 500:subsamp_fac_two_low],
            t_arr.data[idx - 500:-1:subsamp_fac_two_high])
        h_imag_subsampled = np.append(
            h_imag.data[0:idx - 500:subsamp_fac_two_low],
            h_imag.data[idx - 500:-1:subsamp_fac_two_high])
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
            __t0 = time.time()
            print("RomSpline compressing imaginary part of mode")
        func_himag_subsampled_spline = romspline.ReducedOrderSpline(
            t_h_imag_subsampled, h_imag_subsampled, tol=tol_two)
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
        #
        return func_hreal_subsampled_spline, func_himag_subsampled_spline,\
            t_arr.min(), t_arr.max()
        #################################
    elif not to_modes and not to_amp_phase:
        if verbose:
            print("Using mode real/imaginary parts RAW (NOT COMPRESSING)")
        #################################
        if verbose:
            __t0 = time.time()
        if verbose:
            print(" took %.2f seconds.." % (time.time() - __t0))
        #
        return h_real, h_imag, t_arr.min(), t_arr.max()
        #################################
    else:
        IOError(
            "CANNOT compress BOTH of amp/phase OR modes (CAN WRITE RAW though)"
        )
예제 #10
0
def nr2h5(nr_strain_data,
          nr_meta_data,
          nr_init_data,
          output_path=None,
          wfdir_path=None,
          verbose=False,
          testsuite=False):
    '''
    Example formatting for inputs:
    nr_strain_data = { ... (2,2):{'amp':strain_amplitude_array,'phase':strain_phase_array,'t':time_series}, (2,1): ... }
    nr_meta_data   = { 'NR-group':'Your Group Name', 'mass1':0.5, ... }
    NOTE: the time series must all be the same
    '''
    this_module = 'nr2h5'

    # import useful things
    from os import system, remove, makedirs, path
    import shutil
    from os.path import dirname, basename, isdir, realpath, join
    from numpy import array, ones, pi, loadtxt, hstack
    from numpy.linalg import norm
    from os.path import expanduser
    from numpy import array, diff, sort, random

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import sys, os
    #sys.path.append("/nethome/bkhamesra3/Desktop/LIGO-Strain/Strain_Scripts")  #Path to romspline directory
    import romspline
    import h5py
    import random

    #
    def alert(msg, base):
        if verbose:
            print "*(%s)>> %s" % (base, msg)

    # -------- Define useful things for unit scaling -------- #
    # Name intermediate function for unit scaling
    G = 6.67428e-11
    c = 2.99792458e8
    mass_sun = 1.98892e30

    def mass_sec(M):
        return M * G * mass_sun / (c * c * c)

    # Convert code frequency to physical frequency
    def physf(f, M):
        return f / mass_sec(M)

    # ------------------------------------------------------- #

    # ---- Define useful things for input checking & file handling ---- #
    # Make "mkdir" function for directories
    def mkdir(dir):
        # Check for directory existence; make if needed.
        if not path.exists(dir):
            makedirs(dir)
        # Return status
        return path.exists(dir)

    #
    def parent(path):
        '''
        Simple wrapper for getting absolute parent directory
        '''
        import os
        return os.path.abspath(os.path.join(path, os.pardir)) + '/'

    # make sure that both inputs are dictionaries
    if (not isinstance(nr_strain_data, dict)) or (not isinstance(
            nr_meta_data, dict)) or (not isinstance(nr_init_data, dict)):
        msg = 'The inputs must be dictionaries with the appropriate fields '
        raise ValueError(msg)

    # make sure that all of the time series are the same length and have the same values
    alert('Validating inputs.', this_module)
    required_strain_keys = ['amp', 'phase', 't']
    t_length_record = []
    for a in nr_strain_data:
        for b in nr_strain_data[a]:
            if not (b in required_strain_keys):
                msg = 'all multipole keys must contain "amp" and "phase" keys, and the "t" key for time'
                raise ValueError(msg)
            if 't' in nr_strain_data[a]:
                t_length_record.append(len(nr_strain_data[a]['t']))

    # Verify that all time arrays have the same length
    if sum(diff(array(t_length_record))) != 0:
        msg = 'not all time arrays are of the same length in the nr_strain_data input'
        raise ValueError(msg)
    # NOTE: More erro checking possible.

    # Validate output_path
    if not ('.h5' == output_path[-3:]):
        msg = 'output_path input MUST be the full path of the h5 file you wish to create'
        raise ValueError(msg)

    # List required metadata keys
    required_metadata_keys = [
        'Format', 'NR-group', 'type', 'name', 'alternative-names', 'NR-code',
        'modification-date', 'point-of-contact-email', 'simulation-type',
        'INSPIRE-bibtex-keys', 'license', 'Lmax', 'NR-techniques',
        'files-in-error-series', 'comparable-simulation', 'production-run',
        'object1', 'object2', 'mass1', 'mass2', 'eta', 'spin1x', 'spin1y',
        'spin1z', 'spin2x', 'spin2y', 'spin2z', 'LNhatx', 'LNhaty', 'LNhatz',
        'nhatx', 'nhaty', 'nhatz', 'Omega', 'f_lower_at_1MSUN', 'eccentricity',
        'PN_approximant', 'mean_anomaly'
    ]

    # Check for correct metadata keys
    for key in required_metadata_keys:
        if not (key in nr_meta_data):
            #
            msg = '"%s" not present in fist input, but must be.' % key
            raise ValueError(msg)
    # ----------------------------------------------------------------- #

    #Check if the metadata matches the format as in lvcnr scripts

    # ----------------------------------------------------------------- #
    # Output directory of hdf5 file
    if output_path is None:
        #output_path = '/Users/book/JOKI/Libs/KOALA/nrutils_dev/review/data/'
        output_path = './new_h5_file.h5'

    # --> Make sure the output path exists
    mkdir(parent(output_path))
    #print output_path
    # Define a temporary directory for amplitude and phase rom files
    tmp_dir = './.nr2h5tmp/'

    # Make the temp dir if it does not already exist
    alert('Making temporary directory at "%s".' % (tmp_dir), this_module)
    mkdir(tmp_dir)

    # Initiate h5 file for seeding attributes and groups
    alert('Initiating h5 file at "%s".' % (output_path), this_module)
    h5f = h5py.File(output_path, 'w')

    # Define attributes
    alert('Seeding metadata from input:', this_module)
    for key in nr_meta_data:
        if verbose: print "\t\t %s = %s" % (key, nr_meta_data[key])
        h5f.attrs[key] = nr_meta_data[key]

    # Define function to create spline and store temporary h5 file
    def write_spline(output_location, domain_data, feature_data):
        # Create romspline object of multipole data
        spline = romspline.ReducedOrderSpline(domain_data,
                                              feature_data,
                                              verbose=False)
        spline.write(output_location)

#    def read_h5(h5_file):

# Create 'Auxiliary Info' group to provide the initial data information

    auxinfo = h5f.create_group('auxiliary-info')
    for info in nr_init_data:
        if verbose: print "\t\t %s = %s" % (info, nr_init_data[info])
        auxinfo.attrs[info] = nr_init_data[info]

    # Amplitude and phase roms must be created, stored to temporary files, and then added to the main hdf5 file above. This is a pain.
    if (2, 2) in nr_strain_data:
        time_data = nr_strain_data[(2, 2)]['t']
    else:
        time_data = nr_strain_data[lm[0]]['t']

    alert(
        'Storing NR multipoles to h5 file. Tempoary h5 files will be created and deleted on the fly.',
        this_module)
    for lm in nr_strain_data:

        if verbose: print ' ... (l,m)=(%s,%s)' % lm

        # Unpack multipole indeces
        l = lm[0]
        m = lm[1]

        # Create romspline object of multipole amplitude data
        amp_tmp = tmp_dir + 'amp_l%im%i.h5' % lm
        write_spline(amp_tmp, time_data, nr_strain_data[(l, m)]['amp'])

        # Create romspline object of multipole phase data
        phase_tmp = tmp_dir + 'phase_l%im%i.h5' % lm
        write_spline(phase_tmp, time_data, nr_strain_data[(l, m)]['phase'])

        ################################################################################################################
        ##Test - Compare the amplitude and phase after spline interpolation with the original data for (2,2) mode
        ################################################################################################################

        if testsuite == True:
            s = romspline.ReducedOrderSpline()
            if wfdir_path == "None":
                raise ValueError("Directory path not specified")

            strfile = wfdir_path + "/data/Strain/Strain_TimeShifted/Strain_{}{}_timeshift.asc".format(
                l, m)
            if not os.path.exists(strfile):
                raise RuntimeError(
                    "Strain data not found. Please check the file")
            tlm, amp_lm, phase_lm = loadtxt(strfile,
                                            usecols=(0, 1, 2),
                                            unpack=True)

            tt_spline = sort(
                [random.uniform(tlm.min(), tlm.max()) for ii in range(10000)])

            s.read(phase_tmp)
            phi_spline = s.eval(tt_spline)

            s.read(amp_tmp)
            amp_spline = s.eval(tt_spline)

            plt.figure()
            plt.subplot(121)
            plt.plot(tlm, amp_lm, label='Original Data')
            plt.plot(tt_spline,
                     amp_spline,
                     ls='--',
                     label='Spline Interpolant')
            plt.xlabel('Time')
            plt.ylabel('Amplitude')
            plt.legend()

            plt.subplot(122)
            plt.plot(tlm, phase_lm, label='Original Data')
            plt.plot(tt_spline,
                     phi_spline,
                     ls='--',
                     label='Spline Interpolant')
            plt.xlabel('Time')
            plt.ylabel('Phase')
            plt.legend()
            plt.tight_layout()
            plt.savefig(wfdir_path +
                        '/figures/AmpPhase_{}{}_Comparison.png'.format(l, m),
                        dpi=500)
            plt.close()

        # Open the temporary h5 file, and then copy its high level group contents to the main h5 file under the appropriate group
        tmp_amp_h5 = h5py.File(amp_tmp)
        h5py.h5o.copy(tmp_amp_h5.id, '/', h5f.id, '/amp_l%i_m%i' % lm)
        #
        tmp_phase_h5 = h5py.File(phase_tmp)
        h5py.h5o.copy(tmp_phase_h5.id, '/', h5f.id, '/phase_l%i_m%i' % lm)

        # delete temporary h5 files
        remove(amp_tmp)
        remove(phase_tmp)

    # Remove the temporary directory
#    alert('Removing temporary directory at "%s".'%(tmp_dir),this_module )
#   shutil.rmtree(tmp_dir)

#
    alert('I have created an hdf5 file at "%s"' % (output_path), this_module)
예제 #11
0
def writeHybrid_h5(path_name_part, metadata, approx, sim_name, h1, h1_ts, h2,
                   h2_ts, delta_t, ip2, fp2):
    solar_mass_mpc = MRSUN_SI / ((1 * 10**6) * PC_SI)
    grav_m1 = metadata[0][0]
    grav_m2 = metadata[0][1]
    baryon_m1 = metadata[1][0]
    baryon_m2 = metadata[1][1]
    m1 = metadata[2][0]
    m2 = metadata[2][1]
    s1x = metadata[3][0]
    s1y = metadata[3][1]
    s1z = metadata[3][2]
    s2x = metadata[3][3]
    s2y = metadata[3][4]
    s2z = metadata[3][5]
    LNhatx = metadata[4][0]
    LNhaty = metadata[4][1]
    LNhatz = metadata[4][2]
    n_hatx = 1.0  #metadata[5][0]
    n_haty = 0.0  #metadata[5][1]
    n_hatz = 0.0  #metadata[5][2]
    tidal_1 = metadata[6][0]
    tidal_2 = metadata[6][1]
    type_sim = metadata[7]
    f_low = metadata[8]
    EOS = metadata[9]
    f_low_num = metadata[10]
    M = 300  ## length of the windowing function
    total_mass = grav_m1 + grav_m2  ### used masses are the masses used in the characterization procedure
    ### hybridize numerical (h2) and analytical waveform (h1) at a particular match window length set by fp2
    hybridPN_Num = hy.hybridize(h1,
                                h1_ts,
                                h2,
                                h2_ts,
                                match_i=0,
                                match_f=fp2,
                                delta_t=delta_t,
                                M=M,
                                info=1)
    shift_time = (hybridPN_Num[6], fp2)
    hh_freq = (hybridPN_Num[7], fp2)
    match = hybridPN_Num[0]
    ### path_name_part contains simulation details that must be passed into this function.
    path_name = path_name_part + 'fp2_' + str(fp2) + '.h5'
    f_low_M = f_low * (TWOPI * total_mass * MTSUN_SI)
    with h5py.File(path_name, 'w') as fd:
        mchirp, eta = pnutils.mass1_mass2_to_mchirp_eta(grav_m1, grav_m2)
        fd.attrs['type'] = 'Hybrid:%s' % type_sim
        fd.attrs['hgroup'] = 'Read_CSUF'
        fd.attrs['Format'] = 1
        fd.attrs['Lmax'] = 2
        fd.attrs['approx'] = approx
        fd.attrs['sim_name'] = sim_name
        fd.attrs['f_lower_at_1MSUN'] = f_low
        fd.attrs['eta'] = eta
        fd.attrs['spin1x'] = s1x
        fd.attrs['spin1y'] = s1y
        fd.attrs['spin1z'] = s1z
        fd.attrs['spin2x'] = s2x
        fd.attrs['spin2y'] = s2y
        fd.attrs['spin2z'] = s2z
        fd.attrs['LNhatx'] = LNhatx
        fd.attrs['LNhaty'] = LNhaty
        fd.attrs['LNhatz'] = LNhatz
        fd.attrs['nhatx'] = 1.0  #n_hatx
        fd.attrs['nhaty'] = 0.0  #n_haty
        fd.attrs['nhatz'] = 0.0  #n_hatz
        fd.attrs['mass1'] = m1
        fd.attrs['mass2'] = m2
        fd.attrs['grav_mass1'] = grav_m1
        fd.attrs['grav_mass2'] = grav_m2
        fd.attrs['baryon_mass1'] = baryon_m1
        fd.attrs['baryon_mass2'] = baryon_m2
        fd.attrs['lambda1'] = tidal_1
        fd.attrs['lambda2'] = tidal_2
        fd.attrs['fp1'] = len(h1)
        fd.attrs['ip2'] = ip2
        fd.attrs['hybrid_match'] = match
        fd.attrs['shift_time'] = shift_time
        fd.attrs['hybridize_freq'] = hh_freq
        fd.attrs['EOS'] = EOS
        fd.attrs['f_low_num'] = f_low_num
        gramp = fd.create_group('amp_l2_m2')
        grphase = fd.create_group('phase_l2_m2')
        times = hybridPN_Num[5][0]
        hplus = hybridPN_Num[5][1]
        hcross = hybridPN_Num[5][2]
        massMpc = total_mass * solar_mass_mpc
        hplusMpc = pycbc.types.TimeSeries(hplus / massMpc, delta_t=delta_t)
        hcrossMpc = pycbc.types.TimeSeries(hcross / massMpc, delta_t=delta_t)
        times_M = times / (MTSUN_SI * total_mass)
        HlmAmp = wfutils.amplitude_from_polarizations(hplusMpc, hcrossMpc).data
        HlmPhase = wfutils.phase_from_polarizations(hplusMpc, hcrossMpc).data
        sAmph = romspline.ReducedOrderSpline(times_M,
                                             HlmAmp,
                                             rel=True,
                                             verbose=False)
        sPhaseh = romspline.ReducedOrderSpline(times_M,
                                               HlmPhase,
                                               rel=True,
                                               verbose=False)
        sAmph.write(gramp)
        sPhaseh.write(grphase)
        fd.close()
    ## this function returns the hybridization frequency (hh_freq) and the time shift (shift_time) associated with each hybrid.
    return (shift_time, hh_freq)
예제 #12
0
                            times = best_hybrid[5][0]
                            hplus = best_hybrid[5][1]
                            hcross = best_hybrid[5][2]
                            massMpc = total_mass * solar_mass_mpc
                            hplusMpc = pycbc.types.TimeSeries(hplus / massMpc,
                                                              delta_t=delta_t)
                            hcrossMpc = pycbc.types.TimeSeries(hcross /
                                                               massMpc,
                                                               delta_t=delta_t)
                            times_M = times / (MTSUN_SI * total_mass)
                            HlmAmp = wfutils.amplitude_from_polarizations(
                                hplusMpc, hcrossMpc).data
                            HlmPhase = wfutils.phase_from_polarizations(
                                hplusMpc, hcrossMpc).data
                            sAmph = romspline.ReducedOrderSpline(times_M,
                                                                 HlmAmp,
                                                                 rel=True,
                                                                 verbose=False)
                            sPhaseh = romspline.ReducedOrderSpline(
                                times_M, HlmPhase, rel=True, verbose=False)
                            sAmph.write(gramp)
                            sPhaseh.write(grphase)
                            fd.close()
                    else:
                        break
'''
#end_time = (time.time() - start_time)/60.0
#print 'end_time (mins)', end_time
                            print 'saving plots'
                            with PdfPages(path_name_data+'match_v_maxSimTime.pdf') as pdf:
                                plt.plot(h2[0], match_fp2)
                                plt.legend(loc='best')