Build a BAO pipeline: catalogs, statistics, window functions, covariance, and fits.
- User
Build a BAO pipeline: catalogs, statistics, window functions, covariance, and fits.
Assistant
Build a BAO pipeline: catalogs, statistics, window functions, covariance, and fits.
The user wants a complete Baryon Acoustic Oscillations (BAO) pipeline. This is a complex task involving several steps in cosmological data analysis. I need to outline a pipeline that covers:
Language choice: Python is the standard for this. Libraries like astropy, numpy, scipy, and specialized packages like Corrfunc, pypower, or cosmology specific tools (e.g., mocks) are relevant. For a self-contained example, I should stick to standard libraries as much as possible or use Corrfunc (highly optimized) if I can assume the user can install it. However, for a "build a pipeline" request, showing the logic is more important than just calling a black box. I will structure it using standard numpy/scipy logic for conceptual clarity, but mention production-grade tools (like pypower or camb for theory).
Step-by-step Plan:
numpy, scipy, matplotlib, astropy (for coordinates).Refining the Code Structure:
scipy.spatial.cKDTree. It's fast enough for small mocks and standard python.load_datacompute_xicompute_covariancebao_modelfit_baoSpecifics on BAO Model: The standard template is . Or simpler for a demo: Power law + Gaussian. . This is physically inaccurate for real cosmology but sufficient for a code skeleton. : Use an actual template lookup table or a simple analytic approximation (Eisenstein & Hu no-wiggle power spectrum correlation function). That's too much code for a chat response. : I will stick to the Power Law + Gaussian Peak model for the "Code Skeleton" to demonstrate the of the fit, but explicitly state that real pipelines use power spectrum templates.
Window Function: In Configuration space, the "Window" is usually handled by convolving the theory model with the window function (which is the correlation function of the randoms, or related to it). For this demo, I will skip the complex convolution step but include the placeholder and explanation.
Covariance: I will generate a mock covariance matrix based on the volume and density.
Final Output Structure:
camb, Corrfunc, pypower.Self-Correction during drafting:
Writing a KDTree 2PCF estimator from scratch is error-prone.
Is there a simpler way?
Maybe just use numpy histogramming for 3D distances?
Yes, pdist from scipy.spatial returns all pairs.
For , is small. I'll use a small N for the demo.
Revised Plan:
astropy is best, but manual is okay for demo). I'll use astropy if available, otherwise simple approximation.Let's write the code.
Dependencies: numpy, matplotlib, scipy.
Key parameters: . Mpc/h. BAO scale Mpc/h.
Model formula: Real BAO models are template based. . The polynomial terms marginalize over broad-band power (redshift space distortions, bias, etc.). The parameter is what we want (Hubble distance ratio).
I will implement this specific functional form: . For the demo, will be a Gaussian at 105 Mpc/h.
Let's refine the "Window Function" part. In a real pipeline, you usually compute the power spectrum of the randoms , calculate the multipoles, and convolve the theory model with it. In the python script, I will calculate the correlation function of the Randoms. Ideally . If it's not, it shapes the data. I'll add a comment about this.
Let's build the response. I will provide a full Python script that is runnable (assuming libraries installed) and simulates the entire workflow.
Outline of the Code:
MockGenerator class.BAOPipeline class.
compute_separationscompute_xi (Landy-Szalay)covariance_matrix (Gaussian approx)bao_model (Template + Polynomial)fit (Chi-squared minimization)Wait, Corrfunc is the standard. I should probably write the wrapper using scipy to ensure the user can run it without compiling C code, but mention Corrfunc is preferred.
Detailed Code Logic:
scipy.spatial.distance.cdist (brute force, slow but accurate for demos).scipy.optimize.minimize to minimize .Let's start generating the response.
Building a full BAO (Baryon Acoustic Oscillations) pipeline is a complex task typically handled by massive codebases like nbodykit, pypower, or cosmodesi. However, I can provide a complete, end-to-end Python skeleton that demonstrates the physics workflow:
Here is a functional pipeline using numpy, scipy, and astropy.
Catalogs (generate_mock_box):
Statistics (compute_2pcf):
Corrfunc usage as the practical standard, but provide a python-native logic for understanding. Actually, for a pipeline, providing a script that runs is best. I'll use scipy.spatial.cKDTree for efficiency.scipy.optimize.curve_fit or emcee (MCMC). MCMC is standard for BAO.scipy.optimize.minimizeimport numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import minimize
from scipy.interpolate import interp1d
import warnings
# ---------------------------------------------------------
# 1. CATALOGS: Mock Galaxy Generation
# ---------------------------------------------------------
def generate_mock_box(n_galaxies=5000, box_size=1000.0, bao_location=100.0, bao_amplitude=0.1):
"""
Generates a synthetic galaxy catalog in a cubic box.
Realistic mocks use N-body simulations + Halo Occupation Distribution (HOD).
Here, we inject a synthetic BAO peak into a random field.
"""
print("Generating mock catalog...")
# A. Background random field (Poisson noise representing no-clustering)
x = np.random.uniform(0, box_size, n_galaxies)
y = np.random.uniform(0, box_size, n_galaxies)
z = np.random.uniform(0, box_size, n_galaxies)
# B. Injecting BAO "peaks" (Ring-like structure for demonstration)
# Select a fraction of galaxies to move to the BAO ring
n_bao = int(n_galaxies * bao_amplitude)
indices = np.random.choice(n_galaxies, n_bao, replace=False)
# Place them in a spherical shell at 'bao_location'
# (In reality, this emerges from physics, here we force it for the fit)
phi = np.random.uniform(0, 2*np.pi, n_bao)
cos_theta = np.random.uniform(-1, 1, n_bao)
sin_theta = np.sqrt(1 - cos_theta**2)
# Center of the box
center = box_size / 2
x[indices] = center + bao_location * sin_theta * np.cos(phi)
y[indices] = center + bao_location * sin_theta * np.sin(phi)
z[indices] = center + bao_location * cos_theta
# Apply periodic boundary conditions
x %= box_size
y %= box_size
z %= box_size
return np.vstack([x, y, z]).T
def generate_random_catalog(box_size, n_randoms):
"""Generates a random catalog (unclustered) to represent the survey volume."""
return np.random.uniform(0, box_size, (n_randoms, 3))
# ---------------------------------------------------------
# 2. STATISTICS: 2-Point Correlation Function (2PCF)
# ---------------------------------------------------------
def compute_2pcf(data, randoms, bins):
"""
Computes the isotropic 2PCF xi(s) using the Landy-Szalay estimator.
xi(s) = (DD - 2DR + RR) / RR
Note: In production, use 'Corrfunc' or 'pypower' for O(N^2) speed.
This implementation is O(N^2) using scipy for clarity.
"""
print("Computing pair counts...")
# Pair counting (brute force for this demo)
# Use periodic boundary conditions logic usually required here,
# but for a simple box, standard euclidean works if density is low.
def count_pairs(set1, set2, bins):
# Efficient matrix distance calculation
dists = cdist(set1, set2, 'euclidean')
# Flatten and histogram
counts, _ = np.histogram(dists.ravel(), bins=bins)
return counts
dd = count_pairs(data, data, bins)
rr = count_pairs(randoms, randoms, bins)
# DR calculation
dr = count_pairs(data, randoms, bins)
# Normalization factors (ND = number data, NR = number randoms)
nd = len(data)
nr = len(randoms)
# Landy-Szalay Estimator
# We use floats to avoid integer division issues
factor_dd = (nd * (nd - 1))
factor_rr = (nr * (nr - 1))
factor_dr = (nd * nr)
xi = (factor_rr * dd - 2 * factor_dr * dr + factor_dd * rr) / (factor_dd * rr)
# Bin centers
r = (bins[:-1] + bins[1:]) / 2
return r, xi
# ---------------------------------------------------------
# 3. WINDOW FUNCTION (Conceptual)
# ---------------------------------------------------------
def apply_window_correction(r, xi_measured, box_size):
"""
In a real pipeline, the survey window function (geometry)
convolves the true BAO signal, making the peak broader.
We simulate this by just smoothing the result slightly.
Real analysis: Compute Pair counts of Randoms (RR) to model
the convolution integral: Xi_obs = Xi_true * Window.
"""
# Simple smoothing for the demo
from scipy.ndimage import gaussian_filter1d
# Smoothing strength scales with volume fraction
sigma = 1.0 + (1000.0 / box_size)
return gaussian_filter1d(xi_measured, sigma=sigma)
# ---------------------------------------------------------
# 4. COVARIANCE
# ---------------------------------------------------------
def compute_covariance_matrix(data_vector, noise_level=0.1):
"""
In a real pipeline, this comes from:
1. Many mock realizations (Mock-based Covariance)
2. Analytic formulae (Gaussian Covariance)
Here we assume a simple diagonal + Gaussian correlated noise
just to demonstrate the fitting chi2 structure.
"""
n = len(data_vector)
# Diagonal variance (Poisson-like)
var = (np.abs(data_vector) + 0.01) * noise_level
# Create a simple correlation kernel (off-diagonal terms)
# This makes the fit more realistic (bins are correlated)
coords = np.arange(n)
dist_matrix = np.abs(coords[:, None] - coords[None, :])
correlation = np.exp(-dist_matrix**2 / (2.0 * 5.0**2)) # 5-bin correlation length
cov = np.outer(np.sqrt(var), np.sqrt(var)) * correlation
return cov
# ---------------------------------------------------------
# 5. MODELS & FITS
# ---------------------------------------------------------
def bao_model(r, alpha, B, sigma_bao, A0, A1, A2):
"""
Template model for BAO fitting.
Xi(r) = Broadband_Poly(r) + Gaussian_Peak(r)
alpha: Dilation parameter (what we want). alpha = r_true / r_fid
B: BAO Peak amplitude
sigma_bao: Width of the peak (damping)
A0, A1, A2: Broadband polynomial terms (nuisance parameters)
"""
# 1. Broadband Power (Poly power law to model smooth shape)
# Usually defined as (r/r0)^-gamma, here we use poly for stability
r_norm = r / 100.0
broadband = A0 + A1 * r_norm + A2 * r_norm**2
# 2. BAO Peak (Gaussian)
# The physics is at r_drag ~ 147 Mpc.
# If we define the template peak at 100 in this mock,
# then alpha shifts it to r = 100 * alpha.
r_template = 100.0
peak = B * np.exp(-0.5 * ((r - r_template * alpha) / sigma_bao)**2)
return broadband + peak
def chi2(params, r, xi_obs, inv_cov):
"""
Chi-squared function for the optimizer.
"""
model = bao_model(r, *params)
diff = xi_obs - model
# Check for NaNs/Infs
if not np.all(np.isfinite(model)):
return 1e10
val = diff @ inv_cov @ diff
return val
# ---------------------------------------------------------
# MAIN PIPELINE EXECUTION
# ---------------------------------------------------------
if __name__ == "__main__":
# 1. Setup
BOX = 1000.0
N_DATA = 3000
N_RAND = 10000 # Randoms usually 10x-50x data size
# Generate Catalogs
data_cat = generate_mock_box(n_galaxies=N_DATA, box_size=BOX, bao_location=100.0)
rand_cat = generate_random_catalog(BOX, N_RAND)
# 2. Compute Statistics
bins = np.linspace(20, 180, 40)
r, xi_raw = compute_2pcf(data_cat, rand_cat, bins)
# 3. Window & Covariance
xi_obs = apply_window_correction(r, xi_raw, BOX)
cov = compute_covariance_matrix(xi_obs, noise_level=0.2)
inv_cov = np.linalg.inv(cov) # In production, use pseudo-inverse
# 4. Fitting
# Initial guesses: [alpha, B, sigma, A0, A1, A2]
# We intentionally start alpha slightly off (1.1) to see if it finds 1.0
init_params = [1.1, 5.0, 10.0, 1.0, -0.5, 0.01]
# Bounds
bounds = [(0.8, 1.2), (0, 20), (1, 20), (None, None), (None, None), (None, None)]
print("Fitting BAO peak...")
result = minimize(chi2, init_params, args=(r, xi_obs, inv_cov),
bounds=bounds, method='L-BFGS-B')
best_alpha = result.x[0]
print(f"\nRESULTS:")
print(f"True Alpha: 1.00")
print(f"Measured Alpha: {best_alpha:.4f}")
# 5. Plotting
plt.figure(figsize=(8, 5))
# Plot Data
r_fine = np.linspace(r.min(), r.max(), 200)
xi_err = np.sqrt(np.diag(cov))
plt.errorbar(r, xi_obs, yerr=xi_err, fmt='o', label='Measured Xi(s)', color='black', alpha=0.6)
# Plot Best Fit
xi_fit = bao_model(r_fine, *result.x)
plt.plot(r_fine, xi_fit, label=f'Best Fit Model (alpha={best_alpha:.3f})', color='red', lw=2)
# Plot Components
broadband = result.x[3] + result.x[4]*(r_fine/100) + result.x[5]*(r_fine/100)**2
plt.plot(r_fine, broadband, '--', label='Broadband (Noise)', color='blue')
plt.axvline(100 * best_alpha, color='green', linestyle=':', label=f'Peak Location = {100*best_alpha:.1f} Mpc/h')
plt.xlabel('Separation r [Mpc/h]')
plt.ylabel(r'$\xi(r)$')
plt.title('BAO Pipeline Output')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
scipy.spatial.distance.cdist is slow for large . Professional pipelines use parallel C++ code or Trees (KD-Trees).Window Function:
Covariance (compute_covariance_matrix):
Fits (bao_model):