Python 模块可通过 R 中的 reticulate 包访问。不幸的是,它不适用于 GEKKO,这些公式并未得到认可。
当我尝试传递像 m$Equation(x1 + x2 == 7)
这样的方程时,我收到了此类错误消息:x1 + x2 中的错误:非数字参数到二元运算符
。
library(reticulate)
gekko <- reticulate::import("gekko")
m <- gekko$GEKKO(remote=TRUE)
x1 = m$Var(value=1, lb=1, ub=5)
x2 = m$Var(value=5, lb=1, ub=5)
x3 = m$Var(value=5, lb=1, ub=5)
x4 = m$Var(value=1, lb=1, ub=5)
m$Equation(x1 + x2 == 7)
m$Equation(x1 * x2 * x3 * x4 >= 25)
m$Obj(x1 * x4 * (x1 + x2 + x3) + x3)
m$solve(disp=TRUE)
我真的很想在 R 中使用 GEKKO,我们可以做一些调整来实现这一点吗?
重新发布来自 GitHub issue in Gekko repository 的问题查看是否可以在此处找到其他帮助。一个Python Gekko interface in MATLAB如果这有帮助的话,也是可能的。
% start Matlab from Anaconda prompt
close all; clear;
% Solve linear equations
% Initialize Model
m = py.gekko.GEKKO();
% Initialize Variables
x = m.Var(); % define new variable
y = m.Var(); % default=0
% Define Equations
m.Equation(3*x+2*y==1);
m.Equation(x+2*y==0);
% Solve
m.solve();
% Extract values from Python lists using curly brackets
disp(['x: ' num2str(x.VALUE{1})]);
disp(['y: ' num2str(y.VALUE{1})]);
最佳答案
一种方法是使用 py_run_string() 命令在 R 中运行 Python 代码。我使用多个字符串分解了代码来显示步骤。
Sys.setenv(RETICULATE_PYTHON = "set the path for python")
library(reticulate)
#Load the package
str1 = "
from gekko import GEKKO
m = GEKKO()"
py_run_string(str1)
#Assign values with lower and upper bound along with equations
str2 = "
x1 = m.Var(value=1, lb=1, ub=5)
x2 = m.Var(value=5, lb=1, ub=5)
x3 = m.Var(value=5, lb=1, ub=5)
x4 = m.Var(value=1, lb=1, ub=5)
m.Equation(x1 + x2 == 7)
m.Equation(x1 * x2 * x3 * x4 >= 25)
m.Obj(x1 * x4 * (x1 + x2 + x3) + x3)
m.solve(disp=True)"
py_run_string(str2)
#Print the results
str3="
print('')
print('Results')
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))
print('x4: ' + str(x4.value))
"
py_run_string(str3)
#To access an object
py$x1$VALUE
关于python - 尝试通过网状包在 R 中使用 Python Gekko 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65291603/