def append_lambda_to_xml(file_name, eos_name, file_name_out=None):
    param_list = lalsimutils.xml_to_ChooseWaveformParams_array(file_name)

    from gwemlightcurves.KNModels import table

    eos, eos_fam = table.get_lalsim_eos(eos_name)

    print("Writing to xml:")
    print("Event  m1  m2  lambda1  lambda2")
    for i in np.arange(len(param_list)):
        m1 = param_list[i].m1
        m2 = param_list[i].m2
        param_list[i].lambda1 = calc_lambda_from_m(m1, eos_fam)
        param_list[i].lambda2 = calc_lambda_from_m(m2, eos_fam)
        print(i, "[", param_list[i].m1 / lal.MSUN_SI,
              param_list[i].m2 / lal.MSUN_SI, param_list[i].lambda1,
              param_list[i].lambda2, "]")

    if file_name_out is None:
        file_name_out = file_name.replace(".xml.gz", "") + "_" + eos_name
    lalsimutils.ChooseWaveformParams_array_to_xml(param_list,
                                                  fname=file_name_out)
Example #2
0
#
# USAGE
#  python util_TestXMLParameterStorage.py ; ligolw_print -t sim_inspiral -c alpha5 output.xml.gz
import RIFT.lalsimutils as lalsimutils
import numpy as np
import lal

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--output-file", default="output")
opts = parser.parse_args()

P_list_in = []
for i in np.arange(5):
    P_list_in.append(lalsimutils.ChooseWaveformParams(m1=lal.MSUN_SI *
                                                      (i + 1)))
    P_list_in[-1].lambda1 = 3 * i + 1
    P_list_in[-1].lambda2 = 3 * i + 2
    P_list_in[-1].approx = 3 * i + 2
    P_list_in[-1].print_params()

lalsimutils.ChooseWaveformParams_array_to_xml(P_list_in,
                                              fname=opts.output_file)

print(" ------ ")
P_list_out = lalsimutils.xml_to_ChooseWaveformParams_array(opts.output_file +
                                                           ".xml.gz")

for P in P_list_out:
    P.print_params()
    # Loop over everything, and find best point
    best_fits_here = []
    closest_so_far_d = 1e10
    closest_so_far = ()
    for group in glist:
        #        if opts.verbose:
        #            print " Checking ", group
        res = nr_closest_to(P, dist_here, group)  # pair of values returned
        if res[1] < closest_so_far_d:
            closest_so_far = (group, res[0])
            closest_so_far_d = res[1]
            if opts.verbose:
                print(" NEW CLOSEST SIMULATION FOR THIS POSTERIOR POINT",
                      closest_so_far, closest_so_far_d)

    if closest_so_far_d > opts.cut:
        P_list_retain.append(P)
        dist_list_retain.append(closest_so_far_d)
    else:
        print(
            " Skipping point shown below as too close to simulations because the closest has distance",
            closest_so_far_d, " which is less than ", opts.cut)
        P.print_params()

lalsimutils.ChooseWaveformParams_array_to_xml(P_list_retain,
                                              fname=opts.fname_output,
                                              fref=P.fref)
np.savetxt(opts.fname_output + "_distances.dat",
           np.array([dist_list_retain]).T)
            val = val/ lal.MSUN_SI
        if val < downselect_dict[param][0] or val > downselect_dict[param][1]:
            include_item =False
    if include_item:
        P_out.append(P)




# Randomize parameters that have been requested to be randomized
#   - note there is NO SANITY CHECKING if you do this
#   - target: tidal parameters, more efficiently hammer on low-tide corner if necessary
if len(opts.random_parameter) >0:
  random_ranges = {}   
  for indx in np.arange(len(opts.random_parameter)):
    param = opts.random_parameter[indx]
    random_ranges[param] = np.array(eval(opts.random_parameter_range[indx]))
  for P in P_out: 
    for param in opts.random_parameter:
        val = np.random.uniform( random_ranges[param][0], random_ranges[param][1])
        if param in ['mc','m1','m2','mtot']:
            val = val* lal.MSUN_SI
        P.assign_param(param,val)


# Export
lalsimutils.ChooseWaveformParams_array_to_xml(P_out,fname=opts.inj_file_out,fref=P.fref)

    

Example #5
0
    P.m1 = event_dict["m1"]*lal.MSUN_SI; P.m2=event_dict["m2"]*lal.MSUN_SI; P.s1z = event_dict["s1z"]; P.s2z = event_dict["s2z"]
    # Load in ini file to select relevant fmin, fref [latter usually unused]
    config = ConfigParser.ConfigParser()
    config.read(opts.use_ini)
    fmin_vals ={}
    fmin_fiducial = -1
    ifo_list = eval(config.get('analysis','ifos'))
    for ifo in ifo_list:
        fmin_vals[ifo] = unsafe_config_get(config,['lalinference','flow'])[ifo]
        fmin_fiducial = fmin_vals[ifo]
    event_dict["IFOs"] = ifo_list
    print( "IFO list from ini ", ifo_list)
    P.fmin = fmin_fiducial
    P.fref = unsafe_config_get(config,['engine','fref'])
    # Write 'target_params.xml.gz' file
    lalsimutils.ChooseWaveformParams_array_to_xml([P], "target_params")



helper_psd_args = ''
srate=4096  # default, built into helper, unwise to go lower, LI will almost never do higher
if opts.make_bw_psds:
    helper_psd_args += " --assume-fiducial-psd-files --fmax " + str(srate/2-1)


# Create provenance info : we want run to be reproducible
if True:
        os.mkdir("reproducibility")
        # Write this script and its arguments
        import shutil, json
#        thisfile = os.path.realpath(__file__)
if otps.verbose:
    print(downselect_dict)

# downselection procedure: fix units so I can downselect on mass parameters
for p in ['mc', 'm1', 'm2', 'mtot']:
    if p in downselect_dict.keys():
        downselect_dict[p] = np.array(downselect_dict[p], dtype=np.float64)
        downselect_dict[p] *= lal.MSUN_SI  # add back units

P_list_in = lalsimutils.xml_to_ChooseWaveformParams_array(opts.fname)
P_inj = lalsimutils.xml_to_ChooseWaveformParams_array(opts.fname)[opts.event]
param_ref_vals = {}
for param in downselect_dict.keys():
    param_ref_vals[param] = P_inj.extract_param(param)

P_list = []
for P in P_list_in:
    include_item = True
    for param in downselect_dict.keys():
        param_here = P.extract_param(param)
        if not (param_here > downselect_dict[param][0]
                and param_here < downselect_dict[param][1]):
            include_item = False
            continue
    if include_item:
        P_list.append(P)

lalsimutils.ChooseWaveformParams_array_to_xml(
    P_list, opts.fname_out.replace(".xml.gz",
                                   ""))  # don't write the postfix twice
Example #7
0
        if fstart_NR < P.fmin or not opts.require_fmin_above_NR_start:
            # only add mass point if a valid mass choice, given NR starting frequency.
            grid = grid + [newline]

print(" ---- DONE WITH GRID SETUP --- ")
print(" grid points # = ", len(grid))

grid_out, P_list = evaluate_overlap_on_grid(hfBase, param_names, grid)
if len(grid_out) == 0:
    print(" No points survive....")

###
### Optional: Write grid to XML file (ONLY if using cutoff option)
###
lalsimutils.ChooseWaveformParams_array_to_xml(P_list,
                                              fname=opts.fname,
                                              fref=P.fref)

###
### Write output to text file:  p1 p2 p3 ... overlap, only including named params
###
headline = ' '.join(param_names + ['ip'])
if int(
        np.version.short_version.split('.')[1]
) >= 7:  # http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
    np.savetxt(opts.fname + ".dat", grid_out, header=headline)
else:
    np.savetxt(opts.fname + ".dat", grid_out)  #

###
### Optional: Scatterplot
Example #8
0
            else:
                full_spoke[key] = [[mtot, lnLhere, sigma_here]]

###
### Create ILE job to follow it up
###

# Create xml file with correct mass and NR parameters
m1, m2 = best_matches_masses[(opts.nr_group, opts.nr_param)]
wfP = nrwf.WaveformModeCatalog(opts.nr_group,
                               opts.nr_param,
                               metadata_only=True)
wfP.P.assign_param('mtot', (m1 + m2) * lal.MSUN_SI)
wfP.P.print_params()
P_list = [wfP.P]
lalsimutils.ChooseWaveformParams_array_to_xml(
    P_list, fname="single-pt")  # choice of fref irrelevant

with open(str(opts.run_dir) + "/command-single.sh", 'r') as runfile:
    rf = str(runfile.readlines()[1])
    rf = rf.replace('create_event_dag_via_grid',
                    'integrate_likelihood_extrinsic')
    rf += " --maximize-only"
    rf = rf.split()
    rf[rf.index("--sim-xml") + 1] = "single-pt.xml.gz"
    rf[rf.index("--output-file") + 1] = "ILE-single.xml.gz"
    if "--n-copies" in rf:
        rf[rf.index("--n-copies") + 1] = ""
    if "--n-max" in rf:
        rf[rf.index("--n-max") + 1] = " 10000 "
    rf_submit = ' '.join(rf)
    if "--n-copies" in rf:
# Loop, removing duplicates sequentially
P_list_out = []
n = len(P_list)
indxList = np.arange(n - 1)
print(indxList)
param_names = opts.compare_parameter
for indx in indxList:
    print(" Testing ", indx, "out of ", n)
    do_we_add_it = True
    for indx2 in np.arange(indx + 1, n):
        are_all_parameters_the_same = True
        for param in param_names:
            param_val = P_list[indx].extract_param(param)
            param_val2 = P_list[indx2].extract_param(param)
            if rosDebug:
                print(param, param_val, param_val2)
            if not (param_val == param_val2):
                are_all_parameters_the_same = False
        # conclude test for this index
        if are_all_parameters_the_same:
            do_we_add_it = False
            if rosDebug:
                print(" Match between ", indx, " and ", indx2)
    if do_we_add_it:
        P_list_out = P_list_out + [P_list[indx]]

# Write output
print(" Saving ", len(P_list_out))
lalsimutils.ChooseWaveformParams_array_to_xml(
    P_list_out, fname=opts.output_file)  # note xml.gz is appended
      nCount +=1
      # Cross-look-up
      try:
         P_sample = sd_P[spoke_id][0] # if this fails
         P_sample.waveFlags =None
         P_sample.nonGRparams = None
         P_sample.print_params()
      except:
         nFailures +=1
         print(" Failed cross lookup for ", spoke_id, nCount, " failure count = ", nFailures)
         continue
      # Clean
      sd_here =spokes.CleanSpokeEntries(sd_dat[spoke_id])
      # Refine: find mass values
      code, mvals_new = spokes.Refine(sd_here[:,0], sd_here[:,1])
      if mvals_new is None:
              continue  # Failed
      mvals_new = np.array(mvals_new)
      mvals_new = mvals_new[ mvals_new > 0]  # eliminate negtive masses!
      print(key, len(sd_here), code, mvals_new)
      if code == 'refined' or code =='extended':
         for m in mvals_new:
            print(m)
            P = P_sample.manual_copy()
            P.tref = P_sample.tref   # BE VERY CAREFUL: The structure swig-bound to store time is NOT a float, and requires careful memory management
            P.assign_param('mtot',m*lal.MSUN_SI)
            P_list.append(P)
            
   if P_list:
      lalsimutils.ChooseWaveformParams_array_to_xml(P_list, opts.save_refinement_fname)
Example #11
0
        param = parameters_to_center[pIndex]
        val = P_ref_list[indx].extract_param(param)
        dat_ref[indx, pIndex] = val

P_out = []
dx = np.mean(dat, axis=0) - np.mean(dat_ref, axis=0)
dat_out = []
for indx in np.arange(len(P_list)):
    bInclude = True
    vec = np.zeros(len(parameters_to_center))
    for pIndex in np.arange(len(parameters_to_center)):
        param = parameters_to_center[pIndex]
        vec[pIndex] = valNew = dat[indx, pIndex] - dx[pIndex]
        if param == 'eta':
            if valNew > 0.25 or valNew < 0.001:
                bInclude = False
                continue
        if param == 's1z' or param == 's2z':
            if valNew > 1 or valNew < -1:
                bInclude = False
                continue
        P_list[indx].assign_param(param, valNew)
    P_list[indx].tref = float(P_list[indx].tref)
    P_out.append(P_list[indx])
    dat_out.append(vec)

print(" Recentering report: last two should be equal : ", np.mean(dat, axis=0),
      np.mean(dat_ref, axis=0), np.mean(dat_out, axis=0))

lalsimutils.ChooseWaveformParams_array_to_xml(P_out, "shifted.xml.gz")