Tutorial 4: The Galactic Prior¶
Photometry alone often allows a near dwarf or a far giant behind more dust. The Galactic prior decides between them when the data cannot. It says how many stars of each [Fe/H] and age the Milky Way has at each position. This tutorial draws that prior from every side and shows what it does to a fit.
The model and its sources
Structure in Galactic coordinates
Along sightlines and across the sky
[Fe/H] and age
How a star’s labels move its distance prior
Velocities
Switching components off
The dust and parallax terms
The effect on fits
The equations, parameters and references are on the Priors page of the documentation. Sections 1 to 7 need no data files. Section 8 uses the Bayestar dust map if present, and Section 9 needs the MIST grid; Tutorial 00 shows how to download both.
# Optional: download the data files (only needed if not already cached).
# from brutus.data import fetch_dustmaps, fetch_grids
# fetch_dustmaps() # Section 8
# fetch_grids() # Section 9
from functools import partial
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
from brutus.priors import (
bulge_velocity_moments,
galactic_prior_summary,
halo_velocity_moments,
logp_galactic_structure,
solar_velocity,
thick_disk_velocity_moments,
thin_disk_velocity_moments,
velocity_to_observables,
)
from brutus.priors.galactic import BAR_FEH
from brutus.priors.kinematic import K_KMS
from brutus.utils.math import R_SOLAR, Z_SOLAR, galactic_to_galactocentric_cyl
from tutorial_utils import (
DENSITY_CMAP,
GALACTIC_COLORS,
INK,
find_brutus_data_file,
save_figure,
set_prior_style,
setup_tutorial,
)
setup_tutorial(4, title="Tutorial 04: The Galactic Prior")
set_prior_style()
NAMES = list(GALACTIC_COLORS) # thin disk, thick disk, halo, bulge
LN_ZERO_CUT = -1e299 # a log density at or below this is zero
def label_value(label, value):
# The prior's keyword value for [Fe/H] in dex or an age in Gyr.
return value if label == "feh" else np.log10(value * 1e9)
def per_ln_d(d, coord, **kwargs):
# Log Galactic prior per unit ln d along one sightline.
return logp_galactic_structure(d, coord, **kwargs) + np.log(d)
1. The model and its sources¶
The prior is a sum of four components. Each one gives the number density of stars at a position, relative to the thin disk at the Sun, and the distribution of their [Fe/H] and age there.
Component |
Density |
[Fe/H] and age |
|---|---|---|
Thin disk |
exponential surface density; vertical Jeans profile in the potential of Binney & Vasiliev (2024), with the dispersions of Sharma et al. (2021) |
star formation, enrichment and radial migration of Frankel et al. (2018) |
Thick disk |
exponential surface density; isothermal Jeans profile |
old sequence of Xiang & Rix (2022) |
Halo |
broken power law of Amarante et al. (2024), normalized by its mass (Lane et al. 2023) |
[Fe/H] of Naidu et al. (2020) with the tail of Youakim et al. (2020); 12 Gyr |
Bulge |
analytic bar of Sormani et al. (2022) and a metal-poor spheroid, both tapered beyond 5 kpc |
two populations of Gonzalez et al. (2015), with the ages of Bensby et al. (2017) |
The prior derives its normalizations from these shapes. galactic_prior_summary returns them.
summary = galactic_prior_summary()
for key in ("thin_column_height", "thick_column_height", "f_thick_solar", "f_halo_solar"):
print(f"{key:20s} {summary[key]:.4g}")
thin_column_height 0.3531
thick_column_height 1.272
f_thick_solar 0.04995
f_halo_solar 0.001768
2. Structure in Galactic coordinates¶
logp_galactic_structure(d, (l, b), return_components=True) returns the log number density of each component along a sightline, times the volume element \(d^2\). The helper below turns Galactocentric positions into sightlines and removes the volume term, which gives the density at a point. The Sun is at \(X = -R_\odot\), and \(Y\) points toward \(\ell = 90°\).
def to_sightline(X, Y, Z):
# Heliocentric distance (kpc) and (l, b) in degrees of Galactocentric points.
hx, hy, hz = X + R_SOLAR, Y, Z - Z_SOLAR
d = np.maximum(np.sqrt(hx**2 + hy**2 + hz**2), 1e-4)
ell = np.degrees(np.arctan2(hy, hx)) % 360
b = np.degrees(np.arcsin(np.clip(hz / d, -1, 1)))
return d, ell, b
def log10_density(X, Y, Z, **labels):
# log10 number density of each component at (X, Y, Z), shape (4,) + X.shape.
d, ell, b = to_sightline(X.ravel(), Y.ravel(), Z.ravel())
labels = {k: np.broadcast_to(v, X.shape).ravel() for k, v in labels.items()}
_, comps = logp_galactic_structure(d, (ell, b), return_components=True, **labels)
ln_n = np.array(comps["number_density"]) - 2 * np.log(d)
if labels:
ln_n = ln_n + np.array(comps["labels"])
ln_n = np.where(ln_n > LN_ZERO_CUT, ln_n, -np.inf)
return (ln_n / np.log(10)).reshape((4,) + X.shape)
def sun(ax, x=-R_SOLAR, y=0.0):
ax.plot(x, y, "*", ms=8, color=INK, mec="white", mew=0.7)
x, z = np.linspace(-18, 18, 361), np.linspace(-6, 6, 241)
X, Z = np.meshgrid(x, z)
edge = log10_density(X, np.zeros_like(X), Z)
fig, axs = plt.subplots(2, 2, figsize=(12, 5.2), sharex=True, sharey=True, layout="constrained")
for ax, n, name in zip(axs.ravel(), edge, NAMES):
im = ax.imshow(np.clip(n, -6, 1), extent=(x[0], x[-1], z[0], z[-1]), origin="lower",
cmap=DENSITY_CMAP, vmin=-6, vmax=1, aspect="auto", interpolation="bilinear")
ax.contour(x, z, n, levels=[-4, -2, 0], colors="white", linewidths=0.6)
ax.grid(False)
sun(ax)
ax.set_title(name, color=GALACTIC_COLORS[name])
for ax in axs[1]:
ax.set_xlabel("X (kpc)")
for ax in axs[:, 0]:
ax.set_ylabel("Z (kpc)")
fig.colorbar(im, ax=axs, shrink=0.8, pad=0.01, label=r"$\log_{10}\, n / n_{\rm thin}(\odot)$").outline.set_visible(False)
save_figure(fig, 4, "structure_edge_on", tight=False)
plt.show()
The edge-on slice passes through the Sun and the Galactic centre, with contours at 1, \(10^{-2}\) and \(10^{-4}\). The disk heights are not set by hand. Each disk solves the vertical Jeans equation in one potential, so the thin disk flares outward. Inside 4 kpc each disk keeps the density it has at 4 kpc, where the deep potential would otherwise squeeze it, and the bulge fills the inner Galaxy.
g = np.linspace(-16, 16, 241)
X, Y = np.meshgrid(g, g)
fig, axs = plt.subplots(2, 5, figsize=(14, 5.8), sharex=True, sharey=True, layout="constrained")
for row, height in enumerate([0.0, 1.0]):
n = log10_density(X, Y, np.full_like(X, height))
total = np.log10(np.sum(10.0**n, axis=0))
for col, (m, title) in enumerate([(total, "Total")] + list(zip(n, NAMES))):
ax = axs[row, col]
im = ax.imshow(np.clip(m, -6, 1.5), extent=(g[0], g[-1], g[0], g[-1]), origin="lower",
cmap=DENSITY_CMAP, vmin=-6, vmax=1.5, interpolation="bilinear")
ax.grid(False)
ax.set_aspect("equal")
sun(ax)
if row == 0:
ax.set_title(title, color=GALACTIC_COLORS.get(title, INK))
if row == 1:
ax.set_xlabel("X (kpc)")
axs[row, 0].set_ylabel(f"Z = {height:g} kpc\nY (kpc)")
fig.colorbar(im, ax=axs, shrink=0.6, pad=0.01, label=r"$\log_{10}\, n / n_{\rm thin}(\odot)$").outline.set_visible(False)
save_figure(fig, 4, "structure_face_on", tight=False)
plt.show()
Face-on, the bar lies at 25° to the line from the Sun to the centre, with its near end at \(\ell > 0\), inside the round spheroid. The bulge’s density falls to zero between 5 and 6 kpc from the centre.
The next figure gives the radial and vertical structure: the midplane density toward the Sun, the thin-disk vertical profile at six radii, and the column height \(\int n\, dz / n(0)\) of each disk. The markers are thin-disk measurements: Yu et al. (2024) for stars of 0 to 3 Gyr, Uppal et al. (2023) for red-clump stars, and López-Corredoira & Molgó (2014).
R = np.linspace(0.05, 25, 500)
midplane = log10_density(-R, np.zeros_like(R), np.zeros_like(R))
zz = np.linspace(0, 12, 1201)
radii = [4, R_SOLAR, 12, 16, 20, 24]
ramp = ["#f2b45c", "#e0954a", "#d9783a", "#b5452a", "#7c0008", "#2b0505"]
R_col = np.linspace(3, 25, 45)
column = np.array([
[np.trapezoid(10.0 ** (n - n[0]), zz) for n in log10_density(np.full_like(zz, -r), np.zeros_like(zz), zz)[:2]]
for r in R_col
])
fig, axs = plt.subplots(1, 3, figsize=(14, 4), layout="constrained")
ax = axs[0]
for n, name in zip(midplane, NAMES):
ax.plot(R, n, color=GALACTIC_COLORS[name], label=name)
ax.set(ylim=(-6, 2.5), xlabel="R (kpc), midplane toward the Sun", ylabel=r"$\log_{10}\, n / n_{\rm thin}(\odot)$")
ax.legend()
ax = axs[1]
for r, color in zip(radii, ramp):
n = log10_density(np.full_like(zz, -r), np.zeros_like(zz), zz)[0]
ax.plot(zz, n - n[0], color=color, label=f"R = {r:.3g} kpc")
ax.set(xlim=(0, 8), ylim=(-6, 0.2), xlabel="|Z| (kpc)", ylabel=r"thin disk $\log_{10}\, n / n(Z=0)$")
ax.legend()
ax = axs[2]
for k, name in enumerate(NAMES[:2]):
ax.plot(R_col, column[:, k], color=GALACTIC_COLORS[name], label=name)
measurements = [
("Yu et al. 2024, 0-3 Gyr", [8.5, 11.5, 13.0], [0.203, 0.386, 0.536], "o"),
("Uppal et al. 2023, red clump", [8.25, 11.75, 13.75, 15.75], [0.380, 0.589, 1.151, 2.197], "s"),
("López-Corredoira & Molgó 2014", [8.2, 15.0, 20.0], [0.24, 0.79, 1.94], "D"),
]
for label, r, h, marker in measurements:
ax.plot(r, h, marker, ms=6, mfc="white", mec="#57524c", mew=1.2, ls="none", label=label)
ax.set(yscale="log", ylim=(0.1, 6), xlabel="R (kpc)", ylabel="column height (kpc)")
ax.set_yticks([0.1, 0.2, 0.5, 1, 2, 5], ["0.1", "0.2", "0.5", "1", "2", "5"])
ax.minorticks_off()
ax.legend(loc="upper left")
save_figure(fig, 4, "structure_profiles", tight=False)
plt.show()
The thin disk’s vertical dispersion stops rising beyond 14 kpc, and its density is tapered to zero between \(|Z| = 5\) and 7 kpc, so the profiles end there.
The bulge¶
The bulge has two populations. The metal-rich one has the bar’s shape and 0.4 of bar_mass. The metal-poor one, 0.6 of it (bar_feh[0]), is a cored spheroid, \((r^2 + 0.2^2\ {\rm kpc}^2)^{-1.1}\); Zoccali et al. (2017) find the metal-poor bulge more centrally concentrated and rounder than the metal-rich one. Setting bar_feh[0] to 0 or 1 gives each population alone, and the maps below use that to show the metal-poor share of the bulge.
def bulge_share(X, Y, Z):
# Metal-poor share of the bulge at (X, Y, Z): the spheroid alone (bar_feh[0] = 1)
# against the bar alone (bar_feh[0] = 0), weighted by their shares of the mass.
d, ell, b = to_sightline(X.ravel(), Y.ravel(), Z.ravel())
n = []
for share in (0.0, 1.0):
_, comps = logp_galactic_structure(d, (ell, b), return_components=True, bar_feh=(share,) + BAR_FEH[1:])
n.append(np.exp(np.asarray(comps["number_density"][3])))
sph, bar = BAR_FEH[0] * n[1], (1 - BAR_FEH[0]) * n[0]
with np.errstate(invalid="ignore"):
return (sph / (sph + bar)).reshape(X.shape)
g6 = np.linspace(-6, 6, 241)
A, B = np.meshgrid(g6, g6)
fig, axs = plt.subplots(1, 3, figsize=(14, 4.2), layout="constrained")
for ax, (title, ylabel, share) in zip(axs[:2], [
("Edge-on (Y = 0)", "Z (kpc)", bulge_share(A, np.zeros_like(A), B)),
("Face-on (Z = 0)", "Y (kpc)", bulge_share(A, B, np.zeros_like(A))),
]):
im = ax.imshow(share, extent=(-6, 6, -6, 6), origin="lower", cmap="RdBu_r", vmin=0, vmax=1, interpolation="bilinear")
ax.set(title=title, xlabel="X (kpc)", ylabel=ylabel)
ax.grid(False)
fig.colorbar(im, ax=axs[:2], shrink=0.8, pad=0.01, label="metal-poor share of the bulge").outline.set_visible(False)
ax = axs[2]
feh_axis = np.linspace(-2.0, 1.0, 151)
d_bulge = np.linspace(6.8, 9.8, 31)
Dg, Fg = np.meshgrid(d_bulge, feh_axis)
for b_field, color in zip([-1.0, -3.5, -6.0, -8.5], ["#2b0505", "#7c0008", "#d9783a", "#f2b45c"]):
lnp = logp_galactic_structure(Dg.ravel(), (0.0, b_field), feh=Fg.ravel()).reshape(Dg.shape)
p = np.exp(lnp - lnp.max()).sum(axis=1)
ax.plot(feh_axis, p / np.trapezoid(p, feh_axis), color=color, label=f"b = {b_field:g}°")
ax.set(xlabel="[Fe/H]", ylabel="p([Fe/H]), 6.8 to 9.8 kpc", title="[Fe/H] toward ℓ = 0°")
ax.set_yticks([])
ax.legend(loc="upper left")
save_figure(fig, 4, "bulge", tight=False)
plt.show()
The spheroid takes over above and below the bar and at the very centre, so the bulge’s stars grow more metal-poor away from the plane. Along the minor axis the [Fe/H] distribution of all stars at 6.8 to 9.8 kpc, disks included, shifts from metal-rich near the plane to metal-poor at \(b = -8.5°\), as the GIBS spectra of bulge red giants show (Zoccali et al. 2017).
3. Along sightlines and across the sky¶
brutus samples \(\ln d\), so the figures show the prior per unit \(\ln d\): the density times \(d^3\). Each panel is scaled to a peak of 1.
dist = np.geomspace(0.02, 100, 600)
sightlines = [(0, 2), (30, 2), (90, 2), (180, 2), (0, 10), (90, 30), (270, -30), (0, 90)]
fig, axs = plt.subplots(2, 4, figsize=(14, 5.4), sharex=True, layout="constrained")
for ax, (ell, b) in zip(axs.ravel(), sightlines):
lnp, comps = logp_galactic_structure(dist, (ell, b), return_components=True)
peak = np.max(lnp + np.log(dist))
for ln_n, name in zip(comps["number_density"], NAMES):
y = np.exp(np.asarray(ln_n) + np.log(dist) - peak)
if y.max() > 2e-3:
ax.plot(dist, y, color=GALACTIC_COLORS[name], lw=1.6)
ax.plot(dist, np.exp(lnp + np.log(dist) - peak), color=INK, lw=2.2)
ax.set(xscale="log", xlim=(0.02, 100), ylim=(0, 1.08))
ax.set_title(f"ℓ = {ell}°, b = {b}°")
for ax in axs[1]:
ax.set_xlabel("distance (kpc)")
for ax in axs[:, 0]:
ax.set_ylabel("prior per ln d")
handles = [plt.Line2D([], [], color=INK, lw=2.2, label="Total")]
handles += [plt.Line2D([], [], color=c, lw=1.6, label=n) for n, c in GALACTIC_COLORS.items()]
fig.legend(handles=handles, loc="outside upper right", ncol=5)
save_figure(fig, 4, "sightlines", tight=False)
plt.show()
In the plane, the volume pushes the peak out to 5 to 10 kpc, and toward the centre the bulge takes it. Off the plane, the disks add a near peak at 2 to 4 kpc and the halo a far one beyond 10 kpc.
The sky maps evaluate the same prior on a 5° grid. They show the median distance, the mean [Fe/H] and age of the stars along each sightline, and each component’s share of those stars. The maps are in Galactic coordinates, with \(\ell = 0\) at the centre and \(\ell\) increasing to the left.
L, B = np.arange(-177.5, 180, 5.0), np.arange(-87.5, 90, 5.0)
LL, BB = np.meshgrid(L, B)
ds = np.geomspace(0.03, 80, 90)
D = np.broadcast_to(ds, LL.shape + ds.shape).ravel()
ells, bs = np.repeat(LL.ravel() % 360, ds.size), np.repeat(BB.ravel(), ds.size)
shape = LL.shape + ds.shape
lnp, comps = logp_galactic_structure(D, (ells, bs), return_components=True)
lnp = lnp.reshape(shape) + np.log(ds)
top = lnp.max(-1, keepdims=True)
w = np.exp(lnp - top)
cdf = np.cumsum(w, -1) / w.sum(-1, keepdims=True)
median_distance = ds[np.argmax(cdf >= 0.5, -1)]
ln_n = np.array(comps["number_density"]).reshape((4,) + shape) + np.log(ds)
share = np.exp(ln_n - top[None]).sum(-1) / w.sum(-1)[None]
def mean_along_sightline(values, label):
# Mean of a label over each sightline, from the prior with that label fixed.
total, norm = 0.0, 0.0
for v in values:
lnp_v = logp_galactic_structure(D, (ells, bs), **{label: label_value(label, v)}).reshape(shape)
wv = np.exp(lnp_v + np.log(ds) - top).sum(-1)
total, norm = total + wv * v, norm + wv
return total / norm
mean_feh = mean_along_sightline(np.linspace(-2.6, 0.6, 17), "feh")
mean_age = mean_along_sightline(np.linspace(0.5, 13.5, 14), "loga")
lon, lat = np.meshgrid(-np.radians(L), np.radians(B))
METAL_CMAP = LinearSegmentedColormap.from_list("feh", ["#2b0505", "#b5452a", "#f2b45c", "#fff3d6"])
def sky(ax, values, cmap, vmin, vmax, title):
im = ax.pcolormesh(lon, lat, values, cmap=cmap, vmin=vmin, vmax=vmax, shading="nearest")
ax.grid(lw=0.4)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_title(title)
return im
fig = plt.figure(figsize=(14, 6.8), layout="constrained")
grid = fig.add_gridspec(2, 1, height_ratios=[1.45, 1])
top, bottom = grid[0].subgridspec(1, 3), grid[1].subgridspec(1, 4)
panels = [
(top[0], np.log10(median_distance), DENSITY_CMAP, 0.3, 1.3, "Median distance"),
(top[1], mean_feh, METAL_CMAP, -1.4, 0.0, "Mean [Fe/H]"),
(top[2], mean_age, DENSITY_CMAP, 4, 12, "Mean age (Gyr)"),
]
for spec, values, cmap, vmin, vmax, title in panels:
ax = fig.add_subplot(spec, projection="mollweide")
im = sky(ax, values, cmap, vmin, vmax, title)
cb = fig.colorbar(im, ax=ax, orientation="horizontal", shrink=0.7, pad=0.03)
cb.outline.set_visible(False)
if title == "Median distance":
cb.set_ticks(np.log10([2, 5, 10, 20]), labels=["2", "5", "10", "20 kpc"])
for spec, s, name in zip(bottom, share, NAMES):
ax = fig.add_subplot(spec, projection="mollweide")
sky(ax, s, LinearSegmentedColormap.from_list(name, ["white", GALACTIC_COLORS[name]]), 0, 1, f"{name} share")
ax.title.set_color(GALACTIC_COLORS[name])
save_figure(fig, 4, "sky_maps", tight=False)
plt.show()
The shares run from 0 (white) to 1. The thin disk dominates low latitudes, the halo high latitudes beyond a few kpc, and the bulge the sky within about 35° of the centre in longitude and 45° in latitude, except in the plane beyond \(|\ell| \approx 10°\), where the disks take over.
4. [Fe/H] and age¶
With feh and loga (log10 age in yr) given, each component’s density is that of stars with those labels, per dex and per Gyr. The labels not given are summed over. The next figure shows the [Fe/H] and age distributions at six places, with each component scaled by its share of the stars there.
places = {
"Sun": (-R_SOLAR, 0.0, Z_SOLAR),
"1 kpc above the Sun": (-R_SOLAR, 0.0, 1.0),
"Inner disk, R = 4 kpc": (-4.0, 0.0, 0.0),
"Outer disk, R = 14 kpc": (-14.0, 0.0, 0.0),
"2 kpc above the centre": (0.0, 0.0, 2.0),
"Halo, R = 20, Z = 10 kpc": (-20.0, 0.0, 10.0),
}
feh = np.linspace(-3, 0.8, 191)
age = np.linspace(0.05, 13.75, 138)
def at_place(place, **labels):
# log10 density of each component at one place, for each value of the labels.
n = next(iter(labels.values())).size
X0, Y0, Z0 = (np.full(n, c) for c in place)
return log10_density(X0, Y0, Z0, **labels)
fig, axs = plt.subplots(2, 6, figsize=(16, 5.4), layout="constrained")
for j, (title, place) in enumerate(places.items()):
for row, (grid_, labels, xlabel) in enumerate([
(feh, {"feh": feh}, "[Fe/H]"),
(age, {"loga": np.log10(age * 1e9)}, "age (Gyr)"),
]):
ax = axs[row, j]
p = 10.0 ** at_place(place, **labels)
p /= np.trapezoid(p.sum(0), grid_)
for pc, name in zip(p, NAMES):
if pc.max() > 0.02 * p.sum(0).max():
ax.plot(grid_, pc, color=GALACTIC_COLORS[name], lw=1.8)
ax.plot(grid_, p.sum(0), color=INK, lw=2.2)
ax.set_xlabel(xlabel)
ax.set_yticks([])
axs[0, j].set_title(title, fontsize=9.5)
axs[0, 0].set_ylabel("p([Fe/H])")
axs[1, 0].set_ylabel("p(age)")
fig.legend(handles=handles, loc="outside upper right", ncol=5)
save_figure(fig, 4, "labels_by_place", tight=False)
plt.show()
The thin-disk [Fe/H] follows the radial gradient of the gas: metal-rich in the inner disk, metal-poor in the outer disk. In the outer disk, and weakly at the Sun, the age distribution has a peak below 0.5 Gyr, because the youngest thin-disk stars form the thinnest layer and crowd into the midplane.
The joint distribution of [Fe/H] and age at the same places shows the age-metallicity relation of each place.
A2, F2 = np.meshgrid(age[::3], feh[::4])
fig, axs = plt.subplots(1, 6, figsize=(16, 3.2), sharex=True, sharey=True, layout="constrained")
for ax, (title, place) in zip(axs, places.items()):
n = at_place(place, feh=F2.ravel(), loga=np.log10(A2.ravel() * 1e9))
joint = np.log10(np.sum(10.0**n, axis=0)).reshape(A2.shape)
joint -= joint.max()
im = ax.pcolormesh(A2, F2, np.clip(joint, -4, 0), cmap=DENSITY_CMAP, vmin=-4, vmax=0, shading="gouraud")
ax.contour(A2, F2, joint, levels=[-2, -1, -0.3], colors="white", linewidths=0.6)
ax.grid(False)
ax.set_title(title, fontsize=9.5)
ax.set_xlabel("age (Gyr)")
axs[0].set_ylabel("[Fe/H]")
fig.colorbar(im, ax=axs, shrink=0.85, pad=0.01, label="log10 density, peak 0").outline.set_visible(False)
save_figure(fig, 4, "labels_joint", tight=False)
plt.show()
R_grid, Z_grid = np.linspace(0.5, 20, 79), np.linspace(0, 6, 49)
RR, ZZ = np.meshgrid(R_grid, Z_grid)
moments = {}
for label, values in [("feh", np.linspace(-2.6, 0.6, 33)), ("loga", np.linspace(0.25, 13.75, 28))]:
W = []
for v in values:
n = log10_density(-RR, np.zeros_like(RR), ZZ, **{label: label_value(label, v)})
W.append(np.sum(10.0**n, axis=0))
W = np.array(W) / np.sum(W, axis=0)
mean = np.tensordot(values, W, 1)
moments[label] = mean, np.sqrt(np.tensordot(values**2, W, 1) - mean**2)
fig, axs = plt.subplots(1, 4, figsize=(16, 3.4), sharex=True, sharey=True, layout="constrained")
maps = [
(moments["feh"][0], METAL_CMAP, -1.2, 0.2, "mean [Fe/H]"),
(moments["feh"][1], DENSITY_CMAP, 0.1, 0.7, "spread of [Fe/H] (dex)"),
(moments["loga"][0], DENSITY_CMAP, 2, 12, "mean age (Gyr)"),
(moments["loga"][1], DENSITY_CMAP, 1, 4.5, "spread of age (Gyr)"),
]
for ax, (m, cmap, vmin, vmax, title) in zip(axs, maps):
im = ax.pcolormesh(R_grid, Z_grid, m, cmap=cmap, vmin=vmin, vmax=vmax, shading="gouraud")
sun(ax, R_SOLAR, Z_SOLAR)
ax.grid(False)
ax.set_title(title)
ax.set_xlabel("R (kpc)")
fig.colorbar(im, ax=ax, orientation="horizontal", shrink=0.85, pad=0.02).outline.set_visible(False)
axs[0].set_ylabel("|Z| (kpc)")
save_figure(fig, 4, "labels_gradients", tight=False)
plt.show()
These maps give the mean and spread of [Fe/H] and age over all components at each \((R, |Z|)\). Stars grow older and more metal-poor away from the plane, and the bulge makes the region within 5 kpc of the centre old, and richer in metals than the halo around it.
5. How a star’s labels move its distance prior¶
In a fit, each grid model has its own [Fe/H] and age, so it sees its own distance prior. A metal-rich or young star belongs near the plane; a metal-poor or old one belongs to the halo, further out.
cases = [(90, 30), (180, 5), (0, 10)]
ramp5 = ["#f2b45c", "#d9783a", "#b5452a", "#7c0008", "#2b0505"]
fig, axs = plt.subplots(2, 3, figsize=(14, 6), sharex=True, layout="constrained")
for j, coord in enumerate(cases):
for row, (label, values, fmt) in enumerate([
("feh", [0.2, -0.3, -0.8, -1.4, -2.2], "[Fe/H] = {:+.1f}"),
("loga", [1.0, 4.0, 8.0, 11.0, 13.0], "age = {:g} Gyr"),
]):
ax = axs[row, j]
base = per_ln_d(dist, coord)
ax.plot(dist, np.exp(base - base.max()), color="#8c867e", lw=1.4, ls=(0, (4, 3)), label="not given")
for v, color in zip(values, ramp5):
lnp = per_ln_d(dist, coord, **{label: label_value(label, v)})
ax.plot(dist, np.exp(lnp - lnp.max()), color=color, label=fmt.format(v))
ax.set(xscale="log", xlim=(0.05, 100), ylim=(0, 1.08))
if j == 0:
ax.set_ylabel("prior per ln d")
if j == 2:
ax.legend(loc="upper left")
axs[0, j].set_title(f"ℓ = {coord[0]}°, b = {coord[1]}°")
axs[1, j].set_xlabel("distance (kpc)")
save_figure(fig, 4, "conditional_distance", tight=False)
plt.show()
Toward the centre at \(b = 10°\), the prior for every [Fe/H] peaks at 8.4 to 8.9 kpc, in the bulge. Metal-poor stars also belong to the halo, so their prior reaches further: above a tenth of its peak out to 22 kpc for [Fe/H] \(= -1.4\) and 28 kpc for \(-2.2\), against 13.3 to 13.5 kpc for [Fe/H] \(\ge -0.8\).
The same prior gives the probability that a star at distance \(d\) belongs to each component: the component’s density over the total, with the star’s labels.
kinds = [(0.1, 3.0), (-0.6, 10.0), (-1.6, 12.0)]
fig, axs = plt.subplots(3, 3, figsize=(14, 6.6), sharex=True, sharey=True, layout="constrained")
for j, coord in enumerate(cases):
for row, (f, a) in enumerate(kinds):
_, comps = logp_galactic_structure(
dist, coord, return_components=True,
feh=np.full(dist.size, f), loga=np.full(dist.size, np.log10(a * 1e9)),
)
t = np.array(comps["number_density"]) + np.array(comps["labels"])
member = np.exp(t - np.logaddexp.reduce(t, axis=0))
ax = axs[row, j]
ax.stackplot(dist, member, colors=list(GALACTIC_COLORS.values()), alpha=0.85, edgecolor="white", linewidth=0.6)
ax.set(xscale="log", xlim=(0.05, 100), ylim=(0, 1))
if j == 0:
ax.set_ylabel(f"[Fe/H] = {f:+.1f}, {a:g} Gyr\np(component)", fontsize=9)
axs[0, j].set_title(f"ℓ = {coord[0]}°, b = {coord[1]}°")
axs[2, j].set_xlabel("distance (kpc)")
patches = [plt.Rectangle((0, 0), 1, 1, color=c, label=n) for n, c in GALACTIC_COLORS.items()]
fig.legend(handles=patches, loc="outside upper right", ncol=4)
save_figure(fig, 4, "membership", tight=False)
plt.show()
Toward \((0°, 10°)\) a young star of solar [Fe/H] belongs to the bulge at 4.4 to 14 kpc, to the thick disk at 14 to 20 kpc, and to the thin disk again at 20 to 39 kpc, because the sightline crosses the far side of the disk, where the thin disk flares.
The joint prior over distance and one label shows both effects at once.
d4 = dist[::4]
fig, axs = plt.subplots(2, 2, figsize=(12, 6), sharex=True, layout="constrained")
for j, coord in enumerate([(90, 30), (0, 10)]):
for row, (label, values, ylabel) in enumerate([
("feh", np.linspace(-2.6, 0.6, 81), "[Fe/H]"),
("loga", np.linspace(0.2, 13.7, 68), "age (Gyr)"),
]):
Dg, Vg = np.meshgrid(d4, values)
lnp = per_ln_d(Dg.ravel(), coord, **{label: label_value(label, Vg.ravel())}).reshape(Dg.shape)
v = (lnp - lnp.max()) / np.log(10)
ax = axs[row, j]
im = ax.pcolormesh(d4, values, np.clip(v, -4, 0), cmap=DENSITY_CMAP, vmin=-4, vmax=0, shading="gouraud")
ax.contour(d4, values, v, levels=[-2, -1, -0.3], colors="white", linewidths=0.6)
ax.set(xscale="log", xlim=(0.1, 100), ylabel=ylabel)
ax.grid(False)
axs[0, j].set_title(f"ℓ = {coord[0]}°, b = {coord[1]}°")
axs[1, j].set_xlabel("distance (kpc)")
fig.colorbar(im, ax=axs, shrink=0.7, pad=0.01, label="log10 prior per ln d, peak 0").outline.set_visible(False)
save_figure(fig, 4, "distance_label_planes", tight=False)
plt.show()
6. Velocities¶
brutus.priors.kinematic gives each component’s velocity ellipsoid: the mean and covariance of \((v_R, v_\phi, v_z)\). The thin disk’s dispersions grow with age (Sharma et al. 2021), and its rotation lags the circular speed by the asymmetric drift. The bulge takes the axisymmetric bulge disc of Binney & Vasiliev (2024). velocity_to_observables projects an ellipsoid onto the proper motions and radial velocity seen from the Sun. With a proper motion, the prior multiplies each component’s density by the probability of that motion under the component’s ellipsoid; the end of this section shows what that does to the distance prior, and Section 9 to fits.
The Toomre diagram below draws stars from each component at the Sun; each contour set shows one component alone.
rng = np.random.default_rng(1)
n_draw = 60000
ages = np.linspace(0.25, 13.5, 54)
_, comps = logp_galactic_structure(np.full(ages.size, 1e-3), (0.0, 90.0), loga=np.log10(ages * 1e9), return_components=True)
nd, lab = np.array(comps["number_density"])[:, 0], np.array(comps["labels"])
share_sun = np.exp(nd - nd.max())
share_sun /= share_sun.sum()
w_age = np.exp(nd[0] + lab[0] - np.max(nd[0] + lab[0]))
R0, Z0 = np.array([R_SOLAR]), np.array([Z_SOLAR])
draws = {}
picked = rng.choice(ages.size, n_draw, p=w_age / w_age.sum())
v = np.empty((n_draw, 3))
for i in np.unique(picked):
mean, cov = thin_disk_velocity_moments(R0, Z0, ages[i], 0.0)
v[picked == i] = rng.multivariate_normal(mean[0], cov[0], np.sum(picked == i))
draws["Thin disk"] = v
mean, cov = thick_disk_velocity_moments(R0)
draws["Thick disk"] = rng.multivariate_normal(mean[0], cov[0], n_draw)
weight, mean, cov = halo_velocity_moments(R0, Z0)
part = rng.choice(weight.shape[1], n_draw, p=weight[0])
v = np.empty((n_draw, 3))
for q in range(weight.shape[1]):
v[part == q] = rng.multivariate_normal(mean[0, q], cov[0, q], np.sum(part == q))
draws["Halo"] = v
from scipy.ndimage import gaussian_filter
v_sun = solar_velocity()
fig, axs = plt.subplots(1, 3, figsize=(14, 4.2), layout="constrained")
ax = axs[0]
for k, (name, v) in enumerate(draws.items()):
H, xe, ye = np.histogram2d(v[:, 1] - v_sun[1], np.hypot(v[:, 0] - v_sun[0], v[:, 2] - v_sun[2]), bins=(110, 80), range=((-450, 100), (0, 400)))
yc = 0.5 * (ye[1:] + ye[:-1])
H = gaussian_filter(H.T / np.maximum(yc, 2.5)[:, None], 1.5)
ax.contour(0.5 * (xe[1:] + xe[:-1]), yc, H / H.max(), levels=[0.02, 0.2, 0.6],
colors=[GALACTIC_COLORS[name]], linewidths=[0.8, 1.3, 1.8])
ax.plot([], [], color=GALACTIC_COLORS[name], label=f"{name}, {100 * share_sun[k]:.2g}% of stars")
ax.set(xlim=(-450, 100), ylim=(0, 400), xlabel="V relative to the Sun (km/s)", ylabel=r"$\sqrt{U^2 + W^2}$ (km/s)")
ax.set_title("Toomre diagram at the Sun")
ax.legend(loc="upper left")
ax = axs[1]
ell, b = 180.0, 20.0
d = np.geomspace(0.1, 20, 200)
R_los, Z_los = galactic_to_galactocentric_cyl(d, ell, b)
weight, mean_h, cov_h = halo_velocity_moments(R_los, Z_los)
ellipsoids = {
"Thin disk": thin_disk_velocity_moments(R_los, Z_los, 5.0, 0.0),
"Thick disk": thick_disk_velocity_moments(R_los),
"Halo": (mean_h[:, 0], cov_h[:, 0]),
}
for name, (mean, cov) in ellipsoids.items():
obs_mean, obs_cov = velocity_to_observables(d, (ell, b), mean, cov)
vt, sig = K_KMS * d * obs_mean[:, 0], K_KMS * d * np.sqrt(obs_cov[:, 0, 0])
ax.plot(d, vt, color=GALACTIC_COLORS[name], label=name)
ax.fill_between(d, vt - sig, vt + sig, color=GALACTIC_COLORS[name], alpha=0.15, lw=0)
ax.set(xscale="log", xlabel="distance (kpc)", ylabel=r"$4.74\, \mu_{\ell*}\, d$ (km/s)")
ax.set_title("Tangential velocity toward ℓ = 180°, b = 20°")
ax.legend(loc="lower right")
ax = axs[2]
longitudes = np.linspace(0, 360, 361)
for dk, color in zip([1, 2, 4, 8], ramp5):
R_l = galactic_to_galactocentric_cyl(np.full(longitudes.size, dk), longitudes, 0.0)[0]
vr = [velocity_to_observables(np.array([dk]), (l_, 0.0), *thin_disk_velocity_moments(np.array([r_]), np.array([0.0]), 5.0, 0.0))[0][0, 2]
for l_, r_ in zip(longitudes, R_l)]
ax.plot(longitudes, vr, color=color, label=f"d = {dk} kpc")
ax.set(xlim=(360, 0), xlabel="Galactic longitude ℓ (°)", ylabel="mean radial velocity (km/s)")
ax.set_xticks([360, 270, 180, 90, 0])
ax.set_title("Thin-disk rotation seen from the Sun")
ax.legend()
save_figure(fig, 4, "velocities", tight=False)
plt.show()
The bands give \(\pm 1\sigma\) of the tangential velocity; the thin disk is at 5 Gyr, and the halo shows its isotropic part. The next figure gives the dispersions themselves.
fig, axs = plt.subplots(1, 3, figsize=(14, 4), layout="constrained")
ax = axs[0]
age_axis = np.linspace(0.1, 13.5, 100)
sig = np.array([np.sqrt(np.diag(thin_disk_velocity_moments(R0, np.array([0.0]), a, 0.0)[1][0])) for a in age_axis])
sig_thick = np.sqrt(np.diag(thick_disk_velocity_moments(R0)[1][0]))
for k, (label, ls) in enumerate([(r"$\sigma_R$", "-"), (r"$\sigma_\phi$", (0, (5, 2))), (r"$\sigma_z$", (0, (1.5, 1.5)))]):
ax.plot(age_axis, sig[:, k], color=GALACTIC_COLORS["Thin disk"], ls=ls, label=f"thin disk {label}")
ax.axhline(sig_thick[k], color=GALACTIC_COLORS["Thick disk"], ls=ls, lw=1.6, label=f"thick disk {label}")
ax.set(xlabel="age (Gyr)", ylabel="dispersion at the Sun (km/s)", ylim=(0, 72))
ax.set_title("Age-velocity dispersion relation")
ax.legend(ncol=2, loc="lower right")
ax = axs[1]
R_axis = np.linspace(1, 25, 200)
for a, alpha in [(2.0, 0.45), (6.0, 0.7), (11.0, 1.0)]:
cov = thin_disk_velocity_moments(R_axis, np.zeros_like(R_axis), a, 0.0)[1]
ax.plot(R_axis, np.sqrt(cov[:, 2, 2]), color=GALACTIC_COLORS["Thin disk"], alpha=alpha, label=f"thin disk, {a:g} Gyr")
cov = thick_disk_velocity_moments(R_axis)[1]
ax.plot(R_axis, np.sqrt(cov[:, 2, 2]), color=GALACTIC_COLORS["Thick disk"], label="thick disk")
R_in = R_axis[R_axis <= 6]
mean_b, cov_b = bulge_velocity_moments(R_in, np.zeros_like(R_in))
ax.plot(R_in, np.sqrt(cov_b[:, 2, 2]), color=GALACTIC_COLORS["Bulge"], label="bulge")
ax.set(xlabel="R (kpc)", ylabel=r"$\sigma_z$ in the midplane (km/s)", ylim=(0, None))
ax.set_title("Vertical dispersion against radius")
ax.legend()
ax = axs[2]
for a, alpha in [(2.0, 0.45), (11.0, 1.0)]:
mean = thin_disk_velocity_moments(R_axis, np.zeros_like(R_axis), a, 0.0)[0]
ax.plot(R_axis, mean[:, 1], color=GALACTIC_COLORS["Thin disk"], alpha=alpha, label=f"thin disk, {a:g} Gyr")
ax.plot(R_axis, thick_disk_velocity_moments(R_axis)[0][:, 1], color=GALACTIC_COLORS["Thick disk"], label="thick disk")
weight, mean_h, _ = halo_velocity_moments(R_axis, np.zeros_like(R_axis))
ax.plot(R_axis, np.sum(weight * mean_h[:, :, 1], axis=1), color=GALACTIC_COLORS["Halo"], label="halo")
ax.plot(R_in, mean_b[:, 1], color=GALACTIC_COLORS["Bulge"], label="bulge")
ax.set(xlabel="R (kpc)", ylabel=r"mean $v_\phi$ (km/s)", ylim=(-10, 270))
ax.set_title("Rotation")
ax.legend(loc="lower right")
save_figure(fig, 4, "velocity_dispersions", tight=False)
plt.show()
The angular-momentum factor of the thin disk’s \(\sigma_z\) is held beyond 14 kpc, as in its density profile. The thick disk’s dispersions are constant beyond about 13 kpc, and its rotation falls far out, where it has few stars. The bulge is hotter and rotates more slowly than the disks. From 1 to 6 kpc, its \(\sigma_z\) falls from 100 to 63 km/s and its mean rotation rises from 137 to 173 km/s.
How much could a proper motion say about distance? For a component with mean proper motion \(\mathbf{m}(d)\) and covariance \(C\), the Cramér-Rao bound for one perfectly measured proper motion is \(\sigma(\ln d) \ge 1 / \sqrt{4 + \mathbf{m}^\top C^{-1} \mathbf{m}}\), if the velocity ellipsoid does not change along the sightline. With no mean motion, the bound is 0.5. The curves stop where the component has fewer than \(10^{-3}\) of its peak number of stars per kpc of distance.
fig, axs = plt.subplots(1, 2, figsize=(11, 3.8), sharey=True, layout="constrained")
d = np.geomspace(0.1, 30, 200)
for ax, (ell, b) in zip(axs, [(180.0, 20.0), (90.0, 30.0)]):
R_los, Z_los = galactic_to_galactocentric_cyl(d, ell, b)
ln_n = np.array(logp_galactic_structure(d, (ell, b), return_components=True)[1]["number_density"])
weight, mean_h, cov_h = halo_velocity_moments(R_los, Z_los)
ellipsoids = [thin_disk_velocity_moments(R_los, Z_los, 5.0, 0.0), thick_disk_velocity_moments(R_los), (mean_h[:, 0], cov_h[:, 0])]
for k, (mean, cov) in enumerate(ellipsoids):
obs_mean, obs_cov = velocity_to_observables(d, (ell, b), mean, cov)
m, C = obs_mean[:, :2], obs_cov[:, :2, :2]
chi2 = np.einsum("ni,nij,nj->n", m, np.linalg.inv(C), m)
bound = np.where(ln_n[k] - ln_n[k].max() > np.log(1e-3), 1 / np.sqrt(4 + chi2), np.nan)
ax.plot(d, bound, color=GALACTIC_COLORS[NAMES[k]], label=NAMES[k])
ax.axhline(0.5, color="#8c867e", lw=1, ls=(0, (4, 3)))
ax.set(xscale="log", xlabel="distance (kpc)", ylim=(0, 0.6))
ax.set_title(f"ℓ = {ell:g}°, b = {b:g}°")
axs[0].set_ylabel(r"best $\sigma(\ln d)$ from one proper motion")
axs[0].legend(loc="lower left")
save_figure(fig, 4, "proper_motion_information", tight=False)
plt.show()
Toward \((90°, 30°)\), the disks’ bound falls from 0.5 near the Sun to about 0.25 at 10 kpc and beyond. Toward \((180°, 20°)\), the halo’s large motion relative to the Sun gives about 0.33 at every distance, and the disks reach that only at 5 to 10 kpc.
The mean proper motion of a star depends on where it is. For a thin-disk star of 5 Gyr and solar [Fe/H], the maps give it at 1 and 3 kpc across the sky. Its \(\mu_{\ell*}\) shows the Galactic rotation seen from a rotating Sun, and its \(\mu_b\) mostly the reflex of the Sun’s motion out of the plane.
ls_, bs_ = np.linspace(-180, 180, 73), np.linspace(-60, 60, 25)
LG, BG = np.meshgrid(ls_ % 360, bs_)
fig, axs = plt.subplots(2, 2, figsize=(14, 5.6), sharex=True, sharey=True, layout="constrained")
for col, dk in enumerate([1.0, 3.0]):
R_s, Z_s = galactic_to_galactocentric_cyl(np.full(LG.size, dk), LG.ravel(), BG.ravel())[:2]
mean, cov = thin_disk_velocity_moments(R_s, Z_s, 5.0, 0.0)
mu = np.array([velocity_to_observables(np.array([dk]), (l_, b_), mean[k:k + 1], cov[k:k + 1])[0][0, :2]
for k, (l_, b_) in enumerate(zip(LG.ravel(), BG.ravel()))]).reshape(LG.shape + (2,))
for row, label in enumerate([r"$\mu_{\ell*}$", r"$\mu_b$"]):
ax = axs[row, col]
v = np.abs(mu[..., row]).max()
im = ax.imshow(mu[..., row], extent=(180, -180, -60, 60), origin="lower", cmap="RdBu_r", vmin=-v, vmax=v, aspect="auto")
ax.contour(ls_, bs_, mu[..., row], 8, colors=INK, linewidths=0.4)
ax.grid(False)
ax.set_title(f"mean {label} at {dk:g} kpc")
fig.colorbar(im, ax=ax, pad=0.01, label="mas/yr").outline.set_visible(False)
for ax in axs[1]:
ax.set_xlabel("ℓ (°)")
for ax in axs[:, 0]:
ax.set_ylabel("b (°)")
save_figure(fig, 4, "proper_motion_maps", tight=False)
plt.show()
A measured proper motion enters the prior as a likelihood inside each component: \(n_c \to n_c\, \mathcal{N}(\boldsymbol{\mu} \mid P(\bar{\mathbf{v}}_c - \mathbf{v}_\odot), P \Sigma_c P^{\rm T} + C)\), where \(P\) divides the transverse velocity by \(4.74\, d\) and \(C\) is the measurement covariance. 1% of each component (pm_outlier) follows a broad 300 km/s ellipsoid, so that one bad measurement cannot exclude a component. A transverse velocity therefore ties each component to the distances where its prediction matches the observation.
The panels show the prior of a 10.5 Gyr star with [Fe/H] \(= -0.7\) toward \((90°, 45°)\), whose labels fit both the thick disk and the halo, without a proper motion and with the mean motion of each component at 3 kpc.
coord_k = (90.0, 45.0)
d_k = np.geomspace(0.1, 30, 400)
star_labels = dict(feh=-0.7, loga=label_value("loga", 10.5))
pm_cov = np.diag([0.03, 0.03]) ** 2
R3, Z3 = galactic_to_galactocentric_cyl(np.array([3.0]), *coord_k)[:2]
pm_disk = velocity_to_observables(np.array([3.0]), coord_k, *thick_disk_velocity_moments(R3))[0][0, :2]
weight_h, mean_h3, _ = halo_velocity_moments(R3, Z3)
halo_v = np.einsum("k,kj->j", weight_h[0], mean_h3[0])[None]
pm_halo = velocity_to_observables(np.array([3.0]), coord_k, halo_v, np.zeros((1, 3, 3)))[0][0, :2]
motions = [
("No proper motion", {}),
(f"Thick-disk motion ({pm_disk[0]:.1f}, {pm_disk[1]:.1f}) mas/yr", dict(pm=pm_disk, pm_cov=pm_cov)),
(f"Halo motion ({pm_halo[0]:.1f}, {pm_halo[1]:.1f}) mas/yr", dict(pm=pm_halo, pm_cov=pm_cov)),
]
fig, axs = plt.subplots(1, 3, figsize=(14, 3.8), sharey=True, layout="constrained")
for ax, (title, motion) in zip(axs, motions):
lnp, comps = logp_galactic_structure(d_k, coord_k, return_components=True, **star_labels, **motion)
peak = np.max(lnp + np.log(d_k))
for k, name in enumerate(NAMES[:3]):
ln_c = sum(np.asarray(comps[key][k]) for key in comps)
ax.plot(d_k, np.exp(ln_c + np.log(d_k) - peak), color=GALACTIC_COLORS[name], lw=1.6, label=name)
ax.plot(d_k, np.exp(lnp + np.log(d_k) - peak), color=INK, lw=2.4, label="Total")
ax.set(xscale="log", xlim=(0.1, 30), ylim=(0, 1.08), xlabel="distance (kpc)")
ax.set_title(title, fontsize=10)
axs[0].set_ylabel("prior per ln d (peak 1)")
axs[0].legend()
save_figure(fig, 4, "kinematic_prior", tight=False)
plt.show()
Without a proper motion, the thick disk peaks at 3.1 kpc and the halo at 15 kpc, and each holds about half the prior. The thick disk’s own mean motion at 3 kpc moves its peak to 4.4 kpc and the halo’s in to 11 kpc, and raises the thick disk’s share from 0.42 to 0.54. The halo’s mean motion, 12 mas/yr in \(\mu_b\), is mostly the reflex of the Sun’s orbit, because the halo hardly rotates. It pulls the halo peak in to 4.8 kpc, and the thick disk now matches it only nearer, at 1.9 kpc, where the same proper motion is a slower velocity.
7. Switching components off¶
bar_mass=0 (the bar and the spheroid), f_thick_surface=0 or halo_mass=0 removes a component, and the prior then skips it. The thin disk sets the normalization, so it always stays. To fit with a component off, pass the prior to BruteForce.fit as lngalprior=partial(logp_galactic_structure, bar_mass=0.0). Section 9 does that.
switches = [
("No bulge", {"bar_mass": 0.0}, GALACTIC_COLORS["Bulge"]),
("No thick disk", {"f_thick_surface": 0.0}, GALACTIC_COLORS["Thick disk"]),
("No halo", {"halo_mass": 0.0}, GALACTIC_COLORS["Halo"]),
]
d = np.geomspace(0.05, 100, 600)
fig, axs = plt.subplots(1, 4, figsize=(14, 3.4), sharey=True, layout="constrained")
for ax, coord in zip(axs, [(0, 4), (30, 2), (90, 30), (0, 60)]):
full = per_ln_d(d, coord)
ax.plot(d, np.exp(full - full.max()), color=INK, lw=2.4, label="Full prior")
for label, kwargs, color in switches:
lnp = per_ln_d(d, coord, **kwargs)
ax.plot(d, np.exp(lnp - full.max()), color=color, lw=1.6, ls=(0, (4, 2)), label=label)
ax.set(xscale="log", xlim=(0.05, 100), ylim=(0, 1.08), xlabel="distance (kpc)")
ax.set_title(f"ℓ = {coord[0]}°, b = {coord[1]}°")
axs[0].set_ylabel("prior per ln d (full prior peak 1)")
axs[-1].legend()
save_figure(fig, 4, "switch_off", tight=False)
plt.show()
Toward the centre, the bulge holds most of the stars; without it, the prior there is the thin and thick disks seen through the centre. At high latitude, the halo holds the far peak.
8. The dust and parallax terms¶
The Bayestar class in brutus.dust gives A(V) against distance on each sightline, from Pan-STARRS and 2MASS photometry (Green et al. 2019). logp_extinction turns it into a Gaussian prior on A(V) at each distance, with 0.2 mag of scatter added in quadrature. Where the map is masked, it returns the normalized uniform prior over avlim. By default, queries return NaN outside each pixel’s reliable distance range (Bayestar(..., apply_reliability_mask=False) returns the raw profiles). The map does not cover the sky south of declination −30°.
try:
from brutus.dust import Bayestar
dustmap = Bayestar(dustfile=find_brutus_data_file("bayestar2019_v1.h5"))
except FileNotFoundError:
dustmap = None
fig, axs = plt.subplots(1, 2, figsize=(11, 3.8), layout="constrained")
ax = axs[0]
if dustmap is not None:
for (ell, b), color in zip([(0, 0), (90, 0), (180, 0), (45, 30), (0, 90)], ["#2b0505", "#7c0008", "#b5452a", "#d9783a", "#f2b45c"]):
dists, av_mean, av_std = dustmap.query_gal(ell, b)
ok = np.isfinite(av_mean)
ax.plot(dists[ok], av_mean[ok], color=color, label=f"ℓ = {ell}°, b = {b}°")
ax.fill_between(dists[ok], (av_mean - av_std)[ok], (av_mean + av_std)[ok], color=color, alpha=0.15, lw=0)
ax.set(xscale="log", xlabel="distance (kpc)", ylabel="A(V) (mag)")
ax.set_xticks([0.3, 1, 3], ["0.3", "1", "3"])
ax.xaxis.set_minor_formatter(plt.NullFormatter())
ax.legend()
else:
ax.text(0.5, 0.5, "bayestar2019_v1.h5 not found", ha="center", transform=ax.transAxes)
ax.set_title("Bayestar extinction profiles")
ax = axs[1]
rv = np.linspace(2.5, 4.2, 200)
ax.plot(rv, np.exp(-0.5 * ((rv - 3.32) / 0.18) ** 2), color=INK)
ax.set(xlabel="R(V)", ylabel="prior (peak 1)")
ax.set_title("R(V) prior: 3.32 ± 0.18")
save_figure(fig, 4, "dust", tight=False)
plt.show()
A parallax enters the fit as a likelihood, not a prior: logp_parallax is a Gaussian in the model parallax \(1/d\). In distance, a parallax with a low signal-to-noise ratio leaves a long tail to large distances, which the Galactic prior then cuts off. The figure multiplies the two along two sightlines.
from brutus.priors import logp_parallax
fig, axs = plt.subplots(1, 2, figsize=(11, 3.8), sharey=True, layout="constrained")
d = np.geomspace(0.1, 30, 500)
for ax, (coord, plx, plx_err) in zip(axs, [((90, 30), 0.5, 0.2), ((0, 5), 0.3, 0.15)]):
terms = {"Galactic prior": per_ln_d(d, coord), "Parallax": logp_parallax(1 / d, plx, plx_err)}
total = sum(terms.values())
for (label, lnp), color in zip(terms.items(), [GALACTIC_COLORS["Thin disk"], GALACTIC_COLORS["Bulge"]]):
ax.plot(d, np.exp(lnp - lnp.max()), color=color, lw=1.6, label=label)
ax.plot(d, np.exp(total - total.max()), color=INK, lw=2.4, label="Product")
ax.set(xscale="log", xlim=(0.1, 30), xlabel="distance (kpc)")
ax.set_title(f"ℓ = {coord[0]}°, b = {coord[1]}°, parallax {plx} ± {plx_err} mas")
axs[0].set_ylabel("per ln d (each peak 1)")
axs[0].legend()
save_figure(fig, 4, "combined_terms", tight=False)
plt.show()
9. The effect on fits¶
This section draws mock stars from the prior, fits them with and without it, and compares the results with the truth. It needs the MIST grid and takes several minutes.
The mock has 40 stars on each of two sightlines: toward the bulge at \((0°, 4°)\) and at high latitude, \((90°, 45°)\). Each star is a grid model drawn at a distance from the Galactic prior times the model prior that BruteForce applies, with \(G < 17.5\). Its photometry is Gaia and 2MASS with realistic errors, and its A(V) rises with distance: \(A_V(d) = A_{V,\infty} (1 - e^{-d / 1.5\ {\rm kpc}})\).
from brutus.analysis import BruteForce
from brutus.core import StarGrid, get_seds
from brutus.data import filters, load_models
from brutus.priors import logp_imf
from brutus.utils import inv_magnitude
try:
grid_file = find_brutus_data_file("grid_mist_v9.h5")
models, labels, _ = load_models(grid_file, filters=filters.gaia + filters.tmass, verbose=False)
fitter = BruteForce(StarGrid(models, labels), verbose=False)
run_fits = True
except FileNotFoundError:
print("grid_mist_v9.h5 not found: skipping the fits")
run_fits = False
FIELDS = {"bulge (0°, 4°)": (0.0, 4.0, 2.8), "high latitude (90°, 45°)": (90.0, 45.0, 0.1)}
Loaded StarGrid with 613,530 models, 6 filters, 10 labels
def draw_mock(n_per_field=40, seed=2026):
# Draw stars from the Galactic prior times the model prior, with G < 17.5.
rng = np.random.default_rng(seed)
# The model prior that BruteForce applies: IMF, age weight and grid volume.
lnp_model = logp_imf(labels["mini"]) + np.log(np.abs(labels["agewt"]))
for name in [k for k, is_axis in fitter.labels_mask.items() if is_axis]:
u = np.unique(labels[name][np.isfinite(labels[name])])
if u.size > 1: # a single-valued axis adds no volume term
lnp_model += np.interp(labels[name], u, np.log(np.gradient(u)))
ok = np.flatnonzero(np.isfinite(lnp_model))
grid_d = np.geomspace(0.05, 40, 140)
stars = []
for field, (ell, b, av_inf) in FIELDS.items():
av = av_inf * (1 - np.exp(-grid_d / 1.5))
blocks = []
for start in range(0, ok.size, 50000):
idx = ok[start:start + 50000]
dd = np.broadcast_to(grid_d[:, None], (grid_d.size, idx.size))
lw = logp_galactic_structure(dd, (ell, b), feh=labels["feh"][idx], loga=labels["loga"][idx])
lw = lw + np.log(grid_d)[:, None] + lnp_model[idx][None]
c = models[idx, 0]
G = c[None, :, 0] + av[:, None] * (c[None, :, 1] + 3.32 * c[None, :, 2]) + 5 * np.log10(grid_d)[:, None]
blocks.append(np.where(G < 17.5, np.maximum(lw, -1e30), -np.inf).astype(np.float32))
lw = np.concatenate(blocks, axis=1).ravel().astype(float)
p = np.exp(lw - lw.max())
i_d, i_m = np.unravel_index(rng.choice(lw.size, n_per_field, p=p / p.sum()), (grid_d.size, ok.size))
step = np.log(grid_d[1] / grid_d[0])
for i, j in zip(i_d, i_m):
d = grid_d[i] * np.exp(rng.uniform(-0.5, 0.5) * step)
stars.append((field, ell, b, d, av_inf * (1 - np.exp(-d / 1.5)), rng.normal(3.32, 0.18), ok[j]))
truth = np.array(stars, dtype=[("field", "U32"), ("l", "f8"), ("b", "f8"), ("dist", "f8"),
("av", "f8"), ("rv", "f8"), ("model", "i8")])
mags = get_seds(models[truth["model"]], av=truth["av"], rv=truth["rv"])
mags += 5 * np.log10(truth["dist"])[:, None]
floor = np.array([0.003, 0.005, 0.005, 0.02, 0.02, 0.02])
faint = np.array([0.02, 0.05, 0.03, 0.05, 0.05, 0.05]) * 10 ** (0.4 * (mags - np.array([20, 20, 20, 15.5, 14.8, 14.3])))
mag_err = np.hypot(floor, faint)
return truth, mags + rng.normal(size=mags.shape) * mag_err, mag_err
if run_fits:
truth, mags, mag_err = draw_mock()
giant = labels["logg"][truth["model"]] < 3.5
print(f"{len(truth)} stars, {giant.sum()} giants (log g < 3.5)")
80 stars, 42 giants (log g < 3.5)
The fits use the mock’s A(V) relation as a dust map, through the standard dust prior logp_extinction with its 0.2 mag of scatter. Only the Galactic prior then differs between them. Any object with a query(coord) method that returns distances, A(V) means and spreads can serve as dustfile. “No Galactic prior” keeps only the volume term \(d^2\): stars spread evenly through space.
class MockDustMap:
# The mock's A(V) against distance on each field, in the form of Bayestar.query.
distances = np.geomspace(0.01, 100, 400)
def query(self, coord):
av_inf = {(f[0], f[1]): f[2] for f in FIELDS.values()}[(float(coord[0]), float(coord[1]))]
return self.distances, av_inf * (1 - np.exp(-self.distances / 1.5)), np.zeros(self.distances.size)
def volume_only(dist, coord, labels=None):
return 2 * np.log(dist)
PRIORS = {
"No Galactic prior": volume_only,
"Full prior": None, # the default, logp_galactic_structure
"No bulge": partial(logp_galactic_structure, bar_mass=0.0),
"No halo": partial(logp_galactic_structure, halo_mass=0.0),
}
results = {}
if run_fits:
import tempfile
import h5py
flux, flux_err = inv_magnitude(mags, mag_err)
ids = np.array([(i,) for i in range(len(truth))], dtype=[("id", "i8")])
workdir = tempfile.TemporaryDirectory()
for name, prior in PRIORS.items():
out = f"{workdir.name}/{name.lower().replace(' ', '_')}"
fitter.fit(
flux, flux_err, np.ones_like(flux, dtype=bool), ids, out,
data_coords=np.c_[truth["l"], truth["b"]], lngalprior=prior,
dustfile=MockDustMap(), rstate=np.random.RandomState(7), verbose=False,
)
with h5py.File(out + ".h5") as f:
results[name] = f["samps_dist"][:], f["model_idx"][:]
workdir.cleanup()
if run_fits:
fig, axs = plt.subplots(2, 4, figsize=(14, 6.4), sharex="row", sharey="row", layout="constrained")
print(f"{'':20s} {'field':26s} {'median error (dex)':>19s} {'68% coverage':>13s} {'dwarf/giant wrong':>18s}")
for col, (name, (samples, model_idx)) in enumerate(results.items()):
lo, med, hi = np.percentile(samples, [16, 50, 84], axis=1)
p_giant = (labels["logg"][model_idx] < 3.5).mean(axis=1)
for row, field in enumerate(FIELDS):
s = truth["field"] == field
ax = axs[row, col]
ax.plot([0.05, 40], [0.05, 40], color="#cfc7bb", lw=1)
for is_giant, marker in [(False, "o"), (True, "s")]:
t = s & (giant == is_giant)
ax.errorbar(truth["dist"][t], med[t], yerr=[med[t] - lo[t], hi[t] - med[t]], fmt=marker, ms=4,
color=INK if name == "Full prior" else "#8c867e", mfc="white", elinewidth=0.8, capsize=0,
label="giant" if is_giant else "dwarf")
ax.set(xscale="log", yscale="log")
err = np.log10(med[s] / truth["dist"][s])
cover = np.mean((truth["dist"][s] >= lo[s]) & (truth["dist"][s] <= hi[s]))
wrong = np.sum((p_giant[s] > 0.5) != giant[s])
print(f"{name:20s} {field:26s} {np.median(err):+8.3f} ± {np.std(err):.3f} {cover:13.2f} {wrong:12d} of {s.sum()}")
if row == 0:
ax.set_title(name)
if col == 0:
ax.set_ylabel(f"{field}\nposterior distance (kpc)")
if row == 1:
ax.set_xlabel("true distance (kpc)")
axs[0, 0].legend(loc="upper left")
save_figure(fig, 4, "fits", tight=False)
plt.show()
field median error (dex) 68% coverage dwarf/giant wrong
No Galactic prior bulge (0°, 4°) +0.221 ± 0.155 0.30 0 of 40
No Galactic prior high latitude (90°, 45°) +0.528 ± 0.611 0.20 20 of 40
Full prior bulge (0°, 4°) +0.004 ± 0.047 0.70 0 of 40
Full prior high latitude (90°, 45°) +0.027 ± 0.085 0.57 0 of 40
No bulge bulge (0°, 4°) -0.005 ± 0.076 0.65 0 of 40
No bulge high latitude (90°, 45°) +0.027 ± 0.085 0.57 0 of 40
No halo bulge (0°, 4°) +0.003 ± 0.047 0.70 0 of 40
No halo high latitude (90°, 45°) +0.021 ± 0.086 0.57 0 of 40
Each point is one star: its posterior median and 68% interval against its true distance. Without the Galactic prior, only the volume term separates a near dwarf from a far giant, and it favours the far solution:
At high latitude, 20 of the 40 stars are classed wrongly. Most are dwarfs within 2 kpc, fitted several times too far, up to about 90 kpc.
In the bulge, the median star is placed 0.22 dex (66%) too far.
With the full prior, the median errors are \(+0.004\) dex in the bulge and \(+0.027\) dex at high latitude, with a scatter of 0.047 and 0.085 dex, and the 68% intervals hold 70% and 57% of the true distances. Without the bulge, the bulge scatter rises to 0.076 dex. Without the halo, the high-latitude stars, all within 6 kpc, hardly change. With 40 stars per field, each coverage carries about ±0.07.
Fits with proper motions¶
BruteForce.fit takes the Gaia columns pmra, pmdec, pmra_error, pmdec_error and pmra_pmdec_corr, and optionally radial_velocity and radial_velocity_error. It rotates them to Galactic components and binds each star’s motion into the Galactic prior. apply_pm_prior=False switches the term off. With save_motion_draws=True, the output also holds samps_motion, the \((\mu_{\ell*}, \mu_b, v_r)\) that the prior predicts for each posterior draw.
The cell below draws four mock stars from their components’ velocity ellipsoids and fits each from Gaia and 2MASS photometry with the parallax withheld: first without motions, then with the proper motion, then with the radial velocity too. They use the flat A(V) prior.
from brutus.utils.math import galactic_to_icrs, pm_equatorial_to_galactic
if run_fits:
rng_k = np.random.default_rng(4)
kin_stars = [
dict(name="Thin-disk dwarf", feh=0.0, age=4.0, logg=4.6, coord=(180.0, 20.0), dist=0.5, kind="thin"),
dict(name="Thick-disk subgiant", feh=-0.6, age=10.5, logg=3.8, coord=(90.0, 45.0), dist=2.0, kind="thick"),
dict(name="Halo giant", feh=-1.4, age=12.0, logg=2.4, coord=(90.0, 45.0), dist=6.0, kind="halo"),
dict(name="Halo dwarf", feh=-1.4, age=12.0, logg=4.6, coord=(90.0, 45.0), dist=0.8, kind="halo"),
]
single = (labels["smf"] == 0) & np.isfinite(labels["loga"])
kin_err = np.array([0.02, 0.02, 0.02, 0.03, 0.03, 0.03])
pm_err, rv_err = 0.03, 1.0
for star in kin_stars:
# The grid model nearest the star's labels, a velocity from its component's
# ellipsoid, Gaia-like errors and A(V) = 0.05.
score = (np.abs(labels["feh"] - star["feh"]) / 0.1 + np.abs(labels["logg"] - star["logg"]) / 0.1
+ np.abs(labels["loga"] - label_value("loga", star["age"])) / 0.05)
star["model"] = np.flatnonzero(single)[np.argmin(score[single])]
dk = np.array([star["dist"]])
R_k, Z_k = galactic_to_galactocentric_cyl(dk, *star["coord"])[:2]
if star["kind"] == "thin":
mean, cov = thin_disk_velocity_moments(R_k, Z_k, np.array([star["age"]]), np.array([star["feh"]]))
elif star["kind"] == "thick":
mean, cov = thick_disk_velocity_moments(R_k)
else:
weight_k, means_k, covs_k = halo_velocity_moments(R_k, Z_k)
q = rng_k.choice(weight_k.shape[1], p=weight_k[0])
mean, cov = means_k[:, q], covs_k[:, q]
v = rng_k.multivariate_normal(mean[0], cov[0])
obs = velocity_to_observables(dk, star["coord"], v[None], np.zeros((1, 3, 3)))[0][0]
star["pm_gal"] = obs[:2] + rng_k.normal(0, pm_err, 2)
star["rv"] = obs[2] + rng_k.normal(0, rv_err)
star["mag"] = get_seds(models[star["model"]][None], av=0.05, rv=3.32)[0] + 5 * np.log10(star["dist"]) + rng_k.normal(0, kin_err)
# fit() takes Gaia-native proper motions. The rotation from (pmra, pmdec) to
# (mu_l*, mu_b) is [[c, s], [-s, c]], so rotating (1, 0) gives (c, -s), and
# its transpose takes the Galactic motions back.
kin_coords = np.array([s["coord"] for s in kin_stars])
ra, dec = galactic_to_icrs(kin_coords[:, 0], kin_coords[:, 1])
nk = len(kin_stars)
one, zero = np.ones(nk), np.zeros(nk)
unit_pmra_gal = pm_equatorial_to_galactic(ra, dec, one, zero, one, one, zero)[0]
c_, s_ = unit_pmra_gal[:, 0], -unit_pmra_gal[:, 1]
pm_gal = np.array([s["pm_gal"] for s in kin_stars])
pm_columns = dict(
pmra=c_ * pm_gal[:, 0] - s_ * pm_gal[:, 1], pmdec=s_ * pm_gal[:, 0] + c_ * pm_gal[:, 1],
pmra_error=np.full(nk, pm_err), pmdec_error=np.full(nk, pm_err), pmra_pmdec_corr=np.zeros(nk),
)
kin_flux, kin_flux_err = inv_magnitude(np.array([s["mag"] for s in kin_stars]), np.tile(kin_err, (nk, 1)))
kin_cases = {
"Photometry only": {},
"+ proper motion": pm_columns,
"+ proper motion and RV": dict(pm_columns, radial_velocity=np.array([s["rv"] for s in kin_stars]),
radial_velocity_error=np.full(nk, rv_err)),
}
kin_results = {}
workdir = tempfile.TemporaryDirectory()
for k, (case, kwargs) in enumerate(kin_cases.items()):
out = f"{workdir.name}/kin_{k}"
fitter.fit(kin_flux, kin_flux_err, np.ones_like(kin_flux, dtype=bool), np.array([(j,) for j in range(nk)], dtype=[("id", "i8")]),
out, data_coords=kin_coords, save_motion_draws=True, rstate=np.random.default_rng(1), verbose=False, **kwargs)
with h5py.File(out + ".h5") as f:
kin_results[case] = {key: f[key][()] for key in ("samps_dist", "model_idx", "samps_motion")}
workdir.cleanup()
if run_fits:
case_colors = dict(zip(kin_cases, ["#8c867e", GALACTIC_COLORS["Thick disk"], GALACTIC_COLORS["Thin disk"]]))
fig, axs = plt.subplots(len(kin_stars), 3, figsize=(14, 3.1 * len(kin_stars)), layout="constrained")
for j, star in enumerate(kin_stars):
ax_d, ax_g, ax_m = axs[j]
for case, r in kin_results.items():
ax_d.hist(r["samps_dist"][j], bins=np.geomspace(0.1, 20, 60), histtype="step", lw=1.8, density=True,
color=case_colors[case], label=case)
ax_g.hist(labels["logg"][r["model_idx"][j]], bins=np.linspace(0, 5, 51), histtype="step", lw=1.8,
density=True, color=case_colors[case])
ax_d.axvline(star["dist"], color=INK, ls=(0, (4, 2)), label="truth")
ax_g.axvline(labels["logg"][star["model"]], color=INK, ls=(0, (4, 2)))
for case in list(kin_cases)[:2]:
mu = kin_results[case]["samps_motion"][j]
ax_m.scatter(mu[:, 0], mu[:, 1], s=5, alpha=0.4, color=case_colors[case], label=case)
ax_m.errorbar(*star["pm_gal"], xerr=pm_err, yerr=pm_err, fmt="*", ms=13, color=INK, label="observed")
ax_d.set(xscale="log", xlabel="distance (kpc)")
ax_d.set_title(star["name"], loc="left")
ax_g.set_xlabel("log g")
ax_m.set(xlabel=r"$\mu_{\ell*}$ (mas/yr)", ylabel=r"$\mu_b$ (mas/yr)")
for ax in (ax_d, ax_g):
ax.set_yticks([])
axs[0, 0].legend(loc="upper left")
axs[0, 2].legend(loc="best")
axs[0, 1].set_title("surface gravity")
axs[0, 2].set_title("predicted proper motion")
save_figure(fig, 4, "kinematic_fits", tight=False)
plt.show()
Thin-disk dwarf: the photometry already fixes the distance, and the motion changes nothing.
Thick-disk subgiant: the photometry places it at about 1 kpc as a dwarf. Its motion fits the disks at either distance, so the proper motion barely moves it, and the radial velocity shifts only a little weight toward the true distance.
Halo giant: its small proper motion is also that of a disk dwarf at 0.5 kpc, so the dwarf solution survives. The proper motion moves much of the weight to the giant solution, but this star’s radial velocity is close to a disk star’s, and adding it moves the weight back toward the nearer solutions.
Halo dwarf: photometry alone places it beyond the truth. Its large proper motion fits only the halo, and only nearby, so the kinematic term pulls the distance in. Without the motion, the fit’s draws predict small disk-like motions that miss the observation (right); with it, they spread over the halo’s.
The proper motion constrains the distance through the transverse velocity \(4.74\,\mu\,d\), so it separates solutions whose velocities differ, such as a nearby fast dwarf and a distant giant, more than it narrows a single one. The Priors page reports the validation on larger samples.
Summary¶
The Galactic prior has four components: thin disk, thick disk, halo and bulge, where the bulge is a metal-rich bar and a metal-poor spheroid. Each gives a density and a distribution of [Fe/H] and age at every position.
The disk heights come from Jeans equations in one potential, so the thin disk flares outward and both disks pinch above the centre.
A star’s [Fe/H] and age move its distance prior: metal-rich and young stars stay near the plane, metal-poor and old ones go to the halo.
Each component has a velocity ellipsoid. A proper motion, and optionally a radial velocity, weighs each component by how well it predicts the motion, which can separate a near dwarf from a far giant.
bar_mass=0(the whole bulge),f_thick_surface=0orhalo_mass=0removes a component; pass it tofitwithfunctools.partial.Without a parallax, the prior decides between a near dwarf and a far giant. With a precise parallax, the likelihood dominates.
Next: Tutorial 5 fits real stars with BruteForce.