diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..38c3cac --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# OS generated files # +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Packages # +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Plots generated as images +*.jpg +*.png diff --git a/optimizer.py b/optimizer.py new file mode 100644 index 0000000..dd80ba9 --- /dev/null +++ b/optimizer.py @@ -0,0 +1,34 @@ +# EXERCISE 1, PART 1. + +import scipy.optimize + +def optimizer(f,met,x0): + + # This function takes an arbitrary 2D function f(x,y) and return its + # minimizer and all the previous iterations performed until convergence. + + # The inputs are: + # f: function to be minimized --> object, functor + # met: optimization method to be used --> string + # x0: initial guess --> list or array of 2 elements + + # Save initial guess in the lists iterations_x and iterations_y. These + # lists will change size depending on the number of iterations + iterations_x = [x0[0]] + iterations_y = [x0[1]] + + # Define function to store iteration points when calling + # scipy.optimize.minimize and using callback parameter + def store_iterations(X): + x, y = X + iterations_x.append(x) + iterations_y.append(y) + + # Compute optimizer and store iterations by using callback + res = scipy.optimize.minimize(f, x0, method=met, callback=store_iterations, + options={'gtol': 1e-9, 'disp': True}) + # Return the optimizer res.x and all the iteration points inside the + # lists iterations_x and iterations_y (include the initial guess and the + # optimizer res.x + return res.x, iterations_x, iterations_y +