Skip to content

Construction and KL reduction

These functions build full-size operators on CPU in time-frequency blocks, writing them to disk, and return the saved paths. Every participating process makes the same calls; see execution.

Operators

BuildMatrices prepares the physical inputs from a configuration and exposes the same writers as methods. The writers can also be called directly.

bayeseor_jax.model.construction.model_builder.BuildMatrices

Prepare physical responses from model settings and resolved coordinates.

Parameters:

Name Type Description Default
config ModelConfig

Requested spectral, beam and storage settings. A RunConfig is also accepted, but data-selection, prior and sampler fields are not used.

required
frequencies_hz array - like

Resolved observing frequencies in Hz, shape (n_frequency,).

required
uvw_array_m array - like

Resolved physical baselines, shape (n_time, n_baseline, 3), in metres. The first integration supplies the fixed instrument-frame baselines.

required
image_geometry ImageGeometry

Prepared HEALPix pixel selections, time-dependent directions and areas. This fixes the actual image support; it is not rebuilt from config.

required
fourier_geometry FourierGeometry or None

Prepared rectilinear (u, v, eta) grid for the cosmological signal. Required for models containing the 21-cm component, unused for FG-only.

None
Notes

Geometry is resolved before construction. This object prepares the beam, Fourier factors and foreground spectra once, then its component writers construct CPU blocks and save separate operators. Joint assembly, noise weighting, KL reduction and inference remain separate stages.

__init__

__init__(config: ModelConfig, *, frequencies_hz: Array, uvw_array_m: Array, image_geometry: ImageGeometry, fourier_geometry: FourierGeometry | None = None) -> None

Prepare physical responses without changing the requested settings.

T_21_build_save

T_21_build_save(*, matrix_name: str = 'T_21') -> Path

Save the cosmological operator using the configured observation and Fourier grid.

Parameters:

Name Type Description Default
matrix_name str

Output file stem within array_save_directory; defaults to T_21.

'T_21'

Returns:

Name Type Description
path Path

Complete complex128 operator with (uv, eta) coefficient columns.

Notes

Select the cosmological sky pixels from the shared observation geometry, then delegate CPU placement, block partitioning and saving to the standalone T_21_build_save function. No prior weighting or KL is applied.

T_fg_build_save

T_fg_build_save(*, matrix_name: str = 'T_fg') -> Path

Save the physical foreground operator using the configured sky and spectra.

Parameters:

Name Type Description Default
matrix_name str

Output file stem within array_save_directory; defaults to T_fg.

'T_fg'

Returns:

Name Type Description
path Path

Complete complex128 operator with spectral-component/pixel columns.

Notes

The standalone T_fg_build_save function distributes CPU evaluation and saving. The original spectral amplitude columns are retained; compression and foreground-prior transformations are separate stages.

T_fg_weighted_build_save

T_fg_weighted_build_save(*, prior_sqrt, noise_whitener, matrix_name: str = 'A_fg') -> Path

Save the prior- and noise-weighted foreground operator directly on CPU.

Parameters:

Name Type Description Default
prior_sqrt array - like

Nonnegative prior standard deviations in spectral-component/pixel order, one per foreground coefficient.

required
noise_whitener array - like

Positive inverse noise RMS in time/frequency/baseline order, one per visibility. Both weights must be finite real vectors.

required
matrix_name str

Output file stem within array_save_directory; defaults to A_fg.

'A_fg'

Returns:

Name Type Description
path Path

Complete complex128 A = N^-1/2 T_fg Sigma_q^1/2 operator for KL decomposition. No unweighted foreground file is required or saved.

Notes

Weights are explicit inputs, separate from physical model configuration. The shared CPU writer applies them within each time-frequency block; decomposition and truncation are not performed here.

Distribute pure forward-operator evaluations and save their complete matrices.

Each process writes disjoint visibility-row blocks to shared storage. Numerical evaluation stays in model.operators; this module owns CPU placement and file publication. Optional diagonal weights are applied by the pure weighted operator; KL decomposition and truncation remain separate stages.

T_21_build_save

T_21_build_save(lmn, uvw_lambda, beam, pixel_area_sr, transverse_operator, spectral_operator, *, output_path) -> Path

Construct and save T_21 = F^-1 P F' F_z in distributed CPU blocks.

Parameters:

Name Type Description Default
lmn array - like

Cosmological pixel directions, shape (n_time, 3, n_pixel).

required
uvw_lambda array - like

Baselines in wavelengths, shape (n_frequency, 3, n_baseline).

required
beam array - like

Horizon-masked power gains, shape (n_time, n_frequency, n_pixel).

required
pixel_area_sr float

Positive pixel solid angle in steradians.

required
transverse_operator array - like

F' on the same pixels, shape (n_pixel, n_uv_mode).

required
spectral_operator array - like

F_z on the same frequencies, shape (n_frequency, n_eta_mode).

required
output_path str or Path

Shared output file, conventionally T_21.npy.

required

Returns:

Name Type Description
path Path

Complete complex128 matrix, shape (n_time*n_frequency*n_baseline, n_uv_mode*n_eta_mode).

Notes

All participating JAX processes call this function together. It evaluates the pure T_21 function on CPU and writes disjoint rows. Use T_21 directly for an in-memory JAX computation with no file or hardware policy.

T_fg_build_save

T_fg_build_save(lmn, uvw_lambda, beam, pixel_area_sr, spectral_operator, *, output_path) -> Path

Construct and save T_fg = F^-1 P Q_z in distributed CPU blocks.

Parameters:

Name Type Description Default
lmn array - like

Foreground pixel directions, shape (n_time, 3, n_pixel).

required
uvw_lambda array - like

Baselines in wavelengths, shape (n_frequency, 3, n_baseline).

required
beam array - like

Horizon-masked power gains, shape (n_time, n_frequency, n_pixel).

required
pixel_area_sr float

Positive pixel solid angle in steradians.

required
spectral_operator array - like

Q on the same frequencies, shape (n_frequency, n_spectral_component).

required
output_path str or Path

Shared output file, conventionally T_fg.npy.

required

Returns:

Name Type Description
path Path

Complete complex128 matrix, shape (n_time*n_frequency*n_baseline, n_spectral_component*n_pixel).

Notes

All participating JAX processes call this function together. It evaluates the pure T_fg function on CPU and writes disjoint rows. Foreground priors and KL retention are not applied: the saved columns remain physical spectral amplitudes at individual pixels.

T_fg_weighted_build_save

T_fg_weighted_build_save(lmn, uvw_lambda, beam, pixel_area_sr, spectral_operator, *, prior_sqrt, noise_whitener, output_path) -> Path

Construct and save A = N^-1/2 T_fg Sigma_q^1/2 in distributed CPU blocks.

Parameters:

Name Type Description Default
lmn array - like

Foreground pixel directions, shape (n_time, 3, n_pixel).

required
uvw_lambda array - like

Baselines in wavelengths, shape (n_frequency, 3, n_baseline).

required
beam array - like

Horizon-masked power gains, shape (n_time, n_frequency, n_pixel).

required
pixel_area_sr float

Positive pixel solid angle in steradians.

required
spectral_operator array - like

Q_z on the same frequencies, shape (n_frequency, n_spectral_component).

required
prior_sqrt array - like

Finite, nonnegative prior standard deviations, shape (n_spectral_component*n_pixel,), ordered by component then pixel.

required
noise_whitener array - like

Finite, positive inverse noise RMS values, shape (n_time*n_frequency*n_baseline,), ordered by time, frequency, baseline. Supply sqrt(Ninv), not inverse variances.

required
output_path str or Path

Shared output file, conventionally A_fg.npy.

required

Returns:

Name Type Description
path Path

Complete complex128 weighted operator with visibility rows and prior-standardised foreground coefficient columns.

Notes

All participating JAX processes call this function together. Each CPU block evaluates T_fg_weighted and writes disjoint rows directly; no unweighted T_fg file is built or reread. This writer supports diagonal priors and noise only. For dense covariance factors, use the pure T_fg_weighted function. The saved matrix is ready for decomposition, but no KL reduction is applied.

assemble_joint_operator

assemble_joint_operator(T_21_path, T_fg_path, *, output_path, block_rows=1024) -> Path

Concatenate saved component columns without loading the full joint matrix.

Parameters:

Name Type Description Default
T_21_path str or Path or None

Saved two-dimensional complex128 operators with identical visibility-row ordering. The foreground input may be the original physical operator or a retained operator with its prior already absorbed; the caller supplies the corresponding coefficient prior during inference. Both files must describe the same observation. Pass None to omit either component; at least one operator is required.

required
T_fg_path str or Path or None

Saved two-dimensional complex128 operators with identical visibility-row ordering. The foreground input may be the original physical operator or a retained operator with its prior already absorbed; the caller supplies the corresponding coefficient prior during inference. Both files must describe the same observation. Pass None to omit either component; at least one operator is required.

required
output_path str or Path

Shared destination, distinct from either input file; conventionally T.npy.

required
block_rows int

Positive number of visibility rows per copy block, default 1024.

1024

Returns:

Name Type Description
path Path

Complete matrix with cosmological columns followed by foreground columns.

Notes

Copies disjoint row ranges across already participating JAX processes. No numerical operator is rebuilt and neither input file is modified.

KL reduction

T_fg_svd_build_save decomposes a prior- and noise-weighted operator, truncates it and saves the reduced basis.

bayeseor_jax.model.construction.kl_reduction.T_fg_svd_build_save

T_fg_svd_build_save(weighted_operator_path, ninv_path, *, output_path, f=0.1, tile_size=128)

Decompose and truncate A, then save T_fg,r = N^1/2 U_r S_r.

Parameters:

Name Type Description Default
weighted_operator_path Path or str

Saved complex128 matrix A = N^-1/2 T_fg Sigma_q^1/2, shape (n_visibility, n_foreground_coefficient), in time/frequency/baseline row order. Prior and noise weighting must already have been applied.

required
ninv_path Path or str

Saved positive diagonal inverse noise E[|n_i|^2]^-1, shape (n_visibility,). Must be the same diagonal noise used to construct A. Correlated-noise whitening is not supported by this saved-file routine.

required
output_path Path or str

Shared destination, normally T_fg_reduced.npy. Also saves singular values to .singular_values.npy and diagnostics to .svd.json.

required
f float

Maximum discarded RMS as a fraction of thermal-noise RMS, averaged over the original visibility vector. Defaults to 0.1; see select_foreground_rank for the precise criterion.

0.1
tile_size int

Positive JAXMG square tile width, default 128. Unused on CPU.

128

Returns:

Type Description
Path

Completed complex128 operator, shape (n_visibility, retained_rank), ready for joint assembly with a standard-normal foreground prior.

Notes

On CPU, native JAX computes an unpadded, thin SVD on one device in one process. The input, thin singular-vector matrices and solver workspace must fit in local RAM. This path requires neither CUDA nor JAXMG.

On GPU, every process calls together, with one GPU per process and shared storage. Only local shards are read from disk; zero padding permits the distributed JAXMG GESVD. Full U is never gathered, and Vh is not computed. This is a dense SVD: the input, U and solver workspace must fit the allocated GPUs. Padding is excluded from the output and the RMS normalisation.

This function always computes its requested product, independently of setup and cache policy. It neither constructs A nor changes the inference prior. Existing outputs are replaced only after successful computation. The JAX backend selects the implementation; a GPU solver failure does not trigger a CPU fallback. Neither path uses approximate/randomised decomposition.

bayeseor_jax.model.construction.kl_reduction.select_foreground_rank

select_foreground_rank(singular_values, n_vis, f=0.1)

Find the smallest rank meeting the discarded prior-predictive RMS limit.

Parameters:

Name Type Description Default
singular_values array - like

Non-negative singular values of A = N^-1/2 T_fg Sigma_q^1/2, ordered from largest to smallest, with modes introduced by padding excluded.

required
n_vis int

Number of measured complex visibilities, before solver padding.

required
f float

Maximum discarded RMS relative to thermal-noise RMS; defaults to 0.1. Zero retains every mode with a nonzero computed singular value.

0.1

Returns:

Name Type Description
rank int

Smallest retained dimension satisfying the criterion, possibly zero.

tail_rms ndarray

Discarded RMS for every rank, including the zero tail at full rank.

Notes

The criterion is epsilon(r) = sqrt(sum(s[r:]**2) / n_vis) <= f. This is an average in noise-whitened visibility space, not a bound on each sample or on each realisation. The foreground prior is not applied a second time.

Likelihood products

The fixed products of the marginalised likelihood, \(\mathbf T^\dagger\mathbf N^{-1}\mathbf T\), \(\mathbf T^\dagger\mathbf N^{-1}\boldsymbol d\) and \(\boldsymbol d^\dagger\mathbf N^{-1}\boldsymbol d\). save_likelihood_products writes all three; the build_ functions evaluate them in memory.

Prepare likelihood products from an explicitly selected, saved joint operator.

The physical model and any foreground compression have already been constructed. This module knows only T, the inverse-noise diagonal, and the observed data. Pure contractions define the mathematics; save functions handle device sharding and publication. No operator is implicitly built, concatenated or reduced here.

save_likelihood_products

save_likelihood_products(t_path, ninv_path, data, *, output_directory, clobber=False, block_cols=16384, right_block_batch=4)

Prepare G, dbar and data power with one distributed load of T and N^-1.

Parameters:

Name Type Description Default
t_path Path or str

Saved complex128 joint response and positive inverse-noise vector.

required
ninv_path Path or str

Saved complex128 joint response and positive inverse-noise vector.

required
data array - like

Finite complex observations in the operator's visibility-row order.

required
output_directory Path or str

Shared destination for T_Ninv_T.npy, dbar.npy and d_ninv_d.npy.

required
clobber bool

Recompute G even when its cached input-file signatures match.

False
block_cols int

Target Gram-block width, rounded up to a device-count multiple.

16384
right_block_batch int

Number of adjacent right-hand Gram blocks contracted together.

4

Returns:

Type Description
tuple of pathlib.Path

Gram matrix, data projection and scalar data-power paths, respectively.

Notes

All processes call together, using every device in the initialised JAX job. G is reused when T and N^-1 are unchanged; data-dependent terms are always refreshed. Resident input stripes are shared across all three contractions.

build_gram_matrix

build_gram_matrix(operator, inverse_noise)

Compute G = T^H N^-1 T for supplied coefficient responses.

Parameters:

Name Type Description Default
operator Array

Joint coefficient-to-visibility matrix, shape (n_visibility, n_parameter).

required
inverse_noise Array

Real positive inverse variances E[|n_i|^2]^-1, shape (n_visibility,).

required

Returns:

Type Description
Array

Hermitian coefficient overlap matrix, shape (n_parameter, n_parameter).

Notes

Pure JAX contraction; the caller controls placement and validates inputs. Neither the coefficient prior nor the observed data enters this product.

build_data_projection

build_data_projection(operator, inverse_noise, data)

Compute dbar = T^H N^-1 d without fitting the model coefficients.

Parameters:

Name Type Description Default
operator Array

Joint response matrix, shape (n_visibility, n_parameter).

required
inverse_noise Array

Positive inverse variances, shape (n_visibility,).

required
data Array

Complex observations in matching row order, shape (n_visibility,).

required

Returns:

Type Description
Array

Noise-weighted data projection, shape (n_parameter,).

build_data_power

build_data_power(inverse_noise, data)

Compute the scalar data term d^H N^-1 d in the Gaussian likelihood.

Parameters:

Name Type Description Default
inverse_noise Array

Positive inverse variances, shape (n_visibility,).

required
data Array

Complex observations in matching row order, shape (n_visibility,).

required

Returns:

Type Description
Array

Real scalar noise-weighted squared magnitude of the data.

save_gram_matrix

save_gram_matrix(t_path, ninv_path, *, output_path, block_cols=16384, right_block_batch=4)

Compute and save G = T^H N^-1 T in distributed coefficient blocks.

Parameters:

Name Type Description Default
t_path Path or str

Saved complex128 response matrix and positive inverse-noise vector.

required
ninv_path Path or str

Saved complex128 response matrix and positive inverse-noise vector.

required
output_path Path or str

Shared output file, normally T_Ninv_T.npy.

required
block_cols int

Target coefficient-block width, rounded up to a device-count multiple.

16384
right_block_batch int

Number of adjacent right-hand blocks contracted in one launch.

4

Returns:

Type Description
Path

Complete unpadded coefficient overlap matrix.

Notes

All participating processes call together. Each process caches its input stripe on the default backend (typically GPU). Only the output is streamed in blocks. Strictly off-diagonal blocks are mirrored by Hermitian symmetry; disjoint output shards avoid overlapping writes. No prior is applied.

save_data_projection

save_data_projection(t_path, ninv_path, data, *, output_path)

Save dbar = T^H N^-1 d using the same device mesh for one or many devices.

Parameters:

Name Type Description Default
t_path Path or str

Saved response matrix and positive inverse-noise vector.

required
ninv_path Path or str

Saved response matrix and positive inverse-noise vector.

required
data array - like

Complex observations, shape (n_visibility,), in the operator's row order.

required
output_path Path or str

Shared destination, normally dbar.npy.

required

Returns:

Type Description
Path

Completed coefficient-space data projection. Recomputed on every call.

save_data_power

save_data_power(ninv_path, data, *, output_path)

Save d^H N^-1 d independently of the foreground/cosmological representation.

Parameters:

Name Type Description Default
ninv_path Path or str

Saved positive inverse-noise vector.

required
data array - like

Complex visibility vector in matching row order.

required
output_path Path or str

Shared destination, normally d_ninv_d.npy.

required

Returns:

Type Description
Path

Completed scalar data term. Recomputed on every call.