cosmocore.fields module
Cosmological field representations and management.
This module provides a comprehensive framework for handling different types of cosmological fields (scalar and polarization) on the sphere. It includes abstract base classes and concrete implementations for temperature and polarization fields, along with configuration management and field collection utilities.
- The main components are:
FieldConfig: Configuration dataclass for field parameters
BaseField: Abstract base class for all cosmological fields
ScalarField: Implementation for spin-0 fields (e.g., temperature)
PolarizationField: Implementation for spin-2 fields (E/B modes)
FieldCollection: Manager for collections of multiple fields
- Key features:
HEALPix map handling and spherical harmonic transforms
Beam function management for instrumental effects
Power spectra computation and cross-correlation support
Mask handling for partial sky analyses
Type-safe field configuration with validation
- class cosmocore.fields.FieldConfig(spin, nside, lmax, mask, labels)[source]
Bases:
objectConfiguration for a cosmological field.
This dataclass encapsulates all the parameters needed to define a cosmological field on the sphere, including geometric properties, resolution parameters, and field-specific metadata.
- Parameters:
spin (int) – Spin weight of the field. Must be 0 (scalar) or 2 (polarization).
nside (int) – HEALPix nside parameter determining map resolution. Total number of pixels is 12*nside².
lmax (int) – Maximum multipole moment for spherical harmonic analysis. Must satisfy lmax ≤ 4*nside for numerical stability.
mask (numpy.ndarray) – 1D boolean or float array of length 12*nside² indicating which pixels are observed (1) or masked (0).
labels (str or list of str) – Field label(s). Single string for spin-0 (e.g., “T”), list of two strings for spin-2 (e.g., [“E”, “B”]).
- Raises:
ValueError – If spin is not 0 or 2, if mask is not 1D, if lmax < 2, if lmax > 4*nside, or if number of labels doesn’t match spin requirements.
Examples
>>> import numpy as np >>> # Temperature field configuration >>> temp_config = FieldConfig( ... spin=0, nside=512, lmax=1024, ... mask=np.ones(12*512**2), labels="T" ... ) >>> >>> # Polarization field configuration >>> pol_config = FieldConfig( ... spin=2, nside=512, lmax=1024, ... mask=np.ones(12*512**2), labels=["E", "B"] ... )
Notes
The configuration is validated automatically upon creation. The mask array is used for partial sky analyses and should have the same ordering as the HEALPix maps (typically RING ordering).
- __post_init__()[source]
Validate configuration parameters.
This method is called automatically after dataclass initialization to ensure all parameters are valid and consistent. It also normalizes the labels format to a consistent list representation.
- Raises:
ValueError – If any validation check fails, including invalid spin values, incorrect mask dimensions, or mismatched label counts.
- __init__(spin, nside, lmax, mask, labels)
- class cosmocore.fields.BaseField(config)[source]
Bases:
ABCAbstract base class for cosmological fields.
This class provides the common interface and functionality for all types of cosmological fields defined on the sphere. It handles pixel indexing, beam functions, spherical harmonic transforms, and power spectra computations.
The class is designed to work with HEALPix pixelization and supports both full-sky and partial-sky (masked) analyses. Concrete subclasses implement the specific behavior for different field types (scalar vs. polarization).
- Parameters:
config (FieldConfig) – Configuration object containing all field parameters including spin, resolution, mask, and labels.
- config
The input configuration object.
- Type:
- mask
Boolean mask indicating observed pixels.
- Type:
- beam
Beam window function(s) for instrumental effects.
- Type:
numpy.ndarray or None
Notes
This is an abstract class and cannot be instantiated directly. Use the concrete subclasses ScalarField or PolarizationField instead.
Examples
>>> # Use concrete subclasses >>> temp_field = ScalarField(temp_config) >>> pol_field = PolarizationField(pol_config)
- property labels: list[str]
Field labels (e.g., [‘T’] for temperature, [‘E’, ‘B’] for polarization).
- property maps_label: str | list[str]
Backward compatibility property for legacy code.
- Returns:
str or list of str – Single string for scalar fields, list for polarization fields. This property is maintained for compatibility with older code.
Deprecated
———–
Use the labels property instead for new code.
- property mask: ndarray
Boolean mask indicating observed pixels.
- Returns:
1D array of length npix with 1 for observed pixels and 0 for masked pixels.
- Return type:
- property active_pixels: ndarray
Indices of unmasked (active) pixels.
- Returns:
1D array containing pixel indices where mask > 0.5. Computed lazily and cached for efficiency.
- Return type:
- property point_vectors: ndarray | None
Pointing vectors for active pixels.
- Returns:
Array of shape (n_active, 3) containing unit vectors pointing to active pixel centers, or None if not set.
- Return type:
numpy.ndarray or None
- property beam: ndarray | None
Beam window function for instrumental effects.
- Returns:
Beam window function(s). For scalar fields: 1D array of length
lmax + 1(ℓ-indexed:beam[ell]). For polarization fields: 2D array of shape(lmax + 1, 2)for E and B modes. Returns None if beam has not been set.- Return type:
numpy.ndarray or None
- set_point_vectors(vectors)[source]
Set pointing vectors for active pixels.
- Parameters:
vectors (numpy.ndarray) – Array of shape (n_active, 3) containing unit vectors pointing to the center of each active pixel in 3D space.
- Raises:
ValueError – If vectors shape doesn’t match (n_active, 3).
- Return type:
Notes
Pointing vectors are used for spherical harmonic analysis and coordinate transformations. The vectors should be normalized unit vectors in the chosen coordinate system.
Examples
>>> field = ScalarField(...) >>> vectors = get_pixel_pointing_vectors(field.active_pixels) >>> field.set_point_vectors(vectors)
- set_beam(beam)[source]
Set the beam window function for this field.
- Parameters:
beam (numpy.ndarray) –
Beam window function. Expected shape depends on field type: - Scalar fields: 1D array of length
lmax + 1(ℓ-indexed) - Polarization fields: 2D array of shape(lmax + 1, 2)for E and B modes
- Raises:
ValueError – If beam shape doesn’t match expected dimensions for this field type.
- Return type:
Notes
The beam function is applied to correct for instrumental effects in harmonic space analysis. The function is expected to be normalized appropriately for the specific instrument and observation strategy.
Examples
>>> field = ScalarField(...) >>> beam_window = load_beam_function(lmax=field.lmax) >>> field.set_beam(beam_window)
- abstractmethod get_spectrum_labels()[source]
Get labels for all auto-spectra of this field.
- Returns:
List of spectrum labels for this field’s auto-correlations. For scalar fields: [“TT”] For polarization fields: [“EE”, “BB”]
- Return type:
Notes
This abstract method must be implemented by concrete subclasses to define the auto-spectra that can be computed for the field type.
- abstractmethod get_cross_spectrum_labels(other)[source]
Get labels for cross-spectra with another field.
- Parameters:
other (BaseField) – Another field to compute cross-spectra with.
- Returns:
List of spectrum labels for cross-correlations between this field and the other field. Examples: - T x T: [“TT”] - T x QU: [“TQ”, “TU”] - QU x QU: [“QQ”, “QU”, “UQ”, “UU”]
- Return type:
Notes
This abstract method must be implemented by concrete subclasses to define valid cross-spectra between different field types.
- class cosmocore.fields.ScalarField(config)[source]
Bases:
BaseFieldSpin-0 cosmological field representation (e.g., temperature).
Represents scalar fields on the sphere such as temperature anisotropies in the cosmic microwave background. Supports single-component analysis with auto-correlation power spectra.
- Parameters:
config (FieldConfig) – Configuration containing maps, mask, and metadata for this field.
- config
Field configuration and data.
- Type:
- maps
Map data with shape (1, npix).
- Type:
Examples
>>> import numpy as np >>> from cosmocore.fields import FieldConfig, ScalarField >>> >>> # Create temperature field >>> nside = 64 >>> npix = 12 * nside**2 >>> temp_map = np.random.randn(npix) >>> mask = np.ones(npix) # No masking for this example >>> >>> config = FieldConfig( ... maps=[temp_map], ... labels=["T"], ... mask=mask, ... nside=nside, ... lmax=2*nside ... ) >>> temp_field = ScalarField(config) >>> print(f"Field type: {temp_field.spin=}") >>> print(f"Auto-spectra: {temp_field.get_spectrum_labels()}")
- __init__(config)[source]
Initialize a scalar field.
- Parameters:
config (FieldConfig) – Field configuration. Must have spin=0 for scalar fields.
- Raises:
ValueError – If config.spin != 0, as scalar fields must have zero spin.
- get_cross_spectrum_labels(other)[source]
Get cross-spectrum labels with another field.
- Parameters:
other (BaseField) – Another field to compute cross-spectra with.
- Returns:
Cross-spectrum labels. Examples: - With ScalarField: [“TT”] (if both are temperature) - With PolarizationField: [“TQ”, “TU”] (temperature x Q/U)
- Return type:
- Raises:
TypeError – If other field type is not recognized.
Examples
>>> temp_field = ScalarField(temp_config) >>> pol_field = PolarizationField(pol_config) >>> cross_labels = temp_field.get_cross_spectrum_labels(pol_field) >>> print(cross_labels) # ["TQ", "TU"]
- class cosmocore.fields.PolarizationField(config)[source]
Bases:
BaseFieldSpin-2 cosmological field representation (e.g., CMB polarization E/B modes).
Represents spin-2 fields on the sphere such as polarization anisotropies in the cosmic microwave background. Supports two-component analysis with auto-correlation and cross-correlation power spectra between E and B modes.
- Parameters:
config (FieldConfig) – Configuration containing maps, mask, and metadata for this field. Must have exactly 2 maps for Q and U components or E and B components.
- config
Field configuration and data.
- Type:
- labels
Component labels (two elements for polarization fields, e.g., [“Q”, “U”]).
- maps
Map data with shape (2, npix) for Q/U or E/B components.
- Type:
Examples
>>> import numpy as np >>> from cosmocore.fields import FieldConfig, PolarizationField >>> >>> # Create polarization field >>> nside = 64 >>> npix = 12 * nside**2 >>> q_map = np.random.randn(npix) >>> u_map = np.random.randn(npix) >>> mask = np.ones(npix) # No masking >>> >>> config = FieldConfig( ... maps=[q_map, u_map], ... labels=["Q", "U"], ... mask=mask, ... nside=nside, ... lmax=2*nside, ... spin=2 ... ) >>> pol_field = PolarizationField(config) >>> print(f"Field type: {pol_field.spin=}") >>> print(f"Auto-spectra: {pol_field.get_spectrum_labels()}")
- __init__(config)[source]
Initialize a polarization field.
- Parameters:
config (FieldConfig) – Field configuration. Must have spin=2 for polarization fields.
- Raises:
ValueError – If config.spin != 2, as polarization fields must have spin=2.
- get_spectrum_labels()[source]
Get auto-spectrum labels for polarization field.
- Returns:
Three-element list containing [“EE”, “BB”, “EB”] for E/B mode auto-correlations and cross-correlation.
- Return type:
Notes
The labels are generated using the field’s component labels converted to uppercase. For Q/U fields, these become E/B spectrum labels.
- get_cross_spectrum_labels(other)[source]
Get cross-spectrum labels with another field.
- Parameters:
other (BaseField) – Another field to compute cross-spectra with.
- Returns:
Cross-spectrum labels. Examples: - With ScalarField: [“TQ”, “TU”] (temperature x Q/U) - With PolarizationField: [“QQ”, “QU”, “UQ”, “UU”] (all combinations)
- Return type:
- Raises:
TypeError – If other field type is not recognized.
Examples
>>> pol_field = PolarizationField(pol_config) >>> temp_field = ScalarField(temp_config) >>> cross_labels = pol_field.get_cross_spectrum_labels(temp_field) >>> print(cross_labels) # ["TQ", "TU"]
- class cosmocore.fields.FieldCollection(core_params, fields, logger=None)[source]
Bases:
objectCollection of cosmological fields for joint analysis.
Manages multiple cosmological fields (scalar and/or polarization) for joint power spectrum analysis. Provides utilities for cross-correlations, spectrum indexing, and data vector construction.
- Parameters:
core_params (InputParams) – Core analysis parameters including cosmological and numerical settings.
fields (list of BaseField) – List of fields to include in the collection. Can mix scalar and polarization fields.
- core_params
Analysis parameters.
- Type:
Examples
>>> from cosmocore.fields import FieldCollection, ScalarField, PolarizationField >>> from cosmocore.core import InputParams >>> >>> # Create field collection >>> params = InputParams() >>> temp_field = ScalarField(temp_config) >>> pol_field = PolarizationField(pol_config) >>> >>> collection = FieldCollection(params, [temp_field, pol_field]) >>> print(f"Fields: {collection.n_fields}") >>> print(f"Cross-correlations: {collection.n_cross}") >>> print(f"Spectra: {collection.spectrum_labels}")
Notes
The collection automatically validates field consistency (same nside, lmax) and computes all possible auto- and cross-correlations between fields.
- __init__(core_params, fields, logger=None)[source]
Initialize field collection.
- Parameters:
core_params (InputParams) – Core analysis parameters.
fields (list of BaseField) – Fields to include in the collection.
logger (CosmoLogger, optional) – CosmoLogger instance for output messages.
- Raises:
ValueError – If fields have inconsistent parameters (nside, lmax, etc.).
- property n_active: list[int]
Number of active pixels per field component.
- Returns:
Number of active pixels for each component. Scalar fields contribute one entry, polarization fields contribute two entries (one per component).
- Return type:
Notes
For a collection with temperature (T) and polarization (QU) fields, this returns [n_active_T, n_active_Q, n_active_U].
- property total_active_pixels: int
Total number of active pixels across all field components.
- Returns:
Sum of active pixels for all components in the collection.
- Return type:
- get_active_pixels()[source]
Get active pixels for each field component (backward compatible format).
- Returns:
Object array containing active pixel arrays for each component. For scalar fields: one array per field. For polarization fields: two arrays per field (same pixels for Q and U).
- Return type:
Notes
This method provides backward compatibility with legacy code that expects active pixels in object array format.
- set_pointing_vectors(point_vectors)[source]
Set pointing vectors for all fields.
- Parameters:
point_vectors (list of numpy.ndarray) – List of pointing vector arrays, one per field. Each array should have shape (n_active, 3) for the corresponding field.
- Return type:
Notes
The pointing vectors are distributed to individual fields in the collection. Each field validates that the vector count matches its number of active pixels.
- set_cls(cls_data=None, lmax=None)[source]
Set power spectra and apply normalization.
- Parameters:
cls_data (dict or numpy.ndarray or None, optional) – Power spectrum data. Can be: - dict: Spectrum name -> array mapping - array: Pre-formatted spectrum array - None: Load from core_params.inputclfile
lmax (int, optional) – Maximum multipole to use. If None, uses core_params.lmax. This allows loading Cls up to a different lmax than the analysis lmax.
- Return type:
Notes
This method sets the theoretical power spectra for the field collection and applies any necessary normalization based on the analysis parameters.
- get_cls(field_i, field_j, mode=0)[source]
Get power spectrum for field pair.
- Parameters:
- Returns:
Power spectrum C_l values for the specified field pair and mode.
- Return type:
Examples
>>> collection = FieldCollection(params, [temp_field, pol_field]) >>> tt_spectrum = collection.get_cls(0, 0) # T auto-spectrum >>> te_spectrum = collection.get_cls(0, 1, 0) # T-E cross-spectrum