Tutorials / Gaussian measurements: a redshift distribution
Gaussian measurements: a redshift distribution¶
This tutorial infers the redshift distribution of 2000 galaxies. Each galaxy has a photometric redshift with a Gaussian error of its own. The tutorial compares the result with stacking the galaxies’ likelihoods. It then derives quantities with error bars, and shows what the population says about single galaxies.
import matplotlib.pyplot as plt
import numpy as np
import binference
from binference.plotting import SAMPLE_COLOR
A mock catalogue¶
binference.simulate.mock_1d() draws true redshifts \(z\) from a population with two
peaks. It adds Gaussian errors with standard deviations between 0.05 and 0.2. The 30 bins
on \([0, 3]\) are 0.1 wide, so the errors span half a bin to two bins. The
mock catalogue holds the likelihoods, the truth and the measurements.
mock = binference.simulate.mock_1d(2000, rng=42)
lk, bins = mock.likelihoods, mock.bins
print(lk)
print("measured z of the first galaxies:", mock.measurements["mean"][:4].round(2))
print("their errors: ", mock.measurements["sigma"][:4].round(2))
Likelihoods(N=2000, K=30, dense, bins=Bins(K=30, range=(0, 3)))
measured z of the first galaxies: [1.66 0.72 1.74 1.45]
their errors: [0.13 0.18 0.09 0.05]
Each galaxy \(i\) contributes one row of bin-averaged likelihoods \(L_{ik}\), one value per bin \(k\). Five of the rows look like this:
fig, ax = plt.subplots()
L = lk.toarray()
for i in range(5):
ax.step(bins.edges[0], np.append(L[i], L[i, -1]), where="post", color=SAMPLE_COLOR, lw=1.2)
ax.set(xlabel="z", ylabel="likelihood", xlim=(0, 3));
Bin-averaged likelihoods of five galaxies, each scaled to a maximum of one.¶
Stacking versus the hierarchical posterior¶
Stacking adds up the galaxies’ likelihoods and gives no error bars. It is the first step of EM, which converges to the most likely population (theory). binference samples the posterior of the population fractions \(\rho_k\) instead, here with NUTS:
stack = lk.stack()
result = binference.infer(lk, rng=1, n_samples=500) # method="auto" picks the engine
print(result.info["auto_method"], "-", result.info["auto_reason"])
result
nuts - Gibbs would mix too slowly (missing information 0.999 > max_gibbs_missing=0.98); the Laplace importance check failed
PopulationResult(method='nuts', kind='fractions', K=30, n_chains=4, n_draws=2000)
fig, ax = plt.subplots()
result.plot(ax=ax, truth=mock.truth.rho, stack=stack, sample_color=SAMPLE_COLOR, label="median")
ax.legend(ncol=3, loc="lower left", bbox_to_anchor=(0, 1)) # above the plot
ax.set_xlabel("z");
The population posterior under a flat Dirichlet prior, with the truth (dashed) and the stack (dotted). The bands hold 68% and 95% of the posterior.¶
The bands are wide and the median is jagged. The errors are as wide as the bins, so the data barely tell neighbouring bins apart. Under the flat Dirichlet prior, mass moves freely between those bins, so they are strongly anti-correlated:
corr = result.corr()
print("correlation of bin 10 with bins 9, 10, 11:", corr[10, 9:12].round(2))
correlation of bin 10 with bins 9, 10, 11: [-0.66 1. -0.68]
The summary table gives the numbers per bin and the convergence diagnostics:
result.summary()
binference fractions posterior (nuts, 2000 draws; inputs: gaussian)
bin mean sd median q16 q84 ess_bulk rhat support
[0, 0.1) 0.007302 0.003698 0.006995 0.003586 0.01106 2049 1.002 32.63
[0.1, 0.2) 0.01206 0.007709 0.01122 0.003925 0.02042 1070 1.002 47.69
[0.2, 0.3) 0.02102 0.01338 0.01962 0.006877 0.035 904.9 1.003 68.66
[0.3, 0.4) 0.06917 0.02208 0.07038 0.04651 0.09127 984.4 1.001 92.99
[0.4, 0.5) 0.04539 0.02773 0.04259 0.01713 0.07401 906.4 1.003 110.8
[0.5, 0.6) 0.1015 0.02773 0.1033 0.07419 0.1286 1093 1.003 121.1
[0.6, 0.7) 0.03339 0.02436 0.02881 0.008896 0.05742 936 1.001 118.8
[0.7, 0.8) 0.07412 0.02731 0.07536 0.04683 0.1009 1114 1.001 115.5
[0.8, 0.9) 0.05244 0.02554 0.05194 0.02539 0.07749 985.7 1.002 108.6
[0.9, 1) 0.04274 0.02151 0.04136 0.02035 0.06496 1085 1.003 99.93
[1, 1.1) 0.04729 0.02131 0.04829 0.02464 0.06921 1058 1.006 95.6
[1.1, 1.2) 0.03379 0.02123 0.03141 0.01074 0.0558 986.1 1.007 95.46
[1.2, 1.3) 0.06911 0.02295 0.07048 0.04513 0.09202 972.3 1.007 98.47
[1.3, 1.4) 0.03173 0.02292 0.02741 0.008476 0.05558 973.3 1.004 98.64
[1.4, 1.5) 0.05949 0.02331 0.06063 0.03538 0.08325 970.4 1.005 101.1
[1.5, 1.6) 0.04775 0.02559 0.04726 0.02005 0.0743 811.8 1.007 102.4
[1.6, 1.7) 0.05936 0.02558 0.05941 0.03263 0.08652 795.5 1.004 101.7
[1.7, 1.8) 0.04759 0.02466 0.04584 0.02227 0.07297 911.4 1.002 96.49
[1.8, 1.9) 0.05821 0.02211 0.05912 0.03556 0.08029 1118 1.003 85.8
[1.9, 2) 0.02962 0.01707 0.02837 0.011 0.04751 891.3 1.003 67.54
[2, 2.1) 0.0208 0.01276 0.01969 0.00692 0.03403 903.2 1.003 50.13
[2.1, 2.2) 0.02003 0.009161 0.0199 0.01047 0.02927 1225 1.006 35.97
[2.2, 2.3) 0.006607 0.00474 0.005625 0.001786 0.01158 1563 1.001 23.33
[2.3, 2.4) 0.003255 0.002644 0.002686 0.0007103 0.005774 1189 1.003 13.92
[2.4, 2.5) 0.00196 0.001664 0.001543 0.0004282 0.003505 1322 1.001 7.998
[2.5, 2.6) 0.001521 0.001316 0.001167 0.0003313 0.002762 1867 0.9998 4.495
[2.6, 2.7) 0.001074 0.001001 0.0007986 0.0001938 0.001972 1517 0.9997 2.589
[2.7, 2.8) 0.0006842 0.0006727 0.0004906 0.0001116 0.001278 1710 1.002 1.121
[2.8, 2.9) 0.0005304 0.0005312 0.0003724 9.543e-05 0.0009771 1965 1.001 0.4288
[2.9, 3) 0.0005109 0.0005326 0.0003578 7.835e-05 0.0009181 1988 1.002 0.1371
Derived quantities¶
Sums and averages over bins are much better determined than single bins, because the anti-correlations cancel. Compute a derived quantity on each posterior draw:
centers = bins.centers
zbar = result.functional(lambda rho: rho @ centers)
f_high = result.functional(lambda rho: rho[centers > 1.5].sum())
print(f"mean redshift: {zbar.mean():.3f} ± {zbar.std():.3f} (truth {mock.truth.rho @ centers:.3f})")
print(f"fraction z>1.5: {f_high.mean():.3f} ± {f_high.std():.3f} (truth {mock.truth.rho[centers > 1.5].sum():.3f})")
print(f"stacked mean z: {stack @ centers:.3f} (no error bar)")
mean redshift: 1.120 ± 0.013 (truth 1.110)
fraction z>1.5: 0.299 ± 0.017 (truth 0.296)
stacked mean z: 1.116 (no error bar)
Adding the per-bin variances ignores the correlations, and gives a much larger error bar on the mean redshift:
naive = np.sqrt(np.sum((result.std * centers) ** 2))
print(f"error ignoring correlations: {naive:.3f} vs correct: {zbar.std():.3f}")
error ignoring correlations: 0.124 vs correct: 0.013
If you expect the population to be smooth over a few bins, a smoothness prior narrows the bands; Priors and smoothness compares the priors.
Single galaxies¶
The population also narrows each galaxy’s redshift. Its hierarchical posterior
\(P(k_i=k\mid D)\) combines its own likelihood with the inferred population. It is
narrower than the likelihood wherever the population changes across the likelihood’s
width. assignment_probabilities() returns these posteriors for every galaxy. The
measure of narrowing here is the ratio of the spreads of the two over the bins:
def spread(p): # standard deviation of each row over the bin centres
return np.sqrt(p @ centers**2 - (p @ centers) ** 2)
own = L * bins.volumes
own /= own.sum(axis=1, keepdims=True)
post = result.assignment_probabilities()
ratio = spread(own) / spread(post)
broad = mock.measurements["sigma"] > 0.15 # galaxies with large errors
print(f"median narrowing, galaxies with errors above 0.15: {np.median(ratio[broad]):.2f}")
median narrowing, galaxies with errors above 0.15: 1.06
The effect is modest: the median ratio is 1.06, so the spread shrinks by about 6%. Here is a typical broad galaxy. It is the one closest to the median narrowing whose true redshift lies inside the central 68% of its posterior:
from binference.plotting import plot_individual
cdf = np.cumsum(post, axis=1)
k_true = bins.index(mock.truth.values)
def inside_68(j): # the true bin overlaps the central 68% of the posterior
below = cdf[j, k_true[j] - 1] if k_true[j] > 0 else 0.0
return below < 0.84 and cdf[j, k_true[j]] > 0.16
candidates = np.flatnonzero(broad)[np.argsort(np.abs(ratio[broad] - np.median(ratio[broad])))]
i = int(next(j for j in candidates if inside_68(j)))
print(f"galaxy {i}: narrowing {ratio[i]:.2f}")
fig, ax = plt.subplots()
plot_individual(result, i, ax=ax, sample_color=SAMPLE_COLOR)
ax.axvline(mock.truth.values[i], color="k", lw=1, ls=":", label="true z")
ax.set_xlabel("z")
ax.legend(loc="lower left", bbox_to_anchor=(0, 1)); # above the plot
galaxy 1205: narrowing 1.07
A typical galaxy’s own likelihood (dashed) and its hierarchical posterior (solid). The dotted line marks its true redshift.¶
The effect grows where the population has sharp features, as in Empirical Bayes deconvolution.
result.sample_values() gives joint draws of the galaxies’ true redshifts.
\(\rho\) describes the population that the galaxies were drawn from; the redshift histogram of these 2000 galaxies, the realised sample, is a different quantity (population versus realised sample).
Next steps¶
Priors and smoothness compares priors on a sparser catalogue.
Posteriors on a grid and Posterior samples: black-hole masses start from posteriors instead of likelihoods.
Choosing an engine compares the engines.
The guides explain every option.