def principal_coordinates(D, nd=None):
"""
Reconstruction of a multidimensional configuration that
optimally reproduces the input distance matrix.
See: Gower, J (1966)
"""
from numpy import clip, sqrt, take, argsort, sort
from csb.numeric import reverse
from scipy.linalg import eigh
## calculate centered similarity matrix
B = -clip(D, 1e-150, 1e150) ** 2 / 2.
b = B.mean(0)
B = B - b
B = (B.T - b).T
B += b.mean()
## calculate spectral decomposition
v, U = eigh(B)
v = v.real
U = U.real
U = take(U, argsort(v), 1)
v = sort(v)
U = reverse(U, 1)
v = reverse(v)
if nd is None: nd = len(v)
X = U[:, :nd] * sqrt(clip(v[:nd], 0., 1e300))
return X
评论列表
文章目录