diff --git a/optimizer.py b/optimizer.py index e797443..36f6d27 100644 --- a/optimizer.py +++ b/optimizer.py @@ -1,77 +1,78 @@ #!/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=cm.coolwarm,linewidth=0, antialiased=False) # Plot the path. path=np.array(path) x1 = path[:,0] x2 = path[:,1] x3 = S((x1,x2)) ax.plot(x1,x2,x3,'--ko') 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") args = parser.parse_args() if args.BFGS: min_method = 'BFGS' if args.CG: min_method = 'CG' else: sys.stderr.write("Choose a minimization method between BFGS and CG" ) x = (np.random.rand(2)+2) path.append(x) minimum = sopt.minimize(S,x,method=min_method, tol=1e-14, callback=getIterationSteps) plotFunc(S,path) \ No newline at end of file