]> gitweb.michael.orlitzky.com - dunshire.git/blob - src/dunshire/matrices.py
Fix lint warnings and a few variable errors in symmetric_linear_game.py.
[dunshire.git] / src / dunshire / matrices.py
1 """
2 Utility functions for working with CVXOPT matrices (instances of the
3 ``cvxopt.base.matrix`` class).
4 """
5
6 from math import sqrt
7 from cvxopt import matrix
8
9 def append_col(left, right):
10 """
11 Append the matrix ``right`` to the right side of the matrix ``left``.
12
13 EXAMPLES:
14
15 >>> A = matrix([1,2,3,4], (2,2))
16 >>> B = matrix([5,6,7,8,9,10], (2,3))
17 >>> print(append_col(A,B))
18 [ 1 3 5 7 9]
19 [ 2 4 6 8 10]
20 <BLANKLINE>
21
22 """
23 return matrix([left.trans(), right.trans()]).trans()
24
25 def append_row(top, bottom):
26 """
27 Append the matrix ``bottom`` to the bottom of the matrix ``top``.
28
29 EXAMPLES:
30
31 >>> A = matrix([1,2,3,4], (2,2))
32 >>> B = matrix([5,6,7,8,9,10], (3,2))
33 >>> print(append_row(A,B))
34 [ 1 3]
35 [ 2 4]
36 [ 5 8]
37 [ 6 9]
38 [ 7 10]
39 <BLANKLINE>
40
41 """
42 return matrix([top, bottom])
43
44 def identity(domain_dim):
45 """
46 Return a ``domain_dim``-by-``domain_dim`` dense integer identity
47 matrix.
48
49 EXAMPLES:
50
51 >>> print(identity(3))
52 [ 1 0 0]
53 [ 0 1 0]
54 [ 0 0 1]
55 <BLANKLINE>
56
57 """
58 if domain_dim <= 0:
59 raise ValueError('domain dimension must be positive')
60
61 entries = [int(i == j)
62 for i in range(domain_dim)
63 for j in range(domain_dim)]
64 return matrix(entries, (domain_dim, domain_dim))
65
66
67 def norm(matrix_or_vector):
68 """
69 Return the Frobenius norm of ``matrix_or_vector``, which is the same
70 thing as its Euclidean norm when it's a vector (when one of its
71 dimensions is unity).
72
73 EXAMPLES:
74
75 >>> v = matrix([1,1])
76 >>> print('{:.5f}'.format(norm(v)))
77 1.41421
78
79 >>> A = matrix([1,1,1,1], (2,2))
80 >>> norm(A)
81 2.0
82
83 """
84 return sqrt(sum([x**2 for x in matrix_or_vector]))