cosmocore.in_out module
Input/output operations for cosmological data analysis.
This module provides functions for reading and writing various data formats used in cosmological analysis, including covariance matrices, power spectra, masks, geometry files, and map data from FITS files.
Functions
- read_covmat
Read noise covariance matrix from binary file.
- write_covmat_reduced
Write reduced covariance matrix to binary file.
- read_mask
Read HEALPix mask from FITS file.
- output_geometry
Write geometry information to text file.
- readcl
Read power spectra from text file with header.
- writecl
Write power spectra to text file.
- write_out_matrix
Write matrix in formatted text output.
- read_maps
Read map data from multi-simulation FITS files.
- get_field_index
Extract field indices from FITS header information.
Notes
This module handles various file formats commonly used in CMB analysis: - Binary covariance matrices for noise modeling - HEALPix FITS files for masks and maps - Text files for power spectra with flexible header formats - Multi-simulation FITS files with structured field organization
- cosmocore.in_out.read_covmat(covmatfile, npix, nmaps, active, C)[source]
Read noise covariance matrix from binary file and extract active pixel submatrix.
- Parameters:
covmatfile (str) – Path to binary file containing full covariance matrix.
npix (int) – Number of pixels per map.
nmaps (int) – Number of maps/fields.
active (numpy.ndarray) – 1D array of active pixel indices in flattened format.
C (numpy.ndarray) – Output array to store the extracted covariance submatrix.
- Returns:
Filled covariance matrix C for active pixels only.
- Return type:
Notes
Reads a full-sky covariance matrix stored in binary format and extracts only the relevant submatrix corresponding to active (unmasked) pixels. The input matrix is assumed to be stored as float64 in row-major order.
- cosmocore.in_out.read_covmat_reduced(covmatfile, C)[source]
Read a pre-reduced covariance matrix from binary file.
- Parameters:
covmatfile (str) – Path to binary file containing the reduced covariance matrix (active pixels only).
C (numpy.ndarray) – Output array of shape (n_active, n_active) to store the matrix.
- Returns:
Filled covariance matrix C.
- Return type:
- cosmocore.in_out.write_covmat_reduced(outcovmatfile, C)[source]
Write reduced covariance matrix to binary file.
- Parameters:
outcovmatfile (str) – Output filename for the reduced covariance matrix.
C (numpy.ndarray) – Covariance matrix to write, typically for active pixels only.
Notes
Writes the matrix in binary format using numpy’s tofile method. The output can be read back using numpy.fromfile with appropriate reshaping.
- cosmocore.in_out.read_mask(maskfile, mask)[source]
Read HEALPix mask from FITS file.
- Parameters:
maskfile (str) – Path to FITS file containing HEALPix mask(s).
mask (numpy.ndarray) – Output array of shape (npix, nmaps) to store mask values.
- Returns:
Mask array with shape (npix, nmaps) where each column represents a different field mask.
- Return type:
Notes
Uses HEALPix’s read_map function to load mask data and transposes the result to have pixels as rows and maps as columns for consistent indexing with the analysis framework.
- cosmocore.in_out.output_geometry(filegeometry, npixs, point_vectors, active)[source]
Write geometry information to text file.
- Parameters:
filegeometry (str) – Output filename for geometry data.
npixs (list of int) – Number of active pixels for each field.
point_vectors (tuple of numpy.ndarray) – Pointing vectors for each field, each array shape (n_active, 3).
active (numpy.ndarray or tuple) – Active pixel indices for each field.
Notes
Writes geometry information in a structured text format containing: - Field header with field index, number of active pixels - For each active pixel: original pixel index and 3D pointing vector
This format can be used for geometry debugging and external processing.
- cosmocore.in_out.convert_spectra_normalization(cls_dict, from_norm, to_norm)[source]
Convert between Cl and Dl = l(l+1)/(2pi) Cl conventions.
Operates on ℓ-indexed arrays:
cls_dict[label][ell]is the spectrum value at multipoleell. Indices below the physical floor of the spectrum are expected to be zero. Modifiescls_dictin place and returns it.- Parameters:
- Returns:
The same
cls_dict, modified in place.- Return type:
- cosmocore.in_out.readcl(inputclfile, Params, logger=None, lmax=None)[source]
Read power spectra from text file with header.
- Parameters:
inputclfile (str) – Path to text file containing power spectra data.
Params (InputParams) – Analysis parameters containing lmax and feedback level.
logger (CosmoLogger, optional) – CosmoLogger instance for output. If None, uses print for backward compatibility.
lmax (int, optional) – Maximum multipole to read. If None, uses Params.lmax. This allows loading Cls up to a different lmax than the analysis lmax.
- Returns:
Dictionary mapping spectrum labels to ℓ-indexed power-spectrum arrays. Each array has length
effective_lmax + 1:cls_dict[label][ell]is C_ℓ. Indices below the file’s lowest available ℓ are zero-padded.- Return type:
- Raises:
ValueError – If the first line doesn’t start with ‘#’ as expected header format.
Notes
Expected file format: - First line: header starting with ‘#’ containing column labels - Subsequent lines: numerical data with columns for different spectra - ‘ell’ column is used to position rows at the correct ℓ index when
present; otherwise the file is assumed to start at ℓ=2.
Rows for ℓ >
effective_lmaxare dropped silently.
- cosmocore.in_out.writecl(filename, power_spectra)[source]
Write power spectra array to text file.
- Parameters:
filename (str) – Output filename for power spectra data.
power_spectra (numpy.ndarray) – Power spectra array to write to file.
Notes
Uses high precision format (%.16e) to preserve full double precision. Could be enhanced to support more sophisticated formats with headers and labels.
- cosmocore.in_out.write_out_matrix(outfilematrix, matrix)[source]
Write matrix in formatted text output.
- Parameters:
outfilematrix (str) – Output filename for the formatted matrix.
matrix (numpy.ndarray) – 2D array to write in formatted text format.
Notes
Writes the matrix with scientific notation formatting (24.16E format) with each row on a separate line. Suitable for matrices that need to be human-readable or imported into other analysis tools. The 16 decimal places preserve full double precision.
- cosmocore.in_out.read_maps(maps, filename, pixact, field_labels, calibration=1.0)[source]
Read map data from files.
Supports three formats: 1. Numpy format (.npy): 3D array of shape (n_fields, n_pix, n_sims).
The first
len(field_labels)entries along axis 0 are assumed to be ordered exactly asfield_labels.Multi-simulation FITS: HDUs named “SIM_XXX” with FIELDS header.
Simple HEALPix FITS: Standard HEALPix file (for single simulation).
- Parameters:
maps (numpy.ndarray) – Output array of shape (n_total_active, n_sims) to store map data.
filename (str) – Path to data file (.npy or .fits).
pixact (list of numpy.ndarray) – List of active pixel indices for each field.
field_labels (list of str) – Labels identifying which fields to read from each simulation. These should be individual field names (e.g., [“T”, “Q”, “U”]). For numpy format, the first
len(field_labels)entries in the file are assumed to match this ordering exactly.calibration (float, optional) – Calibration factor to multiply all map values. Default is 1.0.
- Raises:
AssertionError – If maps array shape doesn’t match expected total active pixels.
ValueError – If field labels don’t match expected format or pixel indices are invalid.
Notes
For numpy format: - File must contain a 3D array of shape (n_fields, n_pix, n_sims) - Fields are ordered to match the config’s
physical_labels- No header metadata; field ordering is determined by conventionFor multi-simulation FITS: - Each HDU named “SIM_XXX” contains one simulation - HDU headers contain “FIELDS” keyword describing field organization
For simple HEALPix format (nsims=1): - Reads directly using healpy - Field mapping: T=0, Q=1, U=2, E=1, B=2
Applies calibration factor to all loaded data.
- cosmocore.in_out.get_field_index(hdu, field_name)[source]
Extract field index from FITS HDU header information.
- Parameters:
hdu (astropy.io.fits.HDU) – FITS HDU containing field information in header.
field_name (str) – Field name to look up (e.g., “T”, “Q”, “U”, “T1”, “E2”).
- Returns:
Field index corresponding to the requested field name.
- Return type:
- Raises:
ValueError – If requested field is not found in the HDU header.
Notes
Supports two header formats for the “FIELDS” keyword: - Comma-separated: “T,Q,U” or “T1,T2,T3” - Concatenated: “TQU” (for single-character field names)
Field expansion is now handled at the InputParams level, so this function expects individual field names only.