Optimization Exercise 1

Imports


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt

Hat potential

The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential":

$$ V(x) = -a x^2 + b x^4 $$

Write a function hat(x,a,b) that returns the value of this function:


In [2]:
# YOUR CODE HERE
# raise NotImplementedError()
def hat(x, a, b):
    c = x**2
    d = x**4
    p = -a * c + b * d
    q = np.array(p)
    return q

In [3]:
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(1.0, 10.0, 1.0)==-9.0

Plot this function over the range $x\in\left[-3,3\right]$ with $b=1.0$ and $a=5.0$:


In [4]:
a = 5.0
b = 1.0

In [5]:
# YOUR CODE HERE
# raise NotImplementedError()
x = np.arange(-3.0,3.0,0.1)


plt.plot(x,hat(x,a,b))
plt.xlim(-3, 3)
plt.ylim(-7, 35)
plt.box(False)
plt.xlabel('Position')
plt.ylabel('Hat Potential')
plt.title('Hat Potential versus Position')


Out[5]:
<matplotlib.text.Text at 0x7f954e55c668>

In [6]:
assert True # leave this to grade the plot

Write code that finds the two local minima of this function for $b=1.0$ and $a=5.0$.

  • Use scipy.optimize.minimize to find the minima. You will have to think carefully about how to get this function to find both minima.
  • Print the x values of the minima.
  • Plot the function as a blue line.
  • On the same axes, show the minima as red circles.
  • Customize your visualization to make it beatiful and effective.

In [7]:
# YOUR CODE HERE
# raise NotImplementedError() 
# x0 = np.arange(-3.0, 0.0, 0.2)
minima_1 = opt.minimize(hat, -1.5, args = (5.0, 1.0))
minima_2 = opt.minimize(hat, 1.5, args = (5.0, 1.0))


x = np.arange(-3.0,3.0,0.1)
plt.plot(x,hat(x,a,b))
plt.xlim(-3, 3)
plt.ylim(-7, 35)
plt.box(False)
plt.scatter(minima_1.x, hat(minima_1.x, 5.0, 1.0), color = 'r')
plt.scatter(minima_2.x, hat(minima_2.x, 5.0, 1.0), color = 'r')
plt.xlabel('Position')
plt.ylabel('Hat Potential')
plt.title('Hat Potential versus Position')
plt.legend('Vm')


Out[7]:
<matplotlib.legend.Legend at 0x7f954e4b8cf8>

In [8]:
assert True # leave this for grading the plot

To check your numerical results, find the locations of the minima analytically. Show and describe the steps in your derivation using LaTeX equations. Evaluate the location of the minima using the above parameters.

With a = 5.0 and b = 1.0 $$ V'(x) = -2 a x + 4 b x^3 $$ $$ V'(x) = -10 x + 4 x^3 $$ Root are x = -1.581, x = 0, 1.581

$$ V''(x) = -2 a + 12 b x^2 $$$$ V''(x) = -10 + 12 x^2 $$

V''(-1.581) = 19.994, V''(0) = -10, V''(1.581) = 19.994 By second derivative test x=-1.585 and x=1.581 are minima


In [ ]: