def generate_lightcurve(model, samples): t = Table() for key, val in samples.iteritems(): t.add_column(Column(data=[val], name=key)) samples = t model_table = KNTable.model(model, samples) if len(model_table) == 0: return [], [], [] else: t, lbol, mag = model_table["t"][0], model_table["lbol"][ 0], model_table["mag"][0] return t, lbol, mag
def generate_lightcurve(model, samples): t = Table() for key in samples.keys(): val = samples[key] t.add_column(Column(data=[val], name=key)) samples = t if Global.n_coeff > 0: samples["n_coeff"] = Global.n_coeff model_table = KNTable.model(model, samples) if len(model_table) == 0: return [], [], [] else: t, lbol, mag = model_table["t"][0], model_table["lbol"][ 0], model_table["mag"][0] return t, lbol, mag
def generate_spectra(model, samples): #kwargs = {'SaveModel':True,'LoadModel':False,'ModelPath':ModelPath} kwargs = {'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath} kwargs["doAB"] = False kwargs["doSpec"] = True t = Table() for key, val in samples.iteritems(): t.add_column(Column(data=[val], name=key)) samples = t model_table = KNTable.model(model, samples, **kwargs) if len(model_table) == 0: return [], [], [] else: t, lambdas, spec = model_table["t"][0], model_table["lambda"][ 0], model_table["spec"][0] return t, lambdas, spec
# Parse command line opts = parse_commandline() baseplotDir = os.path.join(opts.plotDir, 'angles') if not os.path.isdir(baseplotDir): os.makedirs(baseplotDir) plotDir = baseplotDir if not os.path.isdir(plotDir): os.makedirs(plotDir) multinest_samples = opts.multinest_samples.split(",") samples_all = {} for multinest_sample in multinest_samples: samples = KNTable.read_multinest_samples(multinest_sample, opts.model) #key = multinest_sample.split("/")[-7] key = multinest_sample.split("/")[-2] samples_all[key] = samples color2 = 'coral' color1 = 'cornflowerblue' color3 = 'palegreen' color4 = 'darkmagenta' color_names = [color1, color2, color3, color4] linestyles = ['-', '--', '-.'] bins_hist = np.arange(-95, 95, 5.0) bins_hist = np.arange(-10, 190, 5.0)
mejwind = np.log10(mejwind) dmdt = np.log10(dmdt) dmdti = np.log10(dmdti) else: filename = os.path.join(opts.dataDir, 'standard_candles', 'magcolor.dat') data = np.loadtxt(filename) mej, vej, Xlan, color, Mag, dmdti, dmdt = data.T mej, Xlan = np.log10(mej), np.log10(Xlan) dmdt = np.log10(dmdt) dmdti = np.log10(dmdti) posterior_samples = opts.posterior_samples.split(",") samples_all = {} for posterior_sample in posterior_samples: key = posterior_sample.replace(".dat","").split("/")[-1].split("_")[-2] samples_all[key] = KNTable.read_samples(posterior_sample) if opts.fit_type == "gpr": #idx = np.arange(len(Mag)) #np.random.shuffle(idx) #idx1, idx2 = np.array_split(idx,2) if opts.analysis_type == "measured": param_array = np.vstack((color,dmdt,dmdti)).T elif opts.analysis_type == "inferred": param_array = np.vstack((mej,vej,Xlan)).T elif opts.analysis_type == "inferred_bulla": param_array = np.vstack((mej,phi,theta)).T elif opts.analysis_type == "inferred_bulla_lanthanide": param_array = np.vstack((mejdyn,mejwind,phi,theta)).T
def run_EOS(EOS, m1, m2, thetas, type_set = 'None', N_EOS = 100, model_set = 'Bu2019inc', chirp_q = False): chi = 1 if type_set == 'None': sys.exit('Type is not defined') num_samples = N_EOS if type_set == 'BNS_chirp_q': type_set = 'BNS' if not chirp_q: q = m2/m1 mchirp = np.power((m1*m2), 3/5) / np.power((m1+m2), 1/5) eta = m1*m2/( (m1+m2)*(m1+m2) ) if chirp_q: print('running chirp_q') m1 = np.random.normal(m1, .05, 1) m2 = np.random.normal(m2, .05, 1) #m1 = np.ones(100) * m1 #m2 = np.ones(100) * m2 q = m2 mchirp = m1 eta = lightcurve_utils.q2eta(q) m1, m2 = lightcurve_utils.mc2ms(mchirp, eta) #chi_eff = np.random.uniform(-1,1,100) chi_eff = np.ones(1)*chi Xlan_val = 1e-3 Xlan = Xlan_val #if lan_override: # Xlan_val = lan_override_val #Xlans = np.ones(1)*Xlan_val c1 = np.ones(1) c2 = np.ones(1) mb1 = np.ones(1) mb2 = np.ones(1) data = np.vstack((m1,m2,chi_eff,mchirp,eta,q)).T samples = KNTable((data), names = ('m1','m2','chi_eff','mchirp','eta','q')) #data = np.vstack((m1s,m2s,dists,lambda1s,lambda2s,chi_effs,Xlans,c1,c2,mb1,mb2,mchirps,etas,qs,mej,vej, dyn_mej, wind_mej, mbnss)).T #samples = KNTable((data), names = ('m1','m2','dist','lambda1','lambda2','chi_eff','Xlan','c1','c2','mb1','mb2','mchirp','eta','q','mej','vej', 'dyn_mej', 'wind_mej', 'mbns')) lambda1s=[] lambda2s=[] m1s=[] m2s=[] #dists=[] chi_effs=[] Xlans=[] qs=[] etas=[] mchirps=[] mbnss=[] print('...running') nsamples = num_samples m1s, m2s, dists_mbta = [], [], [] lambda1s, lambda2s, chi_effs = [], [], [] mbnss = [] if EOS == "gp": # read Phil + Reed's EOS files eospostdat = np.genfromtxt("/home/philippe.landry/nseos/eos_post_PSRs+GW170817+J0030.csv",names=True,dtype=None,delimiter=",") idxs = np.array(eospostdat["eos"]) weights = np.array([np.exp(weight) for weight in eospostdat["logweight_total"]]) elif EOS == "Sly": eosname = "SLy" eos = EOS4ParameterPiecewisePolytrope(eosname) Xlan_min, Xlan_max = -9, -1 for ii, row in enumerate(samples): #m1, m2, dist_mbta, chi_eff = row["m1"], row["m2"], row["dist_mbta"], row["chi_eff"] m1, m2, chi_eff = row["m1"], row["m2"], row["chi_eff"] if EOS == "spec": indices = np.random.randint(0, 2396, size=nsamples) elif EOS == "gp": indices = np.random.choice(np.arange(0,len(idxs)), size=nsamples,replace=True,p=weights/np.sum(weights)) for jj in range(nsamples): if (EOS == "spec") or (EOS == "gp"): index = indices[jj] lambda1, lambda2 = -1, -1 mbns = -1 # samples lambda's from Phil + Reed's files if EOS == "spec": while (lambda1 < 0.) or (lambda2 < 0.) or (mbns < 0.): eospath = "/home/philippe.landry/nseos/eos/spec/macro/macro-spec_%dcr.csv" % index data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) if float(f(m1)) > lambda1: lambda1 = f(m1) if float(f(m2)) > lambda2: lambda2 = f(m2) if np.max(marray) > mbns: mbns = np.max(marray) if (lambda1 < 0.) or (lambda2 < 0.) or (mbns < 0.): index = int(np.random.randint(0, 2396, size=1)) # pick a different EOS if it returns negative Lambda or Mmax lambda1, lambda2 = -1, -1 mbns = -1 elif EOS == "gp": while (lambda1 < 0.) or (lambda2 < 0.) or (mbns < 0.): phasetr = 0 eospath = "/home/philippe.landry/nseos/eos/gp/mrgagn/DRAWmod1000-%06d/MACROdraw-%06d/MACROdraw-%06d-%d.csv" % (idxs[index]/1000, idxs[index], idxs[index], phasetr) while os.path.isfile(eospath): data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) if float(f(m1)) > lambda1: lambda1 = f(m1) # pick lambda from least compact stable branch if float(f(m2)) > lambda2: lambda2 = f(m2) if np.max(marray) > mbns: mbns = np.max(marray) # get global maximum mass phasetr += 1 # check all stable branches eospath = "/home/philippe.landry/nseos/eos/gp/mrgagn/DRAWmod1000-%06d/MACROdraw-%06d/MACROdraw-%06d-%d.csv" % (idxs[index]/1000, idxs[index], idxs[index], phasetr) if (lambda1 < 0.) or (lambda2 < 0.) or (mbns < 0.): index = int(np.random.choice(np.arange(0,len(idxs)), size=1,replace=True,p=weights/np.sum(weights))) # pick a different EOS if it returns negative Lambda or Mmax lambda1, lambda2 = -1, -1 mbns = -1 elif EOS == "Sly": lambda1, lambda2 = eos.lambdaofm(m1), eos.lambdaofm(m2) mbns = eos.maxmass() m1s.append(m1) m2s.append(m2) #dists_mbta.append(dist_mbta) lambda1s.append(lambda1) lambda2s.append(lambda2) chi_effs.append(chi_eff) #Xlans.append(10**np.random.uniform(Xlan_min, Xlan_max)) Xlans.append(Xlan) mbnss.append(mbns) #print(len(thetas)) #check theta implementation for reproducibility #thetas = 180. * np.arccos(np.random.uniform(-1., 1., len(samples) * nsamples)) / np.pi idx_thetas = np.where(thetas > 90.)[0] thetas[idx_thetas] = 180. - thetas[idx_thetas] #thetas = list(thetas) Xlans = np.ones(np.array(m1s).shape) * Xlan_val #print(mbnss) #thetas = np.ones(100) # make final arrays of masses, distances, lambdas, spins, and lanthanide fractions data = np.vstack((m1s,m2s,lambda1s,lambda2s,Xlans,chi_effs,thetas,mbnss)).T samples = KNTable(data, names=('m1', 'm2', 'lambda1', 'lambda2','Xlan','chi_eff','theta', 'mbns')) # limit masses #samples = samples.mass_cut(mass1=3.0,mass2=3.0) print("m1: %.5f +-%.5f"%(np.mean(samples["m1"]),np.std(samples["m1"]))) print("m2: %.5f +-%.5f"%(np.mean(samples["m2"]),np.std(samples["m2"]))) # Downsample #samples = samples.downsample(Nsamples=100) print(data) print(samples) samples = samples.calc_tidal_lambda(remove_negative_lambda=True) print(samples) print(samples['lambda1'], samples['lambda2']) # Calc compactness samples = samples.calc_compactness(fit=True) # Calc baryonic mass print(samples) samples = samples.calc_baryonic_mass(EOS=None, TOV=None, fit=True) #---------------------------------------------------------------------------------- if (not 'mej' in samples.colnames) and (not 'vej' in samples.colnames): #mbns = 2.1 #idx1 = np.where((samples['m1'] < mbns) & (samples['m2'] < mbns))[0] #idx2 = np.where((samples['m1'] > mbns) | (samples['m2'] > mbns))[0] #1 BNS, 2 NSBH, 3 BBH idx1 = np.where((samples['m1'] <= samples['mbns']) & (samples['m2'] <= samples['mbns']))[0] idx2 = np.where((samples['m1'] > samples['mbns']) & (samples['m2'] <= samples['mbns']))[0] idx3 = np.where((samples['m1'] > samples['mbns']) & (samples['m2'] > samples['mbns']))[0] mej, vej = np.zeros(samples['m1'].shape), np.zeros(samples['m1'].shape) wind_mej, dyn_mej = np.zeros(samples['m1'].shape), np.zeros(samples['m1'].shape) #from gwemlightcurves.EjectaFits.CoDi2019 import calc_meje, calc_vej from gwemlightcurves.EjectaFits.PaDi2019 import calc_meje, calc_vej # calc the mass of ejecta mej1, dyn_mej1, wind_mej1 = calc_meje(samples['m1'], samples['c1'], samples['m2'], samples['c2'], split_mej=True) # calc the velocity of ejecta vej1 = calc_vej(samples['m1'],samples['c1'],samples['m2'],samples['c2']) samples['mchirp'], samples['eta'], samples['q'] = lightcurve_utils.ms2mc(samples['m1'], samples['m2']) #samples['q'] = 1.0 / samples['q'] from gwemlightcurves.EjectaFits.KrFo2019 import calc_meje, calc_vave # calc the mass of ejecta mej2, dyn_mej2, wind_mej2 = calc_meje(samples['q'],samples['chi_eff'],samples['c2'], samples['m2'], split_mej=True) # calc the velocity of ejecta vej2 = calc_vave(samples['q']) # calc the mass of ejecta mej3 = np.zeros(samples['m1'].shape) dyn_mej3 = np.zeros(samples['m1'].shape) wind_mej3 = np.zeros(samples['m1'].shape) # calc the velocity of ejecta vej3 = np.zeros(samples['m1'].shape) + 0.2 mej[idx1], vej[idx1] = mej1[idx1], vej1[idx1] mej[idx2], vej[idx2] = mej2[idx2], vej2[idx2] mej[idx3], vej[idx3] = mej3[idx3], vej3[idx3] wind_mej[idx1], dyn_mej[idx1] = wind_mej1[idx1], dyn_mej1[idx1] wind_mej[idx2], dyn_mej[idx2] = wind_mej2[idx2], dyn_mej2[idx2] wind_mej[idx3], dyn_mej[idx3] = wind_mej3[idx3], dyn_mej3[idx3] samples['mej'] = mej samples['vej'] = vej samples['dyn_mej'] = dyn_mej samples['wind_mej'] = wind_mej # Add draw from a gaussian in the log of ejecta mass with 1-sigma size of 70% erroropt = 'none' if erroropt == 'none': print("Not applying an error to mass ejecta") elif erroropt == 'log': samples['mej'] = np.power(10.,np.random.normal(np.log10(samples['mej']),0.236)) elif erroropt == 'lin': samples['mej'] = np.random.normal(samples['mej'],0.72*samples['mej']) elif erroropt == 'loggauss': samples['mej'] = np.power(10.,np.random.normal(np.log10(samples['mej']),0.312)) #idx = np.where(samples['mej'] > 0)[0] #samples = samples[idx] idx = np.where(samples['mej'] <= 0)[0] samples['mej'][idx] = 1e-11 if (model_set == "Bu2019inc"): idx = np.where(samples['mej'] <= 1e-6)[0] samples['mej'][idx] = 1e-11 elif (model_set == "Ka2017"): idx = np.where(samples['mej'] <= 1e-3)[0] samples['mej'][idx] = 1e-11 print("Probability of having ejecta") print(100 * (len(samples) - len(idx)) /len(samples)) return samples
plt.figure(figsize=(8, 6)) plt.pcolormesh(m1_grid, m2_grid, mej_log10, vmin=-2.5, vmax=-1) plt.xlabel(r"$M_1 (M_\odot)$") plt.ylabel(r"$M_2 (M_\odot)$") plt.xlim([1.0, 1.7]) plt.ylim([1.0, 1.7]) cbar = plt.colorbar() cbar.set_label(r'$log_{10} (M_{ej}/M_\odot)$') plotName = os.path.join(plotDir, 'mej_pcolor.pdf') plt.savefig(plotName, bbox_inches='tight') plt.close('all') # GW170817 gw170817_samples = '../data/event_data/GW170817_SourceProperties_low_spin.dat' samples = KNTable.read_samples(gw170817_samples) # Calc lambdas samples = samples.calc_tidal_lambda(remove_negative_lambda=True) # Calc compactness samples = samples.calc_compactness(fit=True) # calc the mass of ejecta mej1 = calc_meje(samples['m1'], samples['c1'], samples['m2'], samples['c2']) mej_gw170817 = np.log10(mej1) mej_gw170817_hist, bin_edges = np.histogram(mej_gw170817, bins=bins) mej_gw170817_hist = mej_gw170817_hist / float(np.sum(mej_gw170817_hist)) # GW190425 gw190425_samples = '../data/event_data/GW190425_posterior_samples.dat' samples = KNTable.read_samples(gw190425_samples) # Calc lambdas samples = samples.calc_tidal_lambda(remove_negative_lambda=True)
class EM_Counterpart(): def __init__(self, input_samples, Xlan_fixed, phi_fixed, eostype="spec"): self.samples = KNTable.initialize_object(input_samples) m1s, m2s, dists_mbta = [], [], [] lambda1s, lambda2s, chi_effs = [], [], [] Xlans = [] mbnss = [] if eostype == "gp": # read Phil + Reed's EOS files filenames = glob.glob( "/home/philippe.landry/gw170817eos/gp/macro/MACROdraw-*-0.csv") idxs = [] for filename in filenames: filenameSplit = filename.replace(".csv", "").split("/")[-1].split("-") idxs.append(int(filenameSplit[1])) idxs = np.array(idxs) elif eostype == "Sly": eosname = "SLy" eos = EOS4ParameterPiecewisePolytrope(eosname) for ii, row in enumerate(self.samples): print(ii) m1, m2, dist_mbta, chi_eff = row["m1"], row["m2"], row[ "dist_mbta"], row["chi_eff"] nsamples = 30 if eostype == "spec": indices = np.random.randint(0, 2395, size=nsamples) elif eostype == "gp": indices = np.random.randint(0, len(idxs), size=nsamples) for jj in range(nsamples): if (eostype == "spec") or (eostype == "gp"): index = indices[jj] # samples lambda's from Phil + Reed's files if eostype == "spec": eospath = "/home/philippe.landry/gw170817eos/spec/macro/macro-spec_%dcr.csv" % index data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) lambda1, lambda2 = f(m1), f(m2) mbns = np.max(marray) elif eostype == "gp": lambda1, lambda2 = 0.0, 0.0 phasetr = 0 while (lambda1 == 0.0) or (lambda2 == 0.0): eospath = "/home/philippe.landry/gw170817eos/gp/macro/MACROdraw-%06d-%d.csv" % ( idxs[index], phasetr) if not os.path.isfile(eospath): break data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) lambda1_tmp, lambda2_tmp = f(m1), f(m2) if (lambda1_tmp > 0) and (lambda1 == 0.0): lambda1 = lambda1_tmp if (lambda2_tmp > 0) and (lambda2 == 0.0): lambda2 = lambda2_tmp phasetr = phasetr + 1 mbns = np.max(marray) elif eostype == "Sly": lambda1, lambda2 = eos.lambdaofm(m1), eos.lambdaofm(m2) m1s.append(m1) m2s.append(m2) dists_mbta.append(dist_mbta) lambda1s.append(lambda1) lambda2s.append(lambda2) chi_effs.append(chi_eff) mbnss.append(mbns) np.random.uniform(0) Xlans = [10**Xlan_fixed] * len(self.samples) * nsamples phis = [phi_fixed] * len(self.samples) * nsamples thetas = 180. * np.arccos( np.random.uniform(-1., 1., len(self.samples) * nsamples)) / np.pi idx_thetas = np.where(thetas > 90.)[0] thetas[idx_thetas] = 180. - thetas[idx_thetas] thetas = list(thetas) # make final arrays of masses, distances, lambdas, spins, and lanthanide fractions data = np.vstack((m1s, m2s, dists_mbta, lambda1s, lambda2s, chi_effs, thetas, phis, mbnss, Xlans)).T self.samples = KNTable(data, names=('m1', 'm2', 'dist_mbta', 'lambda1', 'lambda2', 'chi_eff', 'theta', 'phi', 'mbns', "Xlan")) self.samples = self.samples.calc_tidal_lambda( remove_negative_lambda=True) self.samples = self.samples.calc_compactness(fit=True) self.samples = self.samples.calc_baryonic_mass(EOS=None, TOV=None, fit=True) print(self.samples) def calc_ejecta(self, model_KN): idx1 = np.where((self.samples['m1'] <= self.samples['mbns']) & (self.samples['m2'] <= self.samples['mbns']))[0] idx2 = np.where((self.samples['m1'] > self.samples['mbns']) & (self.samples['m2'] <= self.samples['mbns']))[0] idx3 = np.where((self.samples['m1'] > self.samples['mbns']) & (self.samples['m2'] > self.samples['mbns']))[0] mej, vej = np.zeros(self.samples['m1'].shape), np.zeros( self.samples['m1'].shape) from gwemlightcurves.EjectaFits.CoDi2019 import calc_meje, calc_vej # calc the mass of ejecta mej1 = calc_meje(self.samples['m1'], self.samples['c1'], self.samples['m2'], self.samples['c2']) # calc the velocity of ejecta vej1 = calc_vej(self.samples['m1'], self.samples['c1'], self.samples['m2'], self.samples['c2']) self.samples['mchirp'], self.samples['eta'], self.samples[ 'q'] = lightcurve_utils.ms2mc(self.samples['m1'], self.samples['m2']) self.samples['q'] = 1.0 / self.samples['q'] from gwemlightcurves.EjectaFits.KrFo2019 import calc_meje, calc_vave # calc the mass of ejecta mej2 = calc_meje(self.samples['q'], self.samples['chi_eff'], self.samples['c2'], self.samples['m2']) # calc the velocity of ejecta vej2 = calc_vave(self.samples['q']) # calc the mass of ejecta mej3 = np.zeros(self.samples['m1'].shape) # calc the velocity of ejecta vej3 = np.zeros(self.samples['m1'].shape) + 0.2 mej[idx1], vej[idx1] = mej1[idx1], vej1[idx1] mej[idx2], vej[idx2] = mej2[idx2], vej2[idx2] mej[idx3], vej[idx3] = mej3[idx3], vej3[idx3] print( "(mej[1284], self.samples[1284]['m1'], self.samples[1284]['m2'], self.samples[1284]['c1'], self.samples[1284]['c2'], self.samples[1284]['q'], self.samples[1284]['chi_eff'])" ) print((mej[1284], self.samples[1284]['m1'], self.samples[1284]['m2'], self.samples[1284]['c1'], self.samples[1284]['c2'], self.samples[1284]['q'], self.samples[1284]['chi_eff'])) self.samples['mej'] = mej self.samples['vej'] = vej # Add draw from a gaussian in the log of ejecta mass with 1-sigma size of 70% erroropt = 'none' if erroropt == 'none': print("Not applying an error to mass ejecta") elif erroropt == 'log': self.samples['mej'] = np.power( 10., np.random.normal(np.log10(self.samples['mej']), 0.236)) elif erroropt == 'lin': self.samples['mej'] = np.random.normal(self.samples['mej'], 0.72 * self.samples['mej']) elif erroropt == 'loggauss': self.samples['mej'] = np.power( 10., np.random.normal(np.log10(self.samples['mej']), 0.312)) idx = np.where(self.samples['mej'] <= 0)[0] self.samples['mej'][idx] = 1e-11 if (model_KN == "Bu2019inc"): idx = np.where(self.samples['mej'] <= 1e-6)[0] self.samples['mej'][idx] = 1e-11 elif (model_KN == "Ka2017"): idx = np.where(self.samples['mej'] <= 1e-3)[0] self.samples['mej'][idx] = 1e-11 print("Probability of having ejecta") print(100 * (len(self.samples) - len(idx)) / len(self.samples)) return self.samples['mej'] def calc_lightcurve(self, model_KN): self.samples = self.samples.downsample(Nsamples=1000) #add default values from above to table self.samples['tini'] = tini self.samples['tmax'] = tmax self.samples['dt'] = dt self.samples['vmin'] = vmin self.samples['th'] = th self.samples['ph'] = ph self.samples['kappa'] = kappa self.samples['eps'] = eps self.samples['alp'] = alp self.samples['eth'] = eth self.samples['flgbct'] = flgbct self.samples['beta'] = beta self.samples['kappa_r'] = kappa_r self.samples['slope_r'] = slope_r self.samples['theta_r'] = theta_r self.samples['Ye'] = Ye kwargs = { 'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath } kwargs["doAB"] = True kwargs["doSpec"] = False model_tables = {} models = model_KN.split(",") for model in models: model_tables[model] = KNTable.model(model, self.samples, **kwargs) if (model_KN == "Bu2019inc"): idx = np.where(model_tables[model]['mej'] <= 1e-6)[0] model_tables[model]['mag'][idx] = 10. model_tables[model]['lbol'][idx] = 1e30 elif (model_KN == "Ka2017"): idx = np.where(model_tables[model]['mej'] <= 1e-3)[0] model_tables[model]['mag'][idx] = 10. model_tables[model]['lbol'][idx] = 1e30 for model in models: model_tables[model] = lightcurve_utils.calc_peak_mags( model_tables[model]) mag_all = {} app_mag_all_mbta = {} lbol_all = {} for model in models: mag_all[model] = {} app_mag_all_mbta[model] = {} lbol_all[model] = {} lbol_all[model] = np.empty((0, len(tt)), float) for filt, magidx in zip(filts, magidxs): mag_all[model][filt] = np.empty((0, len(tt))) app_mag_all_mbta[model][filt] = np.empty((0, len(tt))) peak_mags_all = {} for model in models: model_tables[model] = lightcurve_utils.calc_peak_mags( model_tables[model]) for row in model_tables[model]: t, lbol, mag = row["t"], row["lbol"], row["mag"] dist_mbta = row['dist_mbta'] if np.sum(lbol) == 0.0: #print "No luminosity..." continue allfilts = True for filt, magidx in zip(filts, magidxs): idx = np.where(~np.isnan(mag[magidx]))[0] if len(idx) == 0: allfilts = False break if not allfilts: continue for filt, magidx in zip(filts, magidxs): idx = np.where(~np.isnan(mag[magidx]))[0] f = interp.interp1d(t[idx], mag[magidx][idx], fill_value='extrapolate') maginterp = f(tt) app_maginterp_mbta = maginterp + 5 * (np.log10( (dist_mbta) * 1e6) - 1) mag_all[model][filt] = np.append(mag_all[model][filt], [maginterp], axis=0) app_mag_all_mbta[model][filt] = np.append( app_mag_all_mbta[model][filt], [app_maginterp_mbta], axis=0) idx = np.where((~np.isnan(np.log10(lbol))) & ~(lbol == 0))[0] f = interp.interp1d(t[idx], np.log10(lbol[idx]), fill_value='extrapolate') lbolinterp = 10**f(tt) lbol_all[model] = np.append(lbol_all[model], [lbolinterp], axis=0) return (mag_all, app_mag_all_mbta, lbol_all) def write_output(self, output_path, model_KN, mej, mag_all, app_mag_mbta_all, lbol_all): output_path = os.path.join(output_path, model_KN) if (not os.path.isdir(output_path)): os.mkdir(output_path) with open(os.path.join(output_path, "ejecta.txt"), 'w') as f: f.write( "#HasEjecta(%) mej_percentile(10%) mej_percentile(50%) mej_percentile(90%)" + "\n") if (model_KN == "Bu2019inc"): idx = np.where(mej <= 1e-6)[0] elif (model_KN == "Ka2017"): idx = np.where(mej <= 1e-3)[0] f.write( str(100 * (len(mej) - len(idx)) / len(mej)) + " " + str(np.percentile(mej, 10)) + " " + str(np.percentile(mej, 50)) + " " + str(np.percentile(mej, 90))) f.close with open(os.path.join(output_path, "lbol.txt"), 'w') as f: f.write( "#lbol_percentile(10%) lbol_percentile(50%) lbol_percentile(90%)" + "\n") f.write( str(np.percentile(lbol_all[model_KN], 10)) + " " + str(np.percentile(lbol_all[model_KN], 50)) + " " + str(np.percentile(lbol_all[model_KN], 90))) f.close for filt in filts: magmed = np.percentile(mag_all[model_KN][filt], 50, axis=0) magmax = np.percentile(mag_all[model_KN][filt], 90, axis=0) magmin = np.percentile(mag_all[model_KN][filt], 10, axis=0) app_magmed_mbta = np.percentile(app_mag_mbta_all[model_KN][filt], 50, axis=0) app_magmax_mbta = np.percentile(app_mag_mbta_all[model_KN][filt], 90, axis=0) app_magmin_mbta = np.percentile(app_mag_mbta_all[model_KN][filt], 10, axis=0) with open(os.path.join(output_path, filt + "_filter.txt"), 'w') as f: f.write( "#time mag_percentile(10%) mag_percentile(50%) mag_percentile(90%) appmag_percentile(10%) appmag_percentile(50%) appmag_percentile(90%)" + "\n") for i in range(len(magmed)): f.write( str(tt[i]) + " " + str(magmin[i]) + " " + str(magmed[i]) + " " + str(magmax[i]) + " " + str(app_magmin_mbta[i]) + " " + str(app_magmed_mbta[i]) + " " + str(app_magmax_mbta[i]) + "\n") f.close
def Test(EOS, m1, m2, chi, type_set=Type, model_set='Bu2019inc', twixie=twixie_tf, lan_override=False, lan_override_val=None, chirp_q=False): if type_set == 'BNS_chirp_q': type_set = 'BNS' if not chirp_q: m1 = np.random.normal(m1, .05, 100) m2 = np.random.normal(m2, .05, 100) q = m2 / m1 mchirp = np.power((m1 * m2), 3 / 5) / np.power((m1 + m2), 1 / 5) eta = m1 * m2 / ((m1 + m2) * (m1 + m2)) if chirp_q: print('running chirp_q') m1 = np.random.normal(m1, .05, 100) m2 = np.random.normal(m2, .05, 100) #m1 = np.ones(100) * m1 #m2 = np.ones(100) * m2 q = m2 mchirp = m1 eta = lightcurve_utils.q2eta(q) m1, m2 = lightcurve_utils.mc2ms(mchirp, eta) dist = np.ones(100) #chi_eff = np.random.uniform(-1,1,100) chi_eff = np.ones(100) * chi Xlan = 1e-3 * np.ones(100) if lan_override: Xlan = lan_override_val * np.ones(100) c1 = np.ones(1000) c2 = np.ones(1000) mb1 = np.ones(1000) mb2 = np.ones(1000) mej = np.ones(1000) vej = np.ones(1000) data = np.vstack((m1, m2, dist, chi_eff, Xlan, mchirp, eta, q)).T samples_tmp = KNTable( (data), names=('m1', 'm2', 'dist', 'chi_eff', 'Xlan', 'mchirp', 'eta', 'q')) if twixie: samples_tmp = KNTable.read_mchirp_samples(opts.mchirp_samples, Nsamples=100, twixie_flag=twixie_tf) lambda1s = [] lambda2s = [] m1s = [] m2s = [] dists = [] chi_effs = [] Xlans = [] qs = [] etas = [] mchirps = [] mbnss = [] term1_list, term2_list, term3_list, term4_list = [], [], [], [] if EOS == "gp": # read Phil + Reed's EOS files filenames = glob.glob( "/home/philippe.landry/gw170817eos/gp/macro/MACROdraw-*-0.csv") idxs = [] for filename in filenames: filenameSplit = filename.replace(".csv", "").split("/")[-1].split("-") idxs.append(int(filenameSplit[1])) idxs = np.array(idxs) elif EOS == "Sly": eosname = "SLy" eos = EOS4ParameterPiecewisePolytrope(eosname) for ii, row in enumerate(samples_tmp): if not twixie: m1, m2, dist, chi_eff, q, mchirp, eta, Xlan = row["m1"], row[ "m2"], row["dist"], row["chi_eff"], row['q'], row[ 'mchirp'], row['eta'], row['Xlan'] if twixie: m1, m2, dist, chi_eff, q, mchirp, eta = row["m1"], row["m2"], row[ "dist_mbta"], row["chi_eff"], row['q'], row['mchirp'], row[ 'eta'] nsamples = 10 if EOS == "spec": indices = np.random.randint(0, 2395, size=nsamples) elif EOS == "gp": indices = np.random.randint(0, len(idxs), size=nsamples) for jj in range(nsamples): if (EOS == "spec") or (EOS == "gp"): index = indices[jj] # samples lambda's from Phil + Reed's files if EOS == "spec": eospath = "/home/philippe.landry/gw170817eos/spec/macro/macro-spec_%dcr.csv" % index data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) lambda1, lambda2 = f(m1), f(m2) mbns = np.max(marray) elif EOS == "Sly": lambda1, lambda2 = eos.lambdaofm(m1), eos.lambdaofm(m2) mbns = eos.maxmass() #print(mbns) elif EOS == "gp": lambda1, lambda2 = 0.0, 0.0 phasetr = 0 while (lambda1 == 0.0) or (lambda2 == 0.0): eospath = "/home/philippe.landry/gw170817eos/gp/macro/MACROdraw-%06d-%d.csv" % ( idxs[index], phasetr) if not os.path.isfile(eospath): break data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) lambda1_tmp, lambda2_tmp = f(m1), f(m2) if (lambda1_tmp > 0) and (lambda1 == 0.0): lambda1 = lambda1_tmp if (lambda2_tmp > 0) and (lambda2 == 0.0): lambda2 = lambda2_tmp phasetr = phasetr + 1 mbns = np.max(marray) lambda1s.append(lambda1) lambda2s.append(lambda2) m1s.append(m1) m2s.append(m2) dists.append(dist) chi_effs.append(chi_eff) Xlans.append(Xlan) qs.append(q) etas.append(eta) mchirps.append(mchirp) mbnss.append(mbns) if twixie: Xlans = np.ones(1000) * 1e-3 data = np.vstack((m1s, m2s, dists, lambda1s, lambda2s, chi_effs, Xlans, c1, c2, mb1, mb2, mchirps, etas, qs, mej, vej, mbnss)).T samples = KNTable((data), names=('m1', 'm2', 'dist', 'lambda1', 'lambda2', 'chi_eff', 'Xlan', 'c1', 'c2', 'mb1', 'mb2', 'mchirp', 'eta', 'q', 'mej', 'vej', 'mbns')) #calc compactness samples = samples.calc_compactness(fit=True) #clac baryonic mass samples = samples.calc_baryonic_mass(EOS=None, TOV=None, fit=True) if type_set == 'BNS': from gwemlightcurves.EjectaFits.CoDi2019 import calc_meje, calc_vej #from gwemlightcurves.EjectaFits.PaDi2019 import calc_meje, calc_vej # calc the mass of ejecta mej = calc_meje(samples['m1'], samples['c1'], samples['m2'], samples['c2']) # calc the velocity of ejecta vej = calc_vej(samples['m1'], samples['c1'], samples['m2'], samples['c2']) samples['mchirp'], samples['eta'], samples[ 'q'] = lightcurve_utils.ms2mc(samples['m1'], samples['m2']) samples['q'] = 1.0 / samples['q'] samples['mej'] = mej samples['vej'] = vej if model_set == 'Bu2019inc': idx = np.where(samples['mej'] <= 1e-6)[0] samples['mej'][idx] = 1e-6 idx2 = np.where(samples['mej'] >= 1)[0] samples['mej'][idx2] = 1e-6 print('mej = ' + str(samples['mej'][0])) if type_set == 'NSBH': from gwemlightcurves.EjectaFits.KrFo2019 import calc_meje, calc_vave # calc the mass of ejecta mej = calc_meje(samples['q'], samples['chi_eff'], samples['c2'], samples['m2']) # calc the velocity of ejecta vej = calc_vave(samples['q']) samples['mej'] = mej samples['vej'] = vej if model_set == 'Bu2019inc': idx = np.where(samples['mej'] <= 1e-6)[0] samples['mej'][idx] = 1e-6 idx2 = np.where(samples['mej'] >= 1)[0] samples['mej'][idx2] = 1e-6 print('mej = ' + str(samples['mej'][0])) if type_set == 'BNS' or 'NSBH': # Add draw from a gaussian in the log of ejecta mass with 1-sigma size of 70% erroropt = 'none' if erroropt == 'none': print("Not applying an error to mass ejecta") elif erroropt == 'log': samples['mej'] = np.power( 10., np.random.normal(np.log10(samples['mej']), 0.236)) elif erroropt == 'lin': samples['mej'] = np.random.normal(samples['mej'], 0.72 * samples['mej']) elif erroropt == 'loggauss': samples['mej'] = np.power( 10., np.random.normal(np.log10(samples['mej']), 0.312)) idx = np.where(samples['mej'] > 0)[0] samples = samples[idx] print(EOS + ' calculation finished') return samples
samples['beta'] = beta samples['kappa_r'] = kappa_r samples['slope_r'] = slope_r samples['theta_r'] = theta_r samples['Ye'] = Ye samples = samples[0:10] ModelPath = "/home/cosmin.stachie/gwemlightcurves/output/svdmodels" kwargs = {'SaveModel':False,'LoadModel':True,'ModelPath':ModelPath} kwargs["doAB"] = True kwargs["doSpec"] = False #model = "Ka2017" model = "Bu2019inc" model_tables = {} model_tables[model] = KNTable.model(model, samples, **kwargs) idx = np.where(model_tables[model]['mej'] <= 1e-3)[0] print("idx") print(idx) model_tables[model]['mag'][idx] = 10. model_tables[model]['lbol'][idx] = 1e30 mags = model_tables[model]['mag'] t = model_tables[model]['t'][0] #bands = ['u', 'g', 'r', 'i', 'z', 'y', 'J', 'H', 'K'] t_list, u_list, g_list, r_list, i_list = [], [], [], [], [] z_list, y_list, J_list, H_list, K_list = [], [], [], [], []
exit(0) baseplotDir = os.path.join(opts.plotDir,'standard_candles','GRB_GW',grbname) if not os.path.isdir(baseplotDir): os.makedirs(baseplotDir) plotDir = os.path.join(baseplotDir,opts.analysis_type) plotDir = os.path.join(plotDir,"%.2f"%opts.errorbudget) if not os.path.isdir(plotDir): os.makedirs(plotDir) ModelPath = '%s/svdmodels'%(opts.outputDir) if not os.path.isdir(ModelPath): os.makedirs(ModelPath) samples = KNTable.read_samples(opts.posterior_samples) gwdist = samples["luminosity_distance_Mpc"] if "bulla" in opts.analysis_type: filename = os.path.join(opts.dataDir, 'standard_candles', 'magcolor_bulla_rband.dat') data = np.loadtxt(filename) mej, phi, theta, color, Mag, dmdti, dmdt = data.T mej = np.log10(mej) dmdt = np.log10(dmdt) dmdti = np.log10(dmdti) else: filename = os.path.join(opts.dataDir, 'standard_candles', 'magcolor_rband.dat') data = np.loadtxt(filename) mej, vej, Xlan, color, Mag, dmdti, dmdt = data.T mej, Xlan = np.log10(mej), np.log10(Xlan) dmdt = np.log10(dmdt)
from gwemlightcurves.KNModels import KNTable from gwemlightcurves import lightcurve_utils import matplotlib.pyplot as plt t = KNTable.read_samples('posterior_samples.dat') t = t.calc_tidal_lambda(remove_negative_lambda=True) t = t.calc_compactness(fit=True) t = t.calc_baryonic_mass(EOS=None, TOV=None, fit=True) t = t.downsample(Nsamples=100) tini = 0.1 tmax = 50.0 dt = 0.1 vmin = 0.02 th = 0.2 ph = 3.14 kappa = 1.0 eps = 1.58 * (10**10) alp = 1.2 eth = 0.5 flgbct = 1 beta = 3.0 kappa_r = 1.0 slope_r = -1.2 theta_r = 0.0 Ye = 0.3 t['tini'] = tini t['tmax'] = tmax t['dt'] = dt t['vmin'] = vmin t['th'] = th t['ph'] = ph t['kappa'] = kappa
plotDir = os.path.join(plotDir, opts.eostype) if opts.analysisType == "cbclist": plotDir = os.path.join(plotDir, opts.cbc_type) plotDir = os.path.join(plotDir, "%d_%d" % (opts.mindistance, opts.maxdistance)) if not os.path.isdir(plotDir): os.makedirs(plotDir) datDir = os.path.join(plotDir, "dat") if not os.path.isdir(datDir): os.makedirs(datDir) if (opts.analysisType == "posterior") or (opts.analysisType == "mchirp"): # read in samples if opts.analysisType == "posterior": samples = KNTable.read_samples(opts.posterior_samples) samples["dist"] = opts.distance else: if opts.nsamples < 1: print('Please set nsamples >= 1') exit(0) # read samples from template analysis samples = KNTable.read_mchirp_samples(opts.mchirp_samples, Nsamples=opts.nsamples) m1s, m2s, dists = [], [], [] lambda1s, lambda2s, chi_effs = [], [], [] Xlans = [] if opts.eostype == "gp": # read Phil + Reed's EOS files
plt.errorbar(10**mej, M, sigma_best * np.ones(M.shape), fmt='k.') plt.plot(10**mej, Mag, 'bo') plt.ylabel('Magnitude') plt.setp(ax1.get_xticklabels(), visible=False) plt.gca().invert_yaxis() plt.axes(ax2) plt.errorbar(10**mej, M - Mag, sigma_best * np.ones(M.shape), fmt='k.') plt.ylabel('Model - Data') plt.xlabel('Ejecta mass [solar masses]') plt.show() plotName = os.path.join(plotDir, 'fit.pdf') plt.savefig(plotName) plt.close() samples = KNTable.read_multinest_samples(multinest_samples, opts.model) if opts.nsamples > 0: samples = samples.downsample(Nsamples=opts.nsamples) # These are the default values supplied with respect to generating lightcurves tini = 0.1 tmax = 14.0 dt = 0.1 #add default values from above to table samples['tini'] = tini samples['tmax'] = tmax samples['dt'] = dt kwargs = {'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath} kwargs["doAB"] = True kwargs["doSpec"] = False
def __init__(self, input_samples, Xlan_fixed, phi_fixed, eostype="spec"): self.samples = KNTable.initialize_object(input_samples) m1s, m2s, dists_mbta = [], [], [] lambda1s, lambda2s, chi_effs = [], [], [] Xlans = [] mbnss = [] if eostype == "gp": # read Phil + Reed's EOS files filenames = glob.glob( "/home/philippe.landry/gw170817eos/gp/macro/MACROdraw-*-0.csv") idxs = [] for filename in filenames: filenameSplit = filename.replace(".csv", "").split("/")[-1].split("-") idxs.append(int(filenameSplit[1])) idxs = np.array(idxs) elif eostype == "Sly": eosname = "SLy" eos = EOS4ParameterPiecewisePolytrope(eosname) for ii, row in enumerate(self.samples): print(ii) m1, m2, dist_mbta, chi_eff = row["m1"], row["m2"], row[ "dist_mbta"], row["chi_eff"] nsamples = 30 if eostype == "spec": indices = np.random.randint(0, 2395, size=nsamples) elif eostype == "gp": indices = np.random.randint(0, len(idxs), size=nsamples) for jj in range(nsamples): if (eostype == "spec") or (eostype == "gp"): index = indices[jj] # samples lambda's from Phil + Reed's files if eostype == "spec": eospath = "/home/philippe.landry/gw170817eos/spec/macro/macro-spec_%dcr.csv" % index data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) lambda1, lambda2 = f(m1), f(m2) mbns = np.max(marray) elif eostype == "gp": lambda1, lambda2 = 0.0, 0.0 phasetr = 0 while (lambda1 == 0.0) or (lambda2 == 0.0): eospath = "/home/philippe.landry/gw170817eos/gp/macro/MACROdraw-%06d-%d.csv" % ( idxs[index], phasetr) if not os.path.isfile(eospath): break data_out = np.genfromtxt(eospath, names=True, delimiter=",") marray, larray = data_out["M"], data_out["Lambda"] f = interp.interp1d(marray, larray, fill_value=0, bounds_error=False) lambda1_tmp, lambda2_tmp = f(m1), f(m2) if (lambda1_tmp > 0) and (lambda1 == 0.0): lambda1 = lambda1_tmp if (lambda2_tmp > 0) and (lambda2 == 0.0): lambda2 = lambda2_tmp phasetr = phasetr + 1 mbns = np.max(marray) elif eostype == "Sly": lambda1, lambda2 = eos.lambdaofm(m1), eos.lambdaofm(m2) m1s.append(m1) m2s.append(m2) dists_mbta.append(dist_mbta) lambda1s.append(lambda1) lambda2s.append(lambda2) chi_effs.append(chi_eff) mbnss.append(mbns) np.random.uniform(0) Xlans = [10**Xlan_fixed] * len(self.samples) * nsamples phis = [phi_fixed] * len(self.samples) * nsamples thetas = 180. * np.arccos( np.random.uniform(-1., 1., len(self.samples) * nsamples)) / np.pi idx_thetas = np.where(thetas > 90.)[0] thetas[idx_thetas] = 180. - thetas[idx_thetas] thetas = list(thetas) # make final arrays of masses, distances, lambdas, spins, and lanthanide fractions data = np.vstack((m1s, m2s, dists_mbta, lambda1s, lambda2s, chi_effs, thetas, phis, mbnss, Xlans)).T self.samples = KNTable(data, names=('m1', 'm2', 'dist_mbta', 'lambda1', 'lambda2', 'chi_eff', 'theta', 'phi', 'mbns', "Xlan")) self.samples = self.samples.calc_tidal_lambda( remove_negative_lambda=True) self.samples = self.samples.calc_compactness(fit=True) self.samples = self.samples.calc_baryonic_mass(EOS=None, TOV=None, fit=True) print(self.samples)
plt.errorbar(10**mej, M, sigma_best * np.ones(M.shape), fmt='k.') plt.plot(10**mej, Mag, 'bo') plt.ylabel('Magnitude') plt.setp(ax1.get_xticklabels(), visible=False) plt.gca().invert_yaxis() plt.axes(ax2) plt.errorbar(10**mej, M - Mag, sigma_best * np.ones(M.shape), fmt='k.') plt.ylabel('Model - Data') plt.xlabel('Ejecta mass [solar masses]') plt.show() plotName = os.path.join(plotDir, 'fit.pdf') plt.savefig(plotName) plt.close() samples = KNTable.read_multinest_samples(multinest_samples, opts.model) if opts.nsamples > 0: samples = samples.downsample(Nsamples=opts.nsamples) # These are the default values supplied with respect to generating lightcurves tini = 0.1 tmax = 14.0 dt = 0.1 #add default values from above to table samples['tini'] = tini samples['tmax'] = tmax samples['dt'] = dt kwargs = {'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath} kwargs["doAB"] = True kwargs["doSpec"] = False
if opts.doSaveModel: kwargs = {'SaveModel': True, 'LoadModel': False, 'ModelPath': ModelPath} else: kwargs = {'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath} kwargs["doAB"] = opts.doAB kwargs["doSpec"] = opts.doSpec kwargs["phi"] = phi t = Table() for key in samples.keys(): val = samples[key] t.add_column(Column(data=[val], name=key)) samples = t if not opts.model in ["SN", "Afterglow"]: model_table = KNTable.model(opts.model, samples, **kwargs) if opts.doAB: t, lbol, mag = model_table["t"][0], model_table["lbol"][ 0], model_table["mag"][0] elif opts.doSpec: t, lambdas, spec = model_table["t"][0], model_table["lambda"][ 0], model_table["spec"][0] if opts.model == "KaKy2016": if opts.doEjecta: name = "KaKy2016_%sM%03dV%02d" % (opts.eos, opts.mej * 1000, opts.vej * 100) elif opts.doMasses: name = "%sQ%.0fa%.0f" % (opts.eos, opts.massratio, opts.chi_eff * 100) elif opts.model == "DiUj2017": if opts.doEjecta:
#grbs_skip = ["GW170817","GRB060614","GRB050709","GRB130603B"] grbs_include = ["GW170817", "GRB060614", "GRB050709", "GRB130603B"] nsamples = 100 data_out = {} for grb, dataDir in zip(grbs, dataDirs): if not grb in grbs_include: continue if not grb in data_out: data_out[grb] = {} multifile = lightcurve_utils.get_post_file(dataDir) data = np.loadtxt(multifile) #if (data.size > 0) and (not grb in grbs_skip): if data.size > 0: data_out[grb]["KN"] = data data_out[grb]["KN_samples"] = KNTable.read_multinest_samples( multifile, 'Ka2017_A') data_out[grb]["KN_samples"] = data_out[grb]["KN_samples"].downsample( Nsamples=nsamples) ModelPath = '%s/svdmodels' % ('../output') kwargs = {'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath} kwargs["doAB"] = True kwargs["doSpec"] = False filts = ["u", "g", "r", "i", "z", "y", "J", "H", "K"] errorbudget = 0.0 tini, tmax, dt = 0.1, 14.0, 0.1 for grb in data_out.keys(): print('Generating lightcurves for %s' % grb) if "KN_samples" in data_out[grb]:
ph = 3.14 kappa = 10.0 eps = 1.58 * (10**10) alp = 1.2 eth = 0.5 flgbct = 1 beta = 3.0 kappa_r = 0.1 slope_r = -1.2 theta_r = 0.0 Ye = 0.3 if opts.analysisType == "posterior": # read in samples samples = KNTable.read_samples(opts.posterior_samples) # limit masses samples = samples.mass_cut(mass1=3.0, mass2=3.0) samples["dist"] = opts.distance print "m1: %.5f +-%.5f" % (np.mean(samples["m1"]), np.std(samples["m1"])) print "m2: %.5f +-%.5f" % (np.mean(samples["m2"]), np.std(samples["m2"])) # Downsample samples = samples.downsample(Nsamples=100) # Calc lambdas samples = samples.calc_tidal_lambda(remove_negative_lambda=True) # Calc compactness samples = samples.calc_compactness(fit=True) # Calc baryonic mass
def calc_lightcurve(self, model_KN): self.samples = self.samples.downsample(Nsamples=1000) #add default values from above to table self.samples['tini'] = tini self.samples['tmax'] = tmax self.samples['dt'] = dt self.samples['vmin'] = vmin self.samples['th'] = th self.samples['ph'] = ph self.samples['kappa'] = kappa self.samples['eps'] = eps self.samples['alp'] = alp self.samples['eth'] = eth self.samples['flgbct'] = flgbct self.samples['beta'] = beta self.samples['kappa_r'] = kappa_r self.samples['slope_r'] = slope_r self.samples['theta_r'] = theta_r self.samples['Ye'] = Ye kwargs = { 'SaveModel': False, 'LoadModel': True, 'ModelPath': ModelPath } kwargs["doAB"] = True kwargs["doSpec"] = False model_tables = {} models = model_KN.split(",") for model in models: model_tables[model] = KNTable.model(model, self.samples, **kwargs) if (model_KN == "Bu2019inc"): idx = np.where(model_tables[model]['mej'] <= 1e-6)[0] model_tables[model]['mag'][idx] = 10. model_tables[model]['lbol'][idx] = 1e30 elif (model_KN == "Ka2017"): idx = np.where(model_tables[model]['mej'] <= 1e-3)[0] model_tables[model]['mag'][idx] = 10. model_tables[model]['lbol'][idx] = 1e30 for model in models: model_tables[model] = lightcurve_utils.calc_peak_mags( model_tables[model]) mag_all = {} app_mag_all_mbta = {} lbol_all = {} for model in models: mag_all[model] = {} app_mag_all_mbta[model] = {} lbol_all[model] = {} lbol_all[model] = np.empty((0, len(tt)), float) for filt, magidx in zip(filts, magidxs): mag_all[model][filt] = np.empty((0, len(tt))) app_mag_all_mbta[model][filt] = np.empty((0, len(tt))) peak_mags_all = {} for model in models: model_tables[model] = lightcurve_utils.calc_peak_mags( model_tables[model]) for row in model_tables[model]: t, lbol, mag = row["t"], row["lbol"], row["mag"] dist_mbta = row['dist_mbta'] if np.sum(lbol) == 0.0: #print "No luminosity..." continue allfilts = True for filt, magidx in zip(filts, magidxs): idx = np.where(~np.isnan(mag[magidx]))[0] if len(idx) == 0: allfilts = False break if not allfilts: continue for filt, magidx in zip(filts, magidxs): idx = np.where(~np.isnan(mag[magidx]))[0] f = interp.interp1d(t[idx], mag[magidx][idx], fill_value='extrapolate') maginterp = f(tt) app_maginterp_mbta = maginterp + 5 * (np.log10( (dist_mbta) * 1e6) - 1) mag_all[model][filt] = np.append(mag_all[model][filt], [maginterp], axis=0) app_mag_all_mbta[model][filt] = np.append( app_mag_all_mbta[model][filt], [app_maginterp_mbta], axis=0) idx = np.where((~np.isnan(np.log10(lbol))) & ~(lbol == 0))[0] f = interp.interp1d(t[idx], np.log10(lbol[idx]), fill_value='extrapolate') lbolinterp = 10**f(tt) lbol_all[model] = np.append(lbol_all[model], [lbolinterp], axis=0) return (mag_all, app_mag_all_mbta, lbol_all)