text: Erwin, a modeling consultant and top Solver Foundation user, encountered some problems trying to do two-way data binding using DataTable objects. There are more details on this discussion thread. Ross, a member of the Solver Foundation team, was kind enough to code up a workaround for Erwin's example. In addition to this CS file, you will need to create a new DBML file called SampleDataContext, as I described in a previous post.
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Data;
  using System.Data.OleDb;
  using System.Data.Linq;
  using System.Text;
  using Microsoft.SolverFoundation.Services;
  using System.IO;
  namespace OML1
  {
  class Test
  {
  static void Main(string[] args)
  {
  Test t = new Test();
  t.Solve();
  }
  // Holds the OML model
  string strModel = @"Model[
  Parameters[Sets,I],
  Parameters[Reals,p[I]],
  Decisions[Reals[0,Infinity],x[I]],
  Constraints[
  Foreach[{i,I}, x[i]==p[i]]
  ]
  ]";
  // SFS
  SolverContext context;
  SampleDataContext data;
  // Constructor
  public Test()
  {
  context = SolverContext.GetContext();
  data = new SampleDataContext("Data Source=Sql_server_name;Initial Catalog=DataPartitionAllocation20_5;Integrated Security=True");
  context.DataSource = data;
  }
  // Solve the problem
  public void Solve()
  {
  context.LoadModel(FileFormat.OML, new StringReader(strModel));
  Parameter p = context.CurrentModel.Parameters.First(q => q.Name == "p");
  p.SetBinding(data.P, "value", new string[] { "index" });
  Decision x = context.CurrentModel.Decisions.First(d => d.Name == "x");
  x.SetBinding(data.X, "value", new string[] { "index" });
  Solution solution = context.Solve();
  Console.Write("{0}", solution.GetReport());
  context.PropagateDecisions();
  }
  }
  }
  GurobiDirective gurobiDirective = new GurobiDirective();
  gurobiDirective.OutputFlag = true;
  Solution solution = context.Solve(gurobiDirective);
  Optimize a model with 185 Rows, 380 Columns and 1199 NonZeroes
  Presolve removed 1 rows and 185 columns
  Presolve time: 0.30s
  Presolved: 184 Rows, 195 Columns, 832 Nonzeros
  Objective GCD is 1
  Root relaxation: objective 2.783286e+03, 36 iterations, 0.02 seconds
  Nodes | Current Node | Objective Bounds | Work
  Expl Unexpl | Obj Depth IntInf | Incumbent BestBd Gap | It/Node Time
  0 0 2783.2857 0 14 - 2783.2857 - - 0s
  0 0 3006.1964 0 29 - 3006.1964 - - 0s
  0 0 3006.1964 0 29 - 3006.1964 - - 0s
  0 0 3006.1964 0 25 - 3006.1964 - - 0s
  0 0 3006.1964 0 25 - 3006.1964 - - 0s
  H 0 0 6029.0000 3006.1964 50.1% - 0s
  0 0 3006.1964 0 25 6029.0000 3006.1964 50.1% - 0s
  H 0 2 3805.0000 3006.1964 21.0% - 0s
  0 2 3006.1964 0 25 3805.0000 3006.1964 21.0% - 0s
  * 75 54 29 3644.0000 3077.0000 15.6% 8.2 0s
  * 129 80 27 3381.0000 3077.0000 8.99% 8.7 0s
  * 158 62 30 3323.0000 3077.0000 7.40% 8.1 0s
  Cutting planes:
  Learned: 3
  Gomory: 1
  MIR: 3
  Explored 1231 nodes (5693 simplex iterations) in 0.69 seconds
  Thread count was 2 (of 2 available processors)
  Optimal solution found (tolerance 1.00e-04)
  Best objective 3.3230000000e+03, best bound 3.3230000000e+03, gap 0.0000%
  gurobiDirective.Heuristics = 0.1;
  gurobiDirective.Presolve = PresolveLevel.None;
  There is a full reference in the Gurobi Solver Programming Primer that ships with Solver Foundation. My point is that you do not get a "least common denominator" solution - you get all the bells and whistles.
  Gurobi is just one example - there are a wide range of plug-ins available, covering most of the popular LP and MIP solvers - check out solverfoundation.com for the full list. To use a plug-in solver, you need to: 1) install the solver (duh), 2) change your exe.config or web.config to point to the solver. No code changes are required. You can find additional documentation on the default MIP directives and the third-party Solver configuration in the SFS Programming Primer.
  Last thing - modern programming languages like C# are cool because they promote reusability and maintainability. Don't forget about that when you are writing SFS code. It's common for models in a particular vertical (say, finance or transportation) to have common "blocks" of goals or constraints that are re-used over and over again. It's pretty easy to build reusable model libraries using extension methods. For example, take the assignment constraints in my TSP example. I could factor them out:
  public static class ModelingExtensions {
  public static void AssignmentConstraintsNoDiag(this Model model, Set s, Decision assign) {
  model.AddConstraint("A1", Model.ForEach(s, i => Model.Sum(Model.ForEachWhere(s, j => assign[i, j], j => i != j)) == 1));
  model.AddConstraint("A2", Model.ForEach(s, j => Model.Sum(Model.ForEachWhere(s, i => assign[i, j], i => i != j)) == 1));
  }
  }
  On the Solver Foundation MSDN forum there was a question about how to read model data from a DB and use it within a Solver Foundation model. In this post I will extend my production planning sample to use LINQ to SQL. To follow along at home you will need to have a recent version of SQL Server installed locally, and some basic knowledge of how to create SQL tables. You should also have compiled and run the code from my previous post.
  Step 1: Create and populate the DB
  The first step is to create tables corresponding to the entities in my model. I created a very simple DB with three tables: Countries, Products, and Yields. The Yields table has foreign key constraints to the Countries and Products tables. Here is a diagram:
  To populate the DB I just wrote a script that inserts my problem data, and ran itin SQL Management Studio. Here's the script (and forgive my SQL):
  GO
  DELETE FROM Yields
  DELETE FROM Products
  DELETE FROM Countries
  GO
  INSERT INTO Countries (Id, Name, Limit, Cost)
  VALUES (0, 'SA', 9000, 20)
  INSERT INTO Countries (Id, Name, Limit, Cost)
  VALUES (1, 'VZ', 6000, 15)
  GO
  INSERT INTO Products (Id, Name, Demand)
  VALUES (0, 'Gas', 1900)
  INSERT INTO Products (Id, Name, Demand)
  VALUES (1, 'Jet Fuel', 1500)
  INSERT INTO Products (Id, Name, Demand)
  VALUES (2, 'Lubricant', 500)
  GO
  INSERT INTO Yields (CountryId, ProductId, Value)
  VALUES (0, 0, 0.3)
  INSERT INTO Yields (CountryId, ProductId, Value)
  VALUES (1, 0, 0.4)
  INSERT INTO Yields (CountryId, ProductId, Value)
  VALUES (0, 1, 0.4)
  INSERT INTO Yields (CountryId, ProductId, Value)
  VALUES (1, 1, 0.2)
  INSERT INTO Yields (CountryId, ProductId, Value)
  VALUES (0, 2, 0.2)
  INSERT INTO Yields (CountryId, ProductId, Value)
  VALUES (1, 2, 0.3)
  Step 2: Create Entity and DataContext classes in Visual Studio
  Scott Guthrie's blog (and the MSDN docs) show you exactly how to do this:
  Step 3: Modify Solver Foundation Services data binding code
  This is in fact very easy because Solver Foundation Services was designed to work well with LINQ. Take the PetrochemDataBinding sample from last time, and change the SetBinding statements to work with the PetrochemDataContext class instead of a hardcoded DataSet. The code is almost identical:
  private static void PetrochemLinqDataBinding() {
  SolverContext context = SolverContext.GetContext();
  context.ClearModel();
  Model model = context.CreateModel();
  PetrochemDataContext db = new PetrochemDataContext();
  Set products = new Set(Domain.Any, "products");
  Set countries = new Set(Domain.Any, "countries");
  Parameter demand = new Parameter(Domain.Real, "demand", products);
  demand.SetBinding(db.Products, "Demand", "Id");
  Parameter yield = new Parameter(Domain.Real, "yield", products, countries);
  yield.SetBinding(db.Yields, "Value", "ProductId", "CountryId");
  Parameter limit = new Parameter(Domain.Real, "limit", countries);
  limit.SetBinding(db.Countries, "Limit", "Id");
  Parameter cost = new Parameter(Domain.Real, "cost", countries);
  cost.SetBinding(db.Countries, "Cost", "Id"););
  }
  That's all there is to it! Note that instead of passing the entire collection (e.g. db.Countries) you could easily use LINQ statements or stored procedures, or whatever you like.
  Here's an example that I walked through during yesterday's INFORMS session. Erwin has two blog postings about Solver Foundation and the traveling salesman problem, but I want to throw in my two cents because I want to emphasize a couple of points:
  The traveling salesman problem is a classical problem in computer science, and you should bow your head in shame if you don't know about it (and turn in your conference badge if you happen to be in Phoenix).;
  using SolverFoundation.Plugin.Gurobi;:
  We have one parameter in our model:
  With that in mind, here's the model. Explanation of the goals and constraints follow.
  static void Main(string[] args) {));
  model.AssignmentNoDiag(city, assign);
  //..
  In this post I am going to present two complete C# programs for modeling and solving a simple production problem using Solver Foundation. In this example we have two refineries (located in Saudi Arabia and Venzuela) that produce three products: gasoline, jet fuel, and lubricant. The goal is to minimize production costs, which depend on location. There is demand for each product which must be met. Finally, each production site has a limited production capacity.
  The code for the simple case is below. Creating a model amounts to adding the goals, decisions, and constraints using the appropriate Add method. The signature for each is similar: the first argument is the name and the second argument is a term. Terms are created by combining decisions or parameters using the usual operators, or by using static methods on the Model class (as we will see in our second example). Finally, notice the call to SolverContext.Solve(). I have supplied a Directive that specifies that the Simplex solver should be used.
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Linq;
  using System.Text;
  using Microsoft.SolverFoundation.Services;
  namespace Microsoft.SolverFoundation.Samples.Petrochem {
  class Program {
  static void Main(string[] args) {
  PetrochemSimple();
  }
  private static void PetrochemSimple() {
  SolverContext context = SolverContext.GetContext();
  context.ClearModel();
  Model model = context.CreateModel();
  Decision sa = new Decision(Domain.RealRange(0, 9000), "SA");
  Decision vz = new Decision(Domain.RealRange(0, 6000), "VZ");
  model.AddDecisions(sa, vz);
  model.AddGoal("goal", GoalKind.Minimize, 20 * sa + 15 * vz);
  model.AddConstraint("demand1", 0.3 * sa + 0.4 * vz >= 1900);
  model.AddConstraint("demand2", 0.4 * sa + 0.2 * vz >= 1500);
  model.AddConstraint("demand3", 0.2 * sa + 0.3 * vz >= 500);
  Solution solution = context.Solve(new SimplexDirective());
  Report report = solution.GetReport();
  Console.WriteLine(report);
  }
  }
  Now let's reimplement the same example using data binding. Data binding is a powerful mechanism for creating large, maintainable models. Notice that in my first example, the numeric data such as the yields, the demands, and capacities were expressed directly in the terms. The first step in using Solver Foundation data binding is to lift these values into Parameters. It is often useful to create indexed parameters using Sets. In this example, there are two clearly defined Sets: the set of countries, and the set of products. In my example below I create a DataSet which contains the data for each of my parameters. (The GetData() method is just an example, it's not pretty but it is needed to complete the example.) Then I create a series of indexed parameters. For each of them I call the SetBinding method to associate the data with the parameter. In addition to the data, SetBinding also requires the caller to indicate which property specifies the values for the parameter. If the parameter is indexed, I also need to specify the parameters of the index properties. Since I am working with DataTables, these are simply column names. Notice that I could swap in any other data source that is enumerable - in particular LINQ works really well with Solver Foundation parameters.
  After the parameters are created, I define the decisions, goals, and constraints. Notice that there is only one decision - it is indexed. The Model.Sum and Model.Foreach operations allow me to define a series of constraints over one or more indexed sets in one single statement. This means that if I were to add more countries or products, my model definition would not change at all.
  private static void PetrochemDataBinding() {
  SolverContext context = SolverContext.GetContext();
  context.ClearModel();
  Model model = context.CreateModel();
  // Retrieve the problem data.
  DataSet data = GetData();
  Set products = new Set(Domain.Any, "products");
  Set countries = new Set(Domain.Any, "countries");
  Parameter demand = new Parameter(Domain.Real, "demand", products);
  demand.SetBinding(data.Tables["Demand"].AsEnumerable(), "Demand", "Product");
  Parameter yield = new Parameter(Domain.Real, "yield", products, countries);
  yield.SetBinding(data.Tables["Yield"].AsEnumerable(), "Yield", "Product", "Country");
  Parameter limit = new Parameter(Domain.Real, "limit", countries);
  limit.SetBinding(data.Tables["Limit"].AsEnumerable(), "Limit", "Country");
  Parameter cost = new Parameter(Domain.Real, "cost", countries);
  cost.SetBinding(data.Tables["Cost"].AsEnumerable(), "Cost", "Country"););
  }
  private static DataSet GetData() {
  string[] products = new string[] { "Gas", "Jet Fuel", "Lubricant" };
  string[] countries = new string[] { "SA", "VZ" };
  double[][] yield = new double[][] {
  new double[] { 0.3, 0.4 },
  new double[] { 0.4, 0.2 },
  new double[] { 0.2, 0.3 }
  };
  double[] demand = new double[] { 1900, 1500, 500 };
  double[] limit = new double[] { 9000, 6000 };
  double[] cost = new double[] { 20, 15 };
  DataSet dataSet = new DataSet();
  #region Fill DataSet
  DataTable table = new DataTable("Yield");
  dataSet.Tables.Add(table);
  table.Columns.Add("Product", typeof(string));
  table.Columns.Add("Country", typeof(string));
  table.Columns.Add("Yield", typeof(double));
  for (int p = 0; p < products.Length; p++) {
  for (int c = 0; c < countries.Length; c++) {
  DataRow row = table.NewRow();
  row[0] = products[p];
  row[1] = countries[c];
  row[2] = yield[p][c];
  table.Rows.Add(row);
  }
  }
  table = new DataTable("Demand");
  dataSet.Tables.Add(table);
  table.Columns.Add("Product", typeof(string));
  table.Columns.Add("Demand", typeof(double));
  for (int p = 0; p < products.Length; p++) {
  DataRow row = table.NewRow();
  row[0] = products[p];
  row[1] = demand[p];
  table.Rows.Add(row);
  }
  table = new DataTable("Limit");
  dataSet.Tables.Add(table);
  table.Columns.Add("Country", typeof(string));
  table.Columns.Add("Limit", typeof(double));
  for (int c = 0; c < countries.Length; c++) {
  DataRow row = table.NewRow();
  row[0] = countries[c];
  row[1] = limit[c];
  table.Rows.Add(row);
  }
  table = new DataTable("Cost");
  dataSet.Tables.Add(table);
  table.Columns.Add("Country", typeof(string));
  table.Columns.Add("Cost", typeof(double));
  for (int c = 0; c < countries.Length; c++) {
  DataRow row = table.NewRow();
  row[0] = countries[c];
  row[1] = cost[c];
  table.Rows.Add(row);
  }
  #endregion
  return dataSet;
  }
  A few of us on the Solver Foundation team will be presenting at the INFORMS Practice Conference in Phoenix, Arizona. I'm looking forward to it! We have both a workshop and a session - I will also be participating in Gurobi's session to show off its integration with Solver Foundation. Here are the details - looking forward to seeing you there.
  Technology WorkshopSunday, April 26, 9AM - 12PMMicrosoft Solver Foundation is a pure, managed code runtime for mathematical programming, modeling, and optimization. Microsoft Solver Foundation Microsoft Solver Foundation.
  Software TutorialsMonday, April 27, 9:10AM - 10:00AMSolver Foundation is a framework and managed code runtime for mathematical programming, modeling and optimization. This tutorial will focus on the technical overview of Solver Foundation, and how Third-party solver vendors, modelers and solution specialists can leverage Solver Foundation from all CLS-compliant languages and Microsoft Office.
  I am pleased to announce that Solver Foundation v1.2 is live on solverfoundation.com! Our goal in 1.2 was to make a few key improvements to address feedback that we have received from partners and customers. If you have feedback, questions, suggestions…please post it here, or on our MSDN forum. Positive or negative - that's okay. I am particularly interested in hearing how you use Solver Foundation in your application - or what features you would like to see.
  Back to 1.2:
  I.
  Two weeks back I posted two articles showing how easy it is to model critical path scheduling using Microsoft Solver Foundation. I received a few emails asking about various extensions; I will be covering those in upcoming posts. Julian just wrote a great blog post that covers the most commonly requested extension - resource constrained scheduling. If you are getting started with Solver Foundation and want to see an interesting, instructive example, I encourage you to check out his post. Two things that I really like about his OML:
  Julian mentions it in his post, but I also want to call out another great resource for learning OML. Erwin Kalvalagen has written an OML tutorial which includes several interesting examples. It's a great complement to the Excel Programming Primer that is part of the Solver Foundation documentation.
  I am going to be rolling out the rest of my branch-and-bound algorithm in the next few posts. To make that easier, in this post I introduce some common matrix, vector, and permutation methods. It turns out that for technical computing applications, C#'s extension methods (introduced in 3.0) are awesome. With vectors it's great because you retain the control of having direct array access, but you get the nice object-oriented notation.
  I've left out comments and error-checking, and it's not super-optimized, but you get the idea. None of these methods end up being the bottleneck. Most of the methods are obvious, but I do want to comment on the permutation methods. The goal of QAP is to find an optimal assignment of facilities to locations, represented as a permutation. In the course of our branch-and-bound algorithm, we'll be making partial assignments - that is, only some of the entries in the permutation will be filled in. By convention, p[i] == -1 will mean that facility i is unassigned. An index where p[i] < 0 is called "unused". When we branch, we'll want to pick an unused facility (or location), and try assigning all unused locations (or facilities) to it. The use of C#'s iterator and yield concepts really help here.
  That said, here's the code.
  public static class MatrixUtilities {
  #region Vector
  public static void ConstantFill(this T[] data, T val) {
  for (int i = 0; i < data.Length; i++) {
  data[i] = val;
  }
  }
  public static int ArgMin(this double[] data, out double best) {
  if (data.Length == 0) {
  best = Double.MinValue;
  return -1;
  }
  int iBest = 0;
  best = data[0];
  for (int i = 1; i < data.Length; i++) {
  if (best > data[i]) {
  best = data[i];
  iBest = i;
  }
  }
  return iBest;
  }
  public static int ArgMax(this double[] data, out double best) {
  if (data.Length == 0) {
  best = Double.MinValue;
  return -1;
  }
  int iBest = 0;
  best = data[0];
  for (int i = 1; i < data.Length; i++) {
  if (best < data[i]) {
  best = data[i];
  iBest = i;
  }
  }
  return iBest;
  }
  #endregion
  #region Permutation
  public static void Swap(this int[] p, int i, int j) {
  int temp = p[i];
  p[i] = p[j];
  p[j] = temp;
  }
  public static int FindUnused(this int[] data, int index) {
  foreach (int unused in data.UnusedIndices()) {
  if (index-- <= 0) {
  return unused;
  }
  }
  return -1;
  }
  public static IEnumerable UnusedIndices(this int[] data) {
  for (int i = 0; i < data.Length; i++) {
  if (data[i] < 0) {
  yield return i;
  }
  }
  }
  public static string PermutationToString(this int[] p, bool oneBased) {
  StringBuilder build = new StringBuilder(p.Length * 4);
  int width = ((int)Math.Log10(p.Length)) + 2;
  build.Append("[");
  for (int i = 0; i < p.Length; i++) {
  int index = oneBased ? p[i] + 1 : p[i];
  build.Append(index.ToString().PadLeft(width));
  }
  build.Append("]");
  return build.ToString();
  }
  #endregion
  #region Matrix
  public static string MatrixToString(this double[][] A) {
  if (A != null) {
  StringBuilder build = new StringBuilder(A.Length * A.Length * 3);
  for (int i = 0; i < A.Length; i++) {
  if (A[i] != null) {
  for (int j = 0; j < A[i].Length; j++) {
  build.AppendFormat("{0,4}", A[i][j]);
  build.Append(" ");
  }
  build.AppendLine();
  }
  }
  return build.ToString();
  }
  return null;
  }
  public static double[][] NewMatrix(int m, int n) {
  double[][] M = new double[m][];
  for (int i = 0; i < M.Length; i++) {
  M[i] = new double[n];
  }
  return M;
  }
  public static double[][] NewMatrix(int n) {
  return NewMatrix(n, n);
  }
  #endregion
  }
  This:
  The motivation and code for enumerating and branching will be the subject of the next two posts.?
  Whew - an exciting and tiring week is over. We had hundreds of employees stop by our TechFest booth to ask questions, talk about their team's optimization or modeling problems, look at our demos, or simply hear more about Solver Foundation. A big thanks to my teammates Lengning, Lucas, and Lin for doing such a great job this last week.
  OML - our declarative language for specifying optimization problems - was received with great interest. Microsoft France's experience using Solver Foundation to schedule TechDays really "worked" as an example. Even our simple quadratic programming example in Excel opened a lot of eyes. There several questions about data binding (and there have been some recent threads in our forums), so I think I'd like to devote a couple of posts to that. Lastly, I was surprised to get several inquiries into our nonlinear unconstrained optimizer - that's an area I will devote some time to that as well.
  I will be attending a couple of conferences over the next several months, but for now it's back to work on the next version of Solver Foundation.
  Another busy day - we spoke with literally hundreds of Microsoft employees about Solver Foundation at TechFest '09. Microsoft is a huge company, so we got a chance to talk to people from many different parts of the company with varying backgrounds. Some are intimately familiar with optimization, others are not. So part of the challenge is to try to "meet people where they are at" and talk about Solver Foundation in a way that makes sense for them, without trivializing it or making it sound like magic beans. If you had the opportunity to come by our booth tomorrow, you'd get a few cool demos, and a variation on the following "pitch". Depending on what you wanted to talk about we could talk more about how to model real problems, or maybe the API, or maybe some of the solvers that we're developing. Or maybe the stock market, or how it sucked to lose the Sonics. If people leave with a good idea of what we're about and can think of some situations where Solver Foundation could help, I'm happy. Anyway, here's goes:
  People and businesses need to be able to juggle different priorities and constraints to make good decisions. Examples include production planning, scheduling projects, configuring IT systems, advertising online. Microsoft Solver Foundation is a managed code platform for planning, scheduling, configuration, and optimization. Solver Foundation lets you easily describe your problem, get it solved, and connect it to your application.
  It has three main layers: • Modeling and Programming: the modeler lets you describe optimization problems declaratively: "what", not "how". You can do it in code, or in our Excel add-in. • Solver Foundation Services: a full-featured .Net library that can be accessed from Visual Studio, C#, VB, ASP.Net, Silverlight. It transparently handles parallelism & multiple cores. It provides a rich object model, events, and data binding. • Solvers: we provide a bunch of solvers that cover a wide range of optimization problems including: LP, QP, constraint, MIP, nonlinear unconstrained. We feature an open, extensible architecture that lets plug-in third party solvers if you so choose.
  Solver Foundation is developed in conjunction with researchers in Redmond and Cambridge, and is a great example of Microsoft Research innovation. We recently released our 1.1 version and you can check out solverfoundation.com to download our free Express version!