Created
March 27, 2018 01:32
-
-
Save krishnanraman/cbdafad9a8b31f6a52bec53bdb7ced6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from lmfit import Minimizer, Parameters, report_fit | |
# create data to be fitted | |
x = np.linspace(0, 15, 301) | |
data = 2*x*x+ 3*x+4 | |
# define objective function: returns the array to be minimized | |
def fcn2min(params, x, data): | |
"""Model a parabola.""" | |
a = params['a'] | |
b = params['b'] | |
c = params['c'] | |
model = a*x*x + b*x +c | |
return model - data | |
# create a set of Parameters | |
params = Parameters() | |
params.add('a', value=0.0, min=0, max=5) | |
params.add('b', value=0.0, min=0, max=5) | |
params.add('c', value=0.0, min=0, max=5) | |
# do fit, here with leastsq model | |
minner = Minimizer(fcn2min, params, fcn_args=(x, data)) | |
result = minner.minimize() | |
# calculate final result | |
final = data + result.residual | |
# write error report | |
report_fit(result) | |
# try to plot results | |
try: | |
import matplotlib.pyplot as plt | |
plt.plot(x, data, 'k+') | |
plt.plot(x, final, 'r') | |
plt.show() | |
except ImportError: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment