Creating custom constraints in google's OR-Tools CP-SAT in python

167 views Asked by At

I have just started learning about constraint programming, so excuse me if my question might be something very trivial.

The main motivation was to optimize a problem I've already solved via brute force. I'm using the CP-SAT solver in the python or tools module.

This is the description of the problem I'm facing- (please note- CP variables are the variables pertinent to the CP module)

I have 'X' CP variables. The constraints I want to impose on these variables are related to the number of differences between these X variables. For instance, I'd like to store all differences - abs(X1-X2) , abs(X3-X4), .. (where X1,X2,... are the CP Variables I initially defined) in a seperate array and then perform some calculations(eg-counting) to impose my constraint.

I've realized that this is not possible at all since involving CP_variables in array creation and normal python variables is apparently not allowed.

How exactly am I supposed to use constraint programming to solve this? Do I have no option but to condense my constraints into mathematics?

I'm sorry if this question was poorly framed, but I'm looking for insights into how I might go about solving this. It doesn't help that the documentation is too rigid for me to make sense of sometimes and there are not a lot of resources online on this.

Thank in advance.

1

There are 1 answers

0
Laurent Perron On

You need to create intermediate variables.

  x = model.NewIntVar(0, 10, 'x')
  y = model.NewIntVar(0, 10, 'y')
  diff = model.NewIntVar(-10, 10, 'diff')
  model.Add(diff == x - y)
  abs_diff = model.NewIntVar(0, 10, 'abs_diff')
  model.AddAbsEquality(abs_diff, diff)