Skip to content

Instantly share code, notes, and snippets.

@kartheikiyer
Created May 17, 2023 18:55
Show Gist options
  • Select an option

  • Save kartheikiyer/43e8fef4946443a34eb83ca4a92f850e to your computer and use it in GitHub Desktop.

Select an option

Save kartheikiyer/43e8fef4946443a34eb83ca4a92f850e to your computer and use it in GitHub Desktop.
Sample from multidimensional posteriors
import scipy.stats
# given an SedFit() object from dense basis, this code allows you to sample from the z-M* posterior
# and can be adapted to more general cases as needed
def sample_from_2d_dist(atlas, sedfit, nsamples, zbins = np.linspace(0, 3, 201), massbins = np.linspace(6,12,201)):
zbin_centers = zbins[0:-1] + np.mean(np.diff(zbins))/2
massbin_centers = massbins[0:-1] + np.mean(np.diff(massbins))/2
hist = np.histogram2d(atlas['mstar']+np.log10(sedfit.norm_fac),
atlas['zval'].ravel(),
bins=(massbins, zbins),
weights=sedfit.likelihood)
hist_normed = hist[0].flatten()
hist_normed = hist_normed/np.nansum(hist_normed)
massindex, zindex = np.meshgrid(massbin_centers, zbin_centers)
mb = massindex.T.ravel()
zb = zindex.T.ravel()
sample_indices = np.random.choice(len(hist_normed), size=(nsamples,), p=hist_normed)
mass_samples = mb[sample_indices]
z_samples = zb[sample_indices]
return mass_samples, z_samples
#-------------------------------------------------------------------------------------------
plt.figure(figsize=(12,4.2))
plt.subplot(1,2,1)
zbins = np.linspace(0, 3, 101)
massbins = np.linspace(6,12,101)
zbin_centers = zbins[0:-1] + np.mean(np.diff(zbins))/2
massbin_centers = massbins[0:-1] + np.mean(np.diff(massbins))/2
hist = np.histogram2d(atlas['mstar']+np.log10(sedfit.norm_fac),
atlas['zval'].ravel(),
bins=(massbins, zbins),
weights=sedfit.likelihood)
plt.pcolor(zbin_centers, massbin_centers,
np.log10(hist[0]/np.amax(hist[0])), vmin=-10, cmap='coolwarm')
# plt.colorbar()
plt.axhline(sedfit.mstar[0],color='k')
plt.axvline(sedfit.z[0],color='k')
plt.title('true posterior')
mass_samples, z_samples = sample_from_2d_dist(atlas, sedfit, nsamples=1000, zbins=zbins, massbins=massbins)
plt.subplot(1,2,2)
hist = np.histogram2d(mass_samples,
z_samples,
bins=(massbins, zbins))
plt.pcolor(zbin_centers, massbin_centers,
np.log10(hist[0]/np.amax(hist[0])), vmin=-10, cmap='coolwarm')
# plt.colorbar()
plt.axhline(sedfit.mstar[0],color='k')
plt.axvline(sedfit.z[0],color='k')
plt.title('samples from posterior')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment