## examples/feffit/doc_feffit7.lar
#
# this revisits the example in doc_feffit1.lar, but
# setting refine_bkg=True to cause the background to
# be refined with the fit.

# read data
cu_data  = read_ascii('../xafsdata/cu_metal_rt.xdi')
autobk(cu_data.energy, cu_data.mutrans, group=cu_data, rbkg=0.9, kw=2)

# define fitting parameter group
pars = param_group(amp    = guess(1.0, min=0),
                   del_e0 = guess(1.0),
                   sig2   = guess(0.01, min=0),
                   del_r  = guess(-0.01, min=-0.25, max=0.25))

# define a Feff Path, give expressions for Path Parameters
path1 = feffpath('feffcu01.dat',
                 s02    = 'amp',
                 e0     = 'del_e0',
                 sigma2 = 'sig2',
                 deltar = 'del_r')

# set tranform / fit ranges
trans = feffit_transform(kmin=3, kmax=16, kw=2, dk=4,
                         window='kaiser', rmin=1.0, rmax=3.0)

# define dataset to include data, pathlist, transform
dset = feffit_dataset(data=cu_data, paths=[path1],
                      epsilon_k=0.002,
                      transform=trans, refine_bkg=True)

out = feffit(pars, dset)
print(feffit_report(out))

plot_chifit(dset)
#
if hasattr(out.datasets[0].data, 'bkgk'):
    mbkg = group(k=out.datasets[0].data.k, chi=out.datasets[0].data.bkgk)
    #
    plot(mbkg.k, mbkg.chi*mbkg.k**2, label='fitted bkg (1x)', win=1)
    plot(mbkg.k, (out.datasets[0]._chi-out.datasets[0]._bkg)*mbkg.k**2, label='chi-bkg', win=1)
    #
    xftf(mbkg, kmin=trans.kmin, kmax=trans.kmax, kweight=trans.kweight,
         dk=trans.dk, kwindow=trans.window)

    plot(mbkg.r, mbkg.chir_mag, label='fitted bkg (1x)', win=2)
#endif
