Files
ortools-clone/ortools/sat/samples/assumptions_sample_sat.py

70 lines
1.9 KiB
Python
Raw 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
2021-02-04 14:21:52 +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.
2021-02-04 14:21:52 +01:00
"""Code sample that solves a model and gets the infeasibility assumptions."""
# [START program]
2021-02-15 12:26:37 +01:00
# [START import]
2021-02-04 14:21:52 +01:00
from ortools.sat.python import cp_model
2025-06-02 14:25:50 +02:00
2021-02-15 12:26:37 +01:00
# [END import]
2021-02-04 14:21:52 +01:00
2023-11-22 17:33:01 +01:00
def main() -> None:
2021-02-04 14:21:52 +01:00
"""Showcases assumptions."""
# Creates the model.
# [START model]
model = cp_model.CpModel()
# [END model]
# Creates the variables.
# [START variables]
2023-11-16 19:46:56 +01:00
x = model.new_int_var(0, 10, "x")
y = model.new_int_var(0, 10, "y")
z = model.new_int_var(0, 10, "z")
a = model.new_bool_var("a")
b = model.new_bool_var("b")
c = model.new_bool_var("c")
2021-02-04 14:21:52 +01:00
# [END variables]
# Creates the constraints.
# [START constraints]
2023-11-16 19:46:56 +01:00
model.add(x > y).only_enforce_if(a)
model.add(y > z).only_enforce_if(b)
model.add(z > x).only_enforce_if(c)
2021-02-04 14:21:52 +01:00
# [END constraints]
# Add assumptions
2023-11-16 19:46:56 +01:00
model.add_assumptions([a, b, c])
2021-02-04 14:21:52 +01:00
# Creates a solver and solves.
# [START solve]
solver = cp_model.CpSolver()
2023-11-16 19:46:56 +01:00
status = solver.solve(model)
2021-02-04 14:21:52 +01:00
# [END solve]
2021-02-15 12:26:37 +01:00
# Print solution.
# [START print_solution]
2023-11-16 19:46:56 +01:00
print(f"Status = {solver.status_name(status)}")
2023-07-31 18:12:03 +02:00
if status == cp_model.INFEASIBLE:
print(
2023-11-16 19:46:56 +01:00
"sufficient_assumptions_for_infeasibility = "
f"{solver.sufficient_assumptions_for_infeasibility()}"
2023-07-31 18:12:03 +02:00
)
2021-02-15 12:26:37 +01:00
# [END print_solution]
2021-02-04 14:21:52 +01:00
if __name__ == "__main__":
2021-02-15 12:26:37 +01:00
main()
2021-02-04 14:21:52 +01:00
# [END program]