jax-fli-experiments / tools /make_spectra.py
ASKabalan's picture
Squash history (post parquet re-encode)
8b829ee
Raw
History Blame Contribute Delete
5.52 kB
import argparse
def parse_args():
parser = argparse.ArgumentParser(
description="Compute the angular power spectrum of a density catalog and write it as a "
"single stacked PowerSpectrum parquet."
)
parser.add_argument(
"--parquet-path",
type=str,
required=True,
help="Path / glob to the density parquet(s). One example (shell) per row.",
)
parser.add_argument(
"--output-path",
type=str,
required=True,
help="Path to save the processed dataset.",
)
parser.add_argument("--codec", default="SNAPPY", help="target compression codec (default: SNAPPY)")
parser.add_argument(
"--name",
type=str,
required=True,
help="Name (legend label) of the output dataset.",
)
parser.add_argument(
"--lmax",
type=int,
default=1500,
help="Maximum multipole moment. For masked (off-center observer) fields this is the "
"underlying lmax that is then binned into nlb-width bandpowers.",
)
parser.add_argument(
"--normalization",
type=str,
default="per_plane",
choices=["per_plane", "global"],
help="Normalization for the overdensity field.",
)
parser.add_argument(
"--deconvolve",
type=str,
default="none",
choices=["none", "ngp", "rbf"],
help="Spherical mass-assignment-window deconvolution applied to the overdensity before "
"the spectrum: 'none' (default), 'ngp' (HEALPix pixel window) or 'rbf' (-> 'rbf_neighbor').",
)
parser.add_argument(
"--nlb",
type=int,
default=16,
help="Bandpower bin width for the masked (off-center observer) estimator.",
)
parser.add_argument(
"--apodization-deg",
type=float,
default=2.0,
dest="apodization_deg",
help="Apodization scale (degrees) for the observer-visibility mask (off-center only).",
)
return parser.parse_args()
def main():
args = parse_args()
import jax
jax.config.update("jax_enable_x64", True)
import numpy as np
import pyarrow.parquet as pq
from datasets import load_dataset
from jax_fli.io import Catalog
from jax_fli import PowerSpectrum
from jax_fli import units, SphericalKappaField
from jax_fli.data.masks import build_observer_visibility_mask
from jax_fli.summary_statistics import compute_mcm
import jax.numpy as jnp
from tqdm.auto import tqdm
# Stream the dataset so big multi-shell globs do not int32-overflow on combine_chunks.
dataset = load_dataset("parquet", data_files=args.parquet_path, split="train", streaming=True)
deconv_method = None if args.deconvolve == "none" else {"rbf": "rbf_neighbor"}.get(args.deconvolve, args.deconvolve)
spectras = []
cosmology_prev = None
mask = None
mcm = None
mask_built = False
def tree_all_close(tree1, tree2, rtol=1e-5, atol=1e-8):
return jax.tree.all(jax.tree.map(lambda x, y: jnp.allclose(x, y, rtol=rtol, atol=atol), tree1, tree2))
for ds in tqdm(dataset , desc="Processing shells", unit=" shell"):
cat = Catalog.from_dataset(ds)
field , cosmology = cat.field[0], cat.cosmology[0]
if cosmology_prev is not None and not tree_all_close(cosmology, cosmology_prev):
raise ValueError("All shells must share the same cosmology.")
cosmology_prev = cosmology
# Observer-visibility mask + MCM are constant across shells (same observer/nside) -> build
# once. supersample=1 keeps the apodized footprint memory-bounded at nside 2048 (the
# supersample=4 default builds an nside*4=8192 grid -> ~0.8B pixels -> OOM). A center
# observer yields the scalar 1 -> mask=None (full sky, plain Cl).
if not mask_built:
vis = build_observer_visibility_mask(
field.observer_position, field.nside, apodization_scale_deg=args.apodization_deg, supersample=1
)
mask = None if jnp.ndim(vis) == 0 else vis
if mask is not None:
mcm = compute_mcm(mask, lmax=args.lmax, nlb=args.nlb, pol=False, method="healpy")
mask_built = True
if isinstance(field, SphericalKappaField):
# For kappa fields no conversion is needed
overdensity = field
else:
overdensity = field.to(units.OVERDENSITY, normalization=args.normalization)
if deconv_method is not None:
# Deconvolve at the field's native bandlimit (default 3*nside-1, which
# satisfies s2fft's lmax >= 2*nside-1); angular_cl truncates to args.lmax.
overdensity = overdensity.deconvolve(deconv_method)
spectra = overdensity.angular_cl(method="healpy", lmax=args.lmax, mask=mask, mcm=mcm, nlb=args.nlb)
# Per-shell density names differ; normalize before stacking so stack's name check passes.
spectras.append(spectra.replace(name=args.name))
# A single source row already yields an (S, n_ell) batched spectrum -> do not re-stack it.
stacked = spectras[0] if len(spectras) == 1 else PowerSpectrum.stack(spectras)
stacked = stacked.replace(name=args.name)
spec_cat = Catalog(field=stacked, cosmology=cosmology)
table = spec_cat.to_dataset().with_format("arrow")[:]
pq.write_table(table, args.output_path, compression=args.codec, use_dictionary=True)
if __name__ == "__main__":
main()