I am trying to fit a Cosine curve but I get an error regarding the shape of my arrays. The error only appears when I change the np.cos(phi - delta) to np.cos(2*phi - delta).
from scipy.optimize import fmin
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import math
axes = plt.gca()
axes.set_ylim([-5,0])
#bond CHARMM
def func(phi, kphi, delta):
return kphi * (1 + np.cos(2*phi - delta))
class Dihedral:
def __init__(self):
self.masses = {'H': 1, 'D': 2, 'C': 12, 'O': 16}
def Dihedral_fit (self,x,y):
self.popt, pcov = curve_fit(func, x, y, p0 =(0,2.3),method='trf')
print "Cosine fit"
print self.popt
plt.plot(xdata, ydata, 'b-', label='data')
diff=sum(abs(func(x,self.popt[0],self.popt[1])-y))/len(x)
print "AAE is"
print diff
plt.plot(xdata, func(xdata, *self.popt), 'r-',label='Cos: kphi=%5.3f, delta=%5.3f' % tuple(self.popt))
if __name__ == "__main__":
xdata = [0,15,30,45,60,75,90,105]
ydata = [-4.24,-3.82,-3.08,-2.07,-1.04,-0.30,0,-30]
x = np.array(xdata)
y = np.array(ydata)
Harm=Dihedral()
Harm.Dihedral_fit(x,y)
plt.legend()
plt.show()
any help will be grateful
