当前位置: 首页>>代码示例>>Python>>正文


Python Minimizer.minimize方法代码示例

本文整理汇总了Python中lmfit.Minimizer.minimize方法的典型用法代码示例。如果您正苦于以下问题:Python Minimizer.minimize方法的具体用法?Python Minimizer.minimize怎么用?Python Minimizer.minimize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lmfit.Minimizer的用法示例。


在下文中一共展示了Minimizer.minimize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_multidimensional_fit_GH205

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
def test_multidimensional_fit_GH205():
    # test that you don't need to flatten the output from the objective
    # function. Tests regression for GH205.
    pos = np.linspace(0, 99, 100)
    xv, yv = np.meshgrid(pos, pos)
    f = lambda xv, yv, lambda1, lambda2: (np.sin(xv * lambda1)
                                             + np.cos(yv * lambda2))

    data = f(xv, yv, 0.3, 3)
    assert_(data.ndim, 2)

    def fcn2min(params, xv, yv, data):
        """ model decaying sine wave, subtract data"""
        lambda1 = params['lambda1'].value
        lambda2 = params['lambda2'].value
        model = f(xv, yv, lambda1, lambda2)
        return model - data

    # create a set of Parameters
    params = Parameters()
    params.add('lambda1', value=0.4)
    params.add('lambda2', value=3.2)

    mini = Minimizer(fcn2min, params, fcn_args=(xv, yv, data))
    res = mini.minimize()
开发者ID:DiamondLightSource,项目名称:auto_tomo_calibration-experimental,代码行数:27,代码来源:test_nose.py

示例2: test_scalar_minimize_has_no_uncertainties

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
def test_scalar_minimize_has_no_uncertainties():
    # scalar_minimize doesn't calculate uncertainties.
    # when a scalar_minimize is run the stderr and correl for each parameter
    # should be None. (stderr and correl are set to None when a Parameter is
    # initialised).
    # This requires a reset after a leastsq fit has been done.
    # Only when scalar_minimize calculates stderr and correl can this test
    # be removed.

    np.random.seed(1)
    x = np.linspace(0, 15, 301)
    data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
            np.random.normal(size=len(x), scale=0.2) )

    # define objective function: returns the array to be minimized
    def fcn2min(params, x, data):
        """ model decaying sine wave, subtract data"""
        amp = params['amp'].value
        shift = params['shift'].value
        omega = params['omega'].value
        decay = params['decay'].value

        model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
        return model - data

    # create a set of Parameters
    params = Parameters()
    params.add('amp',   value= 10,  min=0)
    params.add('decay', value= 0.1)
    params.add('shift', value= 0.0, min=-pi / 2., max=pi / 2)
    params.add('omega', value= 3.0)

    mini = Minimizer(fcn2min, params, fcn_args=(x, data))
    out = mini.minimize()
    assert_(np.isfinite(out.params['amp'].stderr))
    print(out.errorbars)
    assert_(out.errorbars == True)
    out2 = mini.minimize(method='nelder-mead')
    assert_(out2.params['amp'].stderr is None)
    assert_(out2.params['decay'].stderr is None)
    assert_(out2.params['shift'].stderr is None)
    assert_(out2.params['omega'].stderr is None)
    assert_(out2.params['amp'].correl is None)
    assert_(out2.params['decay'].correl is None)
    assert_(out2.params['shift'].correl is None)
    assert_(out2.params['omega'].correl is None)
    assert_(out2.errorbars == False)
开发者ID:DiamondLightSource,项目名称:auto_tomo_calibration-experimental,代码行数:49,代码来源:test_nose.py

示例3: fit_axis

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
def fit_axis(image_nparray2D,axis,minim_method="nelder"):
	axis_data = np.sum(pic_data,axis = 1) if (axis == 0) else np.sum(pic_data,axis = 0)
	axis_points = np.linspace(1,len(axis_data),len(axis_data))
	param_estimates = startparams_estimate(axis_data)
	params_for_fit = Parameters()
	params_for_fit.add('I_zero',value=param_estimates[0],min=0,max=np.amax(axis_data))
	params_for_fit.add('r_zero',value=param_estimates[1],min=1,max=len(axis_data))
	params_for_fit.add('omega_zero',value=param_estimates[2],min=1,max=len(axis_data))
	params_for_fit.add('backgr',value=param_estimates[3])
	fit = Minimizer(residual,params_for_fit,fcn_args=(axis_points,),\
		fcn_kws={"data":axis_data})
	fit_res = fit.minimize(minim_method)
	return (axis_points,axis_data,fit_res)
开发者ID:Oleksiy1990,项目名称:beamFitter,代码行数:15,代码来源:file1VersionMarch4Mac.py

示例4: __fit2D

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
    def __fit2D(self,minim_method="nelder",rotation=False):
        
        self.__fit_axis(0,minim_method)
        self.__fit_axis(1,minim_method)

        # we first take all the initial parameters from 1D fits
        bgr2D_est = self.axis0fitparams.valuesdict()["backgr"]/len(self.axis0pts)
        x2D_est = self.axis0fitparams.valuesdict()["r_zero"]
        omegaX2D_est = self.axis0fitparams.valuesdict()["omega_zero"]
        y2D_est = self.axis1fitparams.valuesdict()["r_zero"]
        omegaY2D_est = self.axis1fitparams.valuesdict()["omega_zero"]

        smoothened_image = gaussian_filter(self.image_array,50)
        peakheight2D_est = np.amax(smoothened_image)
        #now we need to programatically cut out the region of interest out of the
        #whole picture so that fitting takes way less time

        # NOTE! In this implementation, if the beam is small compared to picture size
        # and is very close to the edge, the fitting will fail, because the x and y
        # center position estimates will be off

        self.__format_picture(x2D_est,omegaX2D_est,y2D_est,omegaY2D_est)
        cropped_data = self.formatted_array
        xvals = np.linspace(1,cropped_data.shape[0],cropped_data.shape[0])
        yvals = np.linspace(1,cropped_data.shape[1],cropped_data.shape[1])
        x, y = np.meshgrid(yvals,xvals)
        # NOTE! there's apparently some weird convention, this has to do with
        # Cartesian vs. matrix indexing, which is explain in numpy.meshgrid manual

        estimates_2D = Parameters()
        estimates_2D.add("I_zero",value=peakheight2D_est,min=bgr2D_est)
        estimates_2D.add("x_zero",value=0.5*len(yvals),min=0,max=len(yvals)) # NOTE! weird indexing conventions
        estimates_2D.add("y_zero",value=0.5*len(xvals),min=0,max=len(xvals)) # NOTE! weird indexing conventions
        estimates_2D.add("omegaX_zero",value=omegaX2D_est)
        estimates_2D.add("omegaY_zero",value=omegaY2D_est)
        estimates_2D.add("theta_rot",value=0*np.pi,min = 0,max = np.pi) #just starting with 0
        estimates_2D.add("backgr",value=bgr2D_est)


        if rotation:
            fit2D = Minimizer(residual_G2D,estimates_2D,fcn_args=(x,y),fcn_kws={"data":cropped_data})
            print("Including rotation")
        else:
            fit2D = Minimizer(residual_G2D_norotation,estimates_2D,fcn_args=(x,y),fcn_kws={"data":cropped_data})
            print("Not including rotation")

        fit_res2D = fit2D.minimize(minim_method)

        self.x2Dgrid = x
        self.y2Dgrid = y
        self.fit2Dparams = fit_res2D.params
开发者ID:Oleksiy1990,项目名称:beamFitter,代码行数:53,代码来源:fitterroutines.py

示例5: fit

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
    def fit(self, image):
        """Fit a image of a hologram with the current attribute 
        parameters.

        Example:
        >>> p = {'x':0, 'y':0, 'z':100, 'a_p':0.5, 'n_p':1.5, 'n_m':1.337, 
        ...      'mpp':0.135, 'lamb':0.447}
        >>> mie_fit = Mie_Fitter(p)
        >>> mit_fit.result(image)
        """
        dim = image.shape
        minner = Minimizer(mie_loss, self.p, fcn_args=(image, dim))
        self.result = minner.minimize()
        return self.result
开发者ID:markhannel,项目名称:Python-Enabled-HVM-Routines,代码行数:16,代码来源:mie_fit.py

示例6: setup

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
class MinimizerClassSuite:
    """
    Benchmarks for the Minimizer class
    """
    def setup(self):
        self.x = np.linspace(1, 10, 250)
        np.random.seed(0)
        self.y = (3.0 * np.exp(-self.x / 2)
                  - 5.0 * np.exp(-(self.x - 0.1) / 10.)
                  + 0.1 * np.random.randn(len(self.x)))

        self.p = Parameters()
        self.p.add_many(('a1', 4., True, 0., 10.),
                        ('a2', 4., True, -10., 10.),
                        ('t1', 3., True, 0.01, 10.),
                        ('t2', 3., True, 0.01, 20.))

        self.p_emcee = deepcopy(self.p)
        self.p_emcee.add('noise', 0.2, True, 0.001, 1.)

        self.mini_de = Minimizer(Minimizer_Residual,
                                 self.p,
                                 fcn_args=(self.x, self.y),
                                 kws={'seed': 1,
                                      'polish': False,
                                      'maxiter': 100})

        self.mini_emcee = Minimizer(Minimizer_lnprob,
                                    self.p_emcee,
                                    fcn_args=(self.x, self.y))

    def time_differential_evolution(self):
        self.mini_de.minimize(method='differential_evolution')

    def time_emcee(self):
        self.mini_emcee.emcee(self.p_emcee, steps=100, seed=1)
开发者ID:NWUHEP,项目名称:lmfit-py,代码行数:38,代码来源:benchmarks.py

示例7: fit2D

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
def fit2D(image_nparray2D,fit_axis0=None,fit_axis1=None,minim_method="nelder"):
	if fit_axis0 is None:
		fit_axis0 = fit_axis(image_nparray2D,0,minim_method)
	if fit_axis1 is None:
		fit_axis1 = fit_axis(image_nparray2D,1,minim_method)
		
	# we first take all the initial parameters from 1D fits
	bgr2D_est = fit_axis0[2].params.valuesdict()["backgr"]/len(fit_axis1[0])
	x2D_est = fit_resultsA0[2].params.valuesdict()["r_zero"]
	omegaX2D_est = fit_axis0[2].params.valuesdict()["omega_zero"]
	y2D_est = fit_axis1[2].params.valuesdict()["r_zero"]
	omegaY2D_est = fit_axis1[2].params.valuesdict()["omega_zero"]

	smoothened_image = gaussian_filter(image_nparray2D,50)
	peakheight2D_est = np.amax(smoothened_image)
	#now we need to programatically cut out the region of interest out of the 
	#whole picture so that fitting takes way less time
		
	# NOTE! In this implementation, if the beam is small compared to picture size 
	# and is very close to the edge, the fitting will fail, because the x and y 
	# center position estimates will be off

	cropped_data = format_picture(image_nparray2D,x2D_est,omegaX2D_est,y2D_est,omegaY2D_est)
	xvals = np.linspace(1,cropped_data.shape[0],cropped_data.shape[0])
	yvals = np.linspace(1,cropped_data.shape[1],cropped_data.shape[1])
	x, y = np.meshgrid(yvals,xvals) 
	# NOTE! there's apparently some weird convention, this has to do with 
	# Cartesian vs. matrix indexing, which is explain in numpy.meshgrid manual 

	estimates_2D = Parameters()
	estimates_2D.add("I_zero",value=peakheight2D_est,min=bgr2D_est)
	estimates_2D.add("x_zero",value=0.5*len(yvals),min=0,max=len(xvals)) # NOTE! weird indexing conventions
	estimates_2D.add("y_zero",value=0.5*len(xvals),min=0,max=len(yvals)) # NOTE! weird indexing conventions
	estimates_2D.add("omegaX_zero",value=omegaX2D_est)
	estimates_2D.add("omegaY_zero",value=omegaY2D_est)
	estimates_2D.add("backgr",value=bgr2D_est)
		

	fit2D = Minimizer(residual_2D,estimates_2D,fcn_args=(x,y),fcn_kws={"data":cropped_data})
	fit_res2D = fit2D.minimize(minim_method)
	print(estimates_2D.valuesdict()["x_zero"])
	return (x,y,fit_res2D)
开发者ID:Oleksiy1990,项目名称:beamFitter,代码行数:44,代码来源:file1VersionMarch4Mac.py

示例8: fit_axis

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
def fit_axis(image_nparray2D,axis,minim_method="nelder"):
	"""
	This function fits one axis of a 2D array representing an image by doing 
	a summation along the other axis 

	fit_axis(image_nparray2D,axis,minim_method="nelder")
	"""


	axis_data = np.sum(image_nparray2D,axis = 1) if (axis == 0) else np.sum(image_nparray2D,axis = 0)
	axis_points = np.linspace(1,len(axis_data),len(axis_data))
	param_estimates = startparams_estimate(axis_data)
	params_for_fit = Parameters()
	params_for_fit.add('I_zero',value=param_estimates[0],min=0,max=np.amax(axis_data))
	params_for_fit.add('r_zero',value=param_estimates[1],min=1,max=len(axis_data))
	params_for_fit.add('omega_zero',value=param_estimates[2],min=1,max=len(axis_data))
	params_for_fit.add('backgr',value=param_estimates[3])
	fit = Minimizer(residual_G1D,params_for_fit,fcn_args=(axis_points,),\
		fcn_kws={"data":axis_data})
	fit_res = fit.minimize(minim_method)
	return (axis_points,axis_data,fit_res)
开发者ID:Oleksiy1990,项目名称:beamFitter,代码行数:23,代码来源:fitterroutines.py

示例9: minimize

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
def minimize(fcn, paramgroup, method='leastsq', args=None, kws=None,
             scale_covar=True, iter_cb=None, reduce_fcn=None, nan_polcy='omit',
             _larch=None, **fit_kws):
    """
    wrapper around lmfit minimizer for Larch
    """
    fiteval = _larch.symtable._sys.fiteval
    if isinstance(paramgroup, ParameterGroup):
        params = paramgroup.__params__
    elif isgroup(paramgroup):
        params = group2params(paramgroup, _larch=_larch)
    elif isinstance(Parameters):
        params = paramgroup
    else:
        raise ValueError('minimize takes ParamterGroup or Group as first argument')

    if args is None:
        args = ()
    if kws is None:
        kws = {}

    def _residual(params):
        params2group(params, paramgroup)
        return fcn(paramgroup, *args,  **kws)

    fitter = Minimizer(_residual, params, iter_cb=iter_cb,
                       reduce_fcn=reduce_fcn, nan_policy='omit', **fit_kws)

    result = fitter.minimize(method=method)
    params2group(result.params, paramgroup)

    out = Group(name='minimize results', fitter=fitter, fit_details=result,
                chi_square=result.chisqr, chi_reduced=result.redchi)

    for attr in ('aic', 'bic', 'covar', 'params', 'nvarys',
                 'nfree', 'ndata', 'var_names', 'nfev', 'success',
                 'errorbars', 'message', 'lmdif_message', 'residual'):
        setattr(out, attr, getattr(result, attr, None))
    return out
开发者ID:maurov,项目名称:xraylarch,代码行数:41,代码来源:__init__.py

示例10: __fit_axis

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
    def __fit_axis(self,axis,minim_method="nelder"):
        """
        This function fits one axis of a 2D array representing an image by doing
        a summation along the other axis

        fit_axis(axis,minim_method="nelder")
        """

        if axis not in [0,1]:
            sys.exit("The axis can only be 0 or 1 in fit_axis function")


        axis_data = np.sum(self.image_array,axis = 1) if (axis == 0) else np.sum(self.image_array,axis = 0)
        axis_points = np.linspace(1,len(axis_data),len(axis_data))
        param_estimates = self.__startparams_estimate(axis_data)

        # using lmfit package for fitting (based on Scipy)
        # https://lmfit.github.io/lmfit-py/
        params_for_fit = Parameters()
        params_for_fit.add('I_zero',value=param_estimates[0],min=0,max=np.amax(axis_data))
        params_for_fit.add('r_zero',value=param_estimates[1],min=1,max=len(axis_data))
        params_for_fit.add('omega_zero',value=param_estimates[2],min=1,max=len(axis_data))
        params_for_fit.add('backgr',value=param_estimates[3])
        fit = Minimizer(residual_G1D,params_for_fit,fcn_args=(axis_points,),\
            fcn_kws={"data":axis_data})
        fit_res = fit.minimize(minim_method)

        if axis == 0:
            self.axis0pts = axis_points
            self.axis0data = axis_data
            self.axis0fitparams = fit_res.params

        elif axis == 1:
            self.axis1pts = axis_points
            self.axis1data = axis_data
            self.axis1fitparams = fit_res.params
开发者ID:Oleksiy1990,项目名称:beamFitter,代码行数:38,代码来源:fitterroutines.py

示例11: CommonMinimizerTest

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
class CommonMinimizerTest(unittest.TestCase):

    def setUp(self):
        """
        test scale minimizers except newton-cg (needs jacobian) and
        anneal (doesn't work out of the box).
        """
        p_true = Parameters()
        p_true.add('amp', value=14.0)
        p_true.add('period', value=5.33)
        p_true.add('shift', value=0.123)
        p_true.add('decay', value=0.010)
        self.p_true = p_true

        n = 2500
        xmin = 0.
        xmax = 250.0
        noise = np.random.normal(scale=0.7215, size=n)
        self.x = np.linspace(xmin, xmax, n)
        self.data = self.residual(p_true, self.x) + noise

        fit_params = Parameters()
        fit_params.add('amp', value=11.0, min=5, max=20)
        fit_params.add('period', value=5., min=1., max=7)
        fit_params.add('shift', value=.10, min=0.0, max=0.2)
        fit_params.add('decay', value=6.e-3, min=0, max=0.1)
        self.fit_params = fit_params

        self.mini = Minimizer(self.residual, fit_params, [self.x, self.data])

    def residual(self, pars, x, data=None):
        amp = pars['amp']
        per = pars['period']
        shift = pars['shift']
        decay = pars['decay']

        if abs(shift) > pi/2:
            shift = shift - np.sign(shift) * pi
        model = amp*np.sin(shift + x/per) * np.exp(-x*x*decay*decay)
        if data is None:
            return model
        return model - data

    def test_diffev_bounds_check(self):
        # You need finite (min, max) for each parameter if you're using
        # differential_evolution.
        self.fit_params['decay'].min = -np.inf
        self.fit_params['decay'].vary = True
        self.minimizer = 'differential_evolution'
        pytest.raises(ValueError, self.scalar_minimizer)

        # but only if a parameter is not fixed
        self.fit_params['decay'].vary = False
        self.mini.scalar_minimize(method='differential_evolution', maxiter=1)

    def test_scalar_minimizers(self):
        # test all the scalar minimizers
        for method in SCALAR_METHODS:
            if method in ['newton', 'dogleg', 'trust-ncg', 'cg', 'trust-exact',
                          'trust-krylov', 'trust-constr']:
                continue
            self.minimizer = SCALAR_METHODS[method]
            if method == 'Nelder-Mead':
                sig = 0.2
            else:
                sig = 0.15
            self.scalar_minimizer(sig=sig)

    def scalar_minimizer(self, sig=0.15):
        out = self.mini.scalar_minimize(method=self.minimizer)

        self.residual(out.params, self.x)

        for para, true_para in zip(out.params.values(), self.p_true.values()):
            check_wo_stderr(para, true_para.value, sig=sig)

    def test_nan_policy(self):
        # check that an error is raised if there are nan in
        # the data returned by userfcn
        self.data[0] = np.nan

        major, minor, _micro = scipy_version.split('.', 2)
        for method in SCALAR_METHODS:
            if (method == 'differential_evolution' and int(major) > 0 and
                    int(minor) >= 2):
                pytest.raises(RuntimeError, self.mini.scalar_minimize,
                              SCALAR_METHODS[method])
            else:
                pytest.raises(ValueError, self.mini.scalar_minimize,
                              SCALAR_METHODS[method])

        pytest.raises(ValueError, self.mini.minimize)

        # now check that the fit proceeds if nan_policy is 'omit'
        self.mini.nan_policy = 'omit'
        res = self.mini.minimize()
        assert_equal(res.ndata, np.size(self.data, 0) - 1)

        for para, true_para in zip(res.params.values(), self.p_true.values()):
            check_wo_stderr(para, true_para.value, sig=0.15)
#.........这里部分代码省略.........
开发者ID:lmfit,项目名称:lmfit-py,代码行数:103,代码来源:test_nose.py

示例12: Parameters

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
    v = params.valuesdict()

    model = v['amp'] * np.sin(x * v['omega'] + v['shift']) * np.exp(-x*x*v['decay'])
    return model - data


# create a set of Parameters
params = Parameters()
params.add('amp', value=10, min=0)
params.add('decay', value=0.1)
params.add('shift', value=0.0, min=-np.pi/2., max=np.pi/2)
params.add('omega', value=3.0)

# 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
开发者ID:lmfit,项目名称:lmfit-py,代码行数:33,代码来源:doc_parameters_valuesdict.py

示例13: Parameters

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
    return model - data


if __name__ == '__main__':
    p = Parameters()
    p.add('a', value=0.01)
    p.add('b', value=0.01)
    p.add('c', value=0.1)
    p.add('d', value=0.01, min=-0.9999, max=0.9999)
    p.add('e', value=0.01)
    # p.add('f', value=0.010)
    x = np.linspace(0, 200, 20)
    data = np.sin(x)
    # do fit, here with leastsq model
    minner = Minimizer(residual, p, fcn_args=(x, data))
    result = minner.minimize(method='least_squares')

    # calculate final result
    final = data + result.residual

    # write error report
    report_fit(result)

    # try to plot results
    try:
        import pylab

        pylab.plot(x, data, 'k+')
        pylab.plot(x, final, 'r')
        pylab.show()
    except:
开发者ID:ilikesongdandan,项目名称:Introduction-to-Programming-Using-Python,代码行数:33,代码来源:08.py

示例14: Minimizer

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
#params.add('M', value= 0.53, min=.5,max=1.5)
#params.add('I', value= 0.002, min=.00001)
#params.add('a', value= 5.6, min=3,max=20)
#params.add('b', value= 2.10, min=.0001,max=7)
#params.add('c', value= 1.505, min=.0001,max=7)

params.add('l', value= 0.45, min=.2,max=2)
#params.add('m', value= .35, min= .2,max=1)
#params.add('M', value= 0.8, min=.5,max=1.5)
params.add('I', value= 0.0007, min=.00001)
params.add('a', value= 8.75, min=3,max=20)
params.add('b', value= 3.17, min=.0001,max=7)
params.add('c', value= 2.37, min=.0001,max=7)

minner = Minimizer(predict, params, fcn_args=(time, np.concatenate((x_dot,theta,theta_dot))))
result = minner.minimize(method='powell')
report_fit(result)

fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.set_title("Pendulum parameters fitting")
ax1.set_xlabel('Time, sec')


ax1.plot(time, x,      color='blue', label='cart position, m')
ax1.plot(time, x_dot,  color='cyan', label='cart speed, m/s')

ax1.plot(time, theta,     color='red', label='pendulum angle, rad')
ax1.plot(time, theta_dot, color='magenta', label='pendulum speed, rad/s')
开发者ID:ssloy,项目名称:tutorials,代码行数:32,代码来源:parameter_fitting.py

示例15: Fitter

# 需要导入模块: from lmfit import Minimizer [as 别名]
# 或者: from lmfit.Minimizer import minimize [as 别名]
class Fitter(PlotFit):
    u"""Wrapper for LMFIT, which is a high-level extension for
    scipy.optimize.leastsq. Performs Non-Linear Least Squares fitting using
    the Levenberg-Marquardt method.

    Parameters
    ----------
    residuals : func
        The residuals function, see description below.

    derivatives : func, optional
        Derivatives function, to compute the Jacobian of the residuals
        function with derivatives across the rows. If this is None, the
        Jacobian will be estimated.

    data : tuple, optional
        Default: None

    params0 : list, optional
        Default: None

    parinfo : list, optional
        Default: None

    ftol : float, optional
        Default: 1e-10

    xtol : float, optional
        Default: 1e-10

    epsfcn : float, optional
        Default: 2.2204460492503131e-16

    stepfactor : float, optional
        Default: 100.0

    covtol : float, optional
        Default: 1e-14

    maxiter : int, optional
        Default: 200

    maxfev : int, optional
        Default: 0

    nofinitecheck : bool, optional
        Default: False

    nan_policy : str, optional
        Default: 'omit'. Determines how NaN values are handled: 'raise',
        'propagate' or 'omit'.

    Notes
    -----
    Objects of this class are callable, returning the fitted parameters.

    **Residuals function**
    The residuals function must return an ndarray with weighted deviations
    between the model and the data. It takes two arguments, a list of the
    parameter values and a reference for the attribute :attr:`data`, a tuple
    e.g. ``(x, y, err)``. In a typical scientific problem the residuals should
    be weighted so that each deviate has a Gaussian sigma of 1.0.  If ``x``
    represents the independent variable, ``y`` represents an intensity for
    each value of ``x``, and ``err`` represents the error, then the deviates
    could be calculated as follows:

    .. math::

       d = (y - f(x)) / err

    where *f* is the model function. If *err* are 1-sigma uncertainties in
    ``y``, then

    .. math::

       \sum d^2

    is the total chi-squared.  :py:meth:`Fitter.fit` will minimize this value.
    ``x``, ``y`` and ``err`` are passed to the residuals function from
    :attr:`data`.

    Attributes
    ----------
    parinfo
    params0
    data
    ftol
    xtol
    gtol
    epsfcn
    stepfactor
    covtol
    maxiter
    maxfev
    params
    xerror
    covar
    chi2_min
    orignorm
    rchi2_min
#.........这里部分代码省略.........
开发者ID:neutronpy,项目名称:neutronpy,代码行数:103,代码来源:fitter.py


注:本文中的lmfit.Minimizer.minimize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。