Repository navigation
Description
Is your feature request related to a problem?
tl;dr PCA().run() could be much faster if we compute the covariance matrix in one shot rather than build it incrementally per-frame, and also would benefit a lot from switching from np.linalg.eig to np.linalg.eigh.
Taking the ADK equilibrium trajectory data as an example workflow, we might do something like:
import MDAnalysis as mda
from MDAnalysisData import datasets
from MDAnalysis.analysis import pca
adk = datasets.fetch_adk_equilibrium()
universe = mda.Universe(adk.topology, adk.trajectory)
pc = pca.PCA(universe, align=True)
pc.run()This takes 881 seconds (~15 mins) on a GCloud c2d-standard-4 (only 5.2s though if you only want to look at Calcium atoms or something).
Among the largest contributors to the runtime are the incremental covariance matrix computation (one dot call per frame):
mdanalysis/package/MDAnalysis/analysis/pca.py
Line 332 in 35e4334
| self.cov += np.dot(x[:, np.newaxis], x[:, np.newaxis].T) |
And also using eig to calculate the eigenvalues and eigenvectors of that covariance matrix:
mdanalysis/package/MDAnalysis/analysis/pca.py
Line 336 in 35e4334
| e_vals, e_vects = np.linalg.eig(self.cov) |
Describe the solution you'd like
Two changes here would make a big difference:
- Computing the covariance matrix once during
_conclude(can use the highly optimized blas gemm kernel). - Using
eighinstead ofeig, since the covariance matrix is symmetric and real-valued by construction.
Describe alternatives you've considered
The alternative is to do one or the other or nothing, but I think both of these changes are fairly straightforward. There's going to be a modest change in peak memory usage; building the covariance matrix in one go will require more than before, but eigh allocates a smaller workspace, so it's a bit of a wash. I'll put some memory profiling in my PR.
Activity
lilyminium commentedon Nov 16, 2026
Upvote for replacing eig with eigh -- I think this is also the cause of the 0.0000j value in the PCA notebook of the UserGuide (MDAnalysis/UserGuide#452)
jberg5 commentedon Nov 18, 2026
Thanks @lilyminium ! Yes that's another nice feature of
eigh, we're guaranteed real eigenvalues. Out of interest, where is the PCA notebook you're talking about? I don't see it in your link MDAnalysis/UserGuide#452 but maybe I'm looking in the wrong place.RMeli commentedon Nov 24, 2026
@jberg5 we had values that were real before turning to complex (with zero imaginary part) in the user guide example. See for example here for a failed such test before the snapshots were updated: https://github.com/MDAnalysis/UserGuide/actions/runs/43832271519/job/133180195424#step:7:177