xcsp3team / pycsp3 Goto Github PK
View Code? Open in Web Editor NEWA Python Library for modeling combinatorial constrained problems
Home Page: https://www.pycsp.org
License: MIT License
A Python Library for modeling combinatorial constrained problems
Home Page: https://www.pycsp.org
License: MIT License
Hello !
I have a use case in which I have to solve several constraint problems but I don't know how to assign new variables without restarting the Python kernel.
Example :
for i in range(10):
x = VarArray(10, [0,1])
satisfy( blablabla)
solve()
ERROR: The identifier x is used twice. This is not possible
(add option -ev to your command if you want to see the trace of the error)
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
Thanks !
I am checking the specification of the instances in http://jobshop.jjvh.nl/instance.php?instance_id=84 and apparently, there is no correspondence between the data file that you provide and the specification of the corresponding instance. For example, I couldn't find a Job with the following durations: 86,60,10,59,65,94,71,25,98,49,43,8,90,21,73.
I am using Python 3.9.7 on MacOS 12.4 (21F79) on Apple Silicon. Trying to solve anything will result in UNKNOWN
returned by the solver. The solver log file is empty.
To reproduce, the following example from the documentation fails to work:
from pycsp3 import *
n = 4
R, G, B = colors = 0, 1, 2
# x[i] is the color of the ith node
x = VarArray(size=n, dom=colors)
print("Array x: ", x)
print("Domain of any variable: ", x[0].dom)
satisfy(
x[0] != x[2],
x[1] != x[3]
);
if solve() is SAT:
print(values(x))
satisfy(
x[0] != x[1],
x[1] == x[2],
x[2] != x[3],
x[3] == x[0]
);
if solve() is SAT:
print(values(x))
if solve(sols=ALL) is SAT:
print("Number of solutions: ", n_solutions())
print(solve())
```.
Running this results in the following output:
(base) felixbinder@Felixs-MacBook-Pro tools_block_construction_human_experiments % /Users/felixbinder/opt/anaconda3/bin/python "/Users/felixbinder/Cloud/Grad School/Fan L
ab/Block_Construction/tools_block_construction_human_experiments/stimuli/BIBD_test_main.py"
Array x: [x[0], x[1], x[2], x[3]]
Domain of any variable: 0 1 2
UNKNOWN
I've installed pycsp3 by running `sudo pip3 install pycsp3`.
Examples Auctions.py, SetCovering.py and SetPacking.py use a variable named "values" which collides with the pycsp3.values() function when including solving.
After removing any *.pyc file from the repository so that Python is forced to parse everything again, Python 3.12.4 displays some warnings about suspicious use of escape sequences in some of the regular expressions.
This is on commit 67ff862
I guess the original intention was to use Python's raw string notation?
[...]/pycsp3/classes/entities.py:313: SyntaxWarning: invalid escape sequence '\]'
indexes = [int(v) if len(v) > 0 else None for v in re.split("\]\[", suffix[1:-1])]
[...]/pycsp3/classes/main/variables.py:199: SyntaxWarning: invalid escape sequence '\]'
self.indexes = [int(v) for v in re.split("\]\[", self.suffix[1:-1])]
[...]/gitrepo/pycsp3/tools/aggregator.py:156: SyntaxWarning: invalid escape sequence '\d'
if par not in re.findall('(%\d+)', abstract_tree):
[...]/gitrepo/pycsp3/tools/aggregator.py:157: SyntaxWarning: invalid escape sequence '\d'
t = {int(m[1:]) for m in re.findall('(%\d+)', abstract_tree) if int(m[1:]) > i}
[...]/pycsp3/tools/compactor.py:17: SyntaxWarning: invalid escape sequence '\]'
self.starts = [int(v) for v in re.split("\]\[", self.suffix[1:-1])] # the indexes of the first variable (in case of an array)
[...]/pycsp3/tools/compactor.py:187: SyntaxWarning: invalid escape sequence '\]'
tokens = [int(v) if v.isdigit() else v for v in re.split("\]\[", suffix[1:-1])]
[...]/pycsp3/tools/compactor.py:222: SyntaxWarning: invalid escape sequence '\]'
part = sorted(part, key=lambda x: [int(v) for v in re.split("\]\[", x.id[x.id.index("[") + 1:-1])])
Hello,
I want to build a CSP where I don't know in advance how many variables I need. It seems like this library is using the identifier name as the variable name in the xml file. Thus, I can't figure out how to add new variables on the fly. This is my best guess so far.
from pycsp3 import Var
variables = list()
for i in range(10):
variables.append(None)
variables[i] = Var(dom=[0, 1])
However, I get the following error
self.indexes = [int(v) for v in re.split("\]\[", self.suffix[1:-1])]
ValueError: invalid literal for int() with base 10: 'i'
I know I could pre-compute the exact number of variables I require beforehand, but I would prefer to generate the variables as I require them.
Is there a way to achieve that?
Have a look at:
https://github.com/xcsp3team/pycsp3/blob/6a66bc6f78d10ec0bc195e8bad3af5f3f547260c/problems/g6_testing/TestAbscon.py#L18
I bet a call to AbsCon would be more convenient.
When calling a python file, named csp.py, the xml output filename should be csp.xml, but if you add data using -data, the xml output filename becomes csp-data.xml
Dear PyCSP3 developers,
I came across a strange XML generation behaviour regarding an intension expression of the form z == abs(x[y] - x[i]) for i in range(n)
, where x, y, z are variables and n is a constant. The generated expression in XML becomes eq(z,abs(neg(sub(aux_gb[0],%0))))
.
I did not expect to see a neg
in here.
If I swap the places places of x[y]
and x[i]
, I get eq(z,dist(aux_gb[0], %0))
, which is perfect!
My guess is that you intended that the first case also had a similar conversion.
Here is a small self-contained Python code that demonstrates the behaviour
import pycsp3
from pycsp3 import *
n = 2
m = 3
x = VarArray(size = n, dom = range(m))
y = Var(dom = range(m))
z = Var(dom = range(m))
i = Var(dom = range(n))
satisfy(
(y == abs(x[j] - x[i]) for j in range(n)),
(z == abs(x[i] - x[j]) for j in range(n))
)
On today's master (9af123e) this generates the following XML
<instance format="XCSP3" type="CSP">
<variables>
<array id="x" size="[2]"> 0..2 </array>
<var id="y"> 0..2 </var>
<var id="z"> 0..2 </var>
<var id="i"> 0 1 </var>
<array id="aux_gb" note="aux_gb[i] is the ith auxiliary variable having been automatically introduced" size="[1]"> 0..2 </array>
</variables>
<constraints>
<group>
<intension> eq(y,abs(neg(sub(aux_gb[0],%0)))) </intension>
<args> x[0] </args>
<args> x[1] </args>
</group>
<group>
<intension> eq(z,dist(aux_gb[0],%0)) </intension>
<args> x[0] </args>
<args> x[1] </args>
</group>
<element>
<list> x[0] x[1] </list>
<index> i </index>
<value> aux_gb[0] </value>
</element>
</constraints>
</instance>
To summarize, I would have expected that in the XML above, the first generated intension constraint would
neg
operationI am trying to reproduce the Warehouse Location problem shown in the docs. I am getting the title error as soon as I use the variable w
for indexing:
minimize(
# minimizing the cost of supplying stores
Sum(costs[i][w[i]] for i in range(nStores))
);
Any hints?
I think the BinPacking constraint has some problems. When I use the second variant (which requires the parameter limits) I get this error even using the basic problem of the documentation:
Model:
from pycsp3 import *
sizes = [10, 7, 3, 9, 5, 7, 8, 4, 6, 4]
nItems = len(sizes)
x = VarArray(size=10, dom={0, 1, 2})
satisfy(
BinPacking(x, sizes=sizes, limits=[23,20,21])
);
Error:
File "/Users/jlopez/PhD/RobustSolutions/ROADEF/basic_binPacking.py", line 9, in
BinPacking(x, sizes=sizes, limits=[23,20,21])
TypeError: BinPacking() got an unexpected keyword argument 'limits'
Warning: no constraints for this model!
I tried to run PyCSP3/pycsp3/problems/tests/cop_acad.py
and got the following trace (and error):
|================================================================|
Python: python3 (Python 3.7.1)
Name: BoardColoration
Data: [8,10]
Name XML: BoardColoration-8-10.xml
|================================================================|
Command: python3 ./pycsp3/problems/cop/academic/BoardColoration.py -data=[8,10]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 557, in move
os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory: 'BoardColoration-8-10.xml' -> './pycsp3/problems/tests/tmp/cop/academic/PyCSP/BoardColoration-8-10.xml'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/kyzrsoze/Sources/PyCSP3/pycsp3/problems/tests/cop_acad.py", line 25, in <module>
.add("WaterBucket", data="[8,5,3,4,4,0,8]") # optimum 7
File "/Users/kyzrsoze/Sources/PyCSP3/pycsp3/problems/tests/tester.py", line 40, in run
xcsp.load(mode=2)
File "/Users/kyzrsoze/Sources/PyCSP3/pycsp3/problems/tests/tester.py", line 218, in load
shutil.move(self.name_xml, self.xml_path_py())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 571, in move
copy_function(src, real_dst)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 257, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'BoardColoration-8-10.xml'
PyCSP stderr :
/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file './pycsp3/problems/cop/academic/BoardColoration.py': [Errno 2] No such file or directory
Process finished with exit code 1
Do you have any idea how I can fix that?
In addition, I would appreciate if I could set the solver in __init__()
of Tester
.
Thank you
Python 3.10.6 (default on Ubuntu 22.04) gives a syntax warning about the suspicious use of "is" instead of "==" in the condition on line 271 of compiler.py:
if Compilation.filename is "" and options.output is not None:
When I read the line, I also assume Compilation.filname == ""
is meant instead.
if Compilation.filename == "" and options.output is not None:
I am currently working on a Constraint Optimization Problem (COP) using the pyCSP3 library. However, I encountered an error when trying to initialize the solve() function with the options parameter. The error message in the solver log file reads:
! ERROR: limit=60s is not put at the right position
Use the solver option -ev for more details
Here's the code snippet where the error occurs:
if solve(options=["limit=60s"]) in {SAT, OPTIMUM}:
print(f"Solution: {values(x)}")
To set a time limit of 60 seconds, I used the options parameter with the value "limit=60s". However, it seems that I am not passing the argument properly to the options parameter.
Could you please provide guidance on how to rectify this error and correctly pass the time limit argument to the options parameter in the solve() function?
Thank you for your assistance!
Hi,
I have perused the documentation and source code and I couldn't find how select a heuristic for e.g variable selection. I guess it would be something like.
solve(options="varh dom/wdeg")
This obviously doesn't work, I would greatly appreciate an example. Thanks.
In Vellino sample, there are two variables and a constrains:
c = VarArray(size=nBins, dom=range(nColors))
p = VarArray(size=[nBins, nMaterials], dom=lambda i, j: range(min(maxCapacity, demands[j]) + 1))
satisfy(
# every bin with a real colour must contain something, and vice versa
[(c[i] == Unusable) == (Sum(p[i]) == 0) for i in range(nBins)],
# all components of each material are spread across all bins
[Sum(p[:, j]) == demands[j] for j in range(nMaterials)],
# the capacity of each bin is not exceeded
[Sum(p[i]) <= capacities[c[i]] for i in range(nBins)]
)
Please bear with me if this is not how one raises issues in Github. I am a new user of GitHub
I encountered a ValueError while running a program that uses the pyCSP3 library. The issue arises when using the predicate 0.5 in a particular context. Below is the traceback information for reference:
Traceback (most recent call last):
File "c:\Users\h.kumaravel\Documents\Python\Extras\CSP.py", line 103, in
minimize(Sum(x[i]-x[i-1]*0.5-x[i+1]*0.5 for i in range(1,len(x)-1)))
File "C:\Users\h.kumaravel\AppData\Local\Programs\Python\Python310\lib\site-packages\pycsp3\functions.py", line 1001, in Sum
terms = flatten(list(term)) if isinstance(term, types.GeneratorType) else flatten(term, others)
File "c:\Users\h.kumaravel\Documents\Python\Extras\CSP.py", line 103, in
minimize(Sum(x[i]-x[i-1]*0.5-x[i+1]*0.5 for i in range(1,len(x)-1)))
File "C:\Users\h.kumaravel\AppData\Local\Programs\Python\Python310\lib\site-packages\pycsp3\tools\curser.py", line 372, in mul
return Node.build(TypeNode.MUL, self, other)
File "C:\Users\h.kumaravel\AppData\Local\Programs\Python\Python310\lib\site-packages\pycsp3\classes\entities.py", line 687, in build
node = Node(type, Node._create_sons(*args))
File "C:\Users\h.kumaravel\AppData\Local\Programs\Python\Python310\lib\site-packages\pycsp3\classes\entities.py", line 669, in _create_sons
raise ValueError("Problem: bad form of predicate " + str(arg))
ValueError: Problem: bad form of predicate 0.5
Please let me know if you require any further information. Thank you!
<a href="/path/to/your/receipt.pdf" download>Download Receipt</a>
Warning: Unknown option: -f
apparait au moment de l’import/status()/}: returns the result of the last solving process (last call to \nn{solve()})
Case 3: Starred Tables
, il y a des restes de latex pas interprétéA declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.