Search code examples
c#ms-solver-foundation

How to use If operator in MS Solver Foundation?


What's wrong with this code?:

SolverContext sc = SolverContext.GetContext();
Model m = sc.CreateModel();

m.AddDecision(new Decision(Domain.IntegerNonnegative, "a"));
m.AddDecision(new Decision(Domain.IntegerNonnegative, "b"));

m.AddConstraint(null, "a < 2");
m.AddConstraint(null, "b == If[a == 2, 2, 1]");

var sol = sc.Solve();
Console.WriteLine(sol.GetReport());

The solver freezes and doesn't give any result. I'm playing with the If operator trying to see how it works but doesn't seem to do what I expect. Not sure I'm using it the right way (I'm trying to say, if a equals 2 then b must equal 2, otherwise 1).

I also tried

m.AddConstraint(null, "If[a == 2, b == 2, b == 1]");

with the same result.


Solution

  • It seems like the solver that is applied to this problem is hampered by the extent of the Decision domain. If you limit the domain to for example the integer range [0, 10]:

    m.AddDecision(new Decision(Domain.IntegerRange(0, 10), "a"));
    m.AddDecision(new Decision(Domain.IntegerRange(0, 10), "b"));
    

    a feasible solution to the problem is generated fairly quickly. In other words, the constraint b == If[a == 2, 2, 1] is perfectly valid.

    BTW, it is a little odd that you in the first constraint require that a < 2, and in the second constraint test the condition a == 2. But I assume you are in an experimentation phase right now...