Files
ortools-clone/ortools/linear_solver/samples/simple_mip_program.py

80 lines
2.3 KiB
Python
Raw Normal View History

2021-04-16 00:21:07 +02:00
#!/usr/bin/env python3
2024-01-04 13:43:15 +01:00
# Copyright 2010-2024 Google LLC
2018-11-22 09:32:03 +01:00
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
2018-11-22 09:32:03 +01:00
"""Integer programming examples that show how to use the APIs."""
# [START program]
2019-05-13 10:04:00 +02:00
# [START import]
2018-11-22 09:32:03 +01:00
from ortools.linear_solver import pywraplp
2019-05-13 10:04:00 +02:00
# [END import]
2018-11-22 09:32:03 +01:00
def main():
# [START solver]
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver("SAT")
if not solver:
return
2018-11-22 09:32:03 +01:00
# [END solver]
# [START variables]
infinity = solver.infinity()
# x and y are integer non-negative variables.
x = solver.IntVar(0.0, infinity, "x")
y = solver.IntVar(0.0, infinity, "y")
2018-11-22 09:32:03 +01:00
print("Number of variables =", solver.NumVariables())
2018-11-22 09:32:03 +01:00
# [END variables]
# [START constraints]
# x + 7 * y <= 17.5.
solver.Add(x + 7 * y <= 17.5)
# x <= 3.5.
solver.Add(x <= 3.5)
print("Number of constraints =", solver.NumConstraints())
2018-11-22 09:32:03 +01:00
# [END constraints]
# [START objective]
# Maximize x + 10 * y.
solver.Maximize(x + 10 * y)
# [END objective]
# [START solve]
print(f"Solving with {solver.SolverVersion()}")
status = solver.Solve()
2018-11-22 09:32:03 +01:00
# [END solve]
# [START print_solution]
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.")
2018-11-22 09:32:03 +01:00
# [END print_solution]
# [START advanced]
print("\nAdvanced usage:")
2023-10-25 13:57:55 +02:00
print(f"Problem solved in {solver.wall_time():d} milliseconds")
print(f"Problem solved in {solver.iterations():d} iterations")
print(f"Problem solved in {solver.nodes():d} branch-and-bound nodes")
2018-11-22 09:32:03 +01:00
# [END advanced]
if __name__ == "__main__":
2018-11-22 09:32:03 +01:00
main()
# [END program]