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
|
2018-07-16 18:40:14 -07: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.
|
2022-06-22 17:51:14 +02:00
|
|
|
|
2018-11-16 05:02:48 -08:00
|
|
|
# [START program]
|
2021-10-18 14:24:28 +02:00
|
|
|
"""Simple solve."""
|
|
|
|
|
# [START import]
|
2018-07-16 18:40:14 -07:00
|
|
|
from ortools.sat.python import cp_model
|
2025-06-02 14:25:50 +02:00
|
|
|
|
2021-10-18 14:24:28 +02:00
|
|
|
# [END import]
|
2018-07-16 18:40:14 -07:00
|
|
|
|
|
|
|
|
|
2023-11-17 11:56:36 +01:00
|
|
|
def simple_sat_program():
|
2018-11-16 05:02:48 -08:00
|
|
|
"""Minimal CP-SAT example to showcase calling the solver."""
|
|
|
|
|
# Creates the model.
|
|
|
|
|
# [START model]
|
2018-11-11 09:39:59 +01:00
|
|
|
model = cp_model.CpModel()
|
2018-11-16 05:02:48 -08:00
|
|
|
# [END model]
|
|
|
|
|
|
|
|
|
|
# Creates the variables.
|
|
|
|
|
# [START variables]
|
|
|
|
|
num_vals = 3
|
2023-11-16 19:46:56 +01:00
|
|
|
x = model.new_int_var(0, num_vals - 1, "x")
|
|
|
|
|
y = model.new_int_var(0, num_vals - 1, "y")
|
|
|
|
|
z = model.new_int_var(0, num_vals - 1, "z")
|
2018-11-16 05:02:48 -08:00
|
|
|
# [END variables]
|
|
|
|
|
|
|
|
|
|
# Creates the constraints.
|
|
|
|
|
# [START constraints]
|
2023-11-16 19:46:56 +01:00
|
|
|
model.add(x != y)
|
2018-11-16 05:02:48 -08:00
|
|
|
# [END constraints]
|
|
|
|
|
|
|
|
|
|
# Creates a solver and solves the model.
|
|
|
|
|
# [START solve]
|
|
|
|
|
solver = cp_model.CpSolver()
|
2023-11-16 19:46:56 +01:00
|
|
|
status = solver.solve(model)
|
2018-11-16 05:02:48 -08:00
|
|
|
# [END solve]
|
|
|
|
|
|
2021-10-18 14:24:28 +02:00
|
|
|
# [START print_solution]
|
2021-10-18 15:47:31 +02:00
|
|
|
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
|
2023-11-16 19:46:56 +01:00
|
|
|
print(f"x = {solver.value(x)}")
|
|
|
|
|
print(f"y = {solver.value(y)}")
|
|
|
|
|
print(f"z = {solver.value(z)}")
|
2021-10-18 14:24:28 +02:00
|
|
|
else:
|
2023-06-30 22:49:35 +02:00
|
|
|
print("No solution found.")
|
2021-10-18 14:24:28 +02:00
|
|
|
# [END print_solution]
|
2018-07-16 18:40:14 -07:00
|
|
|
|
|
|
|
|
|
2023-11-17 11:56:36 +01:00
|
|
|
simple_sat_program()
|
2018-11-16 05:02:48 -08:00
|
|
|
# [END program]
|