[英]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.