Search code examples
pythonor-toolsvehicle-routing

Adding Disjunctive constraints in google ortools


I'm trying to add an optional vehicle meeting state in google-ortools.

I am trying to ensure that vehicle 1 can only go to the meeting node if vehicle 2 also visits the meeting node.

The below code compiles, but it does not prevent the first vehicle one from visiting first_vehicle_meet, while second_vehicle_meet being visited by vehicle -1

routing.AddDisjunction([first_vehicle_meet], 0)
routing.AddDisjunction([second_vehicle_meet], 0)

routing.solver().Add(((routing.VehicleVar(first_vehicle_meet) == -1) and (routing.VehicleVar(first_vehicle_meet) == -1))
                     or ((routing.VehicleVar(first_vehicle_meet) != -1) and (routing.VehicleVar(first_vehicle_meet) != -1)))

I have also tried this code, but it gives an error


routing.AddDisjunction([first_vehicle_meet], 0)
routing.AddDisjunction([second_vehicle_meet], 0)

routing.solver().Add(((routing.VehicleVar(first_vehicle_meet) == -1) & (routing.VehicleVar(first_vehicle_meet) == -1))
                     | ((routing.VehicleVar(first_vehicle_meet) != -1) & (routing.VehicleVar(first_vehicle_meet) != -1)))

As does the below.

routing.AddDisjunction([second_vehicle_meet], 0)

routing.solver().Add((routing.VehicleVar(first_vehicle_meet) == -1)\
                     .OnlyEnforceIf(routing.VehicleVar(second_vehicle_meet) == -1))
routing.solver().Add((routing.VehicleVar(second_vehicle_meet) == -1)\
                     .OnlyEnforceIf(routing.VehicleVar(first_vehicle_meet) == -1))

Does anybody know the appropriate code/syntax to add the or operator to one of my constraints?


Solution

  • In the routing library, it you want to add (x == 2) || (y == 3)

    First query the solver

      solver = routing.solver()
    

    Then create one Boolean variable per equality

      x2 = solver.IsEqualCstVar(x, 2)  # You can use x2 == (x == 2).Var()
      y3 = solver.IsEqualCstVar(y, 3)
    

    Then add the disjunction

      solver.Add(x2 + y3 >= 1)
    

    The key is to use linear formulas on Boolean variables to encode OR/AND.