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:
objectFiles 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')forkappa_bin3.fits); intermediate files go to the same relative path underintermediate/of their realization, and smoothed maps tosmoothed/{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_mapandread_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(seewith_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).
- dir(product, *, intermediate=False, smooth_Mpc=None, folder=None)[source]¶
Return the directory of a product.
- Parameters:
- Return type:
- path(product, *name, ext='fits', **dir_kwargs)[source]¶
Return the path of a file of a product,
{dir}/{name}.{ext}.
- 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.
- read_config(product)[source]¶
Return the configuration of a product (its
config.yaml, seepollux.io.config.read_config()).
- write_config(product, config)[source]¶
Write the configuration of a product, or check it against the existing one (
pollux.io.config.write_config()).
- 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. awrite_*method).
- Returns:
The object read from
fnameif it is there and readable (a warning if not readable), otherwise computed and written.- Return type:
- 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
.npzfile 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:
- static write_alm(fname, alm, mean=None)[source]¶
Write spherical harmonic coefficients (healpy ordering).
- Parameters:
- 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.
- static read_columns(fname, columns=None, rows=None)[source]¶
Read columns of a catalog: the table of a FITS file, or the
cataloggroup of an HDF5 file (write_columns()).- Parameters:
- Returns:
Arrays by column name, in native byte order.
- Return type:
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.
- 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
cataloggroup (in their order, chunked by rows, with the metadata as its attributes), and withtxpipealso 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), andweight;lens/bin_{b}:ra,dec,comoving_distance(chi), andweight.
Each has the attributes
nbin = 1andbin_0 = bthat 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,decand (fortxpipe)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()withtxpipe).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 thebinned_shear_catalogand thebinned_lens_catalogof TXPipe.- Parameters:
- 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
interpdistributions (piecewise linear on the gridz, zero outside), in the groupsmetaanddataat the root of the file, asqp.Ensemble.write_towrites them: one row per bin, then that of all the bins, their sum weighted byweights(the last row of TXPipe’sQPNOfZFile, 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 write_npy(fname, array)[source]¶
Write a NumPy array.
- Parameters:
fname (str) – File.
array (array_like)
- Return type:
None
- static write_wsp(fname, wsp)[source]¶
Write a NaMaster workspace.
- Parameters:
fname (str) – File.
wsp (pymaster.NmtWorkspace)
- Return type:
None
- pollux.io.files.atomic_write(fname)[source]¶
Yield a temporary path to write
fnameto, renamed tofnameonce 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 offnameis created if needed.
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) andinputs(directories of the input products), as given by theconfig()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).
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, anddirty: whether tracked files have uncommitted changes.- Return type:
- 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:
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.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:
PolluxIOLoader of the products of one realization, from their files only:
PolluxIOwith named readers.No
polluxbuilder is created, so the products can be read with the I/O dependencies only. Any file can also be read with the generic readers ofPolluxIO(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 withmap_format='healpix'(read_map()), and a_lm from FITS or.npzfiles (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 itsconfig.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, seepollux.shells.ShellBuilder.info_table()).nzs (list of (ndarray, ndarray)) – Redshift distributions, unless
nzis None or'snapshots'.
- read_map(fname, nside_coverage=None, dense=False)[source]¶
Read a map: the HealSparse file
fname, or the dense RING.npyfile of the same name.- Parameters:
- Return type:
hsp.HealSparseMap or ndarray
- read_alm(fname)[source]¶
Read a_lm: the file
fname, or the.npzfile 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.
- 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.
- 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_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 withcatalog_format='fits'.
- read_catalog(ibin, columns=None, rows=None)[source]¶
Read columns of the source catalog of one tomographic bin (
read_columns()).- Parameters:
- 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: