PyCSP3
Go to the PyCSP3 home page
PyCSP3 is a Python library that allows us to write models of combinatorial constrained problems in a declarative manner. Currently, with PyCSP3, you can write models of constraint satisfaction and optimization problems. More specifically, you can build models of:
- CSP (Constraint Satisfaction Problem)
- COP (Constraint Optimization Problem)
You can find two examples of PyCSP3 models below
AllInterval problem
from pycsp3 import *
n = data
# x[i] is the ith note of the series
x = VarArray(size=n, dom=range(n))
satisfy(
# notes must occur once, and so form a permutation
AllDifferent(x),
# intervals between neighbouring notes must form a permutation
AllDifferent(abs(x[i] - x[i + 1]) for i in range(n - 1)),
# tag(symmetry-breaking)
x[0] < x[n - 1]
)
Golomb Ruler problem
from pycsp3 import *
n = data
# x[i] is the position of the ith tick
x = VarArray(size=n, dom=range(n * n))
satisfy(
# all distances are different
AllDifferent(abs(x[i] - x[j]) for i, j in combinations(range(n), 2)),
# tag(symmetry-breaking)
[x[0] == 0, Increasing(x, strict=True)]
)
minimize(
# minimizing the position of the rightmost tick
x[-1]
)
A shown in the figure below, the user who wishes to solve a combinatorial constrained problem has to:
- write a model using the Python library PyCSP3 (i.e., write a Python file)
- provide a data file (in JSON format) for a specific problem instance to be solved
- compile both files (model and data) so as to generate an XCSP3 instance (file)
- solve the XCSP3 file (problem instance under format XCSP3) by using a constraint solver as, e.g., ACE, Choco, Picat or OR-Tools (CP-SAT)
This approach has many advantages:
- Python (and Java), JSON, and XML are robust mainstream technologies
- using JSON for data permits to have a unified notation, easy to read for both humans and computers
- using Python 3 for modeling allows the user to avoid learning again a new programming language
- using a coarse-grained XML structure permits to have compact and readable problem instances. Note that using JSON instead of XML for representing instances would have been possible but has some drawbacks, as explained in an appendix of XCSP3 Specifications