Skip to content

Commit

Permalink
Added Comments and final updates to all functions
Browse files Browse the repository at this point in the history
  • Loading branch information
SK committed Nov 21, 2016
1 parent 16fe1ee commit 7d834b7
Show file tree
Hide file tree
Showing 13 changed files with 1,246 additions and 635 deletions.
10 changes: 6 additions & 4 deletions mainSOR.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
"""
MainSOR program connects remaning modules and serves as a start point
How to Execute:
python mainSOR.py <input_file_name_optional> <output_file_name_optional>
Expand Down Expand Up @@ -45,11 +47,11 @@ def main():
if(not validateMatrix.det_check(matrix_a)):
raise Exception("Determinant check failed for Matrix A.",6)

# if((not validateMatrix.col_diagonally_dominant(matrix_a,dimension_n)) and \
# (not validateMatrix.row_diagonally_dominant(matrix_a,dimension_n))):
if((not validateMatrix.col_diagonally_dominant(matrix_a,dimension_n)) and \
(not validateMatrix.row_diagonally_dominant(matrix_a,dimension_n))):
# If matrix is diagonally dominant, then no need to check spectral radius check
if(not validateMatrix.spectral_radius_convergence_check(matrix_a)):
raise Exception("Spectral radius check failed for Matrix A.",6)
if(not validateMatrix.spectral_radius_convergence_check(matrix_a)):
raise Exception("Spectral radius check failed for Matrix A.",6)

#Dense SOR Calculation
# implementSOR.dense_SOR(matrix_a,vector_b,dimension_n,max_it,w,matrix_x)
Expand Down
39 changes: 31 additions & 8 deletions nas_Daly_Mcdonagh_Tiyyagura_prog2/code/automatedTests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# -*- coding: utf-8 -*-
"""
All test cases in the NAS Programming assignment are tested here.
Output of execution will be printed on screen on this program execution
How to execute:
In Verbose mode - details tests and output
python automatedTests.py -v
In general mode - displays only failed tests
python automatedTests.py
Authors:
Expand All @@ -14,12 +20,18 @@

def automated_tests():
'''
List of all test cases are mentioned below for test
Agruments:
None
Return:
None
>>> mainSOR.main()
Stopping Reason Max num of Iterations Number of Iterations Machine Epsilon X Seq Tolerance Residual Seq Tolerance
Residual convergence 50 30 2.220446049250313e-16 1e-13 1e-13
[ 1. 2. -2.]
>>> sys.argv.append('input_files_test_cases/nas_sor_zero_diagonal.in')
>>> sys.argv[1] = 'input_files_test_cases/nas_sor_zero_diagonal.in'
>>> mainSOR.main()
Stopping Reason Max num of Iterations Number of Iterations Machine Epsilon X Seq Tolerance Residual Seq Tolerance
Zero on diagonal 50 0 2.220446049250313e-16 1e-13 1e-13
Expand Down Expand Up @@ -48,20 +60,31 @@ def automated_tests():
Max Iterations reached 50 50 2.220446049250313e-16 1e-13 1e-13
[ 6. 5. 3.]
>>> sys.argv[1]='input_files_test_cases/nas_large_sparse_matrix_500.in'
>>> sys.argv[1]='input_files_test_cases/nas_large_sparse_matrix_1000.in'
>>> mainSOR.main()
Stopping Reason Max num of Iterations Number of Iterations Machine Epsilon X Seq Tolerance Residual Seq Tolerance
Max Iterations reached 50 50 2.220446049250313e-16 1e-13 1e-13
[ 6. 5. 3.]
Cannot proceed 50 0 2.220446049250313e-16 1e-13 1e-13
Spectral radius check failed for Matrix A.
>>> sys.argv[1]='input_files_test_cases/nas_ill_condition_matrix.in'
>>> mainSOR.main()
Stopping Reason Max num of Iterations Number of Iterations Machine Epsilon X Seq Tolerance Residual Seq Tolerance
Cannot proceed 50 0 2.220446049250313e-16 1e-13 1e-13
Spectral radius check failed for Matrix A.
'''

return



if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
if(len(sys.argv) > 1):
sys.argv[1]='nas_Sor.in'
doctest.testmod(verbose=True)
else:
sys.argv.append('nas_Sor.in')
doctest.testmod(verbose=False)



16 changes: 14 additions & 2 deletions nas_Daly_Mcdonagh_Tiyyagura_prog2/code/blackScholes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# -*- coding: utf-8 -*-
"""
Blackscholes.py is the mainfunction and dependent on SOR algorithm module
Blackscholes is a model to give an estimate of European style options
How to Execute:
python blackScholes.py
Expand All @@ -9,7 +12,7 @@
Srikanth Tiyyagura
"""


#import modules
from math import ceil
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -72,6 +75,9 @@ def put_Black_Scholes(X=10, N=100, M=150, T=30, std=0.3, r=0.02, X_to_Smax = 0.5
plt.show()

def set_A(N, k, std, r):
'''
Creates matrix A for black scholas matrix and converts to csr format
'''
A=[]
for i in range(0, N-1):
A_row = []
Expand All @@ -85,15 +91,21 @@ def set_A(N, k, std, r):
else:
A_row.append(0)
A.append(A_row)
# print(to_csr(A))

return processIO.to_csr_format(A)


def set_alignment(X, k, r, std):
'''
alignment for vecto b to plot on graph
'''
return 0.5 * k * X * ((std**2) - r)


def init_b(X, N, X_to_Smax, alignment):
'''
Vector b intialisation
'''
b = []
N_threshold = ceil(N * X_to_Smax) #value of N where S = X
for i in range(0, N_threshold):
Expand Down
103 changes: 98 additions & 5 deletions nas_Daly_Mcdonagh_Tiyyagura_prog2/code/implementSOR.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# -*- coding: utf-8 -*-
"""
ImplementSOR contains SOR algorithms and convergence / divergence checks
Dependent on main program - mainSOR.py or BlackScholas.py
Authors:
Niall Daly
Ronan Mc.Donagh
Srikanth Tiyyagura
"""
import numpy as np

Expand All @@ -11,6 +15,10 @@ def get_euclid_norm(matrix):
this function accepts one vector
the calling function should compute this vector as the difference of two vectors
the standard Euclidean distance formula sqrt(x1^2+x2^2+....+xn^2) is applied
Agrument:
matrix - matrix to find euclid norm
Return:
ndarray - contains euclid norm value
"""
sum = 0
for each_val in matrix:
Expand All @@ -22,6 +30,13 @@ def get_residual(A, x, b):
return the residual error Ax-b for an approximation of x
input parameters should be numpy arrays
this is not as simple as using numpy.dot because A is in CSR format
Agrument:
A - matrix in CSR format
x - matrix x in the current iteration
b - Vector b
Return:
ndarray - contains euclid norm value for Ax-b matrix
"""
adotx = []
for i in range(0,len(b)):
Expand All @@ -37,12 +52,27 @@ def get_x_seq(xold, xnew):
"""
this function computes Euclidean distance between successive iterations of x
input parameters should be numpy arrays
Agrument:
xold - matrix of x in previous iteration
xnew - matrix x in the current iteration
Return:
ndarray - contains euclid norm value for xnew-xold matrix
"""
return get_euclid_norm(np.subtract(xnew, xold))

def chk_diverge(xold, xnew, A, b):
"""
check if previous approx of x was closer than new approx of x
Agrument:
xold - matrix of x in previous iteration
xnew - matrix x in the current iteration
A - Matrix A in CSR format
b - Vector B
Return:
True - if the matrix is converging
False - if the matrix is diverging
"""
dist_old = get_residual(A, xold, b)
dist_new = get_residual(A, xnew, b)
Expand All @@ -52,7 +82,30 @@ def chk_diverge(xold, xnew, A, b):
return False

def chk_converge(A, xnew, b, xold, x_seq_tol, res_tol, flag):
#checks both residual and x_seq for convergence
'''
checks both residual and X sequence for convergence
and decides further SOR iteration based on
Stop Reason conditions:
1 denotes "x Sequence convergence"
2 denotes "Residual convergence"
4 denotes "X Sequence divergence"
-1 denotes "Continue SOR Loop"
Agrument:
A - Matrix A in CSR format
xnew - matrix x in the current iteration
b - Vector B
xold - matrix of x in previous iteration
x_seq_tol - X Sequence tolerance value
res_tol - residual tolerance
flag - if first time, its True to start SOR loop
Return:
stopping_reason - returns the value to decide if the SOR loop needs
'''
if flag == True:
return -1 #required to enter sparse_sor loop
elif get_residual(A, xnew, b) < res_tol:
Expand All @@ -67,7 +120,32 @@ def chk_converge(A, xnew, b, xold, x_seq_tol, res_tol, flag):

def sparse_sor(matrix_a, vector_b, matrix_x, dimension_n, max_it=50, \
x_tol=1e-13, res_tol=1e-13, w=1.25 ):

'''
Sparse SOR algorithm implementation to find Ax = b
Stop Reasons:
1 denotes "x Sequence convergence"
2 denotes "Residual convergence"
3 denotes "Max Iterations reached"
4 denotes "X Sequence divergence"
-1 denotes "Continue SOR Loop"
Arguments:
matrix_a - Matrix A in CSR format
vector_b - Vector B
x - initial estimate of matrix x
dimension_n - dimesion of matrix A
max_it <optional> - max iterations to check
X_tol <optional> - tolerance allowed in x sequence
res_tol <optional> - residual tolerance allowed in Ax-b sequence
w <optional> - Estimate used
Return:
stop_reason - stop reason for end of algorithm
max_it - number of iterations
num_it - numer of iteration that execution halted
matrix_x_new - final matrix X value
'''
num_it = 1
stop_reason = 6 #something has gone wrong if this does not get overwritten later
matrix_x_last_it = np.array([0.0])
Expand Down Expand Up @@ -104,7 +182,22 @@ def sparse_sor(matrix_a, vector_b, matrix_x, dimension_n, max_it=50, \
return (stop_reason, max_it, num_it-1, matrix_x_new )

def dense_SOR(matrix_a,vector_b,dimension_n,max_iteration,w,matrix_x):
print("Dense SOR Calculation")
'''
Dense SOR algorithm implementation to find Ax = b
Arguments:
matrix_a - Matrix A in CSR format
vector_b - Vector B
dimension_n - dimesion of matrix A
max_iteration - max iterations to check
w <optional> - Estimate used
matrix_x - initial estimate of matrix x
Return:
None
'''
# print("Dense SOR Calculation")
it_counter=0
while(it_counter<=max_iteration):
for row_counter in range(dimension_n):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
4
2 2 3 4
0 3 7 9
1 2 3 6
7 4 2 1
2 1 3 1
Loading

0 comments on commit 7d834b7

Please sign in to comment.