Google OR-Tools

9.15.6755 · active · verified Thu Apr 09

Google OR-Tools is an open-source, fast, and portable software suite for solving combinatorial optimization problems. It provides a comprehensive collection of solvers for linear programming, mixed-integer programming, constraint programming (CP-SAT), vehicle routing, and network flow problems. Written primarily in C++, it offers official wrappers for Python, C#, and Java. As of version 9.15.6755, the library is actively developed with frequent releases delivering new features, performance enhancements, and bug fixes across its various solvers.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to solve a simple linear programming problem using the GLOP solver via the `pywraplp` wrapper. It sets up variables, defines constraints, an objective function, and then solves and prints the results.

from ortools.linear_solver import pywraplp

def main():
    # Create the linear solver with the GLOP backend.
    solver = pywraplp.Solver.CreateSolver('GLOP')
    if not solver:
        return

    # Create the variables x and y.
    x = solver.NumVar(0, 1, 'x')
    y = solver.NumVar(0, 2, 'y')

    print('Number of variables =', solver.NumVariables())

    # Define the constraints: x + y <= 2
    solver.Add(x + y <= 2.0)

    print('Number of constraints =', solver.NumConstraints())

    # Define the objective function: Maximize 3 * x + y.
    solver.Maximize(3 * x + y)

    # Invoke the solver and display the results.
    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 statistics:')
    print('Problem solved in %f milliseconds' % solver.wall_time())
    print('Problem solved in %d iterations' % solver.iterations())

if __name__ == '__main__':
    main()

view raw JSON →