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

80 lines
2.2 KiB
Python
Raw Permalink Normal View History

2021-04-16 00:21:07 +02:00
#!/usr/bin/env python3
2025-01-10 11:35:44 +01:00
# Copyright 2010-2025 Google LLC
# 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.
"""Minimal example to call the GLOP solver."""
# [START program]
# [START import]
from ortools.linear_solver import pywraplp
# [END import]
def main():
# [START solver]
2018-11-22 09:29:22 +01:00
# Create the linear solver with the GLOP backend.
solver = pywraplp.Solver.CreateSolver("GLOP")
if not solver:
return
# [END solver]
2018-11-22 09:29:22 +01:00
# [START variables]
2020-12-07 14:57:58 +01:00
infinity = solver.infinity()
2018-11-22 09:29:22 +01:00
# Create the variables x and y.
x = solver.NumVar(0.0, infinity, "x")
y = solver.NumVar(0.0, infinity, "y")
2018-11-22 09:29:22 +01:00
print("Number of variables =", solver.NumVariables())
# [END variables]
# [START constraints]
2020-12-07 14:57:58 +01:00
# x + 7 * y <= 17.5.
solver.Add(x + 7 * y <= 17.5)
# x <= 3.5.
solver.Add(x <= 3.5)
2018-11-22 09:29:22 +01:00
print("Number of constraints =", solver.NumConstraints())
# [END constraints]
# [START objective]
2020-12-07 14:57:58 +01:00
# Maximize x + 10 * y.
solver.Maximize(x + 10 * y)
# [END objective]
2018-11-22 09:29:22 +01:00
# [START solve]
print(f"Solving with {solver.SolverVersion()}")
2020-12-07 14:57:58 +01:00
status = solver.Solve()
# [END solve]
# [START print_solution]
2020-12-07 14:57:58 +01:00
if status == pywraplp.Solver.OPTIMAL:
print("Solution:")
print("Objective value =", solver.Objective().Value())
print("x =", x.solution_value())
print("y =", y.solution_value())
2020-12-07 14:57:58 +01:00
else:
print("The problem does not have an optimal solution.")
# [END print_solution]
2020-12-07 14:57:58 +01:00
# [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")
2020-12-07 14:57:58 +01:00
# [END advanced]
if __name__ == "__main__":
2018-11-22 09:29:22 +01:00
main()
# [END program]