How to use the lmfit.conf_interval function in lmfit

To help you get started, we’ve selected a few lmfit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lmfit / lmfit-py / tests / test_confidence.py View on Github external
def test_confidence_with_trace(data, pars):
    """Test calculation of confidence intervals with trace."""
    minimizer = lmfit.Minimizer(residual, pars, fcn_args=(data))
    out = minimizer.leastsq()

    ci, tr = lmfit.conf_interval(minimizer, out, sigmas=[0.6827], trace=True)
    for p in out.params:
        diff1 = ci[p][1][1] - ci[p][0][1]
        diff2 = ci[p][2][1] - ci[p][1][1]
        stderr = out.params[p].stderr
        assert abs(diff1 - stderr) / stderr < 0.05
        assert abs(diff2 - stderr) / stderr < 0.05

        assert p in tr.keys()
        assert 'prob' in tr[p].keys()
github lmfit / lmfit-py / tests / test_printfuncs.py View on Github external
p_true = Parameters()
    p_true.add_many(('amp', 14.0), ('period', 5.33), ('shift', 0.123),
                    ('decay', 0.010))

    x = np.linspace(0.0, 250.0, 2500)
    data = residual(p_true, x) + np.random.normal(scale=0.7215, size=x.size)

    fit_params = Parameters()
    fit_params.add_many(('amp', 13.0), ('period', 2), ('shift', 0.0),
                        ('decay', 0.02))

    mini = Minimizer(residual, fit_params, fcn_args=(x,),
                     fcn_kws={'data': data})
    out = mini.leastsq()
    ci = conf_interval(mini, out)
    return ci
github lmfit / lmfit-py / tests / test_confidence.py View on Github external
minimizer = lmfit.Minimizer(residual,
                                pars,
                                calc_covar=False,
                                fcn_args=data)
    out = minimizer.minimize(method='nelder')
    out_lsq = minimizer.minimize(params=out.params, method='leastsq')

    # no uncertainty estimated
    msg = 'Cannot determine Confidence Intervals without sensible uncertainty'
    with pytest.raises(lmfit.MinimizerException, match=msg):
        lmfit.conf_interval(minimizer, out)

    # uncertainty is NaN
    out_lsq.params['a'].stderr = np.nan
    with pytest.raises(lmfit.MinimizerException, match=msg):
        lmfit.conf_interval(minimizer, out_lsq)

    # only one varying parameter
    out_lsq.params['a'].vary = False
    msg = r'Cannot determine Confidence Intervals with < 2 variables'
    with pytest.raises(lmfit.MinimizerException, match=msg):
        lmfit.conf_interval(minimizer, out_lsq)
github lmfit / lmfit-py / tests / test_confidence.py View on Github external
def test_confidence_sigma_vs_prob(data, pars):
    """Calculate confidence by specifying sigma or probability."""
    minimizer = lmfit.Minimizer(residual, pars, fcn_args=(data))
    out = minimizer.leastsq()

    ci_sigmas = lmfit.conf_interval(minimizer, out, sigmas=[1, 2, 3])
    ci_1sigma = lmfit.conf_interval(minimizer, out, sigmas=[1])
    ci_probs = lmfit.conf_interval(minimizer,
                                   out,
                                   sigmas=[0.68269, 0.9545, 0.9973])

    assert_allclose(ci_sigmas['a'][0][1], ci_probs['a'][0][1], rtol=0.01)
    assert_allclose(ci_sigmas['b'][2][1], ci_probs['b'][2][1], rtol=0.01)
    assert len(ci_1sigma['a']) == 3
    assert len(ci_probs['a']) == 7
github lmfit / lmfit-py / tests / test_confidence.py View on Github external
def test_confidence_exceptions(data, pars):
    """Make sure the proper exceptions are raised when needed."""
    minimizer = lmfit.Minimizer(residual,
                                pars,
                                calc_covar=False,
                                fcn_args=data)
    out = minimizer.minimize(method='nelder')
    out_lsq = minimizer.minimize(params=out.params, method='leastsq')

    # no uncertainty estimated
    msg = 'Cannot determine Confidence Intervals without sensible uncertainty'
    with pytest.raises(lmfit.MinimizerException, match=msg):
        lmfit.conf_interval(minimizer, out)

    # uncertainty is NaN
    out_lsq.params['a'].stderr = np.nan
    with pytest.raises(lmfit.MinimizerException, match=msg):
        lmfit.conf_interval(minimizer, out_lsq)

    # only one varying parameter
    out_lsq.params['a'].vary = False
    msg = r'Cannot determine Confidence Intervals with < 2 variables'
    with pytest.raises(lmfit.MinimizerException, match=msg):
        lmfit.conf_interval(minimizer, out_lsq)
github lmfit / lmfit-py / tests / test_fitreports.py View on Github external
x = np.linspace(xmin, xmax, n)
    data = residual(p_true, x) + np.random.normal(scale=0.7215, size=n)

    fit_params = Parameters()
    fit_params.add('amp', value=13.0)
    fit_params.add('period', value=2)
    fit_params.add('shift', value=0.0)
    fit_params.add('decay', value=0.02)

    mini = Minimizer(residual, fit_params, fcn_args=(x,),
                     fcn_kws={'data': data})
    out = mini.leastsq()
    report = fit_report(out)
    assert(len(report) > 500)

    ci, tr = conf_interval(mini, out, trace=True)
    report = ci_report(ci)
    assert(len(report) > 250)
github lmfit / lmfit-py / tests / test_confidence.py View on Github external
def test_confidence_prob_func(data, pars):
    """Test conf_interval with alternate prob_func."""
    minimizer = lmfit.Minimizer(residual, pars, fcn_args=data)
    out = minimizer.minimize(method='leastsq')

    def my_f_compare(best_fit, new_fit):
        nfree = best_fit.nfree
        nfix = best_fit.nfree - new_fit.nfree
        dchi = new_fit.chisqr / best_fit.chisqr - 1.0
        return f.cdf(dchi * nfree / nfix, nfix, nfree)

    lmfit.conf_interval(minimizer, out, sigmas=[1], prob_func=my_f_compare)
github phoebe-project / phoebe2 / phoebe / backend / nonlin.py View on Github external
#-- the same with the errors and correlation coefficients, if there are any
    if result.errorbars:
        sigmas = [pars['{}_{}'.format(ipar.get_qualifier(),ipar.get_unique_label().replace('-','_'))].stderr for ipar in ppars]
        correl = [pars['{}_{}'.format(ipar.get_qualifier(),ipar.get_unique_label().replace('-','_'))].correl for ipar in ppars]
    else:
        sigmas = [np.nan for ipar in pars]
        correl = [np.nan for ipar in pars]
        logger.error("Could not estimate errors (set to nan)")
    #-- when asked, compute detailed confidence intervals
    if fitparams['compute_ci']:
        #-- if we do this, we need to disable boundaries
        for name in pars:
            pars[name].min = None
            pars[name].max = None
        try:
            ci = lmfit.conf_interval(result,sigmas=(0.674,0.997),verbose=True,maxiter=10)
            lmfit.printfuncs.report_ci(ci)
        except Exception,msg:
            logger.error("Could not estimate CI (original error: {}".format(str(msg)))
    feedback = dict(parameters=ppars,values=values,sigmas=sigmas,correls=correl,\
                    redchi=result.redchi,success=result.success)
    fitparams['feedback'] = feedback
    return fitparams
github lmfit / lmfit-py / asv_benchmarking / benchmarks / benchmarks.py View on Github external
np.random.seed(0)
        x = np.linspace(0.3,10,100)
        y = 1/(0.1*x)+2+0.1*np.random.randn(x.size)

        p = Parameters()
        p.add_many(('a', 0.1), ('b', 1))

        def residual(p):
            a = p['a'].value
            b = p['b'].value

            return 1/(a*x)+b-y

        minimizer = Minimizer(residual, p)
        out = minimizer.leastsq()
        return conf_interval(minimizer, out)