def lnprior(params, vsin_obs, sig_vsin_obs, dist_pc, sig_dist_pc, ranges, model, stellar_prior, npy_star, pdf_mas, pdf_obl, pdf_age, pdf_dis, pdf_ebv, grid_mas, grid_obl, grid_age, grid_dis, grid_ebv): if model == 'befavor': Mstar, oblat, Hfrac, cosi, dist, ebv = params[0], params[1],\ params[2], params[3], params[4], params[5] if model == 'aara' or model == 'acol' or model == 'bcmi': Mstar, oblat, Hfrac, cosi, dist, ebv = params[0], params[1],\ params[2], params[6], params[7], params[8] if model == 'beatlas': Mstar, oblat, Hfrac, cosi, dist, ebv = params[0], params[1],\ 0.3, params[4], params[5], params[6] # Reading Stellar Priors if stellar_prior is True: temp, idx_mas = find_nearest(grid_mas, value=Mstar) temp, idx_obl = find_nearest(grid_obl, value=oblat) temp, idx_age = find_nearest(grid_age, value=Hfrac) temp, idx_dis = find_nearest(grid_dis, value=dist) temp, idx_ebv = find_nearest(grid_ebv, value=ebv) chi2_stellar_prior = Mstar * pdf_mas[idx_mas] +\ oblat * pdf_obl[idx_obl] + \ Hfrac * pdf_age[idx_age] + \ dist * pdf_dis[idx_dis] + \ ebv * pdf_ebv[idx_ebv] else: chi2_stellar_prior = 0.0 # Rpole, Lstar, Teff = vkg.geneve_par(Mstar, oblat, Hfrac, folder_tables) t = np.max(np.array([hfrac2tms(Hfrac), 0.])) Rpole, logL = geneva_interp_fast(Mstar, oblat, t, neighbours_only=True, isRpole=False) wcrit = np.sqrt(8. / 27. * G * Mstar * Msun / (Rpole * Rsun)**3) vsini = oblat2w(oblat) * wcrit * (Rpole * Rsun * oblat) *\ np.sin(np.arccos(cosi)) * 1e-5 chi2_vsi = (vsin_obs - vsini)**2 / sig_vsin_obs**2. chi2_dis = (dist_pc - dist)**2 / sig_dist_pc**2. chi2_prior = chi2_vsi + chi2_dis + chi2_stellar_prior return -0.5 * chi2_prior
def plot_fit(par, lbd, logF, dlogF, minfo, listpar, lbdarr, logF_grid, isig, dims, Nwalk, Nmcmc, par_list, ranges, include_rv, npy, log_scale): ''' Plots best model fit over data Usage: plot_fit(par, lbd, logF, dlogF, minfo, logF_grid, isig, Nwalk, Nmcmc) where par = np.array([Mstar, oblat, Sig0, Rd, n, cosi, dist]) ''' # model parameters if include_rv is True: Mstar, oblat, Hfrac, cosi, dist, ebv, rv = par lim = 3 lim2 = 2 else: Mstar, oblat, Hfrac, cosi, dist, ebv = par lim = 2 lim2 = 1 rv = 3.1 # Rpole, Lstar, Teff = vkg.geneve_par(Mstar, oblat, Hfrac, folder_tables) # t = np.max(np.array([hfrac2tms(hfrac), 0.])) t = np.max(np.array([hfrac2tms(Hfrac), 0.])) Rpole, logL = geneva_interp_fast(Mstar, oblat, t, neighbours_only=True, isRpole=False) norma = (10. / dist)**2 # (Lstar*Lsun) / (4. * pi * (dist*pc)**2) uplim = dlogF == 0 keep = np.logical_not(uplim) # chain = np.load(npy) # interpolate models logF_mod = griddataBA(minfo, logF_grid, par[:-lim], listpar, dims) logF_list = np.zeros([len(par_list), len(logF_mod)]) chi2 = np.zeros(len(logF_list)) for i in range(len(par_list)): logF_list[i] = griddataBA(minfo, logF_grid, par_list[i, :-lim], listpar, dims) # convert to physical units logF_mod += np.log10(norma) logF_list += np.log10(norma) for j in range(len(logF_list)): chi2[j] = np.sum( (logF[keep] - logF_list[j][keep])**2 / (dlogF[keep])**2) # chib = chi2[np.argsort(chi2)[-30:]] / max(chi2) flux = 10.**logF dflux = dlogF * flux flux_mod = 10.**logF_mod flux_mod = pyasl.unred(lbd * 1e4, flux_mod, ebv=-1 * ebv, R_V=rv) # Plot definitions bottom, left = 0.75, 0.48 width, height = 0.96 - left, 0.97 - bottom plt.axes([left, bottom, width, height]) # plot fit if log_scale is True: for i in range(len(par_list)): if i % 80 == 0: ebv_temp = np.copy(par_list[i][-lim2]) F_temp = pyasl.unred(lbd * 1e4, 10**logF_list[i], ebv=-1 * ebv_temp, R_V=rv) plt.plot(lbd, lbd * F_temp, color='gray', alpha=0.1) plt.errorbar(lbd, lbd * flux, yerr=lbd * dflux, ls='', marker='o', alpha=0.5, ms=10, color='blue', linewidth=2) plt.plot(lbd, lbd * flux_mod, color='red', ls='-', lw=3.5, alpha=0.4, label='$\mathrm{Best\, fit}$') plt.xlabel('$\lambda\,\mathrm{[\mu m]}$', fontsize=20) plt.ylabel(r'$\lambda F_{\lambda}\,\mathrm{[erg\, s^{-1}\, cm^{-2}]}$', fontsize=20) plt.yscale('log') else: for i in range(len(par_list)): if i % 80 == 0: ebv_temp = np.copy(par_list[i][-lim2]) F_temp = pyasl.unred(lbd * 1e4, 10**logF_list[i], ebv=-1 * ebv_temp, R_V=rv) plt.plot(lbd, F_temp, color='gray', alpha=0.1) plt.errorbar(lbd, flux, yerr=lbd * dflux, ls='', marker='o', alpha=0.5, ms=10, color='blue', linewidth=2) plt.plot(lbd, flux_mod, color='red', ls='-', lw=3.5, alpha=0.4, label='$\mathrm{Best\, fit}$') plt.xlabel('$\lambda\,\mathrm{[\mu m]}$', fontsize=20) plt.ylabel(r'$F_{\lambda}\,\mathrm{[erg\, s^{-1}\, cm^{-2} \mu m]}$', fontsize=20) plt.xlim(min(lbd), max(lbd)) plt.tick_params(direction='in', length=6, width=2, colors='gray', which='both') plt.legend(loc='upper right') return
def plot_residuals(par, lbd, logF, dlogF, minfo, listpar, lbdarr, logF_grid, isig, dims, Nwalk, Nmcmc, ranges, include_rv, npy, log_scale, model): ''' Plots best model fit over data Usage: plot_fit(par, lbd, logF, dlogF, minfo, logF_grid, isig, Nwalk, Nmcmc) where par = np.array([Mstar, oblat, Sig0, Rd, n, cosi, dist]) ''' # model parameters if include_rv is True: Mstar, oblat, Hfrac, cosi, dist, ebv, rv = par lim = 3 lim2 = 2 else: if model == 'befavor': Mstar, oblat, Hfrac, cosi, dist, ebv = par if model == 'aara' or model == 'acol' or model == 'bcmi': Mstar, oblat, Hfrac, Sig0, Rd, n, cosi, dist, ebv = par if model == 'beatlas': Mstar, oblat, Sig0, n, cosi, dist, ebv = par Hfrac = 0.3 lim = 2 lim2 = 1 rv = 3.1 # Rpole, Lstar, Teff = vkg.geneve_par(Mstar, oblat, Hfrac, folder_tables) # t = np.max(np.array([hfrac2tms(hfrac), 0.])) t = np.max(np.array([hfrac2tms(Hfrac), 0.])) Rpole, logL = geneva_interp_fast(Mstar, oblat, t, neighbours_only=True, isRpole=False) norma = (10. / dist)**2 # (Lstar*Lsun) / (4. * pi * (dist*pc)**2) uplim = dlogF == 0 keep = np.logical_not(uplim) # *** chain = np.load(npy) par_list = chain[:, -1, :] # interpolate models if model == 'beatlas': logF_mod = griddataBAtlas(minfo, logF_grid, par[:-lim], listpar, dims, isig) else: logF_mod = griddataBA(minfo, logF_grid, par[:-lim], listpar, dims) logF_list = np.zeros([len(par_list), len(logF_mod)]) chi2 = np.zeros(len(logF_list)) for i in range(len(par_list)): if model == 'beatlas': logF_list[i] = griddataBAtlas(minfo, logF_grid, par_list[i, :-lim], listpar, dims, isig) else: logF_list[i] = griddataBA(minfo, logF_grid, par_list[i, :-lim], listpar, dims) # convert to physical units logF_mod += np.log10(norma) logF_list += np.log10(norma) for j in range(len(logF_list)): chi2[j] = np.sum( (logF[keep] - logF_list[j][keep])**2 / (dlogF[keep])**2) # chib = chi2[np.argsort(chi2)[-30:]] / max(chi2) flux = 10.**logF dflux = dlogF * flux flux_mod = 10.**logF_mod flux_mod = pyasl.unred(lbd * 1e4, flux_mod, ebv=-1 * ebv, R_V=rv) # alphas = (1. - chi2 / max(chi2)) / 50. # Plot definitions bottom, left = 0.71, 0.48 width, height = 0.96 - left, 0.785 - bottom plt.axes([left, bottom, width, height]) # plot fit for i in range(len(par_list)): ebv_temp = np.copy(par_list[i][-lim2]) F_temp = pyasl.unred(lbd * 1e4, 10**logF_list[i], ebv=-1 * ebv_temp, R_V=rv) plt.plot(lbd, (flux - F_temp) / dflux, 'bs', alpha=0.2) # plt.plot(lbd, (flux - flux_mod) / dflux, 'bs', markersize=5, alpha=0.1) # plt.ylabel('$(\mathrm{F}-F_\mathrm{model})/\sigma$', fontsize=20) plt.ylabel('$(F-F_\mathrm{m})/\sigma$', fontsize=20) plt.xlabel('$\lambda\,\mathrm{[\mu m]}$', fontsize=20) # plt.ylim(-100, 100) plt.hlines(y=0, xmin=min(lbd), xmax=max(lbd), linestyles='--', color='black') plt.xlim(min(lbd), max(lbd)) if model == 'aara' or model == 'beatlas' or\ model == 'acol' or model == 'bcmi': plt.xscale('log') plt.tick_params(direction='in', length=6, width=2, colors='gray', which='both') plt.legend(loc='upper right') return
def emcee_inference(star, Ndim, ranges, lbdarr, wave, logF, dlogF, minfo, listpar, logF_grid, vsin_obs, sig_vsin_obs, dist_pc, sig_dist_pc, isig, dims, include_rv, a_parameter, af_filter, tag, plot_fits, long_process, log_scale, model, acrux, pool, Nproc, stellar_prior, npy_star, pdf_mas, pdf_obl, pdf_age, pdf_dis, pdf_ebv, grid_mas, grid_obl, grid_age, grid_dis, grid_ebv): if long_process is True: Nwalk = 500 # 200 # 500 nint_burnin = 100 # 50 nint_mcmc = 1000 # 500 # 1000 else: Nwalk = 20 nint_burnin = 5 nint_mcmc = 10 p0 = [ np.random.rand(Ndim) * (ranges[:, 1] - ranges[:, 0]) + ranges[:, 0] for i in range(Nwalk) ] start_time = time.time() if acrux is True: sampler = emcee.EnsembleSampler( Nwalk, Ndim, lnprob, args=[ wave, logF, dlogF, minfo, listpar, logF_grid, vsin_obs, sig_vsin_obs, dist_pc, sig_dist_pc, isig, ranges, dims, include_rv, model, stellar_prior, npy_star, pdf_mas, pdf_obl, pdf_age, pdf_dis, pdf_ebv, grid_mas, grid_obl, grid_age, grid_dis, grid_ebv ], a=a_parameter, threads=Nproc, pool=pool) else: sampler = emcee.EnsembleSampler( Nwalk, Ndim, lnprob, args=[ wave, logF, dlogF, minfo, listpar, logF_grid, vsin_obs, sig_vsin_obs, dist_pc, sig_dist_pc, isig, ranges, dims, include_rv, model, stellar_prior, npy_star, pdf_mas, pdf_obl, pdf_age, pdf_dis, pdf_ebv, grid_mas, grid_obl, grid_age, grid_dis, grid_ebv ], a=a_parameter, threads=1) sampler_tmp = run_emcee(p0, sampler, nint_burnin, nint_mcmc, Ndim, file_name=star) print("--- %s minutes ---" % ((time.time() - start_time) / 60)) sampler, params_fit, errors_fit, maxprob_index,\ minprob_index, af = sampler_tmp if include_rv is True: mass_true, obt_true, xc_true,\ cos_true, ebv_true, dist_true, rv_true = params_fit else: if model == 'befavor': mass_true, obt_true, xc_true,\ cos_true, ebv_true, dist_true = params_fit if model == 'aara' or model == 'acol' or model == 'bcmi': mass_true, obt_true, xc_true, n0, Rd, n_true,\ cos_true, ebv_true, dist_true = params_fit if model == 'beatlas': mass_true, obt_true, rh0_true, nix_true,\ inc_true, dis_true, ebv_true = params_fit # if model is False: # angle_in_rad = np.arccos(params_fit[6]) # params_fit[6] = (np.arccos(params_fit[6])) * (180. / np.pi) # errors_fit[6] = (errors_fit[6] / (np.sqrt(1. - # (np.cos(angle_in_rad)**2.)))) * (180. / np.pi) chain = sampler.chain if af_filter is True: acceptance_fractions = sampler.acceptance_fraction chain = chain[(acceptance_fractions >= 0.20) & (acceptance_fractions <= 0.50)] af = acceptance_fractions[(acceptance_fractions >= 0.20) & (acceptance_fractions <= 0.50)] af = np.mean(af) af = str('{0:.2f}'.format(af)) # Saving first sample file_npy = 'figures/' + str(star) + '/' + 'Walkers_' +\ str(Nwalk) + '_Nmcmc_' + str(nint_mcmc) +\ '_af_' + str(af) + '_a_' + str(a_parameter) +\ tag + ".npy" np.save(file_npy, chain) # plot results mpl.rcParams['mathtext.fontset'] = 'stix' mpl.rcParams['font.family'] = 'STIXGeneral' mpl.rcParams['font.size'] = 16 # Loading first dataframe chain_1 = np.load(file_npy) Ndim_1 = np.shape(chain_1)[-1] flatchain_1 = chain_1.reshape((-1, Ndim_1)) if model == 'befavor': mas_1 = flatchain_1[:, 0] obl_1 = flatchain_1[:, 1] age_1 = flatchain_1[:, 2] inc_1 = flatchain_1[:, 3] dis_1 = flatchain_1[:, 4] ebv_1 = flatchain_1[:, 5] if model == 'aara' or model == 'acol' or model == 'bcmi': mas_1 = flatchain_1[:, 0] obl_1 = flatchain_1[:, 1] age_1 = flatchain_1[:, 2] rh0_1 = flatchain_1[:, 3] rdk_1 = flatchain_1[:, 4] nix_1 = flatchain_1[:, 5] inc_1 = flatchain_1[:, 6] dis_1 = flatchain_1[:, 7] ebv_1 = flatchain_1[:, 8] if model == 'beatlas': mas_1 = flatchain_1[:, 0] obl_1 = flatchain_1[:, 1] rh0_1 = flatchain_1[:, 2] nix_1 = flatchain_1[:, 3] inc_1 = flatchain_1[:, 4] dis_1 = flatchain_1[:, 5] ebv_1 = flatchain_1[:, 6] if include_rv is True: rv_1 = flatchain_1[:, 6] par_list = np.zeros([len(mas_1), 7]) else: if model == 'befavor': par_list = np.zeros([len(mas_1), 6]) if model == 'aara' or model == 'acol' or model == 'bcmi': par_list = np.zeros([len(mas_1), 9]) if model == 'beatlas': par_list = np.zeros([len(mas_1), 7]) for i in range(len(mas_1)): if include_rv is True: par_list[i] = [ mas_1[i], obl_1[i], age_1[i], inc_1[i], dis_1[i], ebv_1[i], rv_1[i] ] else: if model == 'befavor': par_list[i] = [ mas_1[i], obl_1[i], age_1[i], inc_1[i], dis_1[i], ebv_1[i] ] if model == 'aara' or model == 'acol' or model == 'bcmi': par_list[i] = [ mas_1[i], obl_1[i], age_1[i], rh0_1[i], rdk_1[i], nix_1[i], inc_1[i], dis_1[i], ebv_1[i] ] if model == 'beatlas': par_list[i] = [ mas_1[i], obl_1[i], rh0_1[i], nix_1[i], inc_1[i], dis_1[i], ebv_1[i] ] # plot corner if include_rv is True: samples = np.vstack((mas_1, obl_1, age_1, inc_1, dis_1, ebv_1, rv_1)).T else: if model == 'befavor': samples = np.vstack((mas_1, obl_1, age_1, inc_1, dis_1, ebv_1)).T if model == 'aara' or model == 'acol' or model == 'bcmi': samples = np.vstack((mas_1, obl_1, age_1, rh0_1, rdk_1, nix_1, inc_1, dis_1, ebv_1)).T if model == 'beatlas': samples = np.vstack( (mas_1, obl_1, rh0_1, nix_1, inc_1, dis_1, ebv_1)).T k, arr_t_tc, arr_Xc = t_tms_from_Xc(mass_true, savefig=False, plot_fig=False) ttms_ip = np.arange(0.001, 1., 0.001) Xc_ip = np.interp(ttms_ip, arr_t_tc[k], arr_Xc[k]) for i in range(len(samples)): if model == 'befavor' or model == 'aara' or\ model == 'acol' or model == 'bcmi': # Calculating logg for the non_rotating case Mstar, oblat, Hfrac = samples[i][0], samples[i][1],\ samples[i][2] else: Mstar, oblat, Hfrac = samples[i][0], samples[i][1], 0.3 t = np.max(np.array([hfrac2tms(Hfrac), 0.])) Rpole, logL = geneva_interp_fast(Mstar, oblat, t, neighbours_only=True, isRpole=False) # Converting oblat to W samples[i][1] = obl2W(samples[i][1]) if model == 'befavor': # Converting angles to degrees samples[i][3] = (np.arccos(samples[i][3])) * (180. / np.pi) # Converting Xc to t(tms) samples[i][2] = ttms_ip[find_nearest(Xc_ip, samples[i][2])[1]] if model == 'aara': # Converting Xc to t(tms) samples[i][2] = ttms_ip[find_nearest(Xc_ip, samples[i][2])[1]] samples[i][5] = samples[i][5] + 1.5 samples[i][6] = (np.arccos(samples[i][6])) * (180. / np.pi) if model == 'acol' or model == 'bcmi': # Converting Xc to t(tms) samples[i][2] = ttms_ip[find_nearest(Xc_ip, samples[i][2])[1]] samples[i][6] = (np.arccos(samples[i][6])) * (180. / np.pi) if model == 'beatlas': samples[i][4] = (np.arccos(samples[i][4])) * (180. / np.pi) # plot corner quantiles = [0.16, 0.5, 0.84] if include_rv is True: labels = [ r'$M\,[M_\odot]$', r'$W$', r"$t/t_\mathrm{ms}$", r'$i[\mathrm{^o}]$', r'$d\,[pc]$', r'E(B-V)', r'$R_\mathrm{V}$' ] else: if model == 'befavor': labels = [ r'$M\,[M_\odot]$', r'$W$', r"$t/t_\mathrm{ms}$", r'$i[\mathrm{^o}]$', r'$d\,[pc]$', r'E(B-V)' ] if model == 'aara' or model == 'acol' or model == 'bcmi': labels = [ r'$M\,[M_\odot]$', r'$W$', r"$t/t_\mathrm{ms}$", r'$\log \, n_0 \, [cm^{-3}]$', r'$R_\mathrm{D}\, [R_\star]$', r'$n$', r'$i[\mathrm{^o}]$', r'$d\,[pc]$', r'E(B-V)' ] if model == 'beatlas': labels = [ r'$M\,[M_\odot]$', r'$W$', r'$\Sigma_0$', r'$n$', r'$i[\mathrm{^o}]$', r'$d\,[pc]$', r'E(B-V)' ] if model == 'befavor': ranges[1] = obl2W(ranges[1]) ranges[2][0] = ttms_ip[find_nearest(Xc_ip, ranges[2][1])[1]] ranges[2][1] = ttms_ip[find_nearest(Xc_ip, ranges[2][0])[1]] ranges[3] = (np.arccos(ranges[3])) * (180. / np.pi) ranges[3] = np.array([ranges[3][1], ranges[3][0]]) if model == 'aara': ranges[1] = obl2W(ranges[1]) ranges[2][0] = ttms_ip[find_nearest(Xc_ip, ranges[2][1])[1]] ranges[2][1] = ttms_ip[find_nearest(Xc_ip, ranges[2][0])[1]] ranges[3] = np.array([ranges[3][1], ranges[3][0]]) ranges[5] = ranges[5] + 1.5 ranges[6] = (np.arccos(ranges[6])) * (180. / np.pi) ranges[6] = np.array([ranges[6][1], ranges[6][0]]) if model == 'acol' or model == 'bcmi': ranges[1] = obl2W(ranges[1]) ranges[2][0] = ttms_ip[find_nearest(Xc_ip, ranges[2][1])[1]] ranges[2][1] = ttms_ip[find_nearest(Xc_ip, ranges[2][0])[1]] ranges[3] = np.array([ranges[3][1], ranges[3][0]]) ranges[6] = (np.arccos(ranges[6])) * (180. / np.pi) ranges[6] = np.array([ranges[6][1], ranges[6][0]]) if model == 'beatlas': ranges[1] = obl2W(ranges[1]) ranges[3] = np.array([ranges[3][-1], ranges[3][0]]) ranges[4] = (np.arccos(ranges[4])) * (180. / np.pi) ranges[4] = np.array([ranges[4][1], ranges[4][0]]) corner(samples, labels=labels, range=ranges, quantiles=quantiles, plot_contours=True, smooth=2., smooth1d=False, plot_datapoints=True, label_kwargs={'fontsize': 22}, truths=None, show_titles=True, color_hist='black', plot_density=True, fill_contours=False, no_fill_contours=False, normed=True) if plot_fits is True: # plot_fit(params_fit, wave, logF, dlogF, minfo, # listpar, lbdarr, logF_grid, isig, dims, # Nwalk, nint_mcmc, par_list, ranges, include_rv, # log_scale) plot_fit_last(params_fit, wave, logF, dlogF, minfo, listpar, lbdarr, logF_grid, isig, dims, Nwalk, nint_mcmc, ranges, include_rv, file_npy, log_scale, model) current_folder = 'figures/' + str(star) + '/' fig_name = 'Walkers_' + np.str(Nwalk) + '_Nmcmc_' +\ np.str(nint_mcmc) + '_af_' + str(af) + '_a_' +\ str(a_parameter) + tag plt.savefig(current_folder + fig_name + '.png', dpi=100) # plt.close() # plt.clf() plot_residuals(params_fit, wave, logF, dlogF, minfo, listpar, lbdarr, logF_grid, isig, dims, Nwalk, nint_mcmc, ranges, include_rv, file_npy, log_scale, model) plt.savefig(current_folder + fig_name + '_residuals' + '.png', dpi=100) plot_convergence(file_npy, file_npy[:-4] + '_convergence', model) return