Map Builder

Abstract base classes for building HealSparse maps from simulation data, with I/O and spherical harmonic transform support. Their statistics are in Statistics.

Base class of the map builders (MapBuilder).

Handles file names and I/O of the maps (HealSparse or dense HEALPix files, MapBuilder.map_format), spherical harmonic transforms and smoothing on their footprint (Footprint), and plots of the maps. Their statistics (tracers and predictions, power spectra, moments) are methods inherited from MapStatistics.

class pollux.map_builder.MapBuilder(nmaps, dtype, footprint, io, product, nside_c=32, map_format='healsparse', nocompress=True, sacc_type=None, remove_monopole=True, b=None, pixel_window=True)[source]

Bases: MapStatistics, ABC

Base class to build, store, and analyze Healpix/HealSparse maps.

This class centralizes: - file naming and I/O for HealSparse maps, - alm computation (Healpy), on its footprint (Footprint), - plots of the maps,

and inherits their statistics from MapStatistics (pseudo-C_ell and decoupled bandpowers with NaMaster, SACC export, predictions and plots).

Subclasses must implement _create_tracers() and construct_maps() (abstract). _noise_cls() is optional, needed only for noise-aware predictions.

Parameters:
  • nmaps (int) – Number of maps handled/produced by this builder.

  • dtype (data-type) – Data type used to store map values (dtype for arrays written to HealSparse/Healpix maps and intermediate map buffers).

  • footprint (pollux.footprint.Footprint) – Footprint of the maps (resolution, mask, padding, weights of the harmonic transforms), shared with the builders made from this one.

  • io (pollux.io.files.PolluxIO) – Files of the products, with the options of the builder (e.g. its seed, matter model or n(z)).

  • product (str) – Product of the builder (e.g. 'shells', 'kappa'): its files are io.path(product, ...).

  • nside_c (int, optional) – HealSparse coverage nside. Default is 32.

  • map_format ({'healsparse', 'healpix'}, optional) – Format of the map files: HealSparse maps (NESTED, .fits, the default), or dense full-sky HEALPix maps in RING ordering (healpy’s, .npy), with hp.UNSEEN outside the padded footprint. The maps are computed as dense RING maps (as the harmonic transforms need them) and converted only when written or read in the other format (pollux.utils.healpix). Files of either format are read (iter_maps()).

  • nocompress (bool, optional) – If True, disable HealSparse compression. Default is True.

  • sacc_type (str or None, optional) – SACC data type name used when saving spectra.

  • remove_monopole (bool, optional) – If True (default), subtract the (weighted) mean of maps over the alm weights before harmonic transforms (_alm_field()). Other uses of maps (field_map()) keep their mean.

  • b (pymaster.NmtBin or None, optional) – NaMaster binning of the power spectra. Default is None: 20 logarithmic bands from ell = 8 to 2 * nside, dividing out the pixel window with pixel_window (b). The names of the workspaces identify a binning by its bands and pixel_window, not by a window of its own (not readable from a NmtBin): give distinct binnings distinct bands.

  • pixel_window (bool, optional) – Whether the maps carry the Healpix pixel window (True by default: maps of pixel averages). The default binning divides it out of the bandpowers, and the predictions apply it to the theory before binning, so that they match the measured bandpowers with any binning.

Notes

Healpix ordering: HealSparse maps and the footprint’s pixels are NESTED, dense maps (and the harmonic transforms) RING.

smoothed_field_what: str | None = None
MAP_FORMATS = ('healsparse', 'healpix')
property save_dir: str

Directory of the products of the builder (io.dir(product)).

property map_name: str

Name of the maps in their files (e.g. 'shell', 'kappa', pollux.io.files.PolluxIO.MAP_NAMES).

property map_dtype: dtype

the builder’s dtype, or float32 for an integer one (particle counts).

Type:

dtype of the maps of fields

path(imap=None, sub=None, what=None, smooth_Mpc=None, extra=None, ext=None)[source]

Return the path of a file of the products (or of their intermediate files).

Parameters:
  • imap (int or None, optional) – Map index (e.g. shell, or tomographic bin).

  • sub (int or str or None, optional) – Sub-volume of the map (intermediate file).

  • what (str or None, optional) – Field or product (e.g. 'gamma1', 'density', 'cls', 'alms'), replacing map_name in the name. The smoothing scale goes in smooth_Mpc.

  • smooth_Mpc (float or None, optional) – Comoving Gaussian smoothing scale in Mpc of the map.

  • extra (str or None, optional) – Additional string at the end of the name.

  • ext (str or None, optional) – File extension (without leading dot). Default is that of the format of the maps (map_format, or that of the sub-volume maps, _sub_ext) for map files, 'fits' for the others.

Returns:

{what or map_name}[_{index}][_sub{sub}][_{extra}].{ext} (pollux.io.files.PolluxIO.path()), with the index formatted as _index_format (e.g. 012 or bin3): in the directory of the maps smoothed at smooth_Mpc, in the intermediate files (subs/ for sub-volumes, and a_lm), or in the product’s directory.

Return type:

str

iter(it=None)[source]

Return an iterator over the requested indices.

Parameters:

it (Iterable[int] or int or None, optional) –

  • If None: iterate over range(self.nmaps).

  • If Iterable[int]: return the iterable as is.

  • If int: return a singleton list [it].

Returns:

Iterable over the requested map indices.

Return type:

range or Iterable[int] or list

Raises:

ValueError – If it is neither None, an int, nor an iterable of ints, or if indices are not in [0, self.nmaps).

tqdm(it=None, **tqdm_kwargs)[source]

Wrap an iterable of ints (or default range) with tqdm progress bars.

Parameters:
  • it (Iterable[int] or int or None, optional) –

    • If None: iterate over range(self.nmaps) using trange().

    • If Iterable[int]: wrap with tqdm().

    • If int: return a singleton list [it].

  • **tqdm_kwargs – Options of the progress bar (e.g. desc).

Returns:

Iterable with tqdm progress bar behavior.

Return type:

trange or tqdm or list

Raises:

ValueError – If it is neither None, an int, nor an iterable of ints, or if indices are not in [0, self.nmaps).

abstractmethod construct_maps(imaps=None)[source]

Construct maps, write them and return them.

Parameters:

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

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

iter_maps(imaps=None, isubs=None, allow_missing=False, desc='[iter_maps]', dense=False, **path_kwargs)[source]

Read maps from disk one at a time.

Unlike read_maps(), only one map is held in memory at a time, which allows looping over many large maps (e.g. to sum them).

Parameters:
  • imaps (int or array_like of int or None, optional) – Map indices to read. If None, reads all maps. Must be a single int if isubs is given.

  • isubs (iterable of int or str, or None, optional) – If provided, read the sub-maps isubs of map imaps (e.g. sub-volume indices, or 'orphan') instead of full maps.

  • allow_missing (bool, optional) – If True, skip missing files (logged) instead of raising FileNotFoundError.

  • desc (str, optional) – Progress bar description.

  • dense (bool or None, optional) – As dense RING maps (True), HealSparse maps (False, the default), or as stored (None): files of any format are read, by their extension: .npy for dense RING maps, .npz for RING pixel-value pairs (ipix, values) of sub-volumes (see _to_dense()), HealSparse otherwise.

  • **path_kwargs – Extra keywords forwarded to path() (e.g. what='kappa').

Yields:
  • index (int or str) – Map index, or sub index if isubs is given.

  • map (ndarray or hsp.HealSparseMap or tuple) – The map read from disk.

Return type:

Iterator[tuple[int | str, np.ndarray | hsp.HealSparseMap]]

read_maps(imaps=None, dense=False, **path_kwargs)[source]

Read one or multiple maps from disk.

Parameters:
  • imaps (int or array_like of int or None, optional) – Map indices to load. If None, loads all maps.

  • dense (bool or None, optional) – As dense RING maps (True), HealSparse maps (False, the default), or as stored (None), see iter_maps().

  • **path_kwargs – Extra keywords forwarded to path() (e.g. what='kappa').

Returns:

  • If imaps is a single int: returns a single map.

  • If imaps is None or an iterable: returns a dict keyed by map index with maps as values.

Return type:

ndarray or hsp.HealSparseMap, or dict

field_map(imap, smooth_Mpc=None)[source]

Return the field of one map as a dense RING map.

Parameters:
  • imap (int) – Map index.

  • smooth_Mpc (float or None, optional) – Smoothing scale in Mpc: the smoothed field saved by compute_maps_from_alms() (what=smoothed_field_what). Default is the unsmoothed field.

Returns:

The map on disk (subclasses may convert it, e.g. counts to density contrast), with the sentinel of its dtype (hp.UNSEEN) outside the padded footprint.

Return type:

ndarray

compute_alms(imaps=None, **map2alm_kwargs)[source]

Compute the spherical harmonic coefficients a_lm of maps, and save them (intermediate files).

Parameters:
  • imaps (int or array_like of int or None, optional) – Map indices. If None, uses all maps.

  • **map2alm_kwargs – Forwarded to healpy.map2alm().

Returns:

The a_lm of imaps if an int, else {imap: alm}.

Return type:

ndarray or dict

Notes

The a_lm are those of _alm_field() times the alm weights. They are read back with read_alms().

read_alms(imaps=None)[source]

Read the a_lm saved by compute_alms().

Parameters:

imaps (int or array_like of int or None, optional) – Map indices. If None, uses all maps.

Returns:

The a_lm of imaps if an int, else {imap: alm}.

Return type:

ndarray or dict

Raises:

FileNotFoundError – If the a_lm of a map are not saved.

compute_maps_from_alms(imaps=None, smooth_Mpc=None)[source]

Compute field maps from their a_lm, optionally smoothed.

Parameters:
  • imaps (int or array_like of int or None, optional) – Map indices. If None, uses all maps.

  • smooth_Mpc (float or None, optional) – Comoving Gaussian smoothing scale in Mpc (converted to an angle per map, see _smooth_sigma()). If given, the smoothed maps (pixel window deconvolved) are saved (what=smoothed_field_what); if None, the maps are only reconstructed in memory.

Returns:

Map(s) on the padded footprint: as written with smooth_Mpc (map_format), dense RING maps otherwise (_to_dense()).

Return type:

ndarray or hsp.HealSparseMap, or dict

Notes

The a_lm are those saved by compute_alms() (of the weighted map, up to their lmax), so the maps are the field (with its mean added back, see _alm_field_mean()) on the footprint, but tapered in the padding.

plot_maps(maps_or_imaps=None, plot_dir=None, nx=None, log=False, title_prefix=None, cbar=True, save=True, backend='skyproj', nside_plot=1024, **kwargs)[source]

Plot one or multiple maps.

Parameters:
  • maps_or_imaps (int or iterable or None, optional) –

    • If None: loads and plots all maps.

    • If int: loads and plots that map index.

    • If iterable of int: loads and plots those indices.

    • If iterable of maps: plots provided maps directly (HealSparse maps, dense RING maps or RING pixel-value pairs, see _to_dense()).

  • plot_dir (str or None, optional) – Output directory, with save. Default is {save_dir}/plots.

  • nx (int or None, optional) – Number of columns in the subplot grid. Default is a near-square grid.

  • log (bool, optional) – If True, plot the map on a logarithmic color scale. With backend='healpy', plots log10(map) when the map has positive values. With backend='skyproj', uses norm='log' in skyproj.Skyproj.draw_hspmap() if log(values) are all finite over the valid pixels, otherwise falls back to norm='symlog'.

  • title_prefix (str or None, optional) – Prefix used for subplot titles.

  • cbar (bool, optional) – If True, display a colorbar.

  • save (bool, optional) – If True, save the figure to {plot_dir}/{map_name}_maps.png.

  • backend ({'skyproj', 'healpy'}, optional) – Plotting backend. With 'skyproj' (default), uses skyproj.MollweideSkyproj for full sky and octant footprints, and skyproj.McBrydeSkyproj otherwise. With 'healpy', uses healpy.orthview() (octant footprint) or healpy.mollview() (full sky or custom mask).

  • nside_plot (int or None, optional) – Maps of higher nside are degraded to it before drawing (default 1024, finer than the panels’ resolution): the figure then only holds these copies, not the full-resolution maps. None draws the maps as they are.

  • **kwargs – Forwarded to healpy.orthview()/healpy.mollview() (for backend='healpy') or to skyproj.Skyproj.draw_hspmap() (for backend='skyproj').

Return type:

None

class pollux.map_builder.MapSum(footprint, nside_coverage, dtype)[source]

Bases: object

Weighted sum of maps over the padded footprint, accumulated in place, from maps of any kind.

Maps are added one at a time, so only one input map needs to be in memory at a time (hsp.operations.sum_union needs all maps at once, or rebuilds the output for every pairwise sum). The sum is in the representation of the first map added: HealSparse maps are summed in the output’s own sparse array, by NESTED blocks, and dense RING maps and RING pixel-value pairs (ipix, values) (see MapBuilder._to_dense()) in a dense RING map, without conversion.

Parameters:
  • footprint (pollux.footprint.Footprint) – Footprint of the maps: every pixel of its padded footprint has a value in the sum, starting at zero.

  • nside_coverage (int) – Coverage nside of a HealSparse sum.

  • dtype (data-type) – dtype of the sum.

Notes

In a HealSparse sum, built from sorted coverage pixels, block k of the sparse array (after the leading sentinel block) holds the NESTED pixels of coverage pixel cov_pix[k].

add(m, scale=1.0, offset=0.0)[source]

Add scale * m + offset on the pixels of m with a value.

Parameters:
  • m (ndarray or hsp.HealSparseMap or tuple) – Map to add, of the nside of the footprint, with values inside the padded footprint: dense RING map (values where not its sentinel), HealSparse map (on its valid pixels, of coverage nside nside_coverage), or RING pixel-value pair (ipix, values) (values on distinct RING pixels).

  • scale (float, optional) – Factor applied to the map values.

  • offset (float, optional) – Constant added on each pixel of m with a value.

Return type:

None

to_map()[source]

Return the sum (sharing memory with this accumulator).

Returns:

Sum of the added maps, with a value on every pixel of the padded footprint: a HealSparse map for HealSparse maps, a dense RING map otherwise (also without any map added).

Return type:

ndarray or hsp.HealSparseMap