如何在目标函数python中放置一个不定的积分

发布于 2025-02-05 05:47:10 字数 772 浏览 2 评论 0原文

我有这个目标函数,我想最大程度地减少“ t”,而在此功能中,有一个从0到t的积分必须考虑到优化。但是,我不知道如何包括我的目标功能。我已经使用了小巧而易碎的库,但是它们似乎都没有用。 这是我的代码:

Cf= 100;
Cp=50;
  Eta=72.66585511711865;
  Beta=1.18609324
def R(t):
  return math.exp(-t/Eta)**Beta
def f(t):
  return (Beta/(Eta**Beta))*t**(Beta-1)*(math.exp(-t/Eta)**Beta)  
def M(t):
  return t*f(t)
import sympy as sp 
from scipy import *
import scipy.integrate
t = sp.Symbol('t') 
Mt=t*(Beta/(Eta**Beta))*t**(Beta-1)*(sp.exp(-t/Eta)**Beta);
intM=sp.integrate(Mt,t)
print(intM)
def C(t):
  return (Cp*R(t)+Cf*(1-R(t)))/(t*R(t)+ intM)
from scipy.optimize import minimize_scalar
res = minimize_scalar(C)
res

这给了我错误“ TypeError:无法确定关系的真实价值”。 在scipy.integrate.quad中,我无法将上限定义为“ t”。另一方面,当我尝试将SP.集成输出放在目标函数上时,它将无法使用。 如果您能提供帮助,我会很高兴。 谢谢。

I have this objective function that I want to minimize in regards to 't', and in this function, there is an integral from 0 to t that has to be considered for the optimization. However, I have no Idea how to include this integral to my objective function. I've used simpy and scipy library for that but none of them seems to work.
here is my code:

Cf= 100;
Cp=50;
  Eta=72.66585511711865;
  Beta=1.18609324
def R(t):
  return math.exp(-t/Eta)**Beta
def f(t):
  return (Beta/(Eta**Beta))*t**(Beta-1)*(math.exp(-t/Eta)**Beta)  
def M(t):
  return t*f(t)
import sympy as sp 
from scipy import *
import scipy.integrate
t = sp.Symbol('t') 
Mt=t*(Beta/(Eta**Beta))*t**(Beta-1)*(sp.exp(-t/Eta)**Beta);
intM=sp.integrate(Mt,t)
print(intM)
def C(t):
  return (Cp*R(t)+Cf*(1-R(t)))/(t*R(t)+ intM)
from scipy.optimize import minimize_scalar
res = minimize_scalar(C)
res

this gives me error " TypeError: cannot determine truth value of Relational" .
in scipy.integrate.quad, I can't define my upper limit as 't'. And on the other hand, it won't work when I try to put the sp.integrate output to the objective function.
I would be happy if u could help.
thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一笑百媚生 2025-02-12 05:47:10

首先,您不能在优化例程中具有不可定力的积分,因为它定义为常数。不是功能,而是一类函数。

但是看来您的一个确定的积分 - 您可以通过某些虚拟变量(例如T',从t'= 0到t'= t进行集成。所以这很好,您只需要这样做即可。

首先,让我们做出确定的积分:

intM = sp.integrate(Mt, (t, 0, t))
# second arg is variable of integration, lower bound, upper bound
# we can skip defining tprime, a mathematician would hate you for this but meh

这仍然取决于t,现在让我们将其变成数值函数:

intM_func = sp.lambdify(t, intM)
# note how you can do intM_func(3) and get a number

然后粘贴intm_func(t)而不是符号intm进入您的c最小功能,您应该很好地走:)


对我有用的完整版本:

Cf = 100
Cp = 50
Eta = 72.66585511711865
Beta = 1.18609324


def R(t):
    return math.exp(-t / Eta) ** Beta


def f(t):
    return (Beta / (Eta**Beta)) * t ** (Beta - 1) * (math.exp(-t / Eta) ** Beta)


def M(t):
    return t * f(t)


import sympy as sp
from scipy import *
import scipy.integrate

t = sp.Symbol("t")
Mt = t * (Beta / (Eta**Beta)) * t ** (Beta - 1) * (sp.exp(-t / Eta) ** Beta)
intM = sp.integrate(Mt, (t, 0, t))
intMfunc = sp.lambdify(t, intM)
print(intM)


import numpy as np
def C(t):
    if t == 0:   # dodge a division-by-zero bullet
        return np.inf
    return (Cp * R(t) + Cf * (1 - R(t))) / (t * R(t) + intMfunc(t))


from scipy.optimize import minimize_scalar

res = minimize_scalar(C)
print(res)

我得到:

     fun: 1.5407809938973502
 message: '\nOptimization terminated successfully;\nThe returned value satisfies the termination criteria\n(using xtol = 1.48e-08 )'
    nfev: 61
     nit: 28
 success: True
       x: 2964.8614509894874

作为输出。

First up, you can't have an indefinite integral within an optimization routine, as that's defined up to a constant. Not a function, but a class of functions.

But it looks like yours is a definite integral - you integrate it over some dummy variable, say, t', from t'=0 to t'=t. So that's perfectly fine, and you just have to do it.

First, let's do your definite integral:

intM = sp.integrate(Mt, (t, 0, t))
# second arg is variable of integration, lower bound, upper bound
# we can skip defining tprime, a mathematician would hate you for this but meh

This still depends on t, so now let's turn it into a numerical function:

intM_func = sp.lambdify(t, intM)
# note how you can do intM_func(3) and get a number

Then stick intM_func(t) rather than the symbolic intM into your C minimizable function and you should be good to go :)


The full version that works for me:

Cf = 100
Cp = 50
Eta = 72.66585511711865
Beta = 1.18609324


def R(t):
    return math.exp(-t / Eta) ** Beta


def f(t):
    return (Beta / (Eta**Beta)) * t ** (Beta - 1) * (math.exp(-t / Eta) ** Beta)


def M(t):
    return t * f(t)


import sympy as sp
from scipy import *
import scipy.integrate

t = sp.Symbol("t")
Mt = t * (Beta / (Eta**Beta)) * t ** (Beta - 1) * (sp.exp(-t / Eta) ** Beta)
intM = sp.integrate(Mt, (t, 0, t))
intMfunc = sp.lambdify(t, intM)
print(intM)


import numpy as np
def C(t):
    if t == 0:   # dodge a division-by-zero bullet
        return np.inf
    return (Cp * R(t) + Cf * (1 - R(t))) / (t * R(t) + intMfunc(t))


from scipy.optimize import minimize_scalar

res = minimize_scalar(C)
print(res)

And I get:

     fun: 1.5407809938973502
 message: '\nOptimization terminated successfully;\nThe returned value satisfies the termination criteria\n(using xtol = 1.48e-08 )'
    nfev: 61
     nit: 28
 success: True
       x: 2964.8614509894874

as an output.

〆凄凉。 2025-02-12 05:47:10

我很想“关闭”此问题,因为您没有给出完整的错误 - 带有追溯。但是看来您有一个答案,所以我只是尝试将错误集中在您给出的时。

error " TypeError: cannot determine truth value of Relational" . in scipy.integrate.quad

这类似于带有numpy数组的常见“歧义误差”。有些事情正在尝试执行简单的true/false操作,例如,例如。 Scipy函数可能正在测试范围值是否处于正确的顺序。或者也许在您的func中发生错误。如果没有追溯,我们就可以猜测或从以前的知识中推断出来。因此,您很幸运有人已经熟悉了这些问题。只是不要指望这一点!

要说明:

isympy会话中,请考虑一个符号:

In [35]: x

 

和一个关系:

In [36]: x>0

In [37]: type(_)
Out[37]: sympy.core.relational.StrictGreaterThan

将该关系置于`if:

In [38]: if x>0: print('yes')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <cell line: 1>()
----> 1 if x>0: print('yes')

File ~\anaconda3\lib\site-packages\sympy\core\relational.py:511, in Relational.__bool__(self)
    510 def __bool__(self):
--> 511     raise TypeError("cannot determine truth value of Relational")

TypeError: cannot determine truth value of Relational

sympy无法从一个人返回简单的true/false关系表达。

使用SympyScipy一起需要大量了解两者的工作方式。以数字函数的方式以不起作用的方式使用sympy表达式非常容易。

这是缺少的追溯:

In [59]: res = minimize_scalar(C)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [59], in <cell line: 1>()
----> 1 res = minimize_scalar(C)

File ~\anaconda3\lib\site-packages\scipy\optimize\_minimize.py:794, in minimize_scalar(fun, bracket, bounds, args, method, tol, options)
    792     return method(fun, args=args, bracket=bracket, bounds=bounds, **options)
    793 elif meth == 'brent':
--> 794     return _minimize_scalar_brent(fun, bracket, args, **options)
    795 elif meth == 'bounded':
    796     if bounds is None:

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2396, in _minimize_scalar_brent(func, brack, args, xtol, maxiter, **unknown_options)
   2393 brent = Brent(func=func, args=args, tol=tol,
   2394               full_output=True, maxiter=maxiter)
   2395 brent.set_bracket(brack)
-> 2396 brent.optimize()
   2397 x, fval, nit, nfev = brent.get_result(full_output=True)
   2399 success = nit < maxiter and not (np.isnan(x) or np.isnan(fval))

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2180, in Brent.optimize(self)
   2177 def optimize(self):
   2178     # set up for optimization
   2179     func = self.func
-> 2180     xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info()
   2181     _mintol = self._mintol
   2182     _cg = self._cg

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2154, in Brent.get_bracket_info(self)
   2151 ### BEGIN core bracket_info code ###
   2152 ### carefully DOCUMENT any CHANGES in core ##
   2153 if brack is None:
-> 2154     xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
   2155 elif len(brack) == 2:
   2156     xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
   2157                                                xb=brack[1], args=args)

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2606, in bracket(func, xa, xb, args, grow_limit, maxiter)
   2604 fa = func(*(xa,) + args)
   2605 fb = func(*(xb,) + args)
-> 2606 if (fa < fb):                      # Switch so fa > fb
   2607     xa, xb = xb, xa
   2608     fa, fb = fb, fa

File ~\anaconda3\lib\site-packages\sympy\core\relational.py:511, in Relational.__bool__(self)
    510 def __bool__(self):
--> 511     raise TypeError("cannot determine truth value of Relational")

TypeError: cannot determine truth value of Relational

因此,正如我所怀疑的那样,scipy正在尝试检查范围;

if (fa < fb):                      # Switch so fa > fb

c被给出了一个简单的标量参数会产生sympy表达式 - 具有未化为的积分。

In [57]: C(1)
Out[57]: 

intm您忘了向我们展示:

In [60]: intM
Out[60]: 

“在此处输入图像说明”

I tempted to 'close' this because you did not give the full error - with traceback. But it appears you got an answer, so I'll just try to focus the error as you gave it.

error " TypeError: cannot determine truth value of Relational" . in scipy.integrate.quad

This is similar to a common "ambiguity error" with numpy arrays. Something is trying to do a simple True/False action, such as a if. The scipy function might be testing whether the range values are in correct order. Or maybe the error occurs in your func. Without traceback we are left to guessing, or deducing from previous knowledge. So you are lucky that someone was already familiar with these issues. Just don't count on that!

To illustrate:

In an isympy session, consider a symbol:

In [35]: x

 

And a relational:

In [36]: x>0

In [37]: type(_)
Out[37]: sympy.core.relational.StrictGreaterThan

Putting that relational in an `if:

In [38]: if x>0: print('yes')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <cell line: 1>()
----> 1 if x>0: print('yes')

File ~\anaconda3\lib\site-packages\sympy\core\relational.py:511, in Relational.__bool__(self)
    510 def __bool__(self):
--> 511     raise TypeError("cannot determine truth value of Relational")

TypeError: cannot determine truth value of Relational

sympy can't return a simple True/False from a Relational expression.

Using sympy and scipy together requires considerable knowledge of how both work. It's all too easy to using sympy expressions in a numeric function in ways that don't work.

Here's the missing traceback:

In [59]: res = minimize_scalar(C)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [59], in <cell line: 1>()
----> 1 res = minimize_scalar(C)

File ~\anaconda3\lib\site-packages\scipy\optimize\_minimize.py:794, in minimize_scalar(fun, bracket, bounds, args, method, tol, options)
    792     return method(fun, args=args, bracket=bracket, bounds=bounds, **options)
    793 elif meth == 'brent':
--> 794     return _minimize_scalar_brent(fun, bracket, args, **options)
    795 elif meth == 'bounded':
    796     if bounds is None:

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2396, in _minimize_scalar_brent(func, brack, args, xtol, maxiter, **unknown_options)
   2393 brent = Brent(func=func, args=args, tol=tol,
   2394               full_output=True, maxiter=maxiter)
   2395 brent.set_bracket(brack)
-> 2396 brent.optimize()
   2397 x, fval, nit, nfev = brent.get_result(full_output=True)
   2399 success = nit < maxiter and not (np.isnan(x) or np.isnan(fval))

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2180, in Brent.optimize(self)
   2177 def optimize(self):
   2178     # set up for optimization
   2179     func = self.func
-> 2180     xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info()
   2181     _mintol = self._mintol
   2182     _cg = self._cg

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2154, in Brent.get_bracket_info(self)
   2151 ### BEGIN core bracket_info code ###
   2152 ### carefully DOCUMENT any CHANGES in core ##
   2153 if brack is None:
-> 2154     xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
   2155 elif len(brack) == 2:
   2156     xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
   2157                                                xb=brack[1], args=args)

File ~\anaconda3\lib\site-packages\scipy\optimize\optimize.py:2606, in bracket(func, xa, xb, args, grow_limit, maxiter)
   2604 fa = func(*(xa,) + args)
   2605 fb = func(*(xb,) + args)
-> 2606 if (fa < fb):                      # Switch so fa > fb
   2607     xa, xb = xb, xa
   2608     fa, fb = fb, fa

File ~\anaconda3\lib\site-packages\sympy\core\relational.py:511, in Relational.__bool__(self)
    510 def __bool__(self):
--> 511     raise TypeError("cannot determine truth value of Relational")

TypeError: cannot determine truth value of Relational

So as I suspected, scipy is trying to check ranges;

if (fa < fb):                      # Switch so fa > fb

C is given a simple scalar argument produces a sympy expression - with an unevaluated integral.

In [57]: C(1)
Out[57]: 



That intM that you forgot to show us:

In [60]: intM
Out[60]: 

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文