I/O

Products on disk: their files (PolluxIO, files), configurations (config), the code version of runs (code_version), their index (index) and loader (loader).

Without the dependencies of the builders, so that products can be read without the full pollux package: numpy, healpy, healsparse, pyccl, sacc, astropy and PyYAML, but not NaMaster, TreeCorr, BaryonForge or Parsl.

Layout of the output products (PolluxIO): where every file goes, and reading them back.

A root directory holds the products of one simulation on one footprint (Footprint, whose config.yaml is checked like those of the other products), for any number of seeds:

footprint/                      config.yaml, padded_mask.fits, alm_weights.fits, NaMaster workspaces of the
                                maps (wsp_b{binning}.wsp), shared by all seeds
seed{seed}/                     products of one realization
    halos/                      halo catalogs, shared by all baryon models
    dmo/                        dark-matter-only products
        shells/                 shell_{iii}.fits, cls.fits, shells.fits (table of the shells), smoothed/{s}Mpc/
                                (density_{iii}, t11_{iii}, t22_{iii}, t12_{iii})
        kappa/snapshots/        kappa_{iii}, gamma1_{iii}, gamma2_{iii} (one source plane per shell)
        kappa/{nz}/             kappa_bin{b}, gamma1_bin{b}, gamma2_bin{b}, nzs.txt, smoothed/{s}Mpc/
        catalogs/{nz}/{tag}/    cat_bin{b}.hdf5 (or .fits), binned_catalog.hdf5 and nzs.hdf5 (for TXPipe),
                                cat_2pt[_{shapes}].fits, cat_cls[_{shapes}].fits (shapes: ia,
                                shear_plus_ia, observed)
    dmb/{tag}/                  baryonified products, with the same subtree as dmo/
    intermediate/               files needed only to make or resume the products (sub-volume maps, a_lm,
                                partial catalogs, workspaces, statistics of each bin pair), at the same
                                relative paths
    code_version/{date}/        code and environment of each run

Each product directory (footprint, shells, halos, kappa, catalogs) holds a config.yaml with its parameters, inputs and code version (pollux.io.config), so that it can be shared (e.g. registered) on its own, and that a directory never mixes products of different parameters: the root directory of a run is up to the user, e.g. one per simulation and footprint.

class pollux.io.files.PolluxIO(root_dir, **options)[source]

Bases: object

Files of the products under one root directory: where builders and catalogs write them, and reading them back.

Every file follows one rule: {product directory}[/{folder}]/{name}.{ext}, with the name the parts given, joined by _ (e.g. ('kappa', 'bin3') for kappa_bin3.fits); intermediate files go to the same relative path under intermediate/ of their realization, and smoothed maps to smoothed/{s}Mpc/.

The object holds only the root directory and options: the directory of each product is a template of PRODUCTS, filled with the options that each object adds for its products (with_options()).

Files are written and read by format (write_map and read_map, _alm, _table, _columns, _sacc, _npy, _wsp, _pickle), writes being atomic (atomic_write()): readers and resumed runs never see a partial file.

Parameters:
  • root_dir (str) – Root directory of the products.

  • **options – Options of the templates of PRODUCTS (see with_options()).

PRODUCTS = {'catalogs': ('seed{seed}', '{matter}/catalogs/{nz}/{tag}'), 'footprint': ('', 'footprint'), 'halos': ('seed{seed}', 'halos'), 'kappa': ('seed{seed}', '{matter}/kappa/{nz}'), 'realization': ('seed{seed}', ''), 'shells': ('seed{seed}', '{matter}/shells')}
MAP_NAMES = {'halos': 'halo', 'kappa': 'kappa', 'shells': 'shell'}
SHELL_INDEX = '{:03d}'
BIN_INDEX = 'bin{}'
with_options(**options)[source]

Return a copy with more options, those of an object’s products (e.g. seed, nz).

Parameters:

**options (Any) – Options of the templates of PRODUCTS.

Return type:

PolluxIO

dir(product, *, intermediate=False, smooth_Mpc=None, folder=None)[source]

Return the directory of a product.

Parameters:
  • product (str) – Key of PRODUCTS.

  • intermediate (bool, optional) – The directory of its intermediate files instead.

  • smooth_Mpc (float or None, optional) – The directory of its maps smoothed at this scale (Mpc).

  • folder (str or None, optional) – Subdirectory (e.g. 'plots', 'subs').

Return type:

str

path(product, *name, ext='fits', **dir_kwargs)[source]

Return the path of a file of a product, {dir}/{name}.{ext}.

Parameters:
  • product (str) – Product (see dir()).

  • *name – Parts of the name, joined by _; None parts are left out (e.g. ('cat_2pt', None) for cat_2pt.fits).

  • ext (str, optional) – Extension, without the leading dot.

  • **dir_kwargs – intermediate, smooth_Mpc and folder of dir().

Return type:

str

static catalog_stat_name(stat, shapes='shear')[source]

Return the parts of the name of the statistics of the catalogs (path()), by the shapes of their shear legs.

Parameters:
  • stat ({'2pt', 'cls'}) – Statistics.

  • shapes (str, optional) – Shapes of the shear legs ('shear', 'ia', 'shear_plus_ia', 'observed'). Default is 'shear'.

Returns:

E.g. ('cat_2pt', None) for the shear (cat_2pt.fits), ('cat_2pt', 'ia') (cat_2pt_ia.fits).

Return type:

tuple

read_config(product)[source]

Return the configuration of a product (its config.yaml, see pollux.io.config.read_config()).

Parameters:

product (str) – Key of PRODUCTS.

Return type:

dict

write_config(product, config)[source]

Write the configuration of a product, or check it against the existing one (pollux.io.config.write_config()).

Parameters:
  • product (str) – Key of PRODUCTS.

  • config (dict) – As given by the config() method of the objects.

Return type:

None

static cached(fname, compute, read, write)[source]

Return an object saved at fname, or compute it and save it there.

For objects that computations need and that are expensive to make again (e.g. NaMaster workspaces): the first process computes and saves them, the others (and later calls) read them back. The products themselves are made by the pipeline tasks, which skip those already saved.

Parameters:
  • fname (str) – File of the object.

  • compute (callable) – Returns the object.

  • read (callable) – Reads the object from fname.

  • write (callable) – Writes the object to fname (atomically, e.g. a write_* method).

Returns:

The object read from fname if it is there and readable (a warning if not readable), otherwise computed and written.

Return type:

object

static read_map(fname, nside_coverage=None)[source]

Read a HealSparse map.

Parameters:
  • fname (str) – File.

  • nside_coverage (int or None, optional) – Coverage resolution (default: that of the file).

Return type:

hsp.HealSparseMap

static write_map(fname, hspmap, **kwargs)[source]

Write a HealSparse map.

Parameters:
  • fname (str) – File.

  • hspmap (hsp.HealSparseMap)

  • **kwargs – Forwarded to healsparse.HealSparseMap.write() (e.g. format, nocompress).

Return type:

None

static read_alm(fname)[source]

Read spherical harmonic coefficients (healpy ordering), from a .npz file or a FITS file of healpy.

Parameters:

fname (str) – File.

Return type:

ndarray

static read_alm_mean(fname)[source]

Read the mean removed from a field before its harmonic transform, saved with its a_lm (.npz).

Parameters:

fname (str) – File of write_alm().

Return type:

float

static write_alm(fname, alm, mean=None)[source]

Write spherical harmonic coefficients (healpy ordering).

Parameters:
  • fname (str) – File: .npz (uncompressed, with alm and mean), or a FITS file of healpy otherwise.

  • alm (ndarray)

  • mean (float or None, optional) – Mean removed from the field before its transform (pollux.map_builder.MapBuilder._alm_field()), saved in .npz files (default 0).

Return type:

None

static read_table(fname)[source]

Open a FITS file of tables, e.g. a catalog.

Parameters:

fname (str) – File.

Returns:

To close, e.g. with io.read_table(fname) as hdul:.

Return type:

astropy.io.fits.HDUList

static write_table(fname, hdus)[source]

Write FITS tables, after an empty primary HDU if they don’t start with one.

Parameters:
  • fname (str) – File.

  • hdus (list of HDU)

Return type:

None

static read_columns(fname, columns=None, rows=None)[source]

Read columns of a catalog: the table of a FITS file, or the catalog group of an HDF5 file (write_columns()).

Parameters:
  • fname (str) – File: HDF5 if its extension is .hdf5, FITS otherwise.

  • columns (list of str or None, optional) – Columns to read. Default is all of them.

  • rows (ndarray of int or None, optional) – Sorted indices of the rows to read (e.g. a random subsample). Default is all of them.

Returns:

Arrays by column name, in native byte order.

Return type:

dict

Notes

HDF5 columns are read whole, then their rows selected. FITS rows are read in large contiguous blocks (read_fits_rows()).

static read_columns_info(fname)[source]

Return the number of rows, the columns and the metadata of a catalog (read_columns()), without its data.

Parameters:

fname (str) – File.

Returns:

  • nrows (int)

  • columns (list of str)

  • metadata (dict) – Attributes of the catalog group (HDF5), or header of the table (FITS).

Return type:

tuple[int, list[str], dict]

static write_columns(fname, columns, metadata=None, txpipe=None)[source]

Write the columns of a catalog, with its metadata, as a FITS table or an HDF5 file (by the extension of fname).

An HDF5 file holds the columns in a catalog group (in their order, chunked by rows, with the metadata as its attributes), and with txpipe also the groups of a tomographic bin of TXPipe’s binned catalogs, whose datasets link those of the catalog without copying them:

  • shear/bin_{b}: ra, dec, g1, g2 (the shear columns given), and weight;

  • lens/bin_{b}: ra, dec, comoving_distance (chi), and weight.

Each has the attributes nbin = 1 and bin_0 = b that TXPipe reads; the weights are 1, as a dataset never written (its fill value, without storage). write_txpipe_binned() gathers the bins in one file.

Parameters:
  • fname (str) – File: HDF5 if its extension is .hdf5, FITS otherwise.

  • columns (dict) – Arrays by column name, of equal lengths, including ra, dec and (for txpipe) chi.

  • metadata (dict or None, optional) – Header keywords (FITS) or attributes (HDF5).

  • txpipe ((int, (str, str) or None) or None, optional) – HDF5 only: the tomographic bin, and the columns of the shapes TXPipe correlates (g1, g2), or None for a lens sample only.

Return type:

None

static write_txpipe_binned(fname, bins, kinds=('shear', 'lens'))[source]

Write TXPipe’s binned catalog of tomographic bins written apart (write_columns() with txpipe).

The groups {kind}/bin_{b} are external links to those of the files of the bins, which can be written later (a link to a file not yet written resolves once it is). The file serves as both the binned_shear_catalog and the binned_lens_catalog of TXPipe.

Parameters:
  • fname (str) – HDF5 file, in the directory of the files of the bins.

  • bins (dict) – Files of the bins (relative to the directory of fname, or absolute), by bin index.

  • kinds (tuple of str, optional) – Samples: 'shear' and 'lens' (default), or only 'lens' for catalogs without shapes.

Return type:

None

static write_qp_nz(fname, z, nzs, weights)[source]

Write the redshift distributions of tomographic bins in the format of qp, as TXPipe’s n(z) files.

A qp ensemble of interp distributions (piecewise linear on the grid z, zero outside), in the groups meta and data at the root of the file, as qp.Ensemble.write_to writes them: one row per bin, then that of all the bins, their sum weighted by weights (the last row of TXPipe’s QPNOfZFile, its non-tomographic n(z)). Every row is normalized. Written with h5py: qp, which needs numpy 2, is only needed to read it.

Parameters:
  • fname (str) – HDF5 file.

  • z (ndarray) – Increasing redshift grid.

  • nzs (ndarray) – Redshift distributions on z, shape (nbins, len(z)), normalized or not.

  • weights (ndarray) – Weights of the bins in the distribution of all of them (e.g. their numbers of galaxies).

Return type:

None

static read_sacc(fname)[source]

Read a SACC file of statistics.

Parameters:

fname (str) – File.

Return type:

sacc.Sacc

static write_sacc(fname, s)[source]

Write a SACC file of statistics.

Parameters:
  • fname (str) – File.

  • s (sacc.Sacc)

Return type:

None

static read_npy(fname, allow_pickle=False)[source]

Read a NumPy array.

Parameters:
  • fname (str) – File.

  • allow_pickle (bool, optional) – For arrays of objects. Default is False.

Return type:

ndarray

static write_npy(fname, array)[source]

Write a NumPy array.

Parameters:
  • fname (str) – File.

  • array (array_like)

Return type:

None

static read_wsp(fname, read_unbinned_MCM=True)[source]

Read a NaMaster workspace.

Parameters:
  • fname (str) – File.

  • read_unbinned_MCM (bool, optional) – Also read the unbinned mode-coupling matrix, needed for bandpower windows. Default is True.

Return type:

pymaster.NmtWorkspace

static write_wsp(fname, wsp)[source]

Write a NaMaster workspace.

Parameters:
  • fname (str) – File.

  • wsp (pymaster.NmtWorkspace)

Return type:

None

static read_pickle(fname)[source]

Read a pickled object (intermediate files only: pickles depend on the code that wrote them).

Parameters:

fname (str) – File.

Return type:

object

static write_pickle(fname, obj)[source]

Pickle an object (intermediate files only).

Parameters:
Return type:

None

pollux.io.files.atomic_write(fname)[source]

Yield a temporary path to write fname to, renamed to fname once written.

Readers (and resumed runs, which skip existing files) never see a partial file, and several workers may write the same file at once. The temporary file keeps the extension of fname (for writers that use it) and is removed if the writing fails. The directory of fname is created if needed.

Parameters:

fname (str) – Path of the file.

Yields:

str – Temporary path, in the same directory.

Return type:

Iterator[str]

Configurations of the products: the config.yaml of each product directory (write_config(), read_config()).

A configuration records the kind of product, its parameters, its input products and the code version that first wrote it, so that a product can be shared (e.g. registered) on its own, and that a directory never mixes products of different parameters.

pollux.io.config.write_config(product_dir, config, root_dir=None)[source]

Write the configuration of a product, or check it against the existing one.

The configuration ({product_dir}/config.yaml) records the kind of product, its parameters, its input products and the code version that first wrote it. Products are made or resumed in place, so an existing configuration with other parameters means that the directory holds a different product: this raises instead of mixing them.

Parameters:
  • product_dir (str) – Directory of the product.

  • config (dict) – product (kind of product, e.g. 'shells', 'kappa', 'catalogs'), parameters (defining the product) and inputs (directories of the input products), as given by the config() method of the builders and catalogs.

  • root_dir (str or None, optional) – Root directory of the product’s io: inputs next to it (within its parent) are recorded relative to it (e.g. dmo/shells, ../footprint), others as given (e.g. the file of a mask).

Raises:

ValueError – If the directory already holds a product with other parameters.

Return type:

None

pollux.io.config.read_config(product_dir)[source]

Return the configuration of a product (its config.yaml).

Parameters:

product_dir (str) – Directory of the product.

Returns:

product, parameters, inputs and code_version.

Return type:

dict

Version of the code and environment of runs, recorded with their products.

pollux.io.code_version.code_version()[source]

Return the git version of the running code.

Returns:

commit (None outside a git repository), branch, and dirty: whether tracked files have uncommitted changes.

Return type:

dict

pollux.io.code_version.write_code_version(out_dir, files=(), require_clean=False)[source]

Record the code and environment of a run in a new {out_dir}/code_version/{date} folder.

Each call has its own folder, so that resuming a run keeps the record of the earlier code. Call it from the main process, before launching tasks.

Parameters:
  • out_dir (str) – Output directory of the run.

  • files (iterable of str, optional) – Files to copy in the record, e.g. the run script and its configuration.

  • require_clean (bool, optional) – If True, refuse to run with uncommitted changes (or outside a git repository), so that outputs always come from a known commit. Default is False.

Returns:

The folder written, with:

  • code_version.yaml: git commit, branch and state, date, host, command, Python;

  • uncommitted.diff: the uncommitted changes of tracked files, if any;

  • pip_freeze.txt: the installed Python packages;

  • conda_packages.txt: the conda packages of the environment, if any;

  • the copied files.

Return type:

str

Index of the products under a root directory, from their config.yaml (see pollux.io.config).

Usage:

python -m pollux.io.index ROOT [--output products.yaml]

lists every product (shells, halos, convergence maps, catalogs) under ROOT, with its kind, parameters, inputs and code version, skipping intermediate files. The index is the starting point to share the products, e.g. to register them in the DESC data registry.

pollux.io.index.product_index(root_dir)[source]

Return the products under a root directory.

Parameters:

root_dir (str) – Root directory to search.

Returns:

Per product, sorted by path: path (relative to root_dir), and the product, parameters, inputs (relative to the realization) and code_version of its config.yaml.

Return type:

list of dict

pollux.io.index.main()[source]

Command line: python -m pollux.io.index ROOT [--output FILE] prints the index of the products, or writes it to a YAML file.

Return type:

None

Loader of the products of one realization, from their files only (PolluxLoader).

class pollux.io.loader.PolluxLoader(root_dir, seed=0, baryon_tag=None, nz='SRDv1_nz', catalog_tag=None)[source]

Bases: PolluxIO

Loader of the products of one realization, from their files only: PolluxIO with named readers.

No pollux builder is created, so the products can be read with the I/O dependencies only. Any file can also be read with the generic readers of PolluxIO (e.g. loader.read_map(loader.path('kappa', 'gamma1', 'bin3'))). Maps are read from HealSparse files, or from the dense RING files of products made with map_format='healpix' (read_map()), and a_lm from FITS or .npz files (read_alm()).

Parameters:
  • root_dir (str) – Root directory of the products (see pollux.io.files).

  • seed (int, optional) – Seed of the realization (seed{seed}/). Default is 0.

  • baryon_tag (str or None, optional) – Tag of the baryon model, for the products of dmb/{baryon_tag}. Default is None, the dark-matter-only products (dmo).

  • nz (str or None, optional) – Name of the n(z) of the convergence and shear maps and of the catalogs (kappa/{nz}, catalogs/{nz}), 'snapshots' for one source plane per shell. Default is 'SRDv1_nz'.

  • catalog_tag (str or None, optional) – Tag of the catalogs (catalogs/{nz}/{catalog_tag}). Default is None (default).

Variables:
  • footprint (dict) – Parameters of the footprint (nside, mask, padding), from its config.yaml.

  • simulation (dict) – Simulation of the shells (path, kind, box size, particles, snapshots), from their config.yaml.

  • cosmo (pyccl.Cosmology) – Cosmology of the simulation.

  • nshells (nside,) – Resolution and number of the shells.

  • shell_info (FITS_rec) – Table of the shells (shells.fits, see pollux.shells.ShellBuilder.info_table()).

  • nzs (list of (ndarray, ndarray)) – Redshift distributions, unless nz is None or 'snapshots'.

read_map(fname, nside_coverage=None, dense=False)[source]

Read a map: the HealSparse file fname, or the dense RING .npy file of the same name.

Parameters:
  • fname (str) – File (e.g. from path(), with the default extension).

  • nside_coverage (int or None, optional) – Coverage resolution of the HealSparse map (default: that of the file, 32 for a dense file).

  • dense (bool, optional) – Return a dense RING map instead of a HealSparse map. Default is False.

Return type:

hsp.HealSparseMap or ndarray

read_alm(fname)[source]

Read a_lm: the file fname, or the .npz file of the same name.

Parameters:

fname (str) – File.

Return type:

ndarray

read_shell(ishell, density=False)[source]

Read the particle counts of one shell, or its density contrast.

Parameters:
  • ishell (int) – Shell index.

  • density (bool, optional) – Return the density contrast, counts / pixel_density - 1. Default is False.

Return type:

hsp.HealSparseMap

read_shell_alms(ishell)[source]

Read the a_lm of one shell (intermediate file).

Parameters:

ishell (int) – Shell index.

Return type:

ndarray

read_shell_cls()[source]

Read the measured angular power spectra of the shells.

Return type:

sacc.Sacc

read_density(ishell, smooth_Mpc=None)[source]

Read the density contrast of one shell, smoothed or not.

Parameters:
  • ishell (int) – Shell index.

  • smooth_Mpc (float or None, optional) – Smoothing scale (Mpc) of the map, None (default) for the unsmoothed map.

Return type:

hsp.HealSparseMap

read_tidal(ishell, smooth_Mpc=None)[source]

Read the components of the tidal field of one shell.

Parameters:
  • ishell (int) – Shell index.

  • smooth_Mpc (float or None, optional) – Smoothing scale (Mpc) of the map, None (default) for the unsmoothed map.

Returns:

(t11, t22, t12).

Return type:

tuple of hsp.HealSparseMap

read_haloes(ishell)[source]

Read the halo catalog of one shell, shared by all baryon models.

Parameters:

ishell (int) – Shell index.

Returns:

Arrays by column, concatenated over the sub-volumes.

Return type:

dict

read_kappa(ikappa, smooth_Mpc=None)[source]

Read one convergence map.

Parameters:
  • ikappa (int) – Tomographic bin (or shell, for nz='snapshots').

  • smooth_Mpc (float or None, optional) – Smoothing scale (Mpc) of the map, None (default) for the unsmoothed map.

Return type:

hsp.HealSparseMap

read_kappa_alms(ikappa)[source]

Read the a_lm of one convergence map (intermediate file).

Parameters:

ikappa (int) – Tomographic bin (or shell, for nz='snapshots').

Return type:

ndarray

read_shear(ikappa, smooth_Mpc=None)[source]

Read the shear maps of one tomographic bin (or shell).

Parameters:
  • ikappa (int) – Tomographic bin (or shell, for nz='snapshots').

  • smooth_Mpc (float or None, optional) – Smoothing scale (Mpc) of the map, None (default) for the unsmoothed map.

Returns:

(gamma1, gamma2).

Return type:

tuple of hsp.HealSparseMap

read_kappa_cls()[source]

Read the measured angular power spectra of the convergence maps.

Return type:

sacc.Sacc

path_catalog(ibin)[source]

Return the file of the source catalog of one tomographic bin: HDF5 (cat_bin{b}.hdf5), or FITS for catalogs made with catalog_format='fits'.

Parameters:

ibin (int) – Tomographic bin.

Return type:

str

read_catalog(ibin, columns=None, rows=None)[source]

Read columns of the source catalog of one tomographic bin (read_columns()).

Parameters:
  • ibin (int) – Tomographic bin.

  • columns (list of str or None, optional) – Columns to read. Default is all of them (the catalogs are tens of GB at nside 8192).

  • rows (ndarray of int or None, optional) – Sorted indices of the rows to read (e.g. a random subsample). Default is all of them.

Returns:

Arrays by column name. The number of galaxies, the columns and the metadata are given by read_columns_info(path_catalog(ibin)).

Return type:

dict

read_catalog_2pt(shapes='shear')[source]

Read the measured two-point functions of the catalogs (cat_2pt[_{shapes}].fits).

Parameters:

shapes (str, optional) – Shapes of the shear legs ('shear', 'ia', 'shear_plus_ia', 'observed'). Default is 'shear'.

Return type:

sacc.Sacc

read_catalog_cls(shapes='shear')[source]

Read the measured angular power spectra of the catalogs (cat_cls[_{shapes}].fits).

Parameters:

shapes (str, optional) – Shapes of the shear legs ('shear', 'ia', 'shear_plus_ia', 'observed'). Default is 'shear'.

Return type:

sacc.Sacc