import time

def resid(pars, x, sigma=None, data=None):
    model = gaussian(x,  pars.amp, pars.cen, pars.wid) + pars.off + x * pars.slope
    pars.iter += 1
    if data is None:      return model
    if sigma is  None:    return (model - data)
    return (model - data)/sigma
#enddef


def compare_fit(method):
    meths = ['nelder', 'powell', 'bfgs', 'lbfgs', 'tnc', 'cobyla', 'slsqp']
    if method not in meths:
        print( "unknown / unsupport method: '%s'" % method)
        print( "use one of: %s" % (', ').join(meths))
        return
    #endif

    n = 601
    xmin = 0.
    xmax = 20.0
    x = linspace(xmin, xmax, n)

    data = (gaussian(x, amplitude=27, center=9.3, sigma=1.5) +
            random.normal(scale=0.35,  size=n) + x*.3 - 0.1)

    pfit1 = param_group(amp = guess(21), cen = guess(11), wid = guess(0.5),
                        slope = guess(0), off = guess(0), iter = 0)

    pfit2 = param_group(amp = guess(21), cen = guess(11), wid = guess(0.5),
                        slope = guess(0), off = guess(0), iter=0)

    newplot(x, data, linewidth=0, marker='+', color='blue', label='data', show_legend=True)
    results = {}
    for pars, meth in ((pfit1, 'leastsq'), (pfit2, method)):
        t0 = time.time()
        ret = minimize(resid, pars, args=(x,), method=meth, kws={'data':data})
        print( 'Method = %s, Fit time = %.3f sec' % (meth, time.time()-t0))
        print( fit_report(ret))
        lfit = gaussian(x, pars.amp, pars.cen, pars.wid) + x*pars.slope + pars.off
        plot(x, lfit, linewidth=2, label=meth)
        results[meth] = (lfit)
    #endfor

    diff= 10*(results['leastsq'] - results[meth])

    plot(x, diff, color='blue', label='diff x 10')
#enddef

compare_fit('nelder')
