File: doc_model_with_iter_callback.py

package info (click to toggle)
lmfit-py 0.8.0%2Bdfsg.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,776 kB
  • ctags: 1,203
  • sloc: python: 7,041; makefile: 102; sh: 43
file content (43 lines) | stat: -rw-r--r-- 1,109 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python
#<examples/doc_with_itercb.py>

from numpy import linspace, random
import matplotlib.pylab as pylab

from lmfit.models import LinearModel, GaussianModel
from lmfit.lineshapes import gaussian

def per_iteration(pars, iter, resid, *args, **kws):
    if iter < 3 or iter % 10 == 0:
        out = ['== %i ' % iter]
        for key, val in pars.valuesdict().items():
            out.append('%s=%.3f' % (key, val))
        print ', '.join(out)
        print args, kws


x = linspace(0., 20, 401)
y = gaussian(x, amplitude=24.56, center=7.6543, sigma=1.23)
y = y  - .20*x + 3.333 + random.normal(scale=0.23,  size=len(x))

mod = GaussianModel(prefix='peak_') + LinearModel(prefix='bkg_')

pars = mod.make_params()
pars['peak_amplitude'].value = 3.0
pars['peak_center'].value = 6.0
pars['peak_sigma'].value = 2.0
pars['bkg_intercept'].value = 0.0
pars['bkg_slope'].value = 0.0


out = mod.fit(y, pars, x=x, iter_cb=per_iteration)

pylab.plot(x, y, 'b--')

# print(' Nfev = ', out.nfev)
print( out.fit_report())

pylab.plot(x, out.best_fit, 'k-')
pylab.show()

#<end examples/doc_with_itercb.py>