Principal Component Analysis module
pca
Principal Component Analysis and Independent Component Analysis for delta parameters.
This subpackage provides tools to reduce the N-dimensional bin parameter space to a smaller number of interpretable components, revealing the dominant modes of variation in δ(k).
Supports multiple backends: - NumPy/sklearn (default): CPU-based computation using sklearn's PCA - JAX: GPU-accelerated, JIT-compiled, autodiff-compatible
Use the backend parameter to select:
>>> results = perform_pca(chains, backend="numpy") # Default
>>> results = perform_pca(chains, backend="jax") # GPU-accelerated
PCAResults(n_components, explained_variance_ratio, cumulative_variance, components, transformed_data, pca_model, scaler, effective_dim, dataset_labels=None, backend='numpy', mean=None)
dataclass
Results from Principal Component Analysis.
Container for all PCA outputs including components, scores, variance statistics, and metadata. Supports both NumPy and JAX backends.
| ATTRIBUTE | DESCRIPTION |
|---|---|
n_components |
Number of principal components computed.
TYPE:
|
explained_variance_ratio |
Fraction of variance explained by each PC, shape (n_components,).
TYPE:
|
cumulative_variance |
Cumulative variance explained, shape (n_components,).
TYPE:
|
components |
Principal component vectors (eigenvectors), shape (n_components, nbins).
TYPE:
|
transformed_data |
Data projected to PC space (PC scores), shape (n_samples, n_components).
TYPE:
|
pca_model |
sklearn PCA model for compatibility (None for JAX backend).
TYPE:
|
scaler |
StandardScaler used to normalize data before PCA.
TYPE:
|
effective_dim |
Number of PCs explaining 95% of variance.
TYPE:
|
dataset_labels |
Labels identifying which dataset each sample belongs to.
TYPE:
|
backend |
Backend used ("numpy" or "jax").
TYPE:
|
mean |
Data mean before centering, shape (nbins,). Used for backend-agnostic reconstruction.
TYPE:
|
Examples:
>>> results = perform_pca(chains, nbins=20)
>>> print(f"Effective dimensionality: {results.effective_dim}")
>>> print(f"PC1 explains {results.explained_variance_ratio[0]:.1%}")
>>> print(f"Components shape: {results.components.shape}")
collect_delta_samples(chains_dict, nbins=None, param_pattern='delta_{i}', binning=None)
Collect all \(\delta\) samples from all chains into a single array.
Aggregates samples from multiple MCMC chains into a single data matrix suitable for PCA or other dimensionality reduction methods.
| PARAMETER | DESCRIPTION |
|---|---|
chains_dict
|
Dictionary mapping dataset labels to MCMC chains, or a single chain object (will be wrapped in dict).
TYPE:
|
nbins
|
Number of bins (default: 20).
TYPE:
|
param_pattern
|
Parameter name pattern (default: "delta_{i}").
TYPE:
|
binning
|
optional BinningScheme object (supersedes nbins, param_pattern if provided)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tuple[ndarray, List[str]]
|
Tuple of (X, labels): - X: Array of shape (n_total_samples, nbins) with all \(\delta\) values - labels: List of dataset labels for each sample |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If parameter names are not found in chains. |
Examples:
>>> # Collect from multiple chains
>>> X, labels = collect_delta_samples(chains, nbins=20)
>>> print(f"Total samples: {len(X)}")
>>> print(f"Unique datasets: {set(labels)}")
Source code in src/primefeat/pca/core.py
perform_pca(chains_dict, nbins=None, n_components=None, param_pattern='delta_{i}', mode='pooled', backend=None, verbose=True, binning=None)
Perform Principal Component Analysis on \(\delta\) parameters.
Identifies the dominant modes of variation in the primordial power spectrum deviations across datasets. Supports pooled analysis (combining all chains) or individual analysis (separate PCA per chain).
| PARAMETER | DESCRIPTION |
|---|---|
chains_dict
|
Dictionary mapping dataset labels to MCMC chains, or a single chain object (will be wrapped in dict).
TYPE:
|
nbins
|
Number of bins (default: 20).
TYPE:
|
n_components
|
Number of components to compute (default: nbins).
TYPE:
|
param_pattern
|
Parameter name pattern (default: "delta_{i}").
TYPE:
|
mode
|
Analysis mode (default: "pooled"): - "pooled": Perform PCA on pooled samples from all chains - "individual": Perform PCA separately on each chain
TYPE:
|
backend
|
Computation backend (default: None for auto-detection): - "numpy": NumPy/sklearn backend (CPU) - "jax": JAX backend (GPU-accelerated, autodiff-compatible) - None: Auto-detect (prefer JAX if available)
TYPE:
|
verbose
|
Whether to print progress and results (default: True). Set to False for silent operation in scripts/pipelines.
TYPE:
|
binning
|
optional BinningScheme object (supersedes nbins, param_pattern if provided)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Union[PCAResults, Dict[str, PCAResults]]
|
If mode="pooled": PCAResults object containing analysis results. |
Union[PCAResults, Dict[str, PCAResults]]
|
If mode="individual": Dictionary mapping chain labels to PCAResults objects. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If mode is not "pooled" or "individual". |
ImportError
|
If backend="jax" but JAX is not installed. |
Examples:
>>> # Pooled mode (default)
>>> results = perform_pca(chains, nbins=20)
>>> print(f"Effective dimensionality: {results.effective_dim}")
>>> print(f"Top 5 PCs explain {results.cumulative_variance[4]:.1%}")
>>> # Individual mode - analyze each chain separately
>>> results_dict = perform_pca(chains, nbins=20, mode="individual")
>>> for label, result in results_dict.items():
... print(f"{label}: {result.effective_dim} effective dims")
Source code in src/primefeat/pca/core.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
perform_ica(X, n_components=10, random_state=42)
Perform Independent Component Analysis on a \(\delta\) data matrix.
ICA finds statistically independent patterns, which can be better than PCA for identifying localized features or non-Gaussian structures in the primordial power spectrum deviations.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Data matrix of shape (n_samples, nbins). Typically obtained from collect_delta_samples().
TYPE:
|
n_components
|
Number of independent components to extract (default: 10).
TYPE:
|
random_state
|
Random seed for reproducibility (default: 42).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tuple[FastICA, ndarray, ndarray]
|
Tuple of (ica_model, X_ica, components): - ica_model: Fitted sklearn FastICA object - X_ica: Transformed data in IC space, shape (n_samples, n_components) - components: Independent components (unmixing matrix), shape (n_components, nbins) |
Examples:
>>> X, _ = collect_delta_samples(chains, nbins=20)
>>> ica, X_ica, components = perform_ica(X, n_components=10)
>>> print(f"Converged in {ica.n_iter_} iterations")
>>> # Plot IC1
>>> plt.plot(components[0])
Source code in src/primefeat/pca/core.py
compute_reconstruction_error(results, X_original, n_components)
Compute reconstruction error using only n_components PCs.
Quantifies how much information is lost by using fewer components. Useful for determining the optimal number of PCs to retain.
| PARAMETER | DESCRIPTION |
|---|---|
results
|
PCAResults from perform_pca().
TYPE:
|
X_original
|
Original (unstandardized) data, shape (n_samples, nbins).
TYPE:
|
n_components
|
Number of PCs to use for reconstruction.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Root mean squared error (RMSE) of reconstruction in standardized space. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If n_components > results.n_components. |
Examples:
>>> results = perform_pca(chains, nbins=20)
>>> X, _ = collect_delta_samples(chains, nbins=20)
>>> rmse_5pc = compute_reconstruction_error(results, X, n_components=5)
>>> rmse_10pc = compute_reconstruction_error(results, X, n_components=10)
>>> print(f"5 PCs: RMSE={rmse_5pc:.4f}, 10 PCs: RMSE={rmse_10pc:.4f}")
Source code in src/primefeat/pca/analysis.py
RMSE_vs_n_components(pca_result, X, max_components=None)
Compute reconstruction RMSE as a function of the number of PCs retained.
Evaluates how reconstruction quality improves as more principal components are included. Useful for finding the elbow point in an explained-variance curve.
| PARAMETER | DESCRIPTION |
|---|---|
pca_result
|
PCAResults from perform_pca().
TYPE:
|
X
|
Original (unstandardized) data matrix, shape (n_samples, nbins). Typically obtained from collect_delta_samples().
TYPE:
|
max_components
|
Maximum number of components to test (default: pca_result.n_components).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Dict[str, Any]]
|
List of dicts, one per component count k=1..max_components, each containing:
|
Examples:
>>> pca_result = perform_pca(chains, nbins=20)
>>> X, _ = collect_delta_samples(chains, nbins=20)
>>> errors = RMSE_vs_n_components(pca_result, X)
>>> for e in errors[:5]:
... print(f"PCs={e['n_components']}: RMSE={e['mean_rmse']:.4f}")
Source code in src/primefeat/pca/analysis.py
reconstruct_delta_from_pcs(results, pc_indices, sample_indices=None, return_mean=False)
Reconstruct \(\delta(k)\) using only specified principal components.
Allows selective reconstruction to study impact of individual PCs or groups. For example, reconstruct using PCs 2-8 to see the effect of dropping PC1.
Backend-agnostic: works with both NumPy and JAX PCA results.
| PARAMETER | DESCRIPTION |
|---|---|
results
|
PCAResults object from perform_pca()
TYPE:
|
pc_indices
|
List of PC indices to use (1-indexed, e.g., [2, 3, 4, 5, 6, 7, 8]) Uses 1-indexing to match standard PC naming (PC1, PC2, ...)
TYPE:
|
sample_indices
|
Optional sample index/indices to reconstruct: - None: reconstruct all samples - int: single sample - List[int]: multiple specific samples
TYPE:
|
return_mean
|
If True, average reconstruction across selected samples
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dictionary containing: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Examples:
>>> # Reconstruct using only PCs 2-8 (drop PC1)
>>> result = reconstruct_delta_from_pcs(pca_results, pc_indices=[2,3,4,5,6,7,8])
>>> delta_partial = result['delta'] # Shape: (n_samples, nbins)
>>> # See impact of PC1 alone
>>> result = reconstruct_delta_from_pcs(pca_results, pc_indices=[1])
>>> delta_pc1_only = result['delta']
>>> # Reconstruct single sample using PCs 1-5
>>> result = reconstruct_delta_from_pcs(pca_results, [1,2,3,4,5], sample_indices=42)
>>> delta_sample = result['delta'] # Shape: (nbins,)
>>> # Get mean reconstruction across all samples (for plotting)
>>> result = reconstruct_delta_from_pcs(pca_results, [2,3,4,5,6,7,8], return_mean=True)
>>> delta_mean = result['delta'] # Shape: (nbins,)
Source code in src/primefeat/pca/analysis.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
compare_pc_reconstructions(results, pc_sets, k_values=None, sample_indices=None, figsize=(12, 6), title=None)
Compare \(\delta(k)\) reconstructions using different PC subsets.
Useful for visualizing the impact of specific PCs or understanding how reconstruction quality changes with different PC selections.
| PARAMETER | DESCRIPTION |
|---|---|
results
|
PCAResults object from perform_pca()
TYPE:
|
pc_sets
|
Dictionary mapping labels to PC index lists Example: { 'Full (1-10)': [1,2,3,4,5,6,7,8,9,10], 'Without PC1': [2,3,4,5,6,7,8,9,10], 'PC1 only': [1], 'PCs 2-5': [2,3,4,5] }
TYPE:
|
k_values
|
Optional k-values for x-axis (Mpc\(^{-1}\)) If None, uses bin indices
TYPE:
|
sample_indices
|
Which samples to plot (None = mean over all)
TYPE:
|
figsize
|
Figure size (width, height)
TYPE:
|
title
|
Optional plot title
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
Figure object |
Example:
>>> pc_sets = {
... 'Full (PCs 1-10)': list(range(1, 11)),
... 'Drop PC1 (PCs 2-10)': list(range(2, 11)),
... 'PC1 only': [1],
... 'PCs 2-8': [2,3,4,5,6,7,8]
... }
>>> fig = compare_pc_reconstructions(pca_results, pc_sets, k_values=k)
>>> plt.show()
Source code in src/primefeat/pca/analysis.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
analyze_bin_correlations(chains_or_X, nbins=None, param_pattern='delta_{i}', binning=None)
Compute Pearson correlation matrix between \(\delta\) bins.
Shows which bins are correlated, typically due to smoothness constraints in the primordial power spectrum reconstruction or cosmic variance. High correlations between adjacent bins indicate the data prefers smooth \(\delta(k)\) variations.
| PARAMETER | DESCRIPTION |
|---|---|
chains_or_X
|
Either a chains dictionary (mapping labels to MCMC chains) or a pre-collected data matrix of shape (n_samples, nbins).
TYPE:
|
nbins
|
Number of bins (default: 20). Only used if chains_or_X is a chains dict.
TYPE:
|
param_pattern
|
Parameter name pattern (default: "delta_{i}"). Only used if chains_or_X is a chains dict.
TYPE:
|
binning
|
Optional BinningScheme (supersedes nbins, param_pattern if provided).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Correlation matrix of shape (nbins, nbins). Element [i,j] is the |
ndarray
|
Pearson correlation coefficient between bins i and j. |
Examples:
>>> # With chains dict
>>> corr = analyze_bin_correlations(chains, nbins=20)
>>> plt.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
>>> # With pre-collected data matrix
>>> X, _ = collect_delta_samples(chains, nbins=20)
>>> corr = analyze_bin_correlations(X)
>>> adj_corr = np.diag(corr, k=1).mean()
>>> print(f"Mean adjacent correlation: {adj_corr:.3f}")
Source code in src/primefeat/pca/analysis.py
variance_decomposition(pca_pooled, N_pcs=10, avg_n_eff=None)
Decompose variance into between-dataset and within-dataset components.
Analyzes how much of the variance in each principal component is due to differences between datasets versus variation within individual datasets. Uses ANOVA F-statistics to quantify dataset separation and computes signal-to-noise ratios based on effective sample sizes.
| PARAMETER | DESCRIPTION |
|---|---|
pca_pooled
|
PCAResults object from perform_pca() with mode="pooled".
TYPE:
|
N_pcs
|
Number of principal components to analyze (default: 10).
TYPE:
|
avg_n_eff
|
Average effective sample size for SNR scaling. If None, falls back to total sample count. Compute externally with np.mean([c.getEffectiveSamples() for c in chains.values()]).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Tuple of (variance_between, variance_within, variance_total, f_statistics, snr_values, p_values): - variance_between: List of between-dataset variance for each PC - variance_within: List of within-dataset variance for each PC - variance_total: List of total variance for each PC - f_statistics: List of F-statistics (between/within ratio) - snr_values: List of signal-to-noise ratios - p_values: List of ANOVA p-values testing mean differences |
Examples:
>>> results = perform_pca(chains, mode="pooled")
>>> n_eff = np.mean([c.getEffectiveSamples() for c in chains.values()])
>>> var_b, var_w, var_t, f_stats, snr, pvals = variance_decomposition(
... results, N_pcs=10, avg_n_eff=n_eff
... )
>>> print(f"PC1 F-statistic: {f_stats[0]:.3f}")
Source code in src/primefeat/pca/analysis.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | |