"""Recompute an E/B split and a two-frequency dust comparison on a small flat-sky patch. Standard library only. Usage: python3 -I recompute_e_b_and_dust_bands.py tutorial-inputs.json my-output.json Every map here is synthetic: Gaussian random fields drawn from frozen CAMB model spectra and a power-law dust model. Nothing is a BICEP/Keck, Planck or SPT map, and the gravitational-wave amplitude r is a hypothetical input. Lensing B is drawn as a Gaussian field with the CAMB lensed BB spectrum, which ignores its non-Gaussian structure. """ import cmath import json import math import random import sys SCRIPT_VERSION = "ac70-recompute-e-b-v1" PLANCK_OVER_BOLTZMANN_K_PER_GHZ = 0.0479924 def fft(values, inverse=False): """Iterative radix-2 FFT of a list of complex numbers (length a power of two). No 1/N on inverse.""" n = len(values) data = list(values) j = 0 for i in range(1, n): bit = n >> 1 while j & bit: j ^= bit bit >>= 1 j |= bit if i < j: data[i], data[j] = data[j], data[i] length = 2 sign = 1.0 if inverse else -1.0 while length <= n: step = cmath.exp(sign * 2j * math.pi / length) for start in range(0, n, length): twiddle = 1.0 + 0j half = length // 2 for k in range(half): even = data[start + k] odd = data[start + k + half] * twiddle data[start + k] = even + odd data[start + k + half] = even - odd twiddle *= step length *= 2 return data def fft2(grid, n, inverse=False): """2D FFT of a row-major n x n grid (rows along y, columns along x). Inverse divides by n^2.""" rows = [fft(grid[r * n:(r + 1) * n], inverse) for r in range(n)] out = [0j] * (n * n) for c in range(n): column = fft([rows[r][c] for r in range(n)], inverse) for r in range(n): out[r * n + c] = column[r] / (n * n) if inverse else column[r] return out class Patch: """Flat-sky patch: multipole of each Fourier cell, and the angle of its wavevector.""" def __init__(self, size, side_degrees, band_limit): self.n = size self.side = math.radians(side_degrees) self.pixel = self.side / size self.pixel_arcmin = side_degrees * 60.0 / size self.fundamental = 2.0 * math.pi / self.side self.ell, self.angle, self.keep = [], [], [] for r in range(size): ky = r if r < size // 2 else r - size for c in range(size): kx = c if c < size // 2 else c - size lx, ly = kx * self.fundamental, ky * self.fundamental ell = math.hypot(lx, ly) self.ell.append(ell) self.angle.append(math.atan2(ly, lx)) # Drop the mean, the unpaired Nyquist lines and everything above the band limit. self.keep.append(0.0 < ell <= band_limit and abs(kx) < size // 2 and abs(ky) < size // 2) def interpolate(nodes, values, ell): """Log-log interpolation in ell; linear where a value is zero (tensors vanish at high ell).""" if ell <= nodes[0]: i = 0 elif ell >= nodes[-1]: i = len(nodes) - 2 else: i = max(k for k in range(len(nodes) - 1) if nodes[k] <= ell) x0, x1, y0, y1 = nodes[i], nodes[i + 1], values[i], values[i + 1] if y0 <= 0.0 or y1 <= 0.0: t = min(1.0, max(0.0, (ell - x0) / (x1 - x0))) return max(0.0, y0 + t * (y1 - y0)) t = math.log(ell / x0) / math.log(x1 / x0) return math.exp(math.log(y0) + t * (math.log(y1) - math.log(y0))) def gaussian_modes(patch, spectrum, rng): """Fourier modes of a Gaussian field: FFT of white noise times sqrt(C_ell)/pixel side.""" white = [complex(rng.gauss(0.0, 1.0), 0.0) for _ in range(patch.n * patch.n)] modes = fft2(white, patch.n) return [m * math.sqrt(spectrum(patch.ell[i])) / patch.pixel if patch.keep[i] else 0j for i, m in enumerate(modes)] def q_u_maps(patch, e_modes, b_modes): """Q(l) = E cos 2phi - B sin 2phi and U(l) = E sin 2phi + B cos 2phi, returned as real maps.""" q_modes, u_modes = [], [] for i, phi in enumerate(patch.angle): c, s = math.cos(2.0 * phi), math.sin(2.0 * phi) q_modes.append(e_modes[i] * c - b_modes[i] * s) u_modes.append(e_modes[i] * s + b_modes[i] * c) q = [value.real for value in fft2(q_modes, patch.n, inverse=True)] u = [value.real for value in fft2(u_modes, patch.n, inverse=True)] return q, u def e_b_modes(patch, q_map, u_map, angle_factor=2): """E = Q cos(k phi) + U sin(k phi), B = -Q sin(k phi) + U cos(k phi), with k = 2 for spin 2.""" q_modes = fft2([complex(v, 0.0) for v in q_map], patch.n) u_modes = fft2([complex(v, 0.0) for v in u_map], patch.n) e, b = [], [] for i, phi in enumerate(patch.angle): c, s = math.cos(angle_factor * phi), math.sin(angle_factor * phi) keep = 1.0 if patch.keep[i] else 0.0 e.append(keep * (q_modes[i] * c + u_modes[i] * s)) b.append(keep * (-q_modes[i] * s + u_modes[i] * c)) return e, b def band_powers(patch, modes, edges, normalization=1.0, model=None): """Mean D_ell over each band, D = ell(ell+1)|F|^2 pixel^2 / (2 pi n^2), divided by a mask factor.""" rows = [] for low, high in zip(edges[:-1], edges[1:]): members = [i for i in range(len(modes)) if patch.keep[i] and low <= patch.ell[i] < high] to_d = lambda i: patch.ell[i] * (patch.ell[i] + 1.0) / (2.0 * math.pi) measured = sum(to_d(i) * abs(modes[i]) ** 2 * patch.pixel ** 2 / patch.n ** 2 for i in members) / len(members) / normalization row = {"band": [low, high], "modes": len(members), "measured": measured} if model is not None: expected = sum(to_d(i) * model(patch.ell[i]) for i in members) / len(members) # A real map pairs l with -l, so a band holds half as many independent modes. row.update({"expected": expected, "sigma": expected * math.sqrt(2.0 / len(members))}) rows.append(row) return rows def dust_power_factor(nu, temperature, index, reference, cmb_temperature): """Dust power at nu relative to the reference frequency, in CMB thermodynamic temperature units.""" def graybody(f): return f ** (3.0 + index) / math.expm1(PLANCK_OVER_BOLTZMANN_K_PER_GHZ * f / temperature) def blackbody_slope(f): x = PLANCK_OVER_BOLTZMANN_K_PER_GHZ * f / cmb_temperature return f ** 4 * math.exp(x) / math.expm1(x) ** 2 amplitude = graybody(nu) / graybody(reference) * blackbody_slope(reference) / blackbody_slope(nu) return amplitude ** 2 def rounded(value, digits=6): if isinstance(value, float): return float(f"{value:.{digits}g}") if isinstance(value, list): return [rounded(v, digits) for v in value] if isinstance(value, dict): return {k: rounded(v, digits) for k, v in value.items()} return value def tensor_ratio_estimate(rows, lensing, tensor_per_r, noise, bands): """Inverse-variance estimate of r from B bands after subtracting the lensing and noise expectations.""" numerator = denominator = 0.0 for b in bands: variance = rows[b]["sigma"] ** 2 numerator += (rows[b]["measured"] - lensing[b] - noise[b]) * tensor_per_r[b] / variance denominator += tensor_per_r[b] ** 2 / variance return numerator / denominator, 1.0 / math.sqrt(denominator) def main(input_path, output_path): with open(input_path, encoding="utf-8") as handle: inputs = json.load(handle) edges = inputs["bandEdges"] patch = Patch(inputs["grid"]["size"], inputs["grid"]["sideDegrees"], edges[-1]) s = inputs["spectra"] ee = lambda ell: interpolate(s["ell"], s["lensedScalarEE"], ell) lens_bb = lambda ell: interpolate(s["ell"], s["lensedScalarBB"], ell) tensor_bb = lambda ell: interpolate(s["ell"], s["tensorBBPerUnitR"], ell) dust = inputs["dust"] dust_bb_353 = lambda ell: dust["amplitude353"] * (ell / dust["pivotEll"]) ** dust["bandPowerSlope"] * 2.0 * math.pi / (ell * (ell + 1.0)) dust_ee_353 = lambda ell: dust_bb_353(ell) * 2.0 # BK18 fixes dust EE/BB = 2 as_d = lambda spectrum: (lambda ell: ell * (ell + 1.0) * spectrum(ell) / (2.0 * math.pi)) outputs = {"script": SCRIPT_VERSION, "python": sys.version.split()[0], "inputs": inputs["inputsVersion"], "units": inputs["units"], "provenance": "synthetic Gaussian fields from model spectra; not an observation", "runs": {}} zero = lambda ell: 0.0 for name, run in inputs["runs"].items(): rng = random.Random(run["seed"]) tensor = lambda ell, r=run["tensorRatio"]: r * tensor_bb(ell) cmb_bb = lambda ell: lens_bb(ell) + tensor(ell) e_true = gaussian_modes(patch, ee, rng) b_true = gaussian_modes(patch, cmb_bb, rng) if run["includeB"] else [0j] * len(e_true) result = {"units": "band powers D_ell in muK^2; sigma is the scatter expected from the number of modes"} if "frequencies" not in run: q, u = q_u_maps(patch, e_true, b_true) if "rotationDegrees" in run: psi = math.radians(2.0 * run["rotationDegrees"]) q, u = [qi * math.cos(psi) - ui * math.sin(psi) for qi, ui in zip(q, u)], [qi * math.sin(psi) + ui * math.cos(psi) for qi, ui in zip(q, u)] # Rotation moves sin^2 of the E power into B and leaves cos^2 in E, so BB/EE = tan^2(2 x angle). result["predictedBBOverEE"] = math.tan(psi) ** 2 masks = {"none": [1.0] * len(q)} if "maskHalfWidthFraction" in run: masks = {"hard": [], "tapered": []} n, half, taper = patch.n, run["maskHalfWidthFraction"], run["taperFraction"] for r in range(n): for c in range(n): dx, dy = abs((c + 0.5) / n - 0.5), abs((r + 0.5) / n - 0.5) inside = max(dx, dy) < half masks["hard"].append(1.0 if inside else 0.0) edge = lambda d: 1.0 if d < half - taper else 0.0 if d >= half else 0.5 - 0.5 * math.cos(math.pi * (half - d) / taper) masks["tapered"].append(edge(dx) * edge(dy)) result["masks"] = {} for mask_name, mask in masks.items(): weight = sum(m * m for m in mask) / len(mask) e_rec, b_rec = e_b_modes(patch, [qi * m for qi, m in zip(q, mask)], [ui * m for ui, m in zip(u, mask)], run.get("decompositionAngleFactor", 2)) ee_rows = band_powers(patch, e_rec, edges, weight, model=ee) bb_rows = band_powers(patch, b_rec, edges, weight, model=cmb_bb if run["includeB"] else None) entry = {"skyFraction": weight, "EE": ee_rows, "BB": bb_rows, "BBOverEE": [b["measured"] / e["measured"] for b, e in zip(bb_rows, ee_rows)]} if run["includeB"]: entry["chiSquareBB"] = sum(((row["measured"] - row["expected"]) / row["sigma"]) ** 2 for row in bb_rows) lensing = [row["expected"] for row in band_powers(patch, [0j] * len(b_rec), edges, model=lens_bb)] per_r = [row["expected"] for row in band_powers(patch, [0j] * len(b_rec), edges, model=tensor_bb)] estimate, sigma = tensor_ratio_estimate(bb_rows, lensing, per_r, [0.0] * len(edges), range(4)) entry["tensorRatioEstimate"] = {"value": estimate, "sigma": sigma, "bands": "first four bands, 30 <= ell < 220", "input": run["tensorRatio"]} result["masks"][mask_name] = entry else: assumed = run["assumedSpectralIndex"] factor = lambda nu, index: dust_power_factor(nu, dust["temperatureKelvin"], index, dust["referenceGHz"], inputs["cmbTemperatureKelvin"]) dust_e = gaussian_modes(patch, dust_ee_353, rng) dust_b = gaussian_modes(patch, dust_bb_353, rng) other_e = gaussian_modes(patch, dust_ee_353, rng) other_b = gaussian_modes(patch, dust_bb_353, rng) rho = run["dustCorrelation"] maps = {} for k, (nu, depth) in enumerate(zip(run["frequencies"], run["noise"])): scale = math.sqrt(factor(nu, dust["spectralIndex"])) mix = 1.0 if k == len(run["frequencies"]) - 1 else rho rest = math.sqrt(max(0.0, 1.0 - mix * mix)) de = [scale * (mix * a + rest * o) for a, o in zip(dust_e, other_e)] db = [scale * (mix * a + rest * o) for a, o in zip(dust_b, other_b)] noise_level = (depth / patch.pixel_arcmin) noise_q = [noise_level * rng.gauss(0.0, 1.0) for _ in range(patch.n * patch.n)] noise_u = [noise_level * rng.gauss(0.0, 1.0) for _ in range(patch.n * patch.n)] q, u = q_u_maps(patch, [a + d for a, d in zip(e_true, de)], [a + d for a, d in zip(b_true, db)]) dq, du = q_u_maps(patch, de, db) maps[nu] = {"q": [a + w for a, w in zip(q, noise_q)], "u": [a + w for a, w in zip(u, noise_u)], "dust_q": dq, "dust_u": du, "noise": (depth * math.pi / 10800.0) ** 2} low, high = run["frequencies"] a = math.sqrt(factor(low, assumed) / factor(high, assumed)) combos = {f"{low:g} GHz alone": (1.0, 0.0), f"{low:g} GHz minus scaled {high:g} GHz": (1.0 / (1.0 - a), -a / (1.0 - a))} lensing = [row["expected"] for row in band_powers(patch, [0j] * len(e_true), edges, model=lens_bb)] per_r = [row["expected"] for row in band_powers(patch, [0j] * len(e_true), edges, model=tensor_bb)] result["dustPowerFactorTo353"] = {f"{nu:g}": factor(nu, dust["spectralIndex"]) for nu in run["frequencies"]} result["cleaningCoefficient"] = a result["combinations"] = {} for label, (w_low, w_high) in combos.items(): q = [w_low * x + w_high * y for x, y in zip(maps[low]["q"], maps[high]["q"])] u = [w_low * x + w_high * y for x, y in zip(maps[low]["u"], maps[high]["u"])] noise = w_low ** 2 * maps[low]["noise"] + w_high ** 2 * maps[high]["noise"] residual_q = [w_low * x + w_high * y for x, y in zip(maps[low]["dust_q"], maps[high]["dust_q"])] residual_u = [w_low * x + w_high * y for x, y in zip(maps[low]["dust_u"], maps[high]["dust_u"])] _, b_rec = e_b_modes(patch, q, u) _, b_dust = e_b_modes(patch, residual_q, residual_u) noise_spectrum = lambda ell, level=noise: level expected_total = lambda ell: cmb_bb(ell) + noise bb_rows = band_powers(patch, b_rec, edges, model=expected_total) noise_bands = [row["expected"] for row in band_powers(patch, [0j] * len(b_rec), edges, model=noise_spectrum)] estimate, sigma = tensor_ratio_estimate(bb_rows, lensing, per_r, noise_bands, range(4)) dust_rows = band_powers(patch, b_dust, edges) result["combinations"][label] = { "weights": [w_low, w_high], "noiseMuKArcmin": math.sqrt(noise) * 10800.0 / math.pi, "BB": bb_rows, "dustResidualBB": [row["measured"] for row in dust_rows], "tensorRatioEstimate": {"value": estimate, "sigma": sigma, "bands": "first four bands, 30 <= ell < 220", "input": run["tensorRatio"]}, } outputs["runs"][name] = rounded(result) with open(output_path, "w", encoding="utf-8") as handle: json.dump(outputs, handle, indent=1) handle.write("\n") if __name__ == "__main__": main(sys.argv[1], sys.argv[2])