Python lmfit约束:< b< C [英] Python lmfit constraints: a < b < c

查看:102
本文介绍了Python lmfit约束:< b< C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中使用 lmfit 来拟合一些数据,其中包括拟合变量a,b和c。我需要确保< b< C。我发现 http://cars9.uchicago.edu/software/python/lmfit_MinimizerResult/ Constraints.html 讨论需要将约束定义为不等式并设置虚拟变量。例如,如果我想要a + b< = 10,我可以这样做:

I am using lmfit in Python to fit some data, which includes fitting the variables a, b, and c. I need to ensure that a < b < c. I found http://cars9.uchicago.edu/software/python/lmfit_MinimizerResult/constraints.html which talks about constraints needing to be defined as inequalities and setting up dummy variables. For example, if I wanted a + b <= 10, I could do:

pars.add('a',     value = 5, vary=True)
pars.add('delta', value = 5, max=10, vary=True)
pars.add('b',     expr='delta-a')

这将确保a + b< = 10。

And this would ensure that a + b <= 10.

我想我需要c-b> 0和b-a> 0(或者a-b <0和b-c <0),但是我不确定

I suppose that I would need c - b > 0 and b - a > 0 (or alternatively a - b < 0 and b - c < 0), but I'm not sure how to code this.

推荐答案

遵循您链接到的文档的提示,的不等式约束x> y 应该翻译为 x = y + something 其中 something 具有下限0。

Following the hint from the doc you link to, an inequality constraint of x > y should be translated to x = y + something where something has a lower bound of 0.

因此,两次应用该方法,我认为这应该可以满足您的要求:

So, applying that approach twice, I think this should do what you want:

from lmfit import Parameters
params = Parameters()
params.add('a', value=5, vary=True)
params.add('b_minus_a', value=1,  vary=True, min=0)
params.add('c_minus_b', value=1,  vary=True, min=0)
params.add('b', expr='a + b_minus_a')
params.add('c', expr='b + c_minus_b')

仍然使用三个变量( a b_minus_a c_minus_b )并施加不等式约束,但需要注意的是,差异实际上可能为0。使用浮点数通常就足够了,但是根据变量的大小,您可以将0更改为类似 1.e-12

That still uses three variables (a, b_minus_a, and c_minus_b) and imposes the inequality constraints, with the caveat the differences could actually be 0. With floating point numbers, that's usually sufficient, but depending on the scale of the variables, you could change 0 to something like 1.e-12.

这篇关于Python lmfit约束:&lt; b&lt; C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆