1
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SolverFoundation.Services;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var context= SolverContext.GetContext();
            var model = context.CreateModel();

            var index = new Set(Domain.IntegerRange(0, 6), "index");

            var x = new Decision(Domain.IntegerRange(0, 5), "x", index);
            model.AddDecision(x);

            // When I uncomment the following line, values ends
            // up with only 3 elements instead of 7 as expected

            // model.AddConstraint("constraint", x[0] + x[1] + x[2] == 2);

            model.AddGoal("objective", GoalKind.Minimize, Model.Sum(Model.ForEach(index, i => Model.Power(x[i] - 2, 2))));

            context.Solve();
            var values = x.GetValues().ToArray();
        }
    }
}

If I run this code as it is, Solver Foundation correctly calculates seven values each equal to 2.

When I uncomment model.AddConstraint("constraint", x[0] + x[1] + x[2] == 2), at the end values only contains three values: 0, 1 and 1. Why doesn't it contain the remaining values?

What's going on?

sloth
  • 99,095
  • 21
  • 171
  • 219
ehremo
  • 387
  • 2
  • 8
  • did you try to solve the same model with OML and command-line utility? – denfromufa Feb 12 '14 at 23:14
  • No I didn't. TBH I don't know how to use those tools and I don't want to invest the time learning them, when the above code should work. Thanks anyway for the tip. – ehremo Feb 13 '14 at 08:14

1 Answers1

1

When I run your sample with active constraint, it comes up with 0+1+1 as solution and omits x[3] .. x[6]. This looks like a bug. All of them should have value 2.

Add the following lines to display the results:

foreach (object[] value in values)
   {
       Console.WriteLine("x[{0}] = {1}", value[1], value[0]);
   }

Perhaps, the blog of Nathan Brixius might provide some insights.

After adding the following dummy constraint, I've got the full set of variables again:

    model.AddConstraint("constraint2", (x[3] + x[4] + x[5] + x[6]) < 999);

As an alternative, you could turn to MiniZinc and use a simple model like this:

set of int: ix = 0..6;
array[ix] of var 0..5: x;

constraint
    x[0] + x[1] + x[2] == 2;

solve minimize sum(i in ix)((x[i] - 2)*(x[i] - 2));

output 
["\nx[" ++ show(i) ++ "] = " ++ show(x[i]) | i in ix] ;
Axel Kemper
  • 10,544
  • 2
  • 31
  • 54