xcsp3team / pycsp3

A Python Library for modeling combinatorial constrained problems
https://www.pycsp.org
MIT License
60 stars 9 forks source link

Unknown number of variables #24

Closed maxtremblay closed 1 year ago

maxtremblay commented 2 years ago

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?

xcsp3team commented 2 years ago

It is possible to manage variables on the fly in certain cases for 1-dimensional array now. You need the last commited version (for the Pypi version, you need to wait for the next published version ; planned to be next week).

As an example, the following code is working. x is an array with holes (this is visible when you observe the result of AllDifferent). I don't know if it is a sufficient answer for all the cases you may need to address.

from pycsp3 import *

y = VarArray(size=10, dom=lambda i: {0, 1})

t = list()
for i in range(10):
    if i % 2 == 0:
        t.append(None)
    else:
        t.append(Var(range(10)))

# array x
x = VarArray(t)

satisfy(
    AllDifferent(x)
)
maxtremblay commented 2 years ago

Ok, thanks for the answer. I don't think it covers what I want to achieve. For future version, maybe it would be nice to have the possibility to use an argument in Var and VarArray to set names of variables.

xcsp3team commented 1 year ago

Hi,

In the last version of the code, you can do that. This is not documented yet. Here are a few examples:

from pycsp3 import *

x = Var(range(10))
y = Var(dom=range(5), id="yy_12")
Var(dom=range(10), id="z")

d = dict()
a = 1
d[0] = Var(0, 1, id="d_0")
d[a] = Var(0, 1, id="d_1")

satisfy(
    x >= 3,
    var("x") <= 6,
    y > 2,
    var("yy_12") < 4,
    var("z") != 4,
    d[0] + d[1] != 0,
    var("d_0") + var("d_1") != 2
)
from pycsp3 import *

x = VarArray(size=3, dom={0, 1})
y = VarArray(size=3, dom={0, 1}, id="yy")
VarArray(size=3, dom={0, 1}, id="zz")

d = dict()
a = 1
d[0] = VarArray(size=3, dom={0, 1}, id="d0")
d[a] = VarArray(size=3, dom={0, 1}, id="d_a")

satisfy(
    Sum(x) == 1,
    Sum(y) > 0,
    Sum(var("yy")) < 2,
    Sum(var("zz")) < 2,
    Sum(d[0] + d[a]) > 0,
    Sum(var("d0") + var("d_a")) < 2,
    var("d_a")[1] == 1
)
xcsp3team commented 1 year ago

This will be visible in the documentation very soon. Indeed, Version 2.1 will be published in November 2022.