'Implementing IF-ELSE in or-tools linear solver
as part of my code, I'm trying to get the total number of non-zero contracts that my solver is trying to solve so I can add a constraint and put a limit on it. since or-tools doesn't support if statements directly, I decided to use the .OnlyEnforceIf() solution that I found on numerous websites. this is the code I came up with:
from ortools.linear_solver import pywraplp
solver = pywraplp.Solver.CreateSolver('SCIP')
max_count = 2
symbol = ["a", "b", "c", "d"]
Weights = {sym: solver.IntVar(0.0, 1000, sym) for sym in symbols}
bools = {sym: solver.BoolVar(sym) for sym in symbols}
for sym in symbols:
solver.Add(Weights[sym] == 0).OnlyEnforceIf(bools[sym].Not())
solver.Add(Weights[sym] > 0).OnlyEnforceIf(bools[sym]) solver.Add(solver.Sum(list(bools.values())) == max_count)
I used to run a simple If-Else with z3 solver without a problem but for some reason, or-tools doesn't support it. this is the only way I found online to do this but when I run it I get the following:
File "/Volumes/GoogleDrive/My Drive/xxx/xxStrategy/eng.py", line 63, in runner solver.Add(Weights[sym] == 0).OnlyEnforceIf(bools[sym].Not())
AttributeError: 'Constraint' object has no attribute 'OnlyEnforceIf'
I can't figure out what to do here and it's getting to me! any help would be highly appreciated.
Solution 1:[1]
The API you use is only for CP-SAT.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Laurent Perron |
