#!/usr/bin/env python
# (C) 2000 Huaiyu Zhu <hzhu@users.sourceforge.net>. Licence: GPL
# $Id: test_basic.py,v 1.6 2000/09/13 01:52:36 hzhu Exp $
"""
Test basic operations for Matrix module
"""
from MatPy.Matrix import Matrix,r_range,zeros,ones,eye,rand,norm,mnorm
from MatPy.Matrix import max,min,cumsum,sum,mfunc,solve
from MatPy.mfuncs import expm,logm,sqrtm
import time
def tic(): global _time; _time = time.time()
def toc(): print "time lapse =", time.time() - _time
print "-"*40, "basic vector"
a = r_range(-1, 3)
print a, a.__class__
a[2] = 9
assert a.shape == (1,4)
assert a[0,2] == a[2] == 9
print "-"*40, "basic matrix"
b = zeros((2,2))
b [1,0] = 1; b[0,1] = 2
print b
print b.shape, b[0,1], b[1,0]
print 1 + b + 1
print 2 - b - 2
print 3 * b * 3
print "-"*40, "inverse matrix"
print b.I
print 4 / b
print 4 / b * b
assert norm(b.I * b - eye(2)) < 1e-15
assert norm(b.I - 1/b) < 1e-15
print "-"*40, "arithmatic, norm"
print 1.1 * Matrix(a)*2 + 2 + a
print "-"*40, "special matrices"
c = ones(a.shape) * 2 + zeros(a.shape) + rand(a.shape)
print c
print "-"*40, "transpose, multiplication"
d = -a.T
assert d.shape == (4,1)
assert norm(d.T + a) < 1e-15
print d*c, c*d
print "-"*40, "linear transform"
X = rand((9,4))
y = X * d
print y.T
print "-"*40, "eigenvalues"
C = rand((5,5))
print C
print C.eig
print "-"*40, "matrix functions:"
print "-"*40, "identity function"
print C
D = mfunc(lambda x:x, C)
print D
assert norm(D - C) < 1e-14
print "-"*40, "sqrtm, powm"
A = X.T * X
B = sqrtm(A)
print B
assert norm(B**2 - A) < 4e-14
assert norm(B*B - A) < 2e-14
print "-"*40, "expm, logm"
print expm(C)
assert logm(expm(C)), norm(logm(expm(C)) - C) < 1e-15
print "-"*40, "inverse, eye"
print A.I
assert norm(A.I * A - eye(4)) < 1e-14
print norm(A.I * A - eye(4))
print "-"*40, "solve by inverse"
tic()
A = X.T * X
b = X.T * y
d1 = (A.I * b)
toc()
e = d1 - d
assert norm(e) < 1e-13
assert mnorm(e) < 1e-13
print "-"*40, "linear equation"
tic()
d2 = solve(X , y)
toc()
assert norm(d2 - d) < 8e-14
assert norm(d2 - d1) < 8e-14
assert norm(X*d2 - y) < 2e-14
|