Skip to content

Instantly share code, notes, and snippets.

@krishnanraman
Created March 27, 2018 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krishnanraman/cbdafad9a8b31f6a52bec53bdb7ced6a to your computer and use it in GitHub Desktop.
Save krishnanraman/cbdafad9a8b31f6a52bec53bdb7ced6a to your computer and use it in GitHub Desktop.
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