Page MenuHomec4science

optimizer.py
No OneTemporary

File Metadata

Created
Tue, May 21, 15:42

optimizer.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 12:31:42 2018
@author: alessia
"""
import numpy as np
import scipy.optimize as sopt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import sys
import argparse
def S(x):
x1 = x[0]
x2 = x[1]
return 2. * (x1 ** 2) + 3. / 2. * (x2 ** 2) + x1 * x2 - x1 - 2 * x2 + 6
path = []
def getIterationSteps(x):
path.append(x)
def plotFunc(S,path):
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot the surface.
X1 = np.arange(-3, 3, 0.01)
X2 = np.arange(-3, 3, 0.01)
X1, X2 = np.meshgrid(X1,X2)
X3 = S((X1,X2))
surf = ax.plot_surface(X1, X2, X3, cmap='summer',linewidth=0.0, antialiased=False,alpha=0.2)
ax.contour(X1, X2, X3, 15, colors='k', linewidths=2)
# Plot the path.
path=np.array(path)
x1 = path[:,0]
x2 = path[:,1]
x3 = S((x1,x2))
ax.plot(x1,x2,x3,'--ro', linewidth=2, markersize=8)
plt.xlabel('x')
plt.ylabel('y')
ax.view_init(45,140)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
#-------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="optimizer.py finds the minimum of a given function with different methods")
group = parser.add_mutually_exclusive_group()
group.add_argument("-BFGS", "--BFGS", action="store_true", help="minimize with BFGS method")
group.add_argument("-CG", "--CG", action="store_true", help="minimize with Conjugate Gradient method")
parser.add_argument("-RI", "--RI", action="store_true", help="generate a random initial condition")
args = parser.parse_args()
if args.BFGS:
min_method = 'BFGS'
elif args.CG:
min_method = 'CG'
else:
sys.stderr.write("Choose a minimization method between BFGS and CG \n" )
exit()
if args.RI:
x = 6.*(np.random.rand(2)-0.5)
else:
x = [3., 1.]
path.append(x)
minimum = sopt.minimize(S,x,method=min_method, tol=1e-14, callback=getIterationSteps)
plotFunc(S,path)

Event Timeline