-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarl_algebra.py
103 lines (78 loc) · 2.64 KB
/
carl_algebra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""
Copyright (C) 2015 Nicola Dileo
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
Module: carl_algebra.py
--------
This module contain the code of two iterative methods for solving
sparse linear systems: method of Jacobi and method of Gauss-Seidel.
A detailed discussion of the iterative methods can be found in the
following link:
http://www-users.cs.umn.edu/~saad/books.html
https://en.wikipedia.org/wiki/Iterative_method
"""
import numpy as np
import scipy
import scipy.linalg as algebra
from scipy import sparse
from scipy.sparse import linalg
from time import clock
np.set_printoptions(precision = 3)
def compute(A, method, MAXITER, TOLL):
results = {}
b = np.ones(A.get_shape()[0])
if method == 'JACOBI':
tic = clock()
solution,iterations = Jacobi(A,b,MAXITER,TOLL)
toc = clock()
results['solution'] = solution
results['iterations'] = iterations
results['elapsed'] = toc - tic
else:
tic = clock()
solution,iterations = GaussSeidel(A,b,MAXITER,TOLL)
toc = clock()
results['solution'] = solution
results['iterations'] = iterations
results['elapsed'] = toc - tic
return results
def Jacobi(A, b, MAXITER, TOLL):
n = len(b)
xk = np.ones(shape = n,dtype = float)
D = sparse.diags(A.diagonal(), 0, format = 'csc',)
L = sparse.tril(A, format = 'csc')
U = sparse.triu(A, format = 'csc')
T = -(linalg.inv(D))*(L+U)
c = (linalg.inv(D))*b
i = 0
err = TOLL + 1
while i < MAXITER and err > TOLL:
x = T*xk + c
err = np.linalg.norm(x-xk, 1)/np.linalg.norm(x,1)
xk = x
i += 1
return xk, i
def GaussSeidel(A, b, MAXITER, TOLL):
n = len(b)
xk = np.ones(shape = n,dtype = float)
D = sparse.diags(A.diagonal(), 0, format = 'csc',)
L = sparse.tril(A, format = 'csc')
U = sparse.triu(A, format = 'csc')
T = -(linalg.inv(D+L))* U
c = (linalg.inv(D+L))* b
i = 0
err = TOLL + 1
while i < MAXITER and err > TOLL:
x = T*xk + c
err = np.linalg.norm(x-xk, 1)/np.linalg.norm(x,1)
xk = x
i += 1
return xk, i