X-Git-Url: https://gitweb.michael.orlitzky.com/?a=blobdiff_plain;f=matrices.py;h=a33259e6f3e71f7a4b5f2d47234464d80a9a3199;hb=ab6aa9c36bc06ae0f14f404bd73d8865b161eb0f;hp=82944ee72ab77ca676054601991afadcd804ae77;hpb=45cb81de5baf2765494a11aa87d4d8d5bfcb7fb8;p=dunshire.git diff --git a/matrices.py b/matrices.py index 82944ee..a33259e 100644 --- a/matrices.py +++ b/matrices.py @@ -1,19 +1,84 @@ -from cvxopt import matrix, spmatrix +""" +Utility functions for working with CVXOPT matrices (instances of the +``cvxopt.base.matrix`` class). +""" -def append_col(A,b): +from math import sqrt +from cvxopt import matrix + +def append_col(left, right): """ - Append the column ``b`` to the right side of the matrix ``A``. + Append the matrix ``right`` to the right side of the matrix ``left``. + + EXAMPLES: + + >>> A = matrix([1,2,3,4], (2,2)) + >>> B = matrix([5,6,7,8,9,10], (2,3)) + >>> print(append_col(A,B)) + [ 1 3 5 7 9] + [ 2 4 6 8 10] + + """ - return matrix([A.trans(),b.trans()]).trans() + return matrix([left.trans(), right.trans()]).trans() -def append_row(A,b): +def append_row(top, bottom): """ - Append the row ``b`` to the bottom of the matrix ``A``. + Append the matrix ``bottom`` to the bottom of the matrix ``top``. + + EXAMPLES: + + >>> A = matrix([1,2,3,4], (2,2)) + >>> B = matrix([5,6,7,8,9,10], (3,2)) + >>> print(append_row(A,B)) + [ 1 3] + [ 2 4] + [ 5 8] + [ 6 9] + [ 7 10] + + """ - return matrix([A,b]) + return matrix([top, bottom]) -def identity(n): +def identity(domain_dim): """ - Return the ``n``-by-``n`` identity matrix. + Return a ``domain_dim``-by-``domain_dim`` dense integer identity + matrix. + + EXAMPLES: + + >>> print(identity(3)) + [ 1 0 0] + [ 0 1 0] + [ 0 0 1] + + + """ + if domain_dim <= 0: + raise ValueError('domain dimension must be positive') + + entries = [int(i == j) + for i in range(domain_dim) + for j in range(domain_dim)] + return matrix(entries, (domain_dim, domain_dim)) + + +def norm(matrix_or_vector): + """ + Return the Frobenius norm of ``matrix_or_vector``, which is the same + thing as its Euclidean norm when it's a vector (when one of its + dimensions is unity). + + EXAMPLES: + + >>> v = matrix([1,1]) + >>> print('{:.5f}'.format(norm(v))) + 1.41421 + + >>> A = matrix([1,1,1,1], (2,2)) + >>> norm(A) + 2.0 + """ - return spmatrix(1,range(n),range(n)) + return sqrt(sum([x**2 for x in matrix_or_vector]))