Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
restrepo
GitHub Repository: restrepo/ComputationalMethods
Path: blob/master/material/Minimization.ipynb
934 views
Kernel: Python 3 (ipykernel)

Open In Colab


Minimization

Find the minumum of a function


Bibliography

[1] Optimization and fit scipy optimize

%pylab inline
Populating the interactive namespace from numpy and matplotlib
import numpy as np import scipy.optimize as optimize import scipy.interpolate as interpolate import pandas as pd

Example

Consider the following dataset

df=pd.DataFrame({'X':[2.5,3.1,4.5,5,5.9,6.2], 'Y':[3,-1.01,1.5,0.7,2.8,1.5]}) df

Laggrange interpolation

import numpy as np
p=np.poly1d([1,2,3])
print(p)
2 1 x + 2 x + 3
p(1)
6
p([1,2,3])
array([ 6, 11, 18])
p.roots
array([-1.+1.41421356j, -1.-1.41421356j])
print(p.deriv())
2 x + 2
pol=interpolate.lagrange(df.X,df.Y)
print(pol)
5 4 3 2 -0.8941 x + 19.97 x - 174.7 x + 746.7 x - 1557 x + 1264

df.X is a Pandas Series

df.X
0 2.5 1 3.1 2 4.5 3 5.0 4 5.9 5 6.2 Name: X, dtype: float64

To obtain some specific value by using slices, we must use .iloc

Note that df.X[3]=df.X.loc[3]=df.X.iloc[3]

df.X[3],df.X.loc[3],df.X.iloc[3]
(5.0, 5.0, 5.0)
df.X.iloc[-1],df.X.max()
(6.2, 6.2)

works!

df
x=np.linspace(df.X.iloc[0],df.X.iloc[-1],100) plt.plot(x,pol(x)) plt.plot(df.X,df.Y,'ro') plt.xlabel('X') plt.ylabel('Y') plt.grid()
Image in a Jupyter notebook

Hermite interpolation

The recommend degree for the Hermite polynomial is n1n-1 where nn is the number of data of the dataset

H=np.polynomial.hermite.Hermite.fit(df.X,df.Y,5)
print(H)
3.5768090026661477 - 21.34734250551783·H₁(x) + 3.149481575369614·H₂(x) - 9.275256998110663·H₃(x) + 0.3812886076702684·H₄(x) - 0.6054571273241235·H₅(x)
plt.plot(x,H(x),'k-') plt.plot(x,pol(x),'c--') plt.plot(df.X,df.Y,'ro') plt.grid() plt.xlabel('$x$') plt.ylabel('$H(x)$')
Text(0,0.5,'$H(x)$')
Image in a Jupyter notebook

Finding the local minimum of a function

Finding the first minimum close to 3 (which corresponds to the global minimum), and the second close to 5 (a local minimum)

help(optimize.fmin_powell)
min1=optimize.fmin_powell(pol,3,full_output=True) min2=optimize.fmin_powell(pol,5.2,full_output=True)
Optimization terminated successfully. Current function value: -1.374113 Iterations: 2 Function evaluations: 28 Optimization terminated successfully. Current function value: 0.699898 Iterations: 2 Function evaluations: 50
min1
(array([2.92784955]), array(-1.37411316), array([[1.]]), 2, 28, 0)
min2
(array([5.00492929]), array(0.69989815), array([[0.00045871]]), 2, 50, 0)
print('The global minimum is f(x)={} for x={};\n the local minimum is f(x)={} for x={}'.format( min1[1],min1[0],min2[1],min2[0]))
The global minimum is f(x)=-1.3741131581291484 for x=[2.92784955]; the local minimum is f(x)=0.6998981514389016 for x=[5.00492929]

Activity Find the maximum values of the Hermite interpolation function of degree 5 to the set of points: https://github.com/restrepo/ComputationalMethods/blob/master/data/hermite.csv

df=pd.read_csv('https://raw.githubusercontent.com/restrepo/ComputationalMethods/master/data/hermite.csv') H=np.polynomial.hermite.Hermite.fit(df.X,df.Y,5) x=np.linspace(df.X.iloc[0],df.X.iloc[-1],100) plt.plot(x,-H(x),'k-') plt.grid() plt.xlabel('$x$') plt.ylabel('$H(x)$')
Text(0, 0.5, '$H(x)$')
Image in a Jupyter notebook

fmin_powell try to search the global minimum

optimize.fmin_powell(-H,4.5)
Optimization terminated successfully. Current function value: -2.803764 Iterations: 2 Function evaluations: 27
array([5.918213])

Find a local minumum

close minimum

min1=optimize.minimize(-H,x0=4.5) min1['x']
array([4.01502454])
min1=optimize.minimize(-H,5.2) min1['x']
array([5.91821428])

minimum in a range

min1=optimize.minimize(-H,x0=4,bounds=((3.5, 4.5), ) ) min1['x']
array([4.01502381])
xmin_local = optimize.fminbound(-H, 3.5, 4.5) xmin_local
4.01502533002799
optimize.brute(-H,ranges=((3.5,4.5,0.1),))
array([4.01503906])

Find a global minumum (alternative)

min1=optimize.basinhopping(-H,5.5) min1['x']
array([5.91821428])
%pylab inline
Populating the interactive namespace from numpy and matplotlib
import pandas as pd

The Higgs potential

To write greek letter inside a cell use the LaTeX\rm \LaTeX macro and the tab, e.g: \mu<TAB>, to produce μ

%pylab inline
Populating the interactive namespace from numpy and matplotlib
import numpy as np
α=2
m_proton = 1 #GeV/c²
m_H=126 # GeV/c^2 (c→1) G_F=1.1663787E-5 #GeV^-2 v=1/np.sqrt(np.sqrt(2.)*G_F) # GeV μ=np.sqrt(m_H**2/2) #GeV λ=m_H**2/(2.*v**2) μ,λ,v
(89.09545442950498, 0.13093799079487806, 246.21965079413738)
ϕ=np.linspace(-300,300) Vp=lambda ϕ: 0.5*μ**2*ϕ**2+0.25*λ*ϕ**4 plt.plot(ϕ, Vp(ϕ) ) plt.xlabel(r'$\phi$ [GeV]',size=20 ) plt.ylabel(r'$V(\phi)$ [GeV]',size=20) plt.xlabel(r'$\phi$ [GeV]',size=20 ) plt.ylabel(r'$V(\phi)$ [GeV$^4$]',size=20) plt.grid()
Image in a Jupyter notebook
μ=μ*1j V=lambda ϕ: Vp(ϕ).real
Vp(ϕ)[0].real
-92060568.64037189
ϕ=np.linspace(-380,380) plt.plot(ϕ, V(ϕ) ) plt.xlabel(r'$\phi$ [GeV]',size=20 ) plt.ylabel(r'$V(\phi)$ [GeV]',size=20) plt.xlabel(r'$\phi$ [GeV]',size=20 ) plt.ylabel(r'$V(\phi)$ [GeV$^4$]',size=20) plt.grid()
Image in a Jupyter notebook
from scipy import optimize
fp=optimize.fmin_powell(V,200,ftol=1E-16,full_output=True)
Optimization terminated successfully. Current function value: -120308559.069597 Iterations: 4 Function evaluations: 74
ϕ_min=fp[0]
print(ϕ_min,v)
[246.21964988] 246.21965079413738

Minimization in higher dimensions

For a complex scalar field with potential V(ϕ)=μ2ϕϕ+λ(ϕϕ)2\begin{equation} V(\phi)=\mu^2\phi^*\phi + \lambda (\phi^*\phi)^2 \end{equation} with ϕ=ϕ1+iϕ22\begin{equation} \phi=\frac{\phi_1+i\phi_2 }{\sqrt{2} } \end{equation} and μ2<0\mu^2<0, and λ>0\lambda>0, find some of the infinite number of minimum values of ϕ\phi, as illustrated in the figure, with the plane, ϕ1ϕ2\phi_1-\phi_2, moved to the minimum to easy the visualization. Expanding in terms of the real and imaginary part of ϕ\phi V(ϕ)=μ22(ϕ12+ϕ22)+λ4(ϕ12+ϕ22)2\begin{equation} V(\phi)=\frac{\mu^2}{2}\left(\phi_1^2+\phi_2^2 \right) + \frac{\lambda}{4}\left( \phi_1^2+\phi_2^2\right)^2 \end{equation}

%pylab inline from scipy import optimize import pandas as pd
Populating the interactive namespace from numpy and matplotlib
def f(ϕ,m_H=126,G_F=1.1663787E-5): v=1/np.sqrt(np.sqrt(2.)*G_F) # GeV μ=np.sqrt(m_H**2/2)*1j #imaginary mass λ=m_H**2/(2.*v**2) #print(μ,λ) return ( 0.5*μ**2*(ϕ[0]**2+ϕ[1]**2)+0.25*λ*(ϕ[0]**2+ϕ[1]**2)**2 ).real

Check a point of the function

f([0,10])
-396572.6550230127

Check the minimim obtained when an inizialization point at ϕ0=(0,0)\phi_0=(0,0)

fmin=optimize.fmin_powell(f,x0=[0,10],ftol=1E-16,full_output=True) fmin[0]
Optimization terminated successfully. Current function value: -120308559.069597 Iterations: 3 Function evaluations: 111
array([246.21914011, -0.50137284])

Check the proyection of the minimum in the plane ϕ1ϕ2\phi_1-\phi_2

print('V(ϕ)={} GeV^4'.format(fmin[1].round(1)))
V(ϕ)=-120308559.1 GeV^4
np.sqrt( fmin[0][0]**2+fmin[0][1]**2 )
246.21965057683713

For random initialization points, we can get several minima

np.random.uniform(-300,300,2)
array([255.08701519, 178.66169419])
df=pd.DataFrame() for i in range(1000): ϕ0=np.random.uniform(-300,300,2) ϕmin=optimize.fmin_powell(f,x0=ϕ0,ftol=1E-16,disp=False) df=df.append({'ϕ1':ϕmin[0],'ϕ2':ϕmin[1]},ignore_index=True)

Projection of the minima in the plane, ϕ1,ϕ2\phi_1,\phi_2

df[:3]
plt.figure( figsize=(6,6) ) plt.plot(df['ϕ1'],df['ϕ2'],'r.',label=r'$\phi_{{\rm min}}={}$ GeV'.format( np.sqrt(df.loc[0,'ϕ1']**2+df.loc[0,'ϕ2']**2).round(1))) plt.plot(df.loc[0,'ϕ1'],df.loc[0,'ϕ2'],'k*',label='Our Universe',markersize=10) plt.xlabel('$\phi_1$',size=15) plt.ylabel('$\phi_2$',size=15) plt.legend(loc='best') plt.grid()
Image in a Jupyter notebook