Getting solution values using Solver Foundation Services

Please note that Solver Foundation is no longer supported.

There was a question on the Solver Foundation forum about iterating through the results in a Decision. Here’s a code sample of how to do it in two simple cases.

Decision objects are either indexed or scalar. A decision with one index set is essentially a vector, two means matrix. You supply the Sets in the Decision constructor. In the code below, x is an indexed decision. If you don’t supply any sets then you have a non-indexed scalar Decision – that’s what we’re doing with y.

Once you solve the model you can use two different methods to pull out the results. The GetValues method returns an array: one for each value in an indexed decision. In this case, we have one index set that has 10 values, so GetValues will return 10 items. Each item is an array. The first element in the array is the value for the decision for the specific index. The remaining entries are the index values themselves. By running the program below you will get the idea.

Getting the values for non-indexed decisions is easy: just call the GetDouble method.

Here’s the code:

using System;
using System.Linq;
using Microsoft.SolverFoundation.Services;

namespace DecisionTest {
  class Program {
    static void Main(string[] args) {
      SolverContext context = SolverContext.GetContext();
      Model model = context.CreateModel();
      // Let's create an indexed parameter.
      Set s = new Set(Domain.Real, "s");
      Parameter p = new Parameter(Domain.Real, "p", s);
      // Here's some dummy data.
      var input = Enumerable.Range(1, 10).Select(item => new { Id = item, Value = item });
      p.SetBinding(input, "Value", "Id");

      // Let's create an indexed decision.
      Decision x = new Decision(Domain.Real, "x", s);

      // Here's a scalar decision.
      Decision y = new Decision(Domain.Real, "y");

      // Here are some dummy constraints to tie everything together. Just for fun.
      model.AddConstraint("c1", Model.ForEach(s, i => p[i] == x[i]));
      model.AddConstraint("c2", Model.Sum(Model.ForEach(s, i => x[i])) == y);

      // Extract data from the indexed decision.
      foreach (object[] value in x.GetValues()) {
        Console.WriteLine("x[{0}] = {1}", value[1], value[0]);
      // Extract data from the scalar decision.
      Console.WriteLine("y = {0}", y.GetDouble());


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s