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
def hat(x,a,b):
    v=-1*a*x**2+b*x**4
    return v

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 [48]:
x=np.linspace(-3,3)
b=1.0
a=5.0
plt.plot(x,hat(x,a,b))


Out[48]:
[<matplotlib.lines.Line2D at 0x7f225076f048>]

In [47]:
# YOUR CODE HERE
x0=-2
a = 5.0
b = 1.0
y=opt.minimize(hat,x0,(a,b))
y.x


Out[47]:
array([-1.58113889])

In [121]:
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 [133]:
# YOUR CODE HERE
x0=-2
a = 5.0
b = 1.0
i=0
y.x
mini=[]

x=np.linspace(-3,3)
for i in x:
    y=opt.minimize(hat,i,(a,b))
    z=int(y.x *100000)
    if np.any(mini[:] == z):
        i=i+1
    else: 
        mini=np.append(mini,z)

mini=mini/100000
mini


plt.plot(x,hat(x,a,b),label="Hat Function")
plt.plot(mini[0],hat(mini[0],a,b),'ro',label="Minima")
plt.plot(mini[1],hat(mini[1],a,b),'ro')
plt.xlabel=("X-Axis")
plt.ylabel=("Y-Axis")
plt.title("Graph of Function and its Local Minima")
plt.legend()


Out[133]:
<matplotlib.legend.Legend at 0x7f2250382c88>

In [ ]:
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.

\begin{equation*} V(x) = -a x^2 + b x^4 \\ \frac{dV}{dt}= -2ax + 4bx^3 \\ a=5.0 \ b=1.0 \\ V(x) = -5.0 x^2 + 1.0 x^4 \\ \frac{dV}{dt}= -10x + 4x^3 \\ \frac{dV}{dt}= -10x + 4x^3 =0 \ when \ x= +- \sqrt{\frac{5}{2}}\\ (According\ to \ Wolfram \ Alpha)\\ \sqrt{\frac{5}{2}}=1.58\\ \end{equation*}

In [ ]: