Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_logm():
"""Test matrix logarithm"""
C = 2*np.eye(3)
Ctrue = np.log(2)*np.eye(3)
assert_array_almost_equal(logm(C), Ctrue)
def distance_logeuclid(A, B):
"""Log Euclidean distance between two covariance matrices A and B.
.. math::
d = \Vert \log(\mathbf{A}) - \log(\mathbf{B}) \Vert_F
:param A: First covariance matrix
:param B: Second covariance matrix
:returns: Log-Eclidean distance between A and B
"""
return distance_euclid(logm(A), logm(B))
else:
C = init
k = 0
nu = 1.0
tau = numpy.finfo(numpy.float64).max
crit = numpy.finfo(numpy.float64).max
# stop when J<10^-9 or max iteration = 50
while (crit > tol) and (k < maxiter) and (nu > tol):
k = k + 1
C12 = sqrtm(C)
Cm12 = invsqrtm(C)
J = numpy.zeros((Ne, Ne))
for index in range(Nt):
tmp = numpy.dot(numpy.dot(Cm12, covmats[index, :, :]), Cm12)
J += sample_weight[index] * logm(tmp)
crit = numpy.linalg.norm(J, ord='fro')
h = nu * crit
C = numpy.dot(numpy.dot(C12, expm(nu * J)), C12)
if h < tau:
nu = 0.95 * nu
tau = h
else:
nu = 0.5 * nu
return C
"""Return the mean covariance matrix according to the log-euclidean metric.
.. math::
\mathbf{C} = \exp{(\\frac{1}{N} \sum_i \log{\mathbf{C}_i})}
:param covmats: Covariance matrices set, Ntrials X Nchannels X Nchannels
:param sample_weight: the weight of each sample
:returns: the mean covariance matrix
"""
sample_weight = _get_sample_weight(sample_weight, covmats)
Nt, Ne, Ne = covmats.shape
T = numpy.zeros((Ne, Ne))
for index in range(Nt):
T += sample_weight[index] * logm(covmats[index, :, :])
C = expm(T)
return C
:param Cref: np.ndarray
The reference covariance matrix
:returns: np.ndarray
the Tangent space , a matrix of Ntrials X (Nchannels*(Nchannels+1)/2)
"""
Nt, Ne, Ne = covmats.shape
Cm12 = invsqrtm(Cref)
idx = numpy.triu_indices_from(Cref)
Nf = int(Ne * (Ne + 1) / 2)
T = numpy.empty((Nt, Nf))
coeffs = (numpy.sqrt(2) * numpy.triu(numpy.ones((Ne, Ne)), 1) +
numpy.eye(Ne))[idx]
for index in range(Nt):
tmp = numpy.dot(numpy.dot(Cm12, covmats[index, :, :]), Cm12)
tmp = logm(tmp)
T[index, :] = numpy.multiply(coeffs, tmp[idx])
return T
Matrices', PLoS ONE, 2015
"""
sample_weight = _get_sample_weight(sample_weight, covmats)
Nt, Ne, Ne = covmats.shape
crit = numpy.inf
k = 0
# init with AJD
B, _ = ajd_pham(covmats)
while (crit > tol) and (k < maxiter):
k += 1
J = numpy.zeros((Ne, Ne))
for index, Ci in enumerate(covmats):
tmp = logm(numpy.dot(numpy.dot(B.T, Ci), B))
J += sample_weight[index] * tmp
update = numpy.diag(numpy.diag(expm(J)))
B = numpy.dot(B, invsqrtm(update))
crit = distance_riemann(numpy.eye(Ne), update)
A = numpy.linalg.inv(B)
J = numpy.zeros((Ne, Ne))
for index, Ci in enumerate(covmats):
tmp = logm(numpy.dot(numpy.dot(B.T, Ci), B))
J += sample_weight[index] * tmp
C = numpy.dot(numpy.dot(A.T, expm(J)), A)
return C