Skip to content

Qcp collinear fallback - #5525

Open
sici17 wants to merge 6 commits into
MDAnalysis:developfrom
sici17:qcp-collinear-fallback
Open

sici17 wants to merge 6 commits into
MDAnalysis:developfrom
sici17:qcp-collinear-fallback

Conversation

@sici17

@sici17 sici17 commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Fixes #945, fixes #1747.

Changes made in this Pull Request:

Related issues: #945 and #1747.

Problem

Both issues are caused by the same problem, QCP failure. After centering, both examples have rank-one centered coordinates. This causes repeated largest eigenvalue and the inital estimate E0 to be equal or numerically very close to that value. This causes having to deal with a vanishing derivative which creates zero divisions or unstable convergence for the algorithm.

Proposed Approach

keep the existing QCP standard approach with a fallback in these situations:

  • the polynomial derivative is too small relative to the magnitudes of its terms;
  • the Newton update becomes non-finite;
  • Newton exhausts its iteration limit without satisfying its convergence criterion.

Rotation Recovery

Solving the newton update problem exposed a second one, in the case of repeated largest eigenvalues the cofactors to solve K - λI vanish, if every candidate quaternion is too small, the implementation returns the identity matrix. This matrix could work but not necessarily.

Proposed Approach

A fallback to replace this identity return with a normalized eigenvector associated with the largest eigenvalue, which is then converted in a rotation matrix

LLM / AI generated code disclosure

LLMs or other AI-powered tools (beyond simple IDE use cases) were used in this contribution: yes

I wrote this PR description and worked through the problem and design choices in discussion with GPT 6.1 Sol and Astra. GPT generated the experimental implementation, validation scripts, and ran the local checks. I have the full understanding of the math involved in this problem and what happened inside the code.

PR Checklist

Developers Certificate of Origin

I certify that I can submit this code contribution as described in the [Developer Certificate of Origin](https://developercertificate.org/), under the MDAnalysis [LICENSE](https://github.com/MDAnalysis/mdanalysis/blob/develop/LICENSE).

Experimental eigvalsh/eigh fallback for issues MDAnalysis#945 and MDAnalysis#1747. Implementation generated with GPT during the numerical investigation. The derivative threshold remains experimental.
Cover issues MDAnalysis#945 and MDAnalysis#1747, weighted inputs, native float32/float64, and RMSD-only fallback dispatch. Check returned rotation invariants instead of requiring the identity. Tests generated with GPT.
Replace identity-only expectations with orthogonality, determinant and achieved RMSD checks. Test changes generated with GPT.
@read-the-docs-community

read-the-docs-community Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

@codecov

codecov Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.91%. Comparing base (0fd2f58) to head (6ecbc62).
⚠️ Report is 10 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #5525   +/-   ##
========================================
  Coverage    93.91%   93.91%           
========================================
  Files          184      184           
  Lines        22644    22661   +17     
  Branches      3219     3223    +4     
========================================
+ Hits         21267    21283   +16     
- Misses         917      918    +1     
  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.

@orbeckst

orbeckst commented Nov 3, 2026

Copy link
Copy Markdown
Member

Can you explain the math with the proper equations? You can use mathjax/latex in GH markdown.

@sici17

sici17 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Why QCP needs a fallback

QCP aims to find the rotation between 2 sets of points that minimizes the following term

$$ F(R)=\sum_{i=1}^{N}|Rx_i-y_i|^2, \qquad R\in SO(3). $$

We can write it in terms of rotation $R(q)$ where $q$ is a unit quaternion

$$ F(R(q))=2(E_0-q^\mathsf{T}Kq), \qquad E_0=\frac12\sum_{i=1}^{N}\bigl(|x_i|^2+|y_i|^2\bigr). $$

Minimizing $F$ is about finding the largest eigenvalue of $K$. QCP estimates it by applying Newton’s method.

$$ \lambda_{k+1}=\lambda_k-\frac{p(\lambda_k)}{p'(\lambda_k)}. $$

In both issues, the centered point sets are collinear and their cross-correlation matrix has rank one. If $s$ is its single nonzero singular value, $K$ has eigenvalues $-s,-s,s,s$. This gives

$$ p(\lambda)=(\lambda^2-s^2)^2, \qquad \lambda_{\max}=s, \qquad E_0-s=\frac{N}{2}\cdot\mathrm{RMSD}_{\min}^{2}. $$

The two examples have zero or very small minimum RMSD, so Newton starts at or near the double root $s$, where both $p(s)$ and $p'(s)$ vanish.

Here is the 3 different cases where the fallback is activated, the 2 original issues refer to the first part of the first case:

1. $E_0=s$ or derivative is small relative to its terms

Consider the centered segments

$$ X=\bigl((-1,0,0),(1,0,0)\bigr), \qquad Y=\bigl((0,-1,0),(0,1,0)\bigr). $$

Here $E_0=s=2$, Newton's step attempts $0/0$. The derivative check triggers the fallback before the division.
This check also catches a nonzero derivative whose terms nearly cancel, the fallback is triggered when

$$ |p'(\lambda)|\leq64\sqrt{\varepsilon}\cdot S(\lambda), \qquad S(\lambda)=4|\lambda|^3+2|C_2\lambda|+|C_1|, $$

The ratio $|p'(\lambda)|/S(\lambda)$ measures how much remains after the derivative terms are added, relative to the sum of their magnitudes. When the terms nearly cancel, small rounding errors can have a large effect on the computed derivative and, as a conseguence, on the Newton's step. The guard uses $64\sqrt{\varepsilon}$ as an empirical cutoff, where $\varepsilon$ is double-precision machine epsilon.

2. Non-finite Newton step

As a double-precision stress test, take

$$ X=\bigl((-c,0,0),(c,0,0)\bigr), \qquad Y=\bigl((-2c,0,0),(2c,0,0)\bigr), \qquad c=10^{50}. $$

The polynomial evaluation produces NaN due to overflow, so the Newton step delta is also NaN. The isfinite(delta) check triggers the fallback.

3. Iteration limit

Consider the centered coordinates

$$ X=\bigl((-1,0,0),(1,0,0),(-1,0,0),(1,0,0)\bigr), $$

$$ Y=\bigl((0,-1,0),(0,-1,0),(0,1,0),(0,1,0)\bigr). $$

Their cross-correlation matrix is zero, so $K=0$ and $p(\lambda)=\lambda^4$, while $E_0=4$. Newton gives

$$ \lambda_{k+1}=\frac34\lambda_k, \qquad \lambda_{50}=4\left(\frac34\right)^{50} \approx2.2653\times10^{-6}. $$

Here the relative step $\lvert\lambda_{k+1}-\lambda_k\rvert/\lvert\lambda_{k+1}\rvert$ stays at $1/3$, well above the Newton's step $10^{-14}$ convergence tolerance. The fallback therefore triggers after 50 iterations.

Fallback

In these cases, the fallback uses NumPy to solve the eigenvalue problem directly on the symmetric matrix $K$. This avoids evaluating the characteristic polynomial and dividing by its derivative, making the fallback more robust in these cases. It does more work than the usual QCP path when Newton converges in a few steps.

@sici17

sici17 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

I hope is detailed enough, or maybe I wrote too much, I don't know how deep I should have gone, let me know. I didn't talk about the rotation recovery problem that Astra reported to me after fixing the QCP. Let me know if you want me to write something about it.

@orbeckst

Copy link
Copy Markdown
Member

Thanks for providing more detail. It will likely take a while until I have time to look at this closely. Thank you for your patience. I'd be happy if someone else jumped in an commented/reviewed!

@sici17

sici17 commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the answer. I’ll wait for some feedback then. If I can make a suggestion to who is going to look at this, I’d focus on the $64\sqrt{\varepsilon}$ cutoff, where GPT Astra suggested $64$ as a heuristic after some analysis, and the fallback for recovering the rotation matrix, which is pretty hard to test in isolation.

This branch has not been deployed

No deployments
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.

Division by 0 in alinging two lines with rotation_matrix(a, b) RMSD throws divide-by-zero error if a position is exactly 0.

2 participants