diff --git a/Homework1/conjugate_gradient.py b/Homework1/conjugate_gradient.py index 99b0d4b..22e99b7 100644 --- a/Homework1/conjugate_gradient.py +++ b/Homework1/conjugate_gradient.py @@ -1,83 +1,98 @@ import numpy as np import argparse import math # Arguments parser my_parser = argparse.ArgumentParser() my_parser.add_argument('-A', action='store', type=float, nargs='+', required=True, help='The matrix A in rowmajor format: numbers separated by space') my_parser.add_argument('-b', action='store', type=float, nargs='+', required=True, help='The vector b in rowmajor format: numbers separated by space') my_parser.add_argument('-x0', action='store', type=float, nargs='+', required=True, help='The initial guess x0 in rowmajor format: numbers separated by space') my_parser.add_argument('-Nmax', action='store', type=int, default=20, help='Maximum number of iterations. Default: 20') my_parser.add_argument('-criteria', action='store', type=float, default=1e-6, help='Convergence criteria. Default: 1e-6') +my_parser.add_argument('-detail', action='store_true', default=False, help='Showing details of every step during the convergence.') args = my_parser.parse_args() # Extracting matrix A, vector b, and the initial guess x0 from the input arguments A = np.array(args.A) b = np.array(args.b) x0 = np.array(args.x0) # Checking the compatibility of size of A with b (n: dimension of the problem) n=np.size(b) if np.size(A) != n*n: print('\n=====ERROR=====\n' 'Matrix A and vector b are not compatible in size.\n' '===============\n') exit() # Checking the compatibility of size of x0 with A and b if np.size(x0) != n: print('\n=====ERROR=====\n' 'Initial guess does not match to matrix A and vector b in size.\n' '===============\n') exit() # Converting matrix A from rowmajor to square form A=A.reshape((n,n)) +""" +# The to-be-optimized function +def objective(X, *args): #objective function to be optimized + AA = args[0] + BB = args[1] + S = 0.5*np.einsum('j,j',X,np.einsum('ij,j',AA,X))-np.einsum('j,j',X,BB) + return S +""" + # Converting A to the generalized form: (A+transpose(A))/2 -A=0.5*(A+np.transpose(A)) +A_CG=0.5*(A+np.transpose(A)) # Converting optional settings from the arguments N_max=args.Nmax criteria=args.criteria # Iteration procedure step=0 x=x0 -r=b-np.einsum('ij,j',A,x0) +r=b-np.einsum('ij,j',A_CG,x0) norm_residual=math.sqrt(np.einsum('j,j',r,r)) p=r -print('==========RESULT==========') +print('\n\n\n======================RESULT=======================') +print('Objective function:\n'+ + 'S = 0.5 * transpose(x) * A * x - transpose(x) * b\n\n'+ + 'A =\n'+str(A)+'\n\n'+ + 'b =\n'+str(b)+'\n'+ + '---------------------------------------------------' + ) while norm_residual>criteria and step