clean up matrix.py & square matrices
[matrixnullspace.com.git] / matrix.py
1 import cgi
2 from scipy import compress, transpose
3 from scipy.linalg import svd, det
4 import json
5
6 def calculate_nullspace(A, eps=1e-15):
7 u, s, vh = svd(A)
8 null_mask = (s <= eps)
9 null_space = compress(null_mask, vh, axis=0)
10 return transpose(null_space)
11
12 def calculate_eigenvalues(A, eps=1e-15):
13 u, s, vh = svd(A)
14 return s
15
16 def application(environ, start_response):
17 parameters = cgi.parse_qs(environ.get('QUERY_STRING', ''))
18
19 query_string = str(parameters['matrix'][0])
20 matrix = query_string.splitlines()
21 for index, row in enumerate(matrix):
22 matrix[index] = row.split()
23
24 while len(matrix) < len(matrix[0]):
25 matrix.append([0]*len(matrix[0]))
26
27 nullspace = calculate_nullspace(matrix)
28 if nullspace.max() != 0:
29 nullspace = nullspace / nullspace.max()
30
31 eigenvalues = calculate_eigenvalues(matrix)
32 determinant = det(matrix)
33
34 output = json.dumps({
35 'nullspace' : str(nullspace),
36 'eigenvalues' : str(eigenvalues),
37 'determinant' : str(determinant)
38 })
39
40 output_len = sum(len(line) for line in output)
41 start_response('200 OK', [('Content-type', 'application/json'),
42 ('Content-Length', str(output_len))])
43 return output