Skip to content

Use eigh for PCA - #5563

Merged
RMeli merged 4 commits into
MDAnalysis:developfrom
jberg5:eigh
Nov 27, 2026
Merged

RMeli merged 4 commits into
MDAnalysis:developfrom
jberg5:eigh

Conversation

@jberg5

@jberg5 jberg5 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Partially addresses #5351

Split out of an earlier PR, per #5352 (comment)

Changes made in this Pull Request:

  • Switch from eig to eigh for PCA, since the covariance matrix is symmetric by construction.

This fixes the behavior flagged in #5351 (comment) where sometimes results would be complex. eigh also uses less memory and is much faster.

Rough before/after table (llm generated, it is much better at formatting these than I am) from running this benchmarking script on my macbook (script was also llm generated):

bench_pca_before_after.py
"""Before/after benchmark for PCA.run() and PCA.transform().

Run once per branch with the same venv, then compare:

    .venv/bin/python bench_pca_before_after.py            # backbone (2565 dims)
    .venv/bin/python bench_pca_before_after.py all        # all-atom (10023 dims, slow)

Uses the AdK equilibrium trajectory (4187 frames) from MDAnalysisData's cache.
"""

import resource
import sys
import time
import warnings
from pathlib import Path

import numpy as np
import MDAnalysis as mda
from MDAnalysis.analysis import pca

# DCDReader emits this on every load; unrelated to PCA
warnings.filterwarnings(
    "ignore", message="DCDReader currently makes", category=DeprecationWarning
)

DATA = Path.home() / "MDAnalysis_data" / "adk_equilibrium"
SELECTIONS = {"backbone": "backbone", "ca": "name CA", "all": "all"}
REPEATS = 3

select = SELECTIONS[sys.argv[1] if len(sys.argv) > 1 else "backbone"]
u = mda.Universe(
    str(DATA / "adk4AKE.psf"), str(DATA / "1ake_007-nowater-core-dt240ps.dcd")
)
atoms = u.select_atoms(select)

run_times, transform_times = [], []
for _ in range(REPEATS):
    t0 = time.perf_counter()
    pc = pca.PCA(u, select=select, align=True).run()
    run_times.append(time.perf_counter() - t0)

    t0 = time.perf_counter()
    projected = pc.transform(atoms, n_components=3)
    transform_times.append(time.perf_counter() - t0)

# ru_maxrss is bytes on macOS, kilobytes on Linux
peak_rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
peak_mb = peak_rss / 2**20 if sys.platform == "darwin" else peak_rss / 2**10

print(f"MDAnalysis {mda.__version__} ({Path(mda.__file__).parent}), numpy {np.__version__}")
print(f"selection={select!r} atoms={atoms.n_atoms} frames={u.trajectory.n_frames}")
print(f"run():       min {min(run_times):7.2f} s   (all: {', '.join(f'{t:.2f}' for t in run_times)})")
print(f"transform(): min {min(transform_times):7.2f} s   (all: {', '.join(f'{t:.2f}' for t in transform_times)})")
print(f"peak RSS:    {peak_mb:.0f} MB")
variance = pc.results.variance
print(f"variance dtype={variance.dtype}, PC1 variance={variance[0].real:.5f}")
print(f"cumulated variance (first 3): {np.round(pc.results.cumulated_variance[:3].real, 3)}")
print(f"projection frame 0: {np.round(projected[0], 3)}")
┌────────────────┬───────────────┬─────────────┬────────┐
│                │ develop (eig) │ eigh branch │ change │
├────────────────┼───────────────┼─────────────┼────────┤
│ run()          │ 36.79 s       │ 30.83 s     │ −16%   │
├────────────────┼───────────────┼─────────────┼────────┤
│ transform()    │ 0.35 s        │ 0.25 s      │ −29%   │
├────────────────┼───────────────┼─────────────┼────────┤
│ peak RSS       │ 733 MB        │ 475 MB      │ −35%   │
├────────────────┼───────────────┼─────────────┼────────┤
│ variance dtype │ complex128    │ float64     │ fixed  │
└────────────────┴───────────────┴─────────────┴────────┘

LLM / AI generated code disclosure

  • I have read and understood MDAnalysis's AI policy in AI_POLICY.md.

LLMs or other AI-powered tools (beyond simple IDE use cases) were used in this contribution: not for writing the code in this diff. yes for reviewing the diff, and writing one-off benchmarking scripts like the one above.

PR Checklist

  • Issue raised/referenced?
  • Tests updated/added?
  • Documentation updated/added?
  • package/CHANGELOG file updated?
  • Is your name in package/AUTHORS? (If it is not, add it!)
  • I have read and understand the current AI Policy
  • LLM/AI disclosure was updated.

Developers Certificate of Origin

I certify that I can submit this code contribution as described in the Developer Certificate of Origin, under the MDAnalysis LICENSE.

@read-the-docs-community

read-the-docs-community Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 MDAnalysis | 🛠️ Build #36217776 | 📁 Comparing 00cf1df against latest (5d5a634)

  🔍 Preview build  

3 files changed
± index.html
± documentation_pages/analysis/wbridge_analysis.html
± _modules/MDAnalysis/analysis/pca.html

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.93%. Comparing base (5d5a634) to head (00cf1df).

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #5563      +/-   ##
===========================================
- Coverage    93.93%   93.93%   -0.01%     
===========================================
  Files          184      184              
  Lines        22680    22679       -1     
  Branches      3228     3228              
===========================================
- Hits         21304    21303       -1     
  Misses         916      916              
  Partials       460      460              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@RMeli RMeli left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks.

Comment thread package/CHANGELOG Resolved

@orbeckst orbeckst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thank you!

(I also looked at other uses of eig() and only found one other instances that we may want to change in DistanceMatrix; this is something we may want to look at with #5518 )

def _conclude(self):
self.cov /= self.n_frames - 1
e_vals, e_vects = np.linalg.eig(self.cov)
sort_idx = np.argsort(e_vals)[::-1]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is ok, I just checked that eigh() since at least 1.26 returns evals in sorted order (unlike eig)

@orbeckst orbeckst self-assigned this Nov 27, 2026
@RMeli
RMeli merged commit f4ffee3 into MDAnalysis:develop Nov 27, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants