简体   繁体   English

OR-Tools in python 如何设置变量的幂

[英]OR-Tools in python how to set power of a variable

here is a google OR-tool example to optimize a function:这是一个用于优化 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()

but instead of optimizing 3 x+4y, I would like to optimize 3 x**2+4y.但我不想优化 3 x+4y,而是想优化 3 x**2+4y。 How to set the power of x?如何设置x的幂? I tried x*x, ** or np.power but x is an object. it is not working.我尝试了 x*x、** 或 np.power,但 x 是 object。它不工作。 any solution?任何解决方案?

The current api does not support quadratic terms.目前api不支持二次项。

If you build a protobuf manually, (see linear_solver.proto), you can express it and solve it with scip or gurobi.如果您手动构建一个 protobuf,(请参阅 linear_solver.proto),您可以表达它并使用 scip 或 gurobi 解决它。

But the code is ugly.但是代码很丑。

Math_opt is built to support it, and much more. Math_opt 是为支持它而构建的,等等。 But it is c++, bezel only at the time being.不过暂时是c++,bezel而已。

So you are out of luck.所以你运气不好。

PS: if your problem is purely integral (no continuous variables), you can solve it with CP-SAT own api. PS:如果你的问题是纯积分的(没有连续变量),可以用CP-SAT自己的api解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM