基于GEKKO的双Pandas Dataframe 优化问题

wz3gfoph  于 2023-01-24  发布在  其他
关注(0)|答案(1)|浏览(148)

我有两个格式相同的 Dataframe ,如下所示:
DF1

Value_0  Value_1  Value_2 ...
Date                                        
2020-11-07  7.830    19.630   30.584  ...
2020-11-08  11.100   34.693   40.589  ...
2020-11-09  12.455   34.693   41.236  ...
.
.
.

DF2

Value_0  Value_1  Value_2 ...
Date                                        
2020-11-07  153.601  61.014   55.367  ...
2020-11-08  119.011  70.560   49.052  ...
2020-11-09  133.925  103.417  61.651  ...
.
.
.

我在努力:
1.在每个连续匹配点之间进行线性插值(因此y1 = df1.Value_0,y2 = df1.Value_1,x1= df2.Value_0,x2 = df2.Value_1)。
1.考虑插值中所有可能的值,使每个日期和列对的df 1和df 2乘积最大化。
我目前的方法如下(这将在一个循环中评估每对列,然后只存储最大值的优化结果,但为了简单起见,我在这里忽略了它):

i = 0 # Example for only one use case

# Initial model
m = gekko()

# Variables         
y1 = np.array(df1['Value_'+str(i)])
y2 = np.array(df1['Value_'+str(i+1)])
x1 = np.array(df2['Value_'+str(i)])
x2 = np.array(df2['Value_'+str(i+1)])

s = [None]*len(y1)
c = [None]*len(y1)
ex = [None]*len(y1)

for j in range(len(y1)):
    s[j] = (y1[j]-y2[j])/(x1[j]-x2[j]) # slope
    c[j] = (x1[j]*y2[j] - x2[j]*y1[j])/(x1[j]-x2[j]) # y intersect
    ex[j] = -c[j]/s[j] # x intersect
    
p = m.Var(lb=0, ub=y2) # specific boundaries for case when i=0
n = m.Var(lb=x2, ub=ex) # specific boundaries for case when i=0

# Constraint
m.Equation((s[j]*n)+c[j]==p for j in range(len(y1))) # equation of a line

# Objective function
m.Maximize(n*p)

m.solve(disp=False)

#print('p:'+str(p.value))
#print('n:'+str(n.value))

这是我第一次使用Gekko,我收到“@error:不等式定义无效不等式:z〉x〈y”。如果能提供代码/变量定义的错误提示,我将不胜感激。

tvz2xvvm

tvz2xvvm1#

下限和上限必须是单个值,除非为每个数据行定义单独的变量。这是否适合替换?

p = m.Var(lb=0, ub=max(y2))
n = m.Var(lb=min(x2), ub=max(ex))

尝试使用IMODE=2定义一次公式,并将其应用于每个数据行。下面是对运行在模式2下的脚本的修改。

from gekko import gekko
import numpy as np

# Initial model
m = gekko()

# Variables
ns = 10
y1 = np.random.rand(ns)
y2 = np.random.rand(ns)+1
x1 = np.random.rand(ns)
x2 = np.random.rand(ns)+1

s = [None]*len(y1)
c = [None]*len(y1)
ex = [None]*len(y1)

for j in range(len(y1)):
    # slope
    s[j] = (y1[j]-y2[j])/(x1[j]-x2[j])
    # y-intercept
    c[j] = (x1[j]*y2[j] - x2[j]*y1[j])/(x1[j]-x2[j])
    # x-intercept
    ex[j] = -c[j]/s[j]

s = m.Param(s); c = m.Param(c)
p = m.Var(lb=0, ub=max(y2))
n = m.Var(lb=min(x2), ub=max(ex))

# Constraint
m.Equation(s*n+c==p)

m.options.IMODE=2

# Objective function
m.Maximize(n*p)

m.solve(disp=True)

如果每个插值需要单独的上限和下限,则创建变量数组,例如:

p = m.Array(m.Var,ns,lb=0)
n = m.Array(m.Var,ns)

More information on the modes of calculation在文档中显示。

相关问题