5ae2eba965994938ea283013d490bdf07b5a9878
[matrixnullspace.com.git] / matrix.py
1 import urlparse
2 import json
3
4 import scipy
5 import scipy.linalg
6 from scipy import *
7
8 def null(A, eps=1e-15):
9 u, s, vh = scipy.linalg.svd(A)
10 null_mask = (s <= eps)
11 null_space = scipy.compress(null_mask, vh, axis=0)
12 return scipy.transpose(null_space)
13
14 def eigenvalues(A, eps=1e-15):
15 u, s, vh = scipy.linalg.svd(A)
16 return s
17
18 def application(environ, start_response):
19 if environ['REQUEST_METHOD'] == 'POST':
20 post_data = environ['wsgi.input'].read()
21
22 post_data = urlparse.parse_qsl(post_data, True, True)
23
24 data_string = str(post_data[0][1])
25 data_rows = data_string.splitlines()
26 for index, row in enumerate(data_rows):
27 data_rows[index] = row.split()
28
29 given_matrix = data_rows
30 null_space = null(given_matrix)
31 try:
32 null_space = null_space / null_space.max()
33 except:
34 pass
35
36 # la, v = scipy.linalg.eig(given_matrix)
37 # output += "eigenvalues:<br>"
38 # for l in la:
39 # output += str(l)
40 determinant = scipy.linalg.det(given_matrix)
41
42 output = json.dumps({
43 'nullspace' : str(null_space),
44 'eigenvalues' : str(eigenvalues(given_matrix)),
45 'determinant' : str(determinant)
46 })
47
48 output_len = sum(len(line) for line in output)
49 start_response('200 OK', [('Content-type', 'application/json'),
50 ('Content-Length', str(output_len))])
51 return output