]>
gitweb.michael.orlitzky.com - dunshire.git/blob - src/dunshire/matrices.py
2 Utility functions for working with CVXOPT matrices (instances of the
3 ``cvxopt.base.matrix`` class).
7 from cvxopt
import matrix
8 from cvxopt
.lapack
import syev
10 def append_col(left
, right
):
12 Append the matrix ``right`` to the right side of the matrix ``left``.
16 >>> A = matrix([1,2,3,4], (2,2))
17 >>> B = matrix([5,6,7,8,9,10], (2,3))
18 >>> print(append_col(A,B))
24 return matrix([left
.trans(), right
.trans()]).trans()
26 def append_row(top
, bottom
):
28 Append the matrix ``bottom`` to the bottom of the matrix ``top``.
32 >>> A = matrix([1,2,3,4], (2,2))
33 >>> B = matrix([5,6,7,8,9,10], (3,2))
34 >>> print(append_row(A,B))
43 return matrix([top
, bottom
])
46 def eigenvalues(real_matrix
):
48 Return the eigenvalues of the given ``real_matrix``.
52 >>> A = matrix([[2,1],[1,2]], tc='d')
57 domain_dim
= real_matrix
.size
[0] # Assume ``real_matrix`` is square.
58 eigs
= matrix(0, (domain_dim
, 1), tc
='d')
59 syev(real_matrix
, eigs
)
63 def identity(domain_dim
):
65 Return a ``domain_dim``-by-``domain_dim`` dense integer identity
70 >>> print(identity(3))
78 raise ValueError('domain dimension must be positive')
80 entries
= [int(i
== j
)
81 for i
in range(domain_dim
)
82 for j
in range(domain_dim
)]
83 return matrix(entries
, (domain_dim
, domain_dim
))
86 def inner_product(vec1
, vec2
):
88 Compute the (Euclidean) inner product of the two vectors ``vec1``
95 >>> inner_product(x,y)
98 >>> x = matrix([1,1,1])
99 >>> y = matrix([2,3,4], (1,3))
100 >>> inner_product(x,y)
105 >>> inner_product(x,y)
106 Traceback (most recent call last):
108 TypeError: the lengths of vec1 and vec2 must match
111 if not len(vec1
) == len(vec2
):
112 raise TypeError('the lengths of vec1 and vec2 must match')
114 return sum([x
*y
for (x
, y
) in zip(vec1
, vec2
)])
117 def norm(matrix_or_vector
):
119 Return the Frobenius norm of ``matrix_or_vector``, which is the same
120 thing as its Euclidean norm when it's a vector (when one of its
121 dimensions is unity).
125 >>> v = matrix([1,1])
126 >>> print('{:.5f}'.format(norm(v)))
129 >>> A = matrix([1,1,1,1], (2,2))
134 return sqrt(inner_product(matrix_or_vector
, matrix_or_vector
))
137 def vec(real_matrix
):
139 Create a long vector in column-major order from ``real_matrix``.
143 >>> A = matrix([[1,2],[3,4]])
156 Note that if ``real_matrix`` is a vector, this function is a no-op:
158 >>> v = matrix([1,2,3,4], (4,1))
173 return matrix(real_matrix
, (len(real_matrix
), 1))