Principal Component Analysis module
pca
Dimensionality reduction and feature extraction for primordial features analysis.
This module provides tools to reduce the N-dimensional bin parameter space to a smaller number of interpretable components, revealing the dominant modes of variation in \(\delta(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=20, param_pattern='delta_{i}')
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:
|
| 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.py
perform_pca(chains_dict, nbins=20, n_components=None, param_pattern='delta_{i}', mode='pooled', backend=None, verbose=True)
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:
|
| 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.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 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 | |
perform_ica(chains_dict, nbins=20, n_components=10, param_pattern='delta_{i}', random_state=42)
Perform Independent Component Analysis on \(\delta\) parameters.
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 |
|---|---|
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 independent components to extract (default: 10).
TYPE:
|
param_pattern
|
Parameter name pattern (default: "delta_{i}").
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) |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If parameter names are not found in chains. |
Examples:
>>> ica, X_ica, components = perform_ica(chains, nbins=20, n_components=10)
>>> print(f"Converged in {ica.n_iter_} iterations")
>>> # Plot IC1
>>> plt.plot(components[0])
Source code in src/primefeat/pca.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.
Note
Requires NumPy backend (uses pca_model.inverse_transform).
| 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. |
AttributeError
|
If results.pca_model is None (JAX backend). |
Examples:
>>> results = perform_pca(chains, nbins=20, backend="numpy")
>>> 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.py
RMSE_vs_n_components(chains_dict, nbins=20, max_components=None)
Compute reconstruction error (RMSE) as a function of number of PCs.
Evaluates how reconstruction quality improves as more principal components are included. Useful for determining the optimal number of PCs to retain.
| PARAMETER | DESCRIPTION |
|---|---|
chains_dict
|
Dictionary mapping dataset labels to MCMC chains, or a single chain object (will be wrapped in dict).
|
nbins
|
Number of bins (default: 20).
DEFAULT:
|
max_components
|
Maximum number of components to test (default: nbins).
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Tuple of (error_values, pca_result):
|
Examples:
>>> errors, pca = RMSE_vs_n_components(chains, nbins=20)
>>> # Find elbow point
>>> for e in errors[:5]:
... print(f"PCs={e['n_components']}: RMSE={e['mean_rmse']:.4f}")
>>> # Plot reconstruction error curve
>>> import matplotlib.pyplot as plt
>>> plt.plot([e['n_components'] for e in errors],
... [e['mean_rmse'] for e in errors])
Source code in src/primefeat/pca.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 | |
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.py
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 | |
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.py
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 | |
analyze_bin_correlations(chains_dict, nbins=20)
Compute 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_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:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Correlation matrix of shape (nbins, nbins). Element [i,j] is the |
ndarray
|
Pearson correlation coefficient between bins i and j. |
Examples:
>>> corr = analyze_bin_correlations(chains, nbins=20)
>>> # Visualize correlation structure
>>> plt.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
>>> plt.colorbar(label='Correlation')
>>> # Check adjacent bin correlations
>>> adj_corr = np.diag(corr, k=1).mean()
>>> print(f"Mean adjacent correlation: {adj_corr:.3f}")
Source code in src/primefeat/pca.py
variance_decomposition(pca_pooled, N_pcs=10, chains_dict=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".
|
N_pcs
|
Number of principal components to analyze (default: 10).
DEFAULT:
|
chains_dict
|
Optional dict of chains to compute effective sample sizes. If None, uses total sample count for SNR calculation.
DEFAULT:
|
| 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")
>>> var_b, var_w, var_t, f_stats, snr, pvals = variance_decomposition(
... results, N_pcs=10, chains_dict=chains
... )
>>> # High F-stat indicates PC separates datasets well
>>> print(f"PC1 F-statistic: {f_stats[0]:.3f}")
>>> # Low p-value indicates significant dataset separation
>>> print(f"PC1 p-value: {pvals[0]:.2e}")
Source code in src/primefeat/pca.py
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 | |