Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions package/CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ The rules for this file:
* 2.11.0

Fixes
* QCP falls back to a symmetric eigendecomposition when Newton's update or
cofactor-based rotation recovery fails for collinear inputs
(Issues #945, #1747).
* Fixed PBC handling in triclinic boxes in `_triclinic_pbc()` (used by
`distances.apply_PBC()`) and `lib.nsgrid.NSGrid` (used by `capped_distance`
and `self_capped_distance`):
Expand Down
54 changes: 46 additions & 8 deletions package/MDAnalysis/lib/qcprot.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,36 @@ cimport numpy as cnp
cnp.import_array()
cimport cython

from libc.float cimport DBL_EPSILON
from libc.math cimport isfinite
cdef double _eigh_fallback(cython.floating[:] rot,
cython.floating[:] A,
cython.floating E0, int N):
cdef double sxx=A[0], sxy=A[1], sxz=A[2]
cdef double syx=A[3], syy=A[4], syz=A[5]
cdef double szx=A[6], szy=A[7], szz=A[8]
cdef double w, x, y, z
K = np.array([
[sxx+syy+szz, syz-szy, szx-sxz, sxy-syx],
[syz-szy, sxx-syy-szz, sxy+syx, sxz+szx],
[szx-sxz, sxy+syx, -sxx+syy-szz, syz+szy],
[sxy-syx, sxz+szx, syz+szy, -sxx-syy+szz]], dtype=np.float64)
if rot is None:
values = np.linalg.eigvalsh(K)
else:
values, vectors = np.linalg.eigh(K)
w, x, y, z = vectors[:, -1]
rot[0] = w*w+x*x-y*y-z*z
rot[1] = 2*(x*y+w*z)
rot[2] = 2*(x*z-w*y)
rot[3] = 2*(x*y-w*z)
rot[4] = w*w-x*x+y*y-z*z
rot[5] = 2*(y*z+w*x)
rot[6] = 2*(x*z+w*y)
rot[7] = 2*(y*z-w*x)
rot[8] = w*w-x*x-y*y+z*z
return np.sqrt(abs(2.0*(E0-values[-1])/N))

from ..due import due, BibTeX, Doi

# providing DOI for this citation doesnt seem to work (as of 22/04/18)
Expand Down Expand Up @@ -363,6 +393,9 @@ cpdef double FastCalcRMSDAndRotation(cython.floating[:] rot,
cdef unsigned int i
cdef double mxEigenV
cdef double oldg = 0.0
cdef double numerator, denominator, derivative_scale
# Experimental relative threshold for cancellation in the derivative.
cdef double derivative_tol = 64.0 * sqrt(DBL_EPSILON)
cdef double b, a, delta, rms, qsqr
cdef double q1, q2, q3, q4, normq
cdef double a11, a12, a13, a14, a21, a22, a23, a24
Expand Down Expand Up @@ -428,13 +461,21 @@ cpdef double FastCalcRMSDAndRotation(cython.floating[:] rot,
x2 = mxEigenV*mxEigenV
b = (x2 + C[2])*mxEigenV
a = b + C[1]
delta = ((a*mxEigenV + C[0])/(2.0*x2*mxEigenV + b + a))
numerator = a*mxEigenV + C[0]
denominator = 2.0*x2*mxEigenV + b + a
derivative_scale = (4.0*fabs(x2*mxEigenV)
+ 2.0*fabs(C[2]*mxEigenV) + fabs(C[1]))
if fabs(denominator) <= derivative_tol * derivative_scale:
return _eigh_fallback(rot, A, E0, N)
delta = numerator / denominator
if not isfinite(delta):
return _eigh_fallback(rot, A, E0, N)
mxEigenV -= delta
if (fabs(mxEigenV - oldg) < fabs((evalprec)*mxEigenV)):
break

# if (i == 50):
# print "\nMore than %d iterations needed!\n" % (i)
else:
return _eigh_fallback(rot, A, E0, N)

# the fabs() is to guard against extremely small,
# but *negative* numbers due to floating point error
Expand Down Expand Up @@ -506,11 +547,8 @@ cpdef double FastCalcRMSDAndRotation(cython.floating[:] rot,
qsqr = q1*q1 + q2 *q2 + q3*q3 + q4*q4

if (qsqr < evecprec):
# if qsqr is still too small, return the identity matrix. #
rot[0] = rot[4] = rot[8] = 1.0
rot[1] = rot[2] = rot[3] = rot[5] = rot[6] = rot[7] = 0.0

return rms
# Cofactors cannot provide a usable quaternion.
return _eigh_fallback(rot, A, E0, N)

normq = sqrt(qsqr)
q1 /= normq
Expand Down
16 changes: 14 additions & 2 deletions testsuite/MDAnalysisTests/analysis/test_align.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ def does_not_raise():
yield


def _assert_rotation_matches_rmsd(a, b, rotation, rmsd, weights):
a = np.asarray(a, dtype=np.float64)
b = np.asarray(b, dtype=np.float64)
weights = np.ones(len(a)) if weights is None else np.asarray(weights)
achieved = np.sqrt(
np.average(np.sum((a @ rotation.T - b) ** 2, axis=1), weights=weights)
)
assert_allclose(rotation @ rotation.T, np.eye(3), atol=1e-10)
assert np.linalg.det(rotation) == pytest.approx(1.0, abs=1e-10)
assert achieved == pytest.approx(rmsd, abs=1e-7)


class TestRotationMatrix:
a = np.array([[0.1, 0.2, 0.3], [1.1, 1.1, 1.1]])
b = np.array([[0.1, 0.1, 0.1], [1.1, 1.1, 1.1]])
Expand All @@ -68,15 +80,15 @@ class TestRotationMatrix:
)
def test_rotation_matrix_input(self, a, b, weights, expected):
rot, rmsd = align.rotation_matrix(a, b, weights)
assert_equal(rot, np.eye(3))
_assert_rotation_matches_rmsd(a, b, rot, rmsd, weights)
assert rmsd == pytest.approx(expected)

def test_list_args(self):
a = [[0.1, 0.2, 0.3], [1.1, 1.1, 1.1]]
b = [[0.1, 0.1, 0.1], [1.1, 1.1, 1.1]]
w = [1.3, 2.3]
rot, rmsd = align.rotation_matrix(a, b, w)
assert_equal(rot, np.eye(3))
_assert_rotation_matches_rmsd(a, b, rot, rmsd, w)
assert rmsd == pytest.approx(0.13424643502242328)

def test_exception(self):
Expand Down
6 changes: 5 additions & 1 deletion testsuite/MDAnalysisTests/lib/test_qcprot.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ def test_dummy(self, dtype):

assert r == pytest.approx(0.7174389197644676, abs=err)
assert rot.dtype == dtype
assert_allclose(rot.reshape(3, 3), np.eye(3))
matrix = rot.reshape(3, 3)
assert_allclose(matrix @ matrix.T, np.eye(3), atol=err)
assert np.linalg.det(matrix) == pytest.approx(1.0, abs=err)
achieved = np.sqrt(np.mean(np.sum((a @ matrix.T - b) ** 2, axis=1)))
assert achieved == pytest.approx(r, abs=err)

def test_regression(self, dtype):
u = mda.Universe(PSF, DCD)
Expand Down
119 changes: 119 additions & 0 deletions testsuite/MDAnalysisTests/lib/test_qcprot_degenerate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Regression checks for collinear QCP inputs (issues #945 and #1747)."""

import numpy as np
import pytest
from numpy.testing import assert_allclose

from MDAnalysis.lib import qcprot
from MDAnalysis.analysis import align, rms


def _issue_coordinates(case):
if case == "945":
x = np.ones((100, 3)) + np.arange(100)[:, None]
y = np.zeros((100, 3)) + np.arange(100)[:, None]
elif case == "1747":
x = np.array(
[
[0.13662023, -0.39526145, 0.75835566],
[-0.13662023, 0.39526145, -0.75835566],
]
)
y = np.array(
[
[-0.30452963, 0.78899221, -0.18642158],
[0.30452963, -0.78899221, 0.18642158],
]
)
elif case == "perpendicular":
x = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
y = np.array([[0.0, -1.0, 0.0], [0.0, 1.0, 0.0]])
else:
x = np.zeros((4, 3))
y = np.ones((4, 3))
return x, y


def _svd_reference(x, y, weights):
u, _, vt = np.linalg.svd(x.T @ (weights[:, None] * y))
rotation = u @ np.diag([1.0, 1.0, np.linalg.det(u @ vt)]) @ vt
return np.sqrt(
np.average(np.sum((x @ rotation - y) ** 2, axis=1), weights=weights)
)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize("case", ["945", "1747", "perpendicular", "collapsed"])
@pytest.mark.parametrize("scale", [1e-3, 1.0, 1e3])
@pytest.mark.parametrize("weighted", [False, True])
@pytest.mark.parametrize("with_rotation", [False, True])
def test_collinear_qcp(dtype, case, scale, weighted, with_rotation):
x, y = _issue_coordinates(case)
weights = np.linspace(1.0, 2.0, len(x)) if weighted else np.ones(len(x))
weights /= weights.mean()
x -= np.average(x, axis=0, weights=weights)
y -= np.average(y, axis=0, weights=weights)
x = np.ascontiguousarray(x * scale, dtype=dtype)
y = np.ascontiguousarray(y * scale, dtype=dtype)
low_weights = weights.astype(dtype) if weighted else None
w = np.ones(len(x)) if low_weights is None else low_weights.astype(float)
xd, yd = x.astype(float), y.astype(float)
expected = _svd_reference(xd, yd, w)
coordinate_scale = np.sqrt(
np.average(np.sum(xd * xd + yd * yd, axis=1), weights=w) / 2
)
rot = np.zeros(9, dtype=dtype) if with_rotation else None
result = qcprot.CalcRMSDRotationalMatrix(x, y, len(x), rot, low_weights)
assert np.isfinite(result)
# Accumulation and the E0-lambda subtraction limit RMSD accuracy near zero.
squared_atol = 32 * len(x) * np.finfo(dtype).eps * coordinate_scale**2
assert abs(result**2 - expected**2) <= squared_atol + 1e-24
if with_rotation:
matrix = rot.astype(float).reshape(3, 3)
atol = 1e-6 if dtype is np.float32 else 1e-10
assert_allclose(matrix @ matrix.T, np.eye(3), atol=atol, rtol=0)
assert np.linalg.det(matrix) == pytest.approx(1.0, abs=atol)
achieved = np.sqrt(
np.average(np.sum((xd @ matrix.T - yd) ** 2, axis=1), weights=w)
)
alignment_atol = 1e-6 if dtype is np.float32 else 1e-7
assert (
abs(achieved - expected)
<= alignment_atol * coordinate_scale + 1e-12
)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize("case", ["945", "1747", "perpendicular"])
def test_collinear_public_api(dtype, case):
x, y = _issue_coordinates(case)
x, y = x.astype(dtype), y.astype(dtype)
xc = x.astype(float) - x.astype(float).mean(axis=0)
yc = y.astype(float) - y.astype(float).mean(axis=0)
expected = _svd_reference(xc, yc, np.ones(len(x)))
result = rms.rmsd(x, y, superposition=True)
scale = np.sqrt(np.mean(np.sum(xc * xc + yc * yc, axis=1)) / 2)
assert result == pytest.approx(expected, abs=5e-8 * scale)
rotation, value = align.rotation_matrix(xc, yc)
achieved = np.sqrt(np.mean(np.sum((xc @ rotation.T - yc) ** 2, axis=1)))
assert achieved == pytest.approx(expected, abs=5e-8 * scale)
assert value == pytest.approx(expected, abs=5e-8 * scale)


def test_scalar_fallback_skips_eigenvectors(monkeypatch):
x, y = _issue_coordinates("perpendicular")
original = np.linalg.eigvalsh
calls = []

def eigenvalues(matrix):
calls.append(matrix.shape)
return original(matrix)

def unexpected_eigenvectors(matrix):
pytest.fail("RMSD-only fallback should not compute eigenvectors")

monkeypatch.setattr(np.linalg, "eigvalsh", eigenvalues)
monkeypatch.setattr(np.linalg, "eigh", unexpected_eigenvectors)
result = qcprot.CalcRMSDRotationalMatrix(x, y, len(x), None, None)
assert result == pytest.approx(0.0, abs=1e-12)
assert calls == [(4, 4)]
Loading