Page MenuHomec4science

optimizer.py
No OneTemporary

File Metadata

Created
Mon, May 13, 06:03

optimizer.py

"""
October 2019
Authors: Omid Ashtari and Armand Sieber
Description: Scripts intended to minimize a quadratic function using scipy.optimize built-in function.
The function to be minimized is defined as S(X)= X'AX - X'B, with X = [x, y] and X' being its transpose
A is a 2x2 matrix and B 2x1 vector
"""
import numpy as np
from scipy.optimize import minimize
import argparse
import post_processing
# Arguments parser
my_parser = argparse.ArgumentParser()
my_parser.add_argument('-method', action='store', choices=['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP'], default='CG', help='The optimization method.')
my_parser.add_argument('-x0', action='store', type=float, nargs=2, help='The initial guess x0 in rowmajor format: two numbers separated by space', default=[3.0, 2.0])
args = my_parser.parse_args()
# Objective function to be minimized
def objective(X, *args):
A = args[0]
B = args[1].T
S = np.dot(X.T, np.dot(A, X)) - np.dot(X.T, B)
return S
# Stores intermediates minimization results in X_int
def reporter(X_r):
global X_int
X_int = np.vstack([X_int, X_r])
return 0
# Parameters of the function to minimize + initial guess (can be modified by user)
A = np.array([[4, 0], [1, 3]]) # Matrix A
B = np.array([0, 1]) # Vector B
X0 = np.array(args.x0) # Initial guess
# Extracting method from args
method=args.method
# Minimization process
X_int = X0 #stores solution at each step
solution = minimize(objective, X0, args = (A, B), method = method, callback = reporter,options = {'maxiter':100})
# Display results
print('\n\n\n======================Summary======================')
print('Objective function:\n'+
'S = transpose(x) * A * x - transpose(x) * b\n\n'+
'A =\n'+str(A)+'\n\n'+
'b =\n'+str(B)+'\n\n'+
'method: '+args.method)
print('---------------------------------------------------')
print(solution)
# Post-processing
post_processing.plot_results(X_int, A, B, method)

Event Timeline