The problem originates from fitting a diffraction pattern to data, where the number of slits is known before hand. I have given a simplified version below that highlights the same issue. The function should fit the values of a and b the data, while passing n to the function. I could use a global n which would solve my issues, however I would like to do this using **kwargs as shown in the scipy.optimize.curve_fit() reference.
Here is an example of the issue. The code generates the curve of 4sin(2x)+3cos(2x) with some noise as the data:
import numpy as np
import scipy
import matplotlib.pyplot as plt
def curve(x,a,b,**kwargs):
n = kwargs["n"]
return a*np.sin(n*x)+b*np.cos(n*x)
x = np.linspace(-5,5,1000)
y = np.random.normal(loc=curve(x, 4, 3, n=2), scale=0.2, size=None)
result = scipy.optimize.curve_fit(curve, x, y, n = 2)
y2 = curve(x, *result[0], n=2)
plt.plot(x, y2)
plt.plot(x,y)
plt.show()
This returns the error
File "C:\Users\HP\OneDrive\Documents\Uni\lab year 2\diffraction\kwargs.py", line 13, in <module>
result = scipy.optimize.curve_fit(curve, x, y, n = 2)
File "C:\Users\HP\anaconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 834, in curve_fit
res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
TypeError: leastsq() got an unexpected keyword argument 'n'