Search code examples
c#linear-programmingms-solver-foundation

Converting a string to a constraint "Term" in Solver Foundation


I'm trying to use Solver Foundation to create an application which will be able to solve Linear Programming problems. Long story short I'm stuck when trying to convert a string expression to a Microsoft.SolverFoundation.Services.Term.

What I want to do is add a string as a constraint to the Model, but first it has to be converted to a "Term".

SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();

Decision vz = new Decision(Domain.IntegerNonnegative, "barrels_venezuela");
Decision sa = new Decision(Domain.IntegerNonnegative, "barrels_saudiarabia");
Decision se = new Decision(Domain.IntegerNonnegative, "barrels_saudiarabiad");
model.AddDecisions(vz,sa,se);

string theTerm = "(20 * sa) + (15 * vz) + (3 * se)";
Term T = (Term)theTerm;
model.AddConstraint("Name_of_constraint", T);

I tried casting (as above) but to no avail.

How can I go about to pass a string as an acceptable Term to the addConstraint Function?


Solution

  • What you need to do is use the full names of the Decision:s rather than the names of the variables, and let the AddConstraint(string, string) overload do the parsing for you. Like this:

    string theTerm = "(20 * barrels_saudiarabia) + 
                      (15 * barrels_venezuela) + (3 * barrels_saudiarabiad)";
    model.AddConstraint("Name_of_constraint", theTerm);
    

    For this to work, the expression string must of course comply with the rules of the Optimization Modeling Language.