[英]OR-Tools in python how to set power of a variable
这是一个用于优化 function 的谷歌 OR 工具示例:
from ortools.linear_solver import pywraplp
def LinearProgrammingExample():
"""Linear programming sample."""
# Instantiate a Glop solver, naming it LinearExample.
solver = pywraplp.Solver.CreateSolver('GLOP')
if not solver:
return
# Create the two variables and let them take on any non-negative value.
x = solver.NumVar(0, solver.infinity(), 'x')
y = solver.NumVar(0, solver.infinity(), 'y')
print('Number of variables =', solver.NumVariables())
# Constraint 0: x + 2y <= 14.
solver.Add(x + 2 * y <= 14.0)
# Constraint 1: 3x - y >= 0.
solver.Add(3 * x - y >= 0.0)
# Constraint 2: x - y <= 2.
solver.Add(x - y <= 2.0)
print('Number of constraints =', solver.NumConstraints())
# Objective function: 3x + 4y.
solver.Maximize(3 * x + 4 * y)
# Solve the system.
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
print('Solution:')
print('Objective value =', solver.Objective().Value())
print('x =', x.solution_value())
print('y =', y.solution_value())
else:
print('The problem does not have an optimal solution.')
print('\nAdvanced usage:')
print('Problem solved in %f milliseconds' % solver.wall_time())
print('Problem solved in %d iterations' % solver.iterations())
LinearProgrammingExample()
但我不想优化 3 x+4y,而是想优化 3 x**2+4y。 如何设置x的幂? 我尝试了 x*x、** 或 np.power,但 x 是 object。它不工作。 任何解决方案?
目前api不支持二次项。
如果您手动构建一个 protobuf,(请参阅 linear_solver.proto),您可以表达它并使用 scip 或 gurobi 解决它。
但是代码很丑。
Math_opt 是为支持它而构建的,等等。 不过暂时是c++,bezel而已。
所以你运气不好。
PS:如果你的问题是纯积分的(没有连续变量),可以用CP-SAT自己的api解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.