Tania Faúndez
Tania Faúndez

Reputation: 41

my own constraints Google or-tools

I'm new in CP problems and OR-Tools in Python and I want to do the follows:

# declare variables
for i in range(I):
    for k in range(K):
        x[i,k]=solver.IntVar(0,N,"x %i %i " % (i,k))

#constraints
solver.Add(CustomFunction[(x[i,k])] == 1) # only consider the values of x[i,k] evaluated in CustomFunction is equal to 1

BUT I get the error at the moment of evaluate the CustomFunction:

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

This is right because x is a IntVar.

By the otherhand, I saw in https://developers.google.com/optimization/reference/constraint_solver/constraint_solver/Solver/ that I could add a custom constraint, but I do not know how to do it in Python.

I appreciate your help :)

Upvotes: 4

Views: 1440

Answers (1)

Laurent Perron
Laurent Perron

Reputation: 11064

Unfortunately, adding new constraint is not implemented in the original CP solver. And this solver is deprecated in favor of the CP-SAT solver. The new solver does not support adding new constraints, but has a much more expressive modeling language thanks to the support of boolean constraints and enforcement literals.

See:

Anyway, this does not solve the basis of your questions. You cannot embed any arbitrary code inside a CP solver (original or CP-SAT).

One way is to pre-compute all possible assignments, and add that in a AllowedAssignment constraint.

Upvotes: 0

Related Questions