Here are the examples of the python api numpy.diag taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
164 Examples
3
Example 1
Project: cvxpy Source File: diag.py
@AffAtom.numpy_numeric
def numeric(self, values):
"""Convert the vector constant into a diagonal matrix.
"""
# Convert values to 1D.
value = intf.from_2D_to_1D(values[0])
return np.diag(value)
3
Example 2
Project: EDeN Source File: selector.py
def select(self, data_matrix, target=None):
"""select."""
# compute parent relationship
self.parent_ids = self.parents(data_matrix, target=target)
# compute norm of parent-instance vector
# compute parent vectors
parents = data_matrix[self.parent_ids]
# compute difference
diffs = np.diag(pairwise_distances(data_matrix, Y=parents))
# sort from largest distance to smallest
parent_distance_sorted_ids = list(np.argsort(-diffs))
selected_instances_ids = []
# add root (i.e. instance with distance 0 from parent)
selected_instances_ids = [parent_distance_sorted_ids[-1]] + \
parent_distance_sorted_ids[:self.n_instances - 1]
return selected_instances_ids
3
Example 3
Project: mystic Source File: dejong.py
def hessian(self, coeffs):
"""evaluates an N-dimensional Rosenbrock hessian for the given coeffs
The function f''(x) requires len(x) >= 2."""
x = atleast_1d(coeffs)
H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1)
diagonal = zeros(len(x), dtype=x.dtype)
diagonal[0] = 1200*x[0]-400*x[1]+2
diagonal[-1] = 200
diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:]
H = H + diag(diagonal)
return H
3
Example 4
Project: cardoon Source File: nodal.py
def add_to_diagonal(M, vec):
"""
Adds vec to matrix diagonal
M is dense and vec is a single-dimensional list or array with
length less than matrix size
returns the same matrix with the sum
"""
n = len(vec)
M[0:n, 0:n] += np.diag(vec)
return M
3
Example 5
@property
def lifetimes(self):
r""" Lifetimes of states of the hidden transition matrix
Returns
-------
l : ndarray(nstates)
state lifetimes in units of the input trajectory time step,
defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where
:math:`p_{ii}` are the diagonal entries of the hidden transition matrix.
"""
return -self._lag / np.log(np.diag(self.transition_matrix))
3
Example 6
def symmetrize(M):
"""
If M only has a triangle filled with values, all the rest are zeroes,
this function will copy stuff to the other triangle
"""
return M + M.T - np.diag(M.diagonal())
3
Example 7
def impedance_self(self, s, part_o, Z_full):
"Self impedance of one part"
s_o = self.modes.s[0, part_o]
num_modes = len(s_o)//2
s_r = s_o[:num_modes]
s_i = s_o[num_modes:]
Z_self = np.diag(s_r + (s_i**2 - s_r**2)/s)*0.5
Z_mutual = np.diag(s_i - 2*s_r*s_i/s)*0.5
Z_full.matrices['Z'][part_o, part_o] = np.vstack((np.hstack((Z_self, Z_mutual)),
np.hstack((Z_mutual, -Z_self))))
3
Example 8
Project: systematictradingexamples Source File: optimisation.py
def offdiag_matrix(offvalue, nlength):
identity=np.diag([1.0]*nlength)
for x in range(nlength):
for y in range(nlength):
if x!=y:
identity[x][y]=offvalue
return identity
3
Example 9
Project: decoding-brain-challenge-2016 Source File: base.py
def powm(Ci, alpha):
"""Return the matrix power :math:`\\alpha` of a covariance matrix defined by :
.. math::
\mathbf{C} = \mathbf{V} \left( \mathbf{\Lambda} \\right)^{\\alpha} \mathbf{V}^T
where :math:`\mathbf{\Lambda}` is the diagonal matrix of eigenvalues
and :math:`\mathbf{V}` the eigenvectors of :math:`\mathbf{Ci}`
:param Ci: the coavriance matrix
:param alpha: the power to apply
:returns: the matrix power
"""
D, V = scipy.linalg.eigh(Ci)
D = numpy.diag(D**alpha)
Out = numpy.dot(numpy.dot(V, D), V.T)
return Out
3
Example 10
def _get_precisions(self):
"""Return precisions as a full matrix."""
if self.covariance_type == 'full':
return self.precs_
elif self.covariance_type in ['diag', 'spherical']:
return [np.diag(cov) for cov in self.precs_]
elif self.covariance_type == 'tied':
return [self.precs_] * self.n_components
3
Example 11
Project: pyKriging Source File: matrixops.py
def regneglikelihood(self):
self.LnDetPsi=2*np.sum(np.log(np.abs(np.diag(self.U))))
mu=(self.one.T.dot(np.linalg.solve(self.U, np.linalg.solve(self.U.T, self.y))))/self.one.T.dot(np.linalg.solve(self.U, np.linalg.solve(self.U.T, self.one)))
self.mu=mu
self.SigmaSqr = ((self.y-self.one.dot(self.mu)).T.dot(np.linalg.solve(self.U,np.linalg.solve(self.U.T,(self.y-self.one.dot(self.mu))))))/self.n
self.NegLnLike=-1.*(-(self.n/2.)*np.log(self.SigmaSqr) - 0.5*self.LnDetPsi)
3
Example 12
def P_matrix(self):
"""
return P = K * [R | t]
"""
K = np.diag([self.f,self.f,1])
return np.dot(K, np.hstack((self.R, self.t[:,np.newaxis])))
3
Example 13
Project: word2gauss Source File: test_embeddings.py
def test_ip_energy_diagonal(self):
from scipy.stats import multivariate_normal
embed = sample_embed(energy_type='IP', covariance_type='diagonal')
mui = embed.mu[1, :]
muj = embed.mu[2, :]
sigma = np.diag(embed.sigma[1, :] + embed.sigma[2, :])
expected = np.log(multivariate_normal.pdf(
np.zeros(2), mean=mui - muj, cov=sigma))
actual = embed.energy(1, 2)
self.assertAlmostEqual(actual, expected, places=6)
3
Example 14
def laplacianMatrix(self, outDegree=True):
"""
Return the Laplacian matrix of this graph, which is defined as L_{ii} = deg(i)
L_{ij} = -1 if an edge between i and j, otherwise L_{ij} = 0 . For a directed
graph one can specify whether to use the out-degree or in-degree.
:param outDegree: whether to use the out-degree for the computation of the degree matrix
:type outDegree: :class:`bool`
:returns: A laplacian adjacency matrix as numpy array.
"""
A = self.adjacencyMatrix()
if outDegree:
D = numpy.diag(self.outDegreeSequence())
else:
D = numpy.diag(self.inDegreeSequence())
return -A + D
3
Example 15
Project: ray Source File: linalg.py
@ray.remote(num_return_vals=2)
def tsqr_hr_helper1(u, s, y_top_block, b):
y_top = y_top_block[:b, :b]
s_full = np.diag(s)
t = -1 * np.dot(u, np.dot(s_full, np.linalg.inv(y_top).T))
return t, y_top
3
Example 16
Project: refinery Source File: GaussDistr.py
def logdetL(self):
try:
return self.Cache['logdetL']
except KeyError:
logdetL = 2.0*np.sum( np.log( np.diag( self.cholL() ) ) )
self.Cache['logdetL'] =logdetL
return logdetL
3
Example 17
Project: Uranium Source File: Matrix.py
def setByRotationAxis(self, angle, direction, point = None):
sina = math.sin(angle)
cosa = math.cos(angle)
direction_data = self._unitVector(direction.getData())
# rotation matrix around unit vector
R = numpy.diag([cosa, cosa, cosa])
R += numpy.outer(direction_data, direction_data) * (1.0 - cosa)
direction_data *= sina
R += numpy.array([[ 0.0, -direction_data[2], direction_data[1]],
[ direction_data[2], 0.0, -direction_data[0]],
[-direction_data[1], direction_data[0], 0.0]], dtype = numpy.float64)
M = numpy.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = numpy.array(point[:3], dtype = numpy.float64, copy=False)
M[:3, 3] = point - numpy.dot(R, point)
self._data = M
3
Example 18
def test_norm_nuclear(self):
"""
Test the norm_nuclear derived class.
We test the two methods : eval and prox.
First with default class properties, then custom ones.
"""
f = functions.norm_nuclear(lambda_=3)
self.assertEqual(f.eval(np.diag([10, 0])), 30)
self.assertEqual(f.eval(np.diag(np.array([-10, 0]))), 30)
self.assertEqual(f.eval([[-3]]), 9)
nptest.assert_allclose(f.prox(np.array([[1, 1], [1, 1]]), 1. / 3),
[[.5, .5], [.5, .5]])
3
Example 19
Project: RLScore Source File: steepest_descent_mmc.py
def findNewFocusSet(self, clazz = 0, focsize = 50):
diagR = np.mat(np.diag(self.R)).T
dirsnegdiff = - 4 * diagR + 4 * np.multiply(self.Y, self.RY)
dirscc = dirsnegdiff[np.mat(np.arange(self.size)).T, self.classvec]
dirs = dirsnegdiff + dirscc
dirs[np.mat(np.arange(self.size)).T, self.classvec] = float('Inf')
dirlist = []
for i in range(self.size):
row = dirs[i]
#dirlist.append((amin(row), i))
dirlist.append((row[0, clazz], i))
dirlist = sorted(dirlist)[0:focsize]
focusset = []
for i in range(focsize):
focusset.append(dirlist[i][1])
return set(focusset)
3
Example 20
Project: bci-challenge-ner-2015 Source File: utils.py
def powm(Ci,alpha):
D,V = eig(Ci)
D = matrix(diag(D**alpha))
V = matrix(V)
Out = matrix(V*D*V.T)
return Out
3
Example 21
def update_w(self):
# compute eigenvectors and eigenvalues using SVD
svd_mdl = SVD(self.data)
svd_mdl.factorize()
# argsort sorts in ascending order -> do reverese indexing
# for accesing values in descending order
S = np.diag(svd_mdl.S)
order = np.argsort(S)[::-1]
# select only a few eigenvectors ...
if self._num_bases >0:
order = order[:self._num_bases]
self.W = svd_mdl.U[:,order]
self.eigenvalues = S[order]
3
Example 22
def log_likelihood(self, p):
p = self.to_params(p)
v = self.rvs(p)
res = self.vs - v - p['mu']
cov = p['nu']*p['nu']*np.diag(self.dvs*self.dvs)
cov += generate_covariance(self.ts, p['sigma'], p['tau'])
cfactor = sl.cho_factor(cov)
cc, lower = cfactor
n = self.ts.shape[0]
return -0.5*n*np.log(2.0*np.pi) - np.sum(np.log(np.diag(cc))) - 0.5*np.dot(res, sl.cho_solve(cfactor, res))
3
Example 23
Project: QuantEcon.py Source File: test_ricatti.py
def dare_test_tjm_1():
A = [[0.0, 0.1, 0.0],
[0.0, 0.0, 0.1],
[0.0, 0.0, 0.0]]
B = [[1.0, 0.0],
[0.0, 0.0],
[0.0, 1.0]]
Q = [[10**5, 0.0, 0.0],
[0.0, 10**3, 0.0],
[0.0, 0.0, -10.0]]
R = [[0.0, 0.0],
[0.0, 1.0]]
X = solve_discrete_riccati(A, B, Q, R)
Y = np.diag((1e5, 1e3, 0.0))
assert_allclose(X, Y, atol=1e-07)
3
Example 24
Project: bhmm Source File: gmm.py
def _get_covars(self):
"""Covariance parameters for each mixture component.
The shape depends on `cvtype`::
(`n_states`, 'n_features') if 'spherical',
(`n_features`, `n_features`) if 'tied',
(`n_states`, `n_features`) if 'diag',
(`n_states`, `n_features`, `n_features`) if 'full'
"""
if self.covariance_type == 'full':
return self.covars_
elif self.covariance_type == 'diag':
return [np.diag(cov) for cov in self.covars_]
elif self.covariance_type == 'tied':
return [self.covars_] * self.n_components
elif self.covariance_type == 'spherical':
return [np.diag(cov) for cov in self.covars_]
3
Example 25
def test_lmvnpdf_full():
n_features, n_components, n_samples = 2, 3, 10
mu = rng.randint(10) * rng.rand(n_components, n_features)
cv = (rng.rand(n_components, n_features) + 1.0) ** 2
X = rng.randint(10) * rng.rand(n_samples, n_features)
fullcv = np.array([np.diag(x) for x in cv])
reference = _naive_lmvnpdf_diag(X, mu, cv)
lpr = assert_warns_message(DeprecationWarning, "The function"
" log_multivariate_normal_density is "
"deprecated in 0.18 and will be removed in 0.20.",
mixture.log_multivariate_normal_density,
X, mu, fullcv, 'full')
assert_array_almost_equal(lpr, reference)
3
Example 26
Project: pyKriging Source File: matrixops.py
def neglikelihood(self):
self.LnDetPsi=2*np.sum(np.log(np.abs(np.diag(self.U))))
a = np.linalg.solve(self.U.T, self.one.T)
b = np.linalg.solve(self.U, a)
c = self.one.T.dot(b)
d = np.linalg.solve(self.U.T, self.y)
e = np.linalg.solve(self.U, d)
self.mu=(self.one.T.dot(e))/c
self.SigmaSqr = ((self.y-self.one.dot(self.mu)).T.dot(np.linalg.solve(self.U,np.linalg.solve(self.U.T,(self.y-self.one.dot(self.mu))))))/self.n
self.NegLnLike=-1.*(-(self.n/2.)*np.log(self.SigmaSqr) - 0.5*self.LnDetPsi)
3
Example 27
Project: pyvision Source File: stats.py
def cov2cor(v):
'''
Converts a symmetric positive definite matrix to a correlation matrix by
normalizing by the diagonal.
'''
r,c = v.shape
assert r == c
s = 1.0/np.sqrt(np.diag(v))
v *= s.reshape(r,1)
v *= s.reshape(1,c)
return v
3
Example 28
def testSorting(self):
"""components should be sorted by decreasing variance
"""
x = generate_covsig(np.diag([1, 9, 2, 6, 3, 8, 4, 5, 7]), 500)
w, v = pca(x, reducedim=5)
c = np.cov(np.dot(w.T, x))
self.assertTrue(np.allclose(c, np.diag([9, 8, 7, 6, 5]), rtol=1e-1, atol=1e-2))
3
Example 29
Project: cclib Source File: testPolar.py
def testisotropic(self):
"""Is the isotropic polarizability (average of the diagonal elements)
+/- 0.01 from a reference?
"""
isotropic = numpy.average(numpy.diag(self.data.polarizabilities[0]))
self.assertAlmostEqual(isotropic, self.isotropic, delta=self.isotropic_delta)
3
Example 30
def print_error(name, aat, u, s, ideal_nf, ideal_n2):
err = -numpy.dot(u, numpy.dot(numpy.diag(s), u.T))
err += aat
nf, n2 = numpy.linalg.norm(err), norm2(err)
print ('%s error: norm_frobenius=%f (/ideal=%g), norm2=%f (/ideal=%g), RMSE=%g' %
(name, nf, nf / ideal_nf, n2, n2 / ideal_n2, rmse(err)))
sys.stdout.flush()
3
Example 31
Project: GLRM Source File: pca_test.py
def PCA(A, k):
mean_A = tile(A.mean(0), (A.shape[0],1))
A0 = A - mean_A
u, s, v = svd(A0, full_matrices = False)
u, s, v = u[:,:k], diag(sqrt(s[:k])), v[:k,:]
X = hstack((u.dot(s), ones((m,1))))
Y = vstack((s.dot(v), A.mean(0)))
return X, Y
3
Example 32
def LOO(self, kern, X, Y, likelihood, posterior, Y_metadata=None, K=None):
"""
Leave one out error as found in
"Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models"
Vehtari et al. 2014.
"""
g = posterior.woodbury_vector
c = posterior.woodbury_inv
c_diag = np.diag(c)[:, None]
neg_log_marginal_LOO = 0.5*np.log(2*np.pi) - 0.5*np.log(c_diag) + 0.5*(g**2)/c_diag
#believe from Predictive Approaches for Choosing Hyperparameters in Gaussian Processes
#this is the negative marginal LOO
return -neg_log_marginal_LOO
3
Example 33
Project: aracna Source File: util.py
def randGaussianPoint(center, ranges, stddev = .1, crop=True):
'''
Return a random sampling of a Gaussian distribution specified by
the given'center', 'ranges', and desired 'stddev' along each
dimension. stddev is given as a fraction of the total range.
The ranges of parameters are in a list of tuples.
'''
covar = diag([((x[1]-x[0]) * stddev) ** 2 for x in ranges])
ret = random.multivariate_normal(center, covar)
# crop to min/max values
if crop:
for ii in range(len(ret)):
ret[ii] = max(ranges[ii][0], min(ranges[ii][1], ret[ii]))
return ret
3
Example 34
Project: pymc3 Source File: test_plots.py
def test_plots_multidimensional():
# Test single trace
start, model, _ = multidimensional_model()
with model as model:
h = np.diag(find_hessian(start))
step = Metropolis(model.vars, h)
trace = sample(3000, step, start)
traceplot(trace)
plot_posterior(trace)
3
Example 35
Project: cvxpy Source File: diag.py
@AffAtom.numpy_numeric
def numeric(self, values):
"""Extract the diagonal from a square matrix constant.
"""
# The return type in numpy versions < 1.10 was ndarray.
v = np.diag(values[0])
if isinstance(v, np.matrix):
v = v.A[0]
return v
3
Example 36
Project: pyBAST Source File: classes.py
def llik(self,P=np.array( [0., 0., 0., 0., 0., 1., 1.] ) ):
""" Compute log-likelihood of parameter set P within
likelihood distribution bgmap object.
"""
delta = self.mu - P
sigma = self.sigma.copy()
# Interpret infs in covariance matrix as contributing
# zero to the chi^2 (set delta[i] = 0).
I = np.nonzero(np.isinf(np.diag(sigma)))[0]
delta[I] = 0
sigma[I,:] = 0
sigma[:,I] = 0
sigma[I,I] = 1
return -0.5 * delta.dot( solve( sigma, delta ) )
3
Example 37
Project: refinery Source File: GaussWishDistr.py
def logdetW(self):
try:
return self.Cache['logdetW']
except KeyError:
self.Cache['logdetW'] = -2.0*np.sum(np.log(np.diag(self.cholinvW())))
return self.Cache['logdetW']
3
Example 38
def perform(self, node, inputs, outputs):
(x,) = inputs
(z,) = outputs
if x.ndim != 1:
raise TypeError(x)
z[0] = numpy.diag(x)
3
Example 39
def impedance_self(self, s, part_o, Z_full):
"Self impedance of one part"
s_o = self.modes.s[0, part_o]
num_modes = len(s_o)//2
s_r = s_o[:num_modes]
s_i = s_o[num_modes:]
Z_self = np.diag(s_r*s + (s_i**2 - s_r**2))*0.5
Z_mutual = np.diag(s_i*s - 2*s_r*s_i)*0.5
Z_full.matrices['S'][part_o, part_o] = np.vstack((np.hstack((Z_self, Z_mutual)),
np.hstack((Z_mutual, -Z_self))))
Z_full.matrices['L'][part_o, part_o] = 0.0
3
Example 40
Project: Uranium Source File: Matrix.py
def setByScaleFactor(self, factor, origin = None, direction = None):
if direction is None:
# uniform scaling
M = numpy.diag([factor, factor, factor, 1.0])
if origin is not None:
M[:3, 3] = origin[:3]
M[:3, 3] *= 1.0 - factor
else:
# nonuniform scaling
direction_data = direction.getData()
factor = 1.0 - factor
M = numpy.identity(4,dtype = numpy.float64)
M[:3, :3] -= factor * numpy.outer(direction_data, direction_data)
if origin is not None:
M[:3, 3] = (factor * numpy.dot(origin[:3], direction_data)) * direction_data
self._data = M
3
Example 41
Project: hypergraph Source File: matrix.py
def degree_matrix(H):
"""\
Return the degree matrix of a hypergraph. For directed hypergraphs,
considers the indegree.
@param H: The input hypergraph.
@type H: L{Hypergraph}
@return: The degree matrix.
@rtype: C{numpy.ndarray}
"""
return numpy.diag([H.indegree(v) for v in sorted(list(H.vertices))])
3
Example 42
Project: warpedLMM Source File: linalg.py
def multiple_pdinv(A):
"""
:param A: A DxDxN numpy array (each A[:,:,i] is pd)
:rval invs: the inverses of A
:rtype invs: np.ndarray
:rval hld: 0.5* the log of the determinants of A
:rtype hld: np.array
"""
N = A.shape[-1]
chols = [jitchol(A[:, :, i]) for i in range(N)]
halflogdets = [np.sum(np.log(np.diag(L[0]))) for L in chols]
invs = [dpotri(L[0], True)[0] for L in chols]
invs = [np.triu(I) + np.triu(I, 1).T for I in invs]
return np.dstack(invs), np.array(halflogdets)
3
Example 43
Project: bci-challenge-ner-2015 Source File: utils.py
def invsqrtm(Ci):
D,V = eig(Ci)
D = matrix(diag(1.0/sqrt(D)))
V = matrix(V)
Out = matrix(V*D*V.T)
return Out
3
Example 44
Project: msaf Source File: main.py
def local_ridge(A_rep, A_loc):
n = len(A_rep)
ridge_val = np.diag(A_loc, k=1)
A_out = A_rep.copy()
A_out[range(n-1), range(1,n)] = ridge_val
A_out[range(1,n), range(n-1)] = ridge_val
return A_out
3
Example 45
Project: galry Source File: mesh_visual.py
def scale_matrix(x, y, z):
"""Return a scaling matrix.
Arguments:
* x, y, z: the scaling coefficients in each direction.
Returns:
* S: the 4x4 projection matrix.
"""
return np.diag([x, y, z, 1.])
3
Example 46
Project: warpedLMM Source File: linalg.py
def pddet(A):
"""
Determinant of a positive definite matrix, only symmetric matricies though
"""
L = jitchol(A)
logdetA = 2*sum(np.log(np.diag(L)))
return logdetA
3
Example 47
Project: pymc3 Source File: quadpotential.py
def partial_check_positive_definite(C):
"""Simple but partial check for Positive Definiteness"""
if C.ndim == 1:
d = C
else:
d = np.diag(C)
i, = np.nonzero(np.logical_or(np.isnan(d), d <= 0))
if len(i):
raise PositiveDefiniteError(
"Simple check failed. Diagonal contains negatives", i)
3
Example 48
def test_num():
"Number operator"
n5 = num(5)
assert_equal(
np.allclose(n5.full(),
np.diag([0 + 0j, 1 + 0j, 2 + 0j, 3 + 0j, 4 + 0j])),
True)
3
Example 49
Project: scot Source File: connectivity.py
@memoize
def GPDC(self):
"""Generalized partial directed coherence.
.. math:: \mathrm{GPDC}_{ij}(f) = \\frac{|A_{ij}(f)|}
{\sigma_i \sqrt{A_{:j}'(f) \mathrm{diag}(\mathbf{C})^{-1} A_{:j}(f)}}
References
----------
L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear
multivariate processes: definitions, interpretation, and practical
analysis. Comput. Math. Meth. Med. 2012: 140513, 2012.
"""
A = self.A()
tmp = A / np.sqrt(np.einsum('aj..., a..., aj..., ii... ->ij...',
A.conj(), 1 / np.diag(self.c), A, self.c))
return np.abs(tmp)
3
Example 50
Project: ldsc Source File: regressions.py
def _coef(self, jknife, Nbar):
'''Get coefficient estimates + cov from the jackknife.'''
n_annot = self.n_annot
coef = jknife.est[0, 0:n_annot] / Nbar
coef_cov = jknife.jknife_cov[0:n_annot, 0:n_annot] / Nbar ** 2
coef_se = np.sqrt(np.diag(coef_cov))
return coef, coef_cov, coef_se