Shells

Builds particle and halo lightcone shells with replicated boxes and random isometries (translations, rotations, flips).

Lightcone shells from N-body particles or halos (ShellBuilder and subclasses).

Replicates and transforms the simulation boxes (random isometries), counts the particles in pixels, and computes tidal fields.

class pollux.shells.ShellBuilder(nshells, reader, footprint, seed=12345, dtype=<class 'numpy.float32'>, apply_grid_isometry=False, group_isometries=None, apply_replicate_rotflip=False, subsample_box=None, io=None, sub_format='healsparse', **kwargs)[source]

Bases: MapBuilder

Construct HealSparse shell maps from simulation particle data.

A shell is a radial bin in comoving distance (or equivalently redshift). For each shell, this builder produces a HealSparse map of particle counts (or optionally density / density contrast), computed by reading simulation sub-volumes, applying optional isometries, and replicating the periodic box to cover the shell volume.

This class also provides utilities to: - define shell edges from snapshot redshifts, - compute expected pixel/sky densities, - combine per-subvolume shell maps into final maps, - compute tidal-tensor maps from density maps.

Parameters:
  • nshells (int) – Number of shells to build.

  • reader (pollux.reader.Reader) – Simulation reader returning particle positions for each snapshot/sub-volume.

  • footprint (pollux.footprint.Footprint) – Footprint of the shell maps (resolution, mask, padding), shared with the builders made from this one, with the files of the root directory (footprint.io): the shells go to the 'shells' product ('halos' for a halo reader) of its realization seed{seed}/. For the 'octant' footprint, particles outside x>0, y>0, z>0 are discarded during map construction.

  • seed (int, optional) – Seed of the realization: its directory (seed{seed}/), and the random isometries, rotation/flips and subsampling.

  • dtype (data-type, optional) – dtype used to store shell map values (particle counts, and the maps derived from them). Default is float32.

  • apply_grid_isometry (bool or sequence, optional) – If True, apply one random affine isometry per shell to the underlying particle distribution: xyz' = A(xyz + b) with random orthogonal-ish rotation/permutation/flip (A) and translation (b). If an iterable of length nshells is provided, it is interpreted as user-provided [(A0, b0), (A1, b1), ...].

  • group_isometries (bool or float or None, optional) – If set, reuse the same isometry across multiple consecutive shells until a maximum radial width is reached. If True, uses dchi_max = boxsize. If float, uses dchi_max = group_isometries * boxsize.

  • apply_replicate_rotflip (bool or dict, optional) – If True, apply HACC-style discrete rotations (6) and sign flips (8) to each replicate (48 configs). If a dict is provided, it maps replicate indices (ix, iy, iz) to a rotation code in [0, 48). This option is mutually exclusive with apply_grid_isometry.

  • subsample_box (float or dict or None, optional) –

    Particle subsampling configuration:

    • If float in (0, 1], keep that fraction of particles per sub read.

    • If dict with key 'densitymax_z': choose ratios per shell to keep per-pixel S/N comparable to the shell at that redshift.

    • If dict with key 'clmax_r': choose ratios per shell so that shot noise is below theory C_ell at lmax by the requested factor.

  • io (pollux.io.files.PolluxIO or None, optional) – Files of the shells, if not those of the footprint with the seed (e.g. with the options of a baryon model).

  • sub_format ({'healsparse', 'healpix'}, optional) – Format of the maps of the sub-volumes (intermediate files), binned in the matching ordering so that they are written without conversion: HealSparse maps of the non-empty pixels (NESTED, the default), or the RING pixels and counts of the non-empty pixels (.npz, ipix and counts; full-sky dense maps of each sub-volume would be too large). The shells are written in map_format, converted once when combined if needed.

  • **kwargs – Forwarded to pollux.map_builder.MapBuilder (e.g. map_format).

Notes

  • apply_grid_isometry and apply_replicate_rotflip do not commute; only one should be used at a time.

Variables:

smoothed_field_what (str) – what of the smoothed density maps ('density'), see compute_maps_from_alms().

Parameters:
smoothed_field_what: str | None = 'density'
config()[source]

Return the configuration of the products, for their config.yaml (pollux.io.config.write_config()).

Returns:

product ('halos' or 'shells'), parameters (simulation: path, kind, box, particles, snapshots; cosmology: CCL parameters; seed and isometries of the shells) and inputs (the footprint, with the resolution and mask).

Return type:

dict

property shell_edges_redshift: ndarray[source]

one shell around each snapshot, its edges placed by shell_edges_match.

Returns:

Length nshells + 1.

Return type:

ndarray

Raises:

ValueError – If shell_edges_match is invalid.

Type:

Redshifts of the shell edges

property shell_edges_comoving_distance: ndarray[source]

Comoving distances to shell edges.

ndarray

Comoving radial distances (Mpc) of all shell edges. Length is nshells + 1.

mean_redshift_volume(ishell)[source]

Compute the volume-weighted mean redshift of a shell.

Parameters:

ishell (int) – Shell index.

Returns:

Mean redshift in the shell, weighted by the comoving volume element.

Return type:

float

info_table()[source]

Return the table of the shells.

Returns:

Structured array, one row per shell: ishell, redshift and comoving distance (Mpc) edges (zmin, zmax, chimin, chimax), and for snapshot shells the snapshot (zsnapshot, chisnapshot, snapshot_id), then the mean number of particles per pixel (pixel_density) and per steradian (sky_density), which turn counts into density contrasts.

Return type:

ndarray

write_info()[source]

Save the table of the shells (info_table()) to shells.fits, unless it exists.

The table follows from the configuration of the products, which pollux.io.config.write_config() checks against the existing one, so an existing table is the same.

Return type:

None

random_isometries(group_isometries=None, get_shell_identifier=False)[source]

Generate random affine isometries for shells.

Parameters:
  • group_isometries (bool or float or None, optional) – If provided, reuse a given isometry across multiple shells until the cumulative shell width exceeds dchi_iso_max (see class docstring).

  • get_shell_identifier (bool, optional) – If True, also return a mapping from shell index to isometry id.

Returns:

  • list – List of length nshells of (A, b) pairs where: - A is a (3,3) matrix (rotation/permutation/flip), - b is a (3,) translation vector.

  • dict, optional – Only if get_shell_identifier=True. Maps ishell -> iso_id.

Return type:

list

Notes

Each isometry moves the particles of a box (and all its replicas) as

\[\mathbf{x}' = (\mathbf{x} + \mathbf{b})\, A, \qquad A = R\, \mathrm{diag}(s_1, s_2, s_3),\]

with \(R\) a uniformly random rotation, \(s_k = \pm 1\) random flips and \(\mathbf{b}\) a uniformly random translation in \([0, L)^3\); the replica \(\mathbf{n} \in \mathbb{Z}^3\) is shifted by \(L\, \mathbf{n} A\). With group_isometries, consecutive shells share an isometry until their cumulative radial width would exceed group_isometries times the box size \(L\), so that structures are not cut at each shell.

property valid_replicas: list[source]

Valid replica indices for each (snapshot, sub-volume) job.

Reads only box edges (no particle data) and calls _valid_replicas_sub() to determine which periodic-box replicas overlap each shell.

Returns:

List of tuples (ijob, replicates) where replicates is a list of (ix, iy, iz) replica indices that may overlap the shell.

Return type:

list

estimate_replicates(ishell)[source]

Estimate how many periodic-box replicates are needed (volume ratio).

Parameters:

ishell (int) – Shell index.

Returns:

Approximate number of box volumes required to fill the shell volume, accounting for octant-only mode if enabled.

Return type:

float

subsample_ratio(ishell)[source]

Return the particle subsampling ratio applied for a given shell.

Parameters:

ishell (int) – Shell index.

Returns:

Fraction of particles retained when reading sub-volumes for this shell.

Return type:

float

Raises:

ValueError – If subsample_box has an unsupported type or key.

Notes

With {'densitymax_z': z*}, shells keep the fraction

\[r_i = \min\left(1, \frac{\bar N(z_*)}{\bar N_i}\right), \qquad \bar N_i = \frac{4\pi (\chi_{i+1}^3 - \chi_i^3)}{3}\, \frac{N_p}{L^3 N_{\rm pix}},\]

where \(\bar N_i\) is the mean number of particles per pixel of shell \(i\) (\(N_p\) particles in a box of side \(L\), \(N_{\rm pix}\) pixels on the sky) and \(\bar N(z_*)\) its value interpolated at \(z_*\) in the volume-weighted mean redshift of the shells: beyond \(z_*\), the particle shot noise per pixel stays that of the shell at \(z_*\). With {'clmax_r': r}, the shot noise \(1 / (r_i \bar n_i)\) (\(\bar n_i\) per steradian) is \(r\) times below the predicted \(C_\ell\) at the largest multipole.

box_comoving_density(ishell)[source]

Return the comoving particle number density after subsampling.

Parameters:

ishell (int) – Shell index.

Returns:

Effective comoving particle density (Mpc^-3).

Return type:

float

pixel_density(ishell)[source]

Return the expected mean number of particles per pixel in a shell.

Parameters:

ishell (int) – Shell index.

Returns:

Mean particles per pixel expected from comoving density and shell volume.

Return type:

float

sky_density(ishell, degrees=False)[source]

Return the expected mean number of particles per unit solid angle.

Parameters:
  • ishell (int) – Shell index.

  • degrees (bool, optional) – If True, return per square degree. If False, return per steradian.

Returns:

Mean surface density (particles / sr or particles / deg^2).

Return type:

float

construct_maps(imaps=None)[source]

Construct all requested shell maps.

This constructs sub-maps for each (shell, subvolume) and then calls combine_maps_subs() to produce final shell maps.

Parameters:

imaps (int or array_like of int or None, optional) – Shell indices to construct. If None, constructs all shells.

Returns:

The maps as written (map_format): a single map if imaps is an int, else a dict keyed by map index.

Return type:

ndarray or hsp.HealSparseMap, or dict

combine_maps_subs(ishells=None, allow_missing_subs=False)[source]

Sum per-subvolume shell maps into final per-shell maps.

Parameters:
  • ishells (int or array_like of int or None, optional) – Shell indices to combine. If None, combines all shells.

  • allow_missing_subs (bool, optional) – If True, iterate sub indices and skip missing files silently. Deprecated — only kept as a workaround for incomplete runs where not all sub-files were produced. Prefer completing all subs first.

Returns:

The maps as written (map_format): a single map if ishells is an int, else a dict keyed by shell index. The sub-volume maps are summed as stored (MapSum).

Return type:

ndarray or hsp.HealSparseMap, or dict

Notes

The maps summed are those of _subs() (with the orphan particles for SnapshotInterpShellBuilder). Every pixel of the padded footprint has a count (zero if empty).

field_map(ishell, smooth_Mpc=None)[source]

Return the density contrast of one shell as a dense RING map.

Parameters:
Returns:

Density contrast relative to the cosmic mean, on the padded footprint: shell_count / pixel_density - 1 (-1 on empty pixels), hp.UNSEEN outside.

Return type:

ndarray

compute_tidal_tensor_maps(ishells=None, smooth_Mpc=None, save_field_map=True)[source]

Compute tidal tensor component maps from shell density maps.

For each shell, computes a spin-2 transform of the E-mode a_lm of the density map (saved by compute_alms()), and combines it with the density (trace) to obtain approximate 2D tidal components (t11, t22, t12) on the sky:

t11 = delta / 6 + Q / 2,  t22 = delta / 6 - Q / 2,  t12 = U = 2 s12

with (Q, U) the spin-2 field of the density (as the shear from the convergence), Q = s11 - s22, and the trace delta / 3 of the 3D tidal field removed. t12 is twice the off-diagonal component, so that the tidal alignment is e1 = C1 (t11 - t22), e2 = C1 t12 (see pollux.ia).

Parameters:
  • ishells (int or array_like of int or None, optional) – Shell indices to process. If None, process all.

  • smooth_Mpc (float or None, optional) – Comoving Gaussian smoothing scale in Mpc of the density a_lm (angular width at the shell’s far edge, see _smooth_sigma()).

  • save_field_map (bool, optional) – With smooth_Mpc, also save the smoothed density map, from the same a_lm (as compute_maps_from_alms()). Default is True.

Returns:

[t11, t22, t12] as written (map_format, as what='t11', 't22', 't12', in smoothed/{smooth_Mpc}Mpc/ if smoothed) if ishells is an int, else a dict of them keyed by shell index.

Return type:

list or dict

Notes

With \((Q, U)\) the spin-2 maps of the density contrast \(\delta\) of the shell (its E-mode \(a_{\ell m}\) multiplied by \(\sqrt{(\ell - 1)(\ell + 2) / (\ell (\ell + 1))}\), as the shear from the convergence),

\[t_{11} = \frac{\delta}{6} + \frac{Q}{2}, \qquad t_{22} = \frac{\delta}{6} - \frac{Q}{2}, \qquad t_{12} = U,\]

the transverse part of the traceless tidal tensor \(s_{ij} = (\partial_i \partial_j / \nabla^2 - \delta_{ij} / 3)\, \delta\), for a shell with no line-of-sight component: \(t_{11} + t_{22} = \delta / 3\).

snapshot_lensing_builder(tag='snapshots')[source]

Return a lensing builder with one convergence map per shell snapshot.

Parameters:

tag (str or None, optional) – Name of the output subdirectory, kappa/{tag} (default kappa/snapshots).

Return type:

pollux.lensing.SnapshotBornLensingBuilder

class pollux.shells.SnapshotShellBuilder(reader, footprint, io=None, shell_edges_match='center_scale_factor', **kwargs)[source]

Bases: ShellBuilder

ShellBuilder specialized for snapshot-based shells.

This builder defines shell edges from snapshot redshifts using the selected shell_edges_match strategy and constructs each shell by replicating the periodic snapshot box in comoving coordinates.

Parameters:
  • reader (pollux.reader.Reader) – Simulation snapshot reader.

  • footprint (pollux.footprint.Footprint) – Footprint of the shell maps.

  • io (optional) – See ShellBuilder.

  • shell_edges_match ({'center_redshift','center_scale_factor','center_comoving_distance','center_comoving_volume'}, optional) – Defines how shell edges are placed relative to snapshot centers.

  • **kwargs – Forwarded to ShellBuilder.

construct_maps_sub(ishell, isub, ijob=None)[source]

Construct a single shell map for one snapshot/sub-volume.

Parameters:
  • ishell (int) – Shell index.

  • isub (int) – Sub-volume index.

  • ijob (int or None, optional) – If provided, overrides (ishell, isub) using reader.job_args(ijob).

Returns:

Map of this sub-volume (_write_sub()).

Return type:

hsp.HealSparseMap or tuple

Notes

This method reads a sub-volume, optionally subsamples particles, applies optional isometries / rotflips, replicates the box to cover the shell, bins particles into healpix, and writes a HealSparse map.

construct_catalogs(ishells=None, extra_columns=None, **kwargs)[source]

Construct and save a per-shell (halo/particle) FITS catalog.

Parameters:
  • ishells (int or array_like of int or None, optional) – Shell indices to construct. If None, constructs all shells.

  • extra_columns (list of str, optional) – Extra properties to load using reader.read_props and store as additional FITS columns.

  • **kwargs – Forwarded to construct_catalog_sub() / reader.read_sub.

Returns:

  • If ishells is a single int: returns a FITS HDU list (primary HDU + one table HDU per sub-volume).

  • If ishells is None or an iterable: returns a dict keyed by shell index with FITS HDU list values.

Return type:

astropy.io.fits.HDUList or dict

Notes

Output filename is what='catalog' under path().

construct_catalogs_sub(ishell, isub, **kwargs)[source]

Construct a particle catalog for a given shell/sub-volume.

Parameters:
  • ishell (int) – Shell index.

  • isub (int) – Sub-volume index.

  • **kwargs – Forwarded to reader.read_sub.

Returns:

  • idx (ndarray) – Indices of selected particles in the input array (per replicate, concatenated).

  • ra (ndarray) – Right ascension in degrees.

  • dec (ndarray) – Declination in degrees.

  • r (ndarray) – Comoving radial distance (Mpc).

Return type:

tuple[ndarray, ndarray, ndarray, ndarray]

read_catalogs(ishells=None, variables=None)[source]

Read previously constructed per-shell catalogs as concatenated arrays.

Parameters:
  • ishells (int or array_like of int or None, optional) – Shell indices to load. If None, loads all shells.

  • variables (list of str or None, optional) – If None, return every column stored in the catalog (as saved by construct_catalogs(), e.g. 'ihaloes', 'ra', 'dec', 'chi', 'z', and any extra_columns). If given, any requested variable missing from the catalog is fetched from the reader via _read_props(), and the returned dict is restricted to exactly the requested variables.

Returns:

  • If ishells is a single int: mapping from column/variable name to 1D concatenated numpy arrays.

  • If ishells is None or an iterable: mapping from shell index to the per-shell dict described above.

Return type:

dict

class pollux.shells.LightconeShellBuilder(reader, footprint, io=None, shell_edges_match='center_scale_factor', **kwargs)[source]

Bases: ShellBuilder

ShellBuilder that slices a lightcone by stacking multiple snapshots.

For each shell, this builder reads multiple lightcone snapshots whose redshift range intersects the shell, concatenates particles, then bins them into a shell map.

Parameters:
  • reader (pollux.reader.Reader) – Lightcone-capable reader providing zsnapshots_fulllist and read_sub(isnapshot, isub) for lightcone snapshots.

  • footprint (pollux.footprint.Footprint) – Footprint of the shell maps.

  • io (optional) – See ShellBuilder.

  • shell_edges_match (str, optional) – Shell-edge placement strategy (same meaning as for SnapshotShellBuilder).

  • **kwargs – Forwarded to ShellBuilder.

construct_maps_sub(ishell, isub, ijob=None)[source]

Construct a single shell map for one lightcone sub-volume.

Parameters:
  • ishell (int) – Shell index.

  • isub (int) – Sub-volume index.

  • ijob (int or None, optional) – If provided, overrides (ishell, isub) using reader.job_args(ijob).

Returns:

Map of this sub-volume (_write_sub()).

Return type:

hsp.HealSparseMap or tuple

class pollux.shells.SnapshotInterpShellBuilder(reader, footprint, io=None, **kwargs)[source]

Bases: ShellBuilder

ShellBuilder that interpolates particle worldlines between snapshots.

This builder treats consecutive snapshot boxes as endpoints of particle worldlines and finds their intersections with a lightcone defined by a sequence of scale factors. It supports orphan handling when particles appear or disappear between snapshot subvolumes.

Parameters:

Notes

The shells lie between consecutive snapshots: nshells = nsnapshots - 1.

property shell_edges_redshift: ndarray[source]

the snapshots, the shells lying between consecutive ones.

Returns:

Length nshells + 1.

Return type:

ndarray

Type:

Redshifts of the shell edges

construct_maps_sub(ishell, isub, ijob=None, do_orphan_ishell=None)[source]

Construct one interpolated lightcone shell map for a sub-volume.

Parameters:
  • ishell (int) – Shell index: the interval between snapshots ishell and ishell + 1.

  • isub (int) – Sub-volume index.

  • ijob (int or None, optional) – If provided, overrides (ishell, isub) using reader.job_args(ijob).

  • do_orphan_ishell (int or None, optional) – If provided, build the orphan shell (stored under sub='orphan') by loading previously dumped orphan particle arrays.

Returns:

Map of this sub-volume (_write_sub()).

Return type:

hsp.HealSparseMap or tuple

Notes

The lightcone is approximated by a tabulated chi(a) curve between the two snapshots, and particle worldlines (linear in a) are intersected with it to determine sky positions via _worldline2pix_ring() (or _nest).