/// <summary> /// Takes the decision domain as a parameter and builds LP/MIP model /// depending on the domain /// </summary> /// <param name="domain"></param> /// <returns></returns> private Model BuildMasterModel(Domain domain) { _context.ClearModel(); Model masterModel = _context.CreateModel(); //Creating the sets Set setPattern = new Set(domain: Domain.IntegerNonnegative, name: "Pattern"); //parameter for demanded sizes Parameter paramDemands = new Parameter(domain: Domain.IntegerNonnegative, name: "ParamDemands", indexSets: _setRoll); paramDemands.SetBinding(binding: _demands, valueField: "Demand", indexFields: "Width"); //parameter for number that each pattern must be applied to get all sizes and their demanded quantityv Parameter paramPatternRolls = new Parameter(domain: Domain.IntegerNonnegative, name: "paramPatternRolls", indexSets: new Set[] { setPattern, _setRoll }); paramPatternRolls.SetBinding(binding: _patternRolls, valueField: "Count", indexFields: new string[] { "PatternID", "Width" }); //Add both parameters to model masterModel.AddParameters(paramDemands, paramPatternRolls); //Decision: Created, bind data and add to the model //This is where the solver will place values (how many times to cut each pattern) Decision decisionPatternCounts = new Decision(domain: domain, name: "PatternCounts", indexSets: setPattern); decisionPatternCounts.SetBinding(binding: _patterns, valueField: "Count", indexFields: "PatternID"); masterModel.AddDecision(decision: decisionPatternCounts); //Adding the demand constraint masterModel.AddConstraint(_demandConstraintName, Model.ForEach ( _setRoll, roll => //from _setRoll, run for each roll //sum of (pattern items for given roll) * (pattern count) >= (demandf for size) Model.Sum ( Model.ForEach ( setPattern, pattern => //from setPattern, run for each pattern decisionPatternCounts[pattern] * paramPatternRolls[pattern, roll] ) ) >= paramDemands[roll] )); //Minize the total cuts masterModel.AddGoal("TotalRolls", GoalKind.Minimize, Model.Sum(Model.ForEach(setPattern, pattern => decisionPatternCounts[pattern]))); return(masterModel); }
private void TestService2(Directive directive) { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Decision x1 = new Decision(Domain.RealNonnegative, "x1"); Decision x2 = new Decision(Domain.RealNonnegative, "x2"); Decision z = new Decision(Domain.IntegerRange(0, 1), "z"); Rational M = 100; model.AddDecisions(x1, x2, z); model.AddConstraint("Row0", x1 + x2 >= 1); model.AddConstraint("Row1", x1 - z * 100 <= 0); model.AddConstraint("Row2", x2 + z * 100 <= 100); Goal goal = model.AddGoal("Goal0", GoalKind.Maximize, x1 + x2); Solution solution = context.Solve(directive); Assert.IsTrue(goal.ToInt32() == 100); context.ClearModel(); }
//Voorbeeld LP uit de opgave void Initialize() { //Introduceer de keuzes SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Decision aardappel = new Decision(Domain.RealNonnegative, "ingredient_aardappel"); Decision vlees = new Decision(Domain.RealNonnegative, "ingredient_vlees"); Decision groente = new Decision(Domain.RealNonnegative, "ingredient_groente"); model.AddDecisions(aardappel, vlees, groente); //Constraints toevoegen model.AddConstraint("calorie", 800 * aardappel + 1000 * vlees + 5 * groente == 600); model.AddConstraints("prot_vit", 150 <= 5 * aardappel + 500 * vlees <= 250, 10 * aardappel + 100 * groente >= 200); //Introduceer doelstelling model.AddGoal("prijs", GoalKind.Minimize, 5 * aardappel + 20 * vlees + 7 * groente); //Roep solver aan Solution solution = context.Solve(new SimplexDirective()); Report report = solution.GetReport(); Console.Write(report); }
private SolverContext CreateSolver(double earningsCap = 0) { SolverContext context = new SolverContext(); Model model = context.CreateModel(); Set movieSet = new Set(Domain.Any, "movies"); Decision numberOfScreensToPlayMovieOn = new Decision(Domain.IntegerNonnegative, "numberOfScreensToPlayMovieOn", movieSet); model.AddDecision(numberOfScreensToPlayMovieOn); Parameter estimatedEarnings = new Parameter(Domain.RealNonnegative, "EstimatedBoxOfficeRevenue", movieSet); estimatedEarnings.SetBinding(_movies, "EarningsAsDouble", "Name"); Parameter fmlBux = new Parameter(Domain.IntegerNonnegative, "FmlBux", movieSet); fmlBux.SetBinding(_movies, "CostAsDouble", "Name"); model.AddParameters(estimatedEarnings, fmlBux); // constraints: 2 // 1: number of screens <= AvailableScreens // 2: available money to spend <= AvailableFmlBux model.AddConstraint("cinePlexScreensConstraint", Model.Sum(Model.ForEach(movieSet, term => numberOfScreensToPlayMovieOn[term])) <= AvailableScreens); model.AddConstraint("cinePlexFmlBuxConstraint", Model.Sum(Model.ForEach(movieSet, term => numberOfScreensToPlayMovieOn[term] * fmlBux[term])) <= AvailableFmlBux); // goal: maximize earnings. // earnings = selectedMovies.Sum(Estimated Earnings) - ((AvailableScreens - selectedMovies.Count) * Penalty) var revenueTerm = Model.Sum(Model.ForEach(movieSet, t => numberOfScreensToPlayMovieOn[t] * estimatedEarnings[t])); var penaltyTerm = Model.Product(-(double)PenaltyForUnusedScreens , Model.Difference(8, Model.Sum(Model.ForEach(movieSet, t => numberOfScreensToPlayMovieOn[t])))); model.AddGoal("cinePlexMaximizeRevenueMinimizeUnusedScreens", GoalKind.Maximize, Model.Sum(revenueTerm, penaltyTerm)); return(context); }
public void SolverLinear() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Decision vz = new Decision(Domain.RealNonnegative, "barrels_venezuela"); Decision sa = new Decision(Domain.RealNonnegative, "barrels_saudiarabia"); model.AddDecisions(vz, sa); model.AddConstraints("limits", 0 <= vz <= 9000, 0 <= sa <= 6000); model.AddConstraints("production", 0.3 * sa + 0.4 * vz >= 2000, 0.4 * sa + 0.2 * vz >= 1500, 0.2 * sa + 0.3 * vz >= 500); model.AddGoal("cost", GoalKind.Minimize, 20 * sa + 15 * vz); Solution solution = context.Solve(new SimplexDirective()); Report report = solution.GetReport(); Console.WriteLine("vz: {0}, sa: {1}", vz, sa); Console.Write("{0}", report); Assert.AreEqual("3500", vz.ToString()); Assert.AreEqual("2000", sa.ToString()); }
public void OptMethod1() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); //decisions Decision xs = new Decision(Domain.Real, "Number_of_small_chess_boards"); Decision xl = new Decision(Domain.Real, "Number_of_large_chess_boards"); model.AddDecisions(xs, xl); //constraints model.AddConstraints("limits", 0 <= xs, 0 <= xl); model.AddConstraint("BoxWood", 1 * xs + 3 * xl <= 200); model.AddConstraint("Lathe", 3 * xs + 2 * xl <= 160); //Goals model.AddGoal("Profit", GoalKind.Maximize, 5 * xs + 20 * xl); // This doesn't work! // model.AddGoal("Profit", GoalKind.Maximize, objfunc(xs, xl)); Solution sol = context.Solve(new SimplexDirective()); Report report = sol.GetReport(); Console.WriteLine(report); }
public void SolverSingleChannel() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Domain domain = Domain.Enum("CreateItem", "ConnectItem", "DeleteItem"); Decision channel = new Decision(domain, "channel"); model.AddDecision(channel); Parameter p = new Parameter(Domain.Integer, "p"); model.AddParameter(p); p.SetBinding(3); model.AddConstraint("constraint", channel == "CreateItem" & p == 3 ); Solution solution = context.Solve(new SimplexDirective()); Report report = solution.GetReport(); Console.WriteLine("channel: {0}", channel); Console.Write("{0}", report); Assert.AreEqual("CreateItem", channel.GetString()); }
public void OptMethod2() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); //decisions Decision x1 = new Decision(Domain.RealNonnegative, "dis_boyanin_gunluk_uretim_miktari"); Decision x2 = new Decision(Domain.RealNonnegative, "ic_boyanin_gunluk_uretim_miktari"); model.AddDecisions(x1, x2); //Goals model.AddGoal("Profit", GoalKind.Maximize, 5 * x2 + 4 * x2); //constraints model.AddConstraint("M1_Hammaddesi", 6 * x1 + 4 * x2 <= 24); model.AddConstraint("M2_Hammaddesi", x1 + 2 * x2 <= 6); model.AddConstraint("ic_boya_gun_fazlasi", -x1 + x2 <= 1); model.AddConstraint("ic_boya_en_çok", x2 <= 2); // This doesn't work! // model.AddGoal("Profit", GoalKind.Maximize, objfunc(xs, xl)); Solution sol = context.Solve(new SimplexDirective()); Report report = sol.GetReport(); Console.WriteLine(report); }
public void SolverEnum() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Domain colors = Domain.Enum("red", "green", "blue", "yellow"); Decision be = new Decision(colors, "belgium"); Decision de = new Decision(colors, "germany"); Decision fr = new Decision(colors, "france"); Decision nl = new Decision(colors, "netherlands"); model.AddDecisions(be, de, fr, nl); model.AddConstraints("borders", be != de, be != fr, be != nl, de != fr, de != nl); DecisionBinding bindBe = be.CreateBinding(); DecisionBinding bindDe = de.CreateBinding(); DecisionBinding bindFr = fr.CreateBinding(); DecisionBinding bindNl = nl.CreateBinding(); DecisionBinding[] bindings = new DecisionBinding[] { bindBe, bindDe, bindFr, bindNl }; bindBe.Fix("red"); bindDe.Fix("blue"); context.FindAllowedValues(bindings); string[] valuesFr = bindFr.StringFeasibleValues.ToArray(); Console.WriteLine("France: \t{0}", string.Join(", ", valuesFr)); string[] valuesNl = bindNl.StringFeasibleValues.ToArray(); Console.WriteLine("Netherlands: \t{0}", string.Join(", ", valuesNl)); }
public IActionResult Index() { ////////////////// Поиск решений SolverContext problem = SolverContext.GetContext(); Model model = problem.CreateModel(); Decision[] component = new Decision[3]; //// Модель component[0] = new Decision(Domain.RealRange(0, 9), $"Num1"); component[1] = new Decision(Domain.RealRange(0, 9), $"Num2"); component[2] = new Decision(Domain.RealRange(0, 9), $"Num3"); // связываем модель model.AddDecisions(component); // Ограничения model.AddConstraint($"Usl1", component[0] == 3); model.AddConstraint($"Usl2", component[1] == 0.5); model.AddConstraint($"Summ5", (component[0] + component[1] * component[2]) == 5); // Расчет Solution solution = problem.Solve(); //////////////////// Конец поиска решений // Сделать, что бы, если колличество требуемых стлбоцов 7, то автоматически заполняем предсгенерироваными данными // Начало теста InputValues inputValues = new InputValues(); inputValues.ComponentInputValues = new List <ComponentInputValue>(); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Чугун литейный", PercentSi = 1.26, PercentMn = 0.68, Cost = 75.5, MinPercent = 24, MaxPercent = 50 }); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Чугун передельный", PercentSi = 1.08, PercentMn = 0.26, Cost = 60, MinPercent = 24, MaxPercent = 50 }); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Чугун зеркальный", PercentSi = 1.64, PercentMn = 1.57, Cost = 97, MinPercent = 0, MaxPercent = 100 }); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Лом чугунный", PercentSi = 1.5, PercentMn = 0.7, Cost = 36.2, MinPercent = 0, MaxPercent = 100 }); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Лом стальной", PercentSi = 0.5, PercentMn = 0.5, Cost = 34.3, MinPercent = 8, MaxPercent = 12 }); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Возврат", PercentSi = 0.4, PercentMn = 0.65, Cost = 36.2, MinPercent = 20, MaxPercent = 40 }); inputValues.ComponentInputValues.Add(new ComponentInputValue() { Name = "Ферросилиций 45%", PercentSi = 52.02, PercentMn = 0.44, Cost = 120, MinPercent = 0, MaxPercent = 100 }); //Конец теста return(View(inputValues)); }
public void SolverMultiChannel() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Domain domain = Domain.Enum("CreateItem", "ConnectItem", "DeleteItem"); Decision channel = new Decision(domain, "channel"); model.AddDecision(channel); model.AddConstraint("constraint", channel == "CreateItem" | channel == "ConnectItem" ); // Find all possible values. DecisionBinding binding = channel.CreateBinding(); DecisionBinding[] bindings = new DecisionBinding[] { binding }; context.FindAllowedValues(bindings); string[] values = binding.StringFeasibleValues.ToArray(); Console.WriteLine("channel: {0}", string.Join(", ", values)); CollectionAssert.AreEqual(new List <string>() { "CreateItem", "ConnectItem" }, values); }
public static IList <Tuple <Ore, int> > MiningPlanToEarnSpecifiedGoldAndGems(double hpc, double goldNeeded, double gemsNeeded) { IList <Ore> localOreList = BuildFeasibleOreList(hpc); SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Set items = new Set(Domain.Any, "items"); Decision mine = new Decision(Domain.IntegerNonnegative, "mine", items); model.AddDecision(mine); Parameter value = new Parameter(Domain.RealNonnegative, "value", items); value.SetBinding(localOreList, "Value", "Name"); Parameter clicks = new Parameter(Domain.IntegerNonnegative, "clicks", items); clicks.SetBinding(localOreList, "Clicks", "Name"); model.AddParameters(value, clicks); model.AddConstraint("knap_value", Model.Sum(Model.ForEach(items, t => mine[t] * value[t])) >= goldNeeded); model.AddConstraint("knap_gems", Model.Sum(Model.ForEach(items, t => mine[t])) >= gemsNeeded); model.AddGoal("knap_time", GoalKind.Minimize, Model.Sum(Model.ForEach(items, t => mine[t] * clicks[t]))); var report = context.CheckModel(); Console.Write(report); Solution solution = context.Solve(new SimplexDirective()); //Report report = solution.GetReport(); List <Tuple <Ore, int> > retval = new List <Tuple <Ore, int> >(); for (int i = 0; i < localOreList.Count; i++) { int temp = (int)mine.GetDouble(i); retval.Add(Tuple.Create(localOreList[i], temp)); } return(retval); }
/// <summary> /// The problem of integer programming: /// Selection employees necessary to minimize the total cost /// for given parameters of the cash amount and fixed productivity. /// </summary> /// <param name="selector">Contains cash amount and productivity</param> /// <returns>Possible solutions for the composition of the team of employees</returns> public override List <Dictionary <FellowWorker, int> > Select(StaffSelector selector) { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); // init fellow workers Junior junior = selector.Staffs.Junior; Middle middle = selector.Staffs.Middle; Senior senior = selector.Staffs.Senior; Lead lead = selector.Staffs.Lead; // init decisions - counts of number of employees of different qualifications Decision juniorDecision = new Decision(Domain.IntegerNonnegative, junior.GetQualificationString()); Decision middleDecision = new Decision(Domain.IntegerNonnegative, middle.GetQualificationString()); Decision seniorDecision = new Decision(Domain.IntegerNonnegative, senior.GetQualificationString()); Decision leadDecision = new Decision(Domain.IntegerNonnegative, lead.GetQualificationString()); model.AddDecisions(juniorDecision, middleDecision, seniorDecision, leadDecision); // constraint of fixed productivity model.AddConstraints("fixProductivity", junior.Productivity * juniorDecision + middle.Productivity * middleDecision + senior.Productivity * seniorDecision + lead.Productivity * leadDecision == selector.Productivity); // constraint of max cash amount model.AddConstraints("maxAmount", junior.Salary * juniorDecision + middle.Salary * middleDecision + senior.Salary * seniorDecision + lead.Salary * leadDecision <= selector.Amount); // criterion of optimization - total cost model.AddGoal("cost", GoalKind.Minimize, junior.Salary * juniorDecision + middle.Salary * middleDecision + senior.Salary * seniorDecision + lead.Salary * leadDecision); Solution solution = context.Solve(new ConstraintProgrammingDirective()); // packing results List <Dictionary <FellowWorker, int> > solutionsList = new List <Dictionary <FellowWorker, int> >(); while (solution.Quality != SolverQuality.Infeasible) { solutionsList.Add(PackSolutionInDictionary(new Decision[] { juniorDecision, middleDecision, seniorDecision, leadDecision }, selector.Staffs)); solution.GetNext(); } context.ClearModel(); return(solutionsList); }
public static double ComputePortfolioMinimumVariance(LabeledMatrix <Security> matrix, double expectedReturn, out Dictionary <Security, double> weights, bool allowShortSelling = false) { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); // since the row securities are the same as the column securities. use row. var securities = matrix.RowEntities; var weightDecisions = new Dictionary <Security, Decision>(); var rangeOfWeights = allowShortSelling ? Domain.RealRange(-10, 10) : Domain.RealRange(0, 10); Term t1 = 0d; // constraint 1, sum of weights = 1 Term t2 = 0d; // constraint 2, expected portfolio return (sum of weight*price) = expectedReturn foreach (var security in securities) { var securityWeightDecision = new Decision(rangeOfWeights, security.Symbol); // -10 <= w <= 10 weightDecisions[security] = securityWeightDecision; model.AddDecisions(securityWeightDecision); t1 += securityWeightDecision; t2 += (securityWeightDecision * security.MarketPrice); } model.AddConstraint("SumOfWeights", t1 == 1d); model.AddConstraint("ExpectedPortfolioReturn", t2 == expectedReturn); // goal 1, the ptf var to be minimized Term varianceTerm = 0d; foreach (Security rowEntity in matrix.RowEntities) { foreach (Security columnEntity in matrix.ColumnEntities) { varianceTerm += (matrix.Get(rowEntity, columnEntity) * weightDecisions[rowEntity] * weightDecisions[columnEntity]); } } Goal goal = model.AddGoal("MeanVariance", GoalKind.Minimize, varianceTerm); var gurobiDirective = new GurobiDirective(); //gurobiDirective.OutputFlag = true; context.Solve(gurobiDirective); //Report report = solution.GetReport(); //Console.WriteLine("{0}", report); //Console.WriteLine(goal.ToDouble()); //foreach (var weightDecision in weightDecisions) //{ // Console.WriteLine(weightDecision.Key.Symbol + ":" + weightDecision.Value.GetDouble()); //} context.ClearModel(); weights = weightDecisions.ToDictionary(p => p.Key, p => p.Value.GetDouble()); return(goal.ToDouble()); }
public static Tuple <double, List <double> > PlayerBStrategy(List <List <int> > matrix) { SolverContext context = SolverContext.GetContext(); context.ClearModel(); Model model = context.CreateModel(); List <Decision> decicionList = new List <Decision>(); for (int j = 0; j < matrix[0].Count; j++) { decicionList.Add(new Decision(Domain.RealNonnegative, "B" + j)); } foreach (var decision in decicionList) { model.AddDecision(decision); } for (int i = 0; i < matrix.Count; i++) { SumTermBuilder rowSum = new SumTermBuilder(decicionList.Count); for (int j = 0; j < decicionList.Count; j++) { rowSum.Add(decicionList[j] * matrix[i][j]); } model.AddConstraint("con" + i, rowSum.ToTerm() <= 1); } SumTermBuilder decisionSum = new SumTermBuilder(decicionList.Count); for (int j = 0; j < decicionList.Count; j++) { model.AddConstraint("nonneg" + j, decicionList[j] >= 0); decisionSum.Add(decicionList[j]); } model.AddGoal("max", GoalKind.Maximize, decisionSum.ToTerm()); Solution solution = context.Solve(new SimplexDirective()); double gameValue = 1 / solution.Goals.First().ToDouble(); List <double> parsedDecicionList = new List <double>(); foreach (var decision in decicionList) { parsedDecicionList.Add(decision.ToDouble() * gameValue); } return(new Tuple <double, List <double> >(gameValue, parsedDecicionList)); }
public void GenerateProbabilities() { if (_problem.Variables.Count == 0) { return; } SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Dictionary <Variable, (Decision NotNegated, Decision Negated)> decisions = _problem.Variables.ToDictionary( variable => variable, variable => (new Decision(Domain.RealNonnegative, variable.Name), new Decision(Domain.RealNonnegative, "_" + variable.Name))); model.AddDecisions(decisions.Values.SelectMany(t => new[] { t.NotNegated, t.Negated }).ToArray()); foreach (var pair in decisions) { model.AddConstraint("balance_" + pair.Key.Name, pair.Value.NotNegated + pair.Value.Negated == 1); } int clauseNum = 0; foreach (var problemClause in _problem.Clauses) { Term term = null; foreach (var lieral in problemClause) { var decisionToAdd = lieral.Value ? decisions[lieral.Key].Negated : decisions[lieral.Key].NotNegated; term = object.Equals(term, null) ? decisionToAdd : term + decisionToAdd; } if (!object.Equals(term, null)) { model.AddConstraint($"clause_{clauseNum++}", term >= 1); } } foreach (var valueTuple in decisions) { model.AddGoal($"goal_{valueTuple.Key.Name}", GoalKind.Maximize, valueTuple.Value.NotNegated + valueTuple.Value.Negated); } Solution solution = context.Solve(new SimplexDirective()); context.ClearModel(); _probailities = decisions.ToDictionary(pair => pair.Key, pair => pair.Value.NotNegated.ToDouble()); }
public static void Main(string[] args) { var Names = new string[] { "Alice", "Bob", "Carol", "David", "Eve", }; Domain Recipients = Domain.Enum(Names); SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Dictionary<string, string[]> PossiblyBuysFor = new Dictionary<string, string[]>(); //Alice and Carol are sisters //Bob and David are brothers //Can't buy for siblings or yourself PossiblyBuysFor["Alice"] = new string[] { "Bob", "David", "Eve", }; PossiblyBuysFor["Bob"] = new string[] { "Alice", "Carol", "Eve", }; PossiblyBuysFor["Carol"] = new string[] { "Bob", "David", "Eve", }; PossiblyBuysFor["David"] = new string[] { "Alice", "Carol", "Eve", }; PossiblyBuysFor["Eve"] = new string[] { "Alice", "Bob", "Carol", "David", }; foreach (var giver in PossiblyBuysFor.Keys) { Decision d = new Decision(Recipients, giver.ToLower()); model.AddDecision(d); } foreach (var giver in PossiblyBuysFor.Keys) { string term = "1 == 0 "; foreach (var valid in PossiblyBuysFor[giver]) { term += string.Format(" | {0} == \"{1}\"", giver.ToLower(), valid); } model.AddConstraint("domain_restriction_" + giver, term); } model.AddConstraint("one_present_each", Model.AllDifferent(model.Decisions.ToArray())); Solution solution = context.Solve(new ConstraintProgrammingDirective()); int i = 0; while (solution.Quality != SolverQuality.Infeasible && i < 10) { Console.WriteLine(i); foreach (var d in solution.Decisions) { Console.WriteLine(string.Format("{0} buys for {1}", d.Name, d.ToString())); } Console.ReadKey(); solution.GetNext(); i++; } Console.WriteLine("The end"); Console.ReadKey(); }
/// <summary>Create the model. /// </summary> /// <param name="project">The project to be scheduled.</param> public void Initialize(Project project) { context = SolverContext.GetContext(); context.ClearModel(); model = context.CreateModel(); int eventCount = project.Tasks.Count; // we will fill these in in the remainder of the post. InitializeSets(project.Tasks.Count, eventCount, project.Resources.Count); InitializeParameters(project.Tasks, project.Resources); InitializeDecisions(); InitializeGoal(); InitializeConstraints(project, eventCount); }
static void Main(string[] args) { Double[,] y = { { 5, 1, 0 }, { 1, 9, 1 }, { 0, 1, 9 }, }; Term goal; Term[,] tx; Term[,] ty; SolverContext context = SolverContext.GetContext(); // Get context environment Model model = context.CreateModel(); // Create a new model Decision d1 = new Decision(Domain.RealNonnegative, "d1"); // First item in "x" vector (must be >= 0) Decision d2 = new Decision(Domain.RealNonnegative, "d2"); // Second item in "x" vector (must be >= 0) Decision d3 = new Decision(Domain.RealNonnegative, "d3"); // Third item in "x" vector (must be >= 0) model.AddDecisions(d1, d2, d3); // Add these to the model (this is where the outputs will be stored) model.AddConstraints("limits", // Add constraints 0 <= d1 <= 1, // Each item must be between 0 and 1 0 <= d2 <= 1, 0 <= d3 <= 1, d1 + d2 + d3 == 1); // All items must add up to 1 ty = matrix(y); tx = new Term[, ] { { d1, d2, d3 } }; goal = matMult(matMult(tx, ty), transpose(tx))[0, 0]; model.AddGoal("goal", GoalKind.Minimize, goal); // Specifying the IPM solver, as we have a quadratic goal Solution solution = context.Solve(new InteriorPointMethodDirective()); Report report = solution.GetReport(); Console.WriteLine("x {{{0}, {1}, {2}}}", d1, d2, d3); Console.Write("{0}", report); }
private void button1_Click(object sender, EventArgs e) { pobierzDane(); SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Decision z1 = new Decision(Domain.RealNonnegative, "z1"); Decision z2 = new Decision(Domain.RealNonnegative, "z2"); Decision z3 = new Decision(Domain.RealNonnegative, "z3"); Decision z4 = new Decision(Domain.RealNonnegative, "z4"); model.AddDecisions(z1, z2, z3, z4); model.AddConstraints("limits", z1 >= 0, z2 >= 0, z3 >= 0, z4 >= 0 ); model.AddConstraints("production", pierwiastki[0] * z1 + pierwiastki[1] * z2 + pierwiastki[2] * z3 + pierwiastki[3] * z4 >= minimum[0], pierwiastki[4] * z1 + pierwiastki[5] * z2 + pierwiastki[6] * z3 + pierwiastki[7] * z4 >= minimum[1], pierwiastki[8] * z1 + pierwiastki[9] * z2 + pierwiastki[10] * z3 + pierwiastki[11] * z4 >= minimum[2], pierwiastki[12] * z1 + pierwiastki[13] * z2 + pierwiastki[14] * z3 + pierwiastki[15] * z4 >= minimum[3] ); Goal g = model.AddGoal("cost", GoalKind.Minimize, ceny[0] * z1 + ceny[1] * z2 + ceny[2] * z3 + ceny[3] * z4 ); Solution solution = context.Solve(new SimplexDirective()); Report report = solution.GetReport(); //Console.WriteLine("vz: {0}, sa: {1}", z1, sa); wynik1.Text = z1.ToDouble().ToString(); wynik2.Text = z2.ToDouble().ToString(); wynik3.Text = z3.ToDouble().ToString(); wynik4.Text = z4.ToDouble().ToString(); wynik5.Text = g.ToString(); Console.Write("{0}", report); Console.ReadLine(); }
private void solveLLP() { #region 1 реализация SolverContext context = SolverContext.GetContext(); context.ClearModel(); modelOfLLP = context.CreateModel(); x1 = new Decision(Domain.IntegerNonnegative, "X1"); x2 = new Decision(Domain.IntegerNonnegative, "X2"); modelOfLLP.AddDecisions(x1, x2); modelOfLLP.AddConstraints("limits", 0 <= x1, 0 <= x2); addConstraintsSystem(); addObjectFunction(); solution = context.Solve(new SimplexDirective()); #endregion }
static void Main(string[] args) { try { //https://nathanbrixius.wordpress.com/2009/04/24/modeling-a-production-planning-problem-using-solver-foundation/ SolverContext context = SolverContext.GetContext(); context.ClearModel(); Model model = context.CreateModel(); Set fabricas = new Set(Domain.Any, "fabricas"); Set distribuidores = new Set(Domain.Any, "distribuidores"); Parameter demanda = new Parameter(Domain.Integer, "demanda", distribuidores); demanda.SetBinding(getDemanda().AsEnumerable(), "Demanda", "Distribuidor"); Parameter costos = new Parameter(Domain.Integer, "costos", fabricas, distribuidores); costos.SetBinding(getCostos().AsEnumerable(), "Costo", "Fabrica", "Distribuidor"); Parameter disponibilidad = new Parameter(Domain.Integer, "disponibilidad", fabricas); disponibilidad.SetBinding(getDisponibilidad().AsEnumerable(), "Disponibilidad", "Fabrica"); model.AddParameters(demanda, costos, disponibilidad); Decision x = new Decision(Domain.RealNonnegative, "x", fabricas, distribuidores); model.AddDecision(x); model.AddConstraint("Disponibilidad", Model.ForEach(fabricas, f => Model.Sum(Model.ForEach(distribuidores, d => x[f, d])) <= disponibilidad[f])); model.AddConstraint("Demanda", Model.ForEach(distribuidores, d => Model.Sum(Model.ForEach(fabricas, f => x[f, d])) >= demanda[d])); model.AddGoal("Meta", GoalKind.Minimize, Model.Sum(Model.ForEach(fabricas, f => Model.ForEach(distribuidores, d => costos[f, d] * x[f, d])))); Solution solution = context.Solve(new SimplexDirective()); Report report = solution.GetReport(); Console.WriteLine(report); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex); Console.ReadLine(); } }
private void button1_Click(object sender, EventArgs e) { string[] names = { "Алюминий", "Медь", "Олово", "Цинк", "Свинец" }; int[] prod1 = { 10, 20, 15, 30, 20 }; int[] prod2 = { 70, 50, 35, 40, 45 }; int[] volume = { 570, 420, 300, 600, 400 }; dataGridView1.Rows.Add(); dataGridView1.Rows.Add(); dataGridView1.Rows.Add(); dataGridView1.Rows.Add(); dataGridView1.Rows.Add(); for (int i = 0; i <= 4; i++) { dataGridView1.Rows[i].Cells[0].Value = names[i]; dataGridView1.Rows[i].Cells[1].Value = prod1[i]; dataGridView1.Rows[i].Cells[2].Value = prod2[i]; dataGridView1.Rows[i].Cells[3].Value = volume[i]; } SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Decision x01 = new Decision(Domain.IntegerNonnegative, "product1"); Decision x02 = new Decision(Domain.IntegerNonnegative, "product2"); model.AddDecisions(x01, x02); model.AddConstraints("production", 0.4 * x01 - 0.6 * x02 >= 0, x01 * prod1[0] + x02 * prod2[0] <= volume[0], x01 * prod1[1] + x02 * prod2[1] <= volume[1], x01 * prod1[2] + x02 * prod2[2] <= volume[2], x01 * prod1[3] + x02 * prod2[3] <= volume[3], x01 * prod1[4] + x02 * prod2[4] <= volume[4] ); { model.AddGoal("cost", GoalKind.Maximize, 30 * x01 + 80 * x02); Solution solution = context.Solve(new SimplexDirective()); Report report = solution.GetReport(); x1.Text = x01.ToDouble().ToString(); x2.Text = x02.ToDouble().ToString(); cost.Text = model.Goals.First().ToDouble().ToString(); res.Text += report; } }
public static float[] Execute(SimplexFundsData fundsData, double portfolioValue, double acceptableSingleDD, double riskSigmaMultiplier, double maxSinglePositionSize, double maxPortfolioRisk, int truncateBalanceToNthPlace) { SimplexExecutorData data = new SimplexExecutorData(fundsData); if (data.ActiveFunds.Length == 0) { return(new float[fundsData.Stocks.Length]); } double maxSingleDDValue = portfolioValue * acceptableSingleDD; double maxPositionValue = portfolioValue * maxSinglePositionSize; double maxPortfolioAggressiveValue = portfolioValue * maxPortfolioRisk; SolverContext solverContext = new SolverContext(); Model model = solverContext.CreateModel(); model.AddDecisions(data.ActiveFunds.Select(i => new Decision(Domain.RealNonnegative, $"_{i}")).ToArray()); model.AddConstraint("acceptable_single_DD", TermBuilder.SumProducts(model.Decisions, (i) => data.Prices[i] * (data.AvgChange[i] + data.AvgChangeSigma[i] * riskSigmaMultiplier)) <= maxSingleDDValue); model.AddConstraint("max_portfolio_aggressive_value", TermBuilder.SumProducts(model.Decisions, data.Prices) <= maxPortfolioAggressiveValue); model.AddConstraints("max_single_position_size", TermBuilder.BuildTerms(model.Decisions, (decision, i) => data.Prices[i] * decision <= maxPositionValue)); model.AddConstraints("all_positions_positive", TermBuilder.BuildTerms(model.Decisions, (decision, i) => data.AvgProfit[i] * decision >= 0)); model.AddConstraints("nonnegative", TermBuilder.NonNegative(model.Decisions)); model.AddGoal("max_avg_profit", GoalKind.Maximize, TermBuilder.SumProducts(model.Decisions, data.AvgProfit)); return(CalculateBalance(solverContext.Solve(new SimplexDirective()), fundsData, portfolioValue, truncateBalanceToNthPlace)); }
public void OptMethod3() { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); //decisions Decision vz = new Decision(Domain.RealNonnegative, "barrels_venezuela"); Decision sa = new Decision(Domain.RealNonnegative, "barrels_saudiarabia"); model.AddDecisions(vz, sa); //Goals model.AddGoal("cost", GoalKind.Minimize, 20 * sa + 15 * vz); //constraints model.AddConstraints("limits", 0 <= vz <= 9000, 0 <= sa <= 6000); model.AddConstraints("production", 0.3 * sa + 0.4 * vz >= 2000, 0.4 * sa + 0.2 * vz >= 1500, 0.2 * sa + 0.3 * vz >= 500); // This doesn't work! // model.AddGoal("Profit", GoalKind.Maximize, objfunc(xs, xl)); Solution sol = context.Solve(new SimplexDirective()); Report report = sol.GetReport(); Console.WriteLine("vz: {0}, sa: {1}", vz, sa); Console.Write("{0}", report); Console.ReadLine(); //Console.WriteLine(report); }
private void button_Click(object sender, RoutedEventArgs e) { context.ClearModel(); Model model = context.CreateModel(); List <Decision> decisions = new List <Decision>(); var formula = ""; string con = ""; foreach (var item in dataGridVars.Items) { string li = "L" + (item as Invester).Line; double maxValue = Double.Parse((item as Invester).MaxValue) * Double.Parse(Value.Text) / 100f; String contrain = li + " <= " + maxValue; ParseContrain(contrain); con += " " + li + " +"; Decision dc = new Decision(Domain.RealRange(0, maxValue), li); decisions.Add(dc); model.AddDecision(dc); } ParseContrain(con.Substring(0, con.Length - 1) + " >= " + Value.Text); foreach (var item in dataGridVars.Items) { formula += " " + Double.Parse((item as Invester).Interest) + " * L" + (item as Invester).Line; if ((item as Invester).Line <= dataGridVars.Items.Count - 1) { formula += " +"; } String contrain = "L" + (item as Invester).Line + " >= 0 "; ParseContrain(contrain); } TargetFormula = formula.Substring(1, formula.Length - 2); FormulaTB.Text = TargetFormula; foreach (var list in ListOfContrains) { string c = ""; for (int i = 0; i < list.Capacity; i++) { if (i != 0 && i < list.Capacity - 1) { c += list[i] >= 0 ? " + " : " - "; } if (i == list.Capacity - 1) { c += " " + listOfStringContrains[ListOfContrains.IndexOf(list)] + " " + list[i]; } else { c += Math.Abs(list[i]) + " * L" + i; } } model.AddConstraint("C" + ListOfContrains.IndexOf(list), c); Console.WriteLine(c); } model.AddGoal("Goal", GoalKind.Minimize, TargetFormula); var directive = new SimplexDirective() { IterationLimit = -1, TimeLimit = -1, Arithmetic = Arithmetic.Exact, GetSensitivity = true }; Solution solution = context.Solve(directive); Quality.Text = solution.Quality.ToString(); Console.WriteLine(solution.GetReport().ToString()); if (solution.Quality != SolverQuality.Optimal) { return; } context.PropagateDecisions(); for (int i = 0; i < decisions.Count; i++) { var old = (dataGridVars.Items[i] as Invester); old.SelectedValue = decisions[i].ToDouble().ToString(); dataGridVars.Items[i] = old; } dataGridVars.Items.Refresh(); dataGridVars.UpdateLayout(); }
private void CreateModel() { context = SolverContext.GetContext(); context.ClearModel(); model = context.CreateModel(); items = new Set(Domain.Any, "items"); cost = new Parameter(Domain.Integer, "cost", items); cost.SetBinding(Round.Players, "Cost", "Name"); score = new Parameter(Domain.Integer, "score", items); score.SetBinding(Round.Players, "Score", "Name"); team = new Parameter(Domain.IntegerNonnegative, "team", items); team.SetBinding(Round.Players, "TeamId", "Name"); dummy = new Parameter(Domain.Boolean, "dummy", items); dummy.SetBinding(Round.Players, "IsDummyPlayer", "Name"); model.AddParameters(cost, score, team, dummy); choose = new Decision(Domain.IntegerRange(0, 1), "choose", items); choose.SetBinding(Round.Players, "SelectedValue", "Name"); model.AddDecision(choose); }
/// <summary> /// Handles the given action, which may result in a synchronized transition. /// </summary> public bool HandleAction(ActionType type, string channel, Dictionary <string, object> parameters) { Log.Debug(this, nameof(HandleAction) + " Type: " + type + " Channel: " + channel + " Parameters:\n" + string.Join("\n", parameters.Select(x => x.Key + ": " + x.Value).ToArray())); List <SymbolicTransition> validTransitions = new List <SymbolicTransition>(); foreach (SymbolicTransition transition in Transitions) { // Transition must come from the current state. if (transition.From != State) { continue; } // Transition must have the same type (input or output). if (transition.Type != type) { continue; } // Transition must have the same channel name. if (transition.Channel != channel) { continue; } bool valid = true; try { SolverContext solver = SolverContext.GetContext(); if (!modelCache.TryGetValue(transition, out Model model)) { solver.ClearModel(); model = solver.CreateModel(); modelCache.Add(transition, model); Log.Debug(this, "Created new model: " + model); // Add location variables, and interaction variables. //model.AddParameters(Variables.ToArray()); model.AddDecisions(transition.Variables.ToArray()); // Let the transition add its guard expression. transition.Guard(model, Variables, transition.Variables); } else { Log.Debug(this, "Re-using existing model: " + model); solver.ClearModel(); solver.CurrentModel = model; } // Does it solve? Solution solution = solver.Solve(new HybridLocalSearchDirective() { TimeLimit = 1000, }); Log.Debug(this, "Succesfully solved: " + transition); foreach (Decision decision in transition.Variables) { Log.Debug(this, string.Format("<Decision> {0}: {1}", decision.Name, decision)); } Report report = solution.GetReport(); Log.Debug(this, string.Format("{0}", report)); solver.ClearModel(); } catch (Exception e) { Log.Error(this, "Exception solving: " + transition + "\n" + e); valid = false; } // Transition must have the same parameters (but order does not matter). //if (!transition.Parameters.SetEquals(new HashSet<string>(parameters.Keys))) continue; // Transition guard function must evaluate to true. //if (!transition.GuardFunction(Variables, parameters)) continue; // All checks passed! if (valid) { validTransitions.Add(transition); } } Log.Debug(this, "Valid transitions:\n" + string.Join("\n", validTransitions.Select(x => x.ToString()).ToArray())); if (validTransitions.Count == 0) { return(false); } // DEBUG: For testing, we pick the first compatible transition, not a random one. (TPE) SymbolicTransition chosenTransition = validTransitions.First(); Log.Debug(this, "Chosen transition:\n" + chosenTransition); chosenTransition.Update(Variables, chosenTransition.Variables); Log.Debug(this, "From: " + State + " To: " + chosenTransition.To); State = chosenTransition.To; return(true); }
public static Dictionary <string, MySolver.Parameter> Solve(double[] Xvals, double[] Yvals, string formula, Dictionary <string, MySolver.Parameter> coefficients) { if (formula.StartsWith("If[FRAP"))//Send to frapa model and return the result { return(FRAPA_Model.AllModels.Solve(formula, Xvals, Yvals, coefficients)); } // create solver model SolverContext solver = SolverContext.GetContext(); solver.ClearModel(); Model model = solver.CreateModel(); foreach (var parameter in coefficients) { if (parameter.Value.Variable)//add variable { //m.AddDecision(new Decision(Domain.IntegerRange(0, 100), "b")); //Decision des = new Decision(Domain.Real, parameter.Key); Decision des = new Decision(Domain.RealRange(parameter.Value.Min, parameter.Value.Max), parameter.Key); des.SetInitialValue(parameter.Value.Value); model.AddDecision(des); } else // add scalar { Microsoft.SolverFoundation.Services.Parameter par = new Microsoft.SolverFoundation.Services.Parameter( Domain.Real, parameter.Key); //par.SetBinding(new double[] { parameter.Value.Value }, parameter.Key); par.SetBinding((double)parameter.Value.Value); model.AddParameters(par); } } //operators: https://msdn.microsoft.com/en-us/library/gg261757(v=vs.93).aspx string theTerm = "((" + formula.Replace("t", Xvals[0].ToString()).Replace("Sqr" + Xvals[0].ToString(), "Sqrt") + ") - " + Yvals[0].ToString() + ") ^ 2"; for (int i = 1; i < Xvals.Length && i < Yvals.Length; i++) { theTerm += " + ((" + formula.Replace("t", Xvals[i].ToString()).Replace("Sqr" + Xvals[i].ToString(), "Sqrt") + ") - " + Yvals[i].ToString() + ") ^ 2"; } // // define optimization type and give objective function SUM(e^2) to be minimized model.AddGoal("SumOfSquaredErrors", GoalKind.Minimize, theTerm); // // solve model and transfer results (optimized decision variables) from // model into a dictionary object which will be returned for the caller Solution solution = solver.Solve(); //return the result Dictionary <string, MySolver.Parameter> parameters = new Dictionary <string, MySolver.Parameter>(); foreach (Decision parameter in model.Decisions) { MySolver.Parameter p; if (!coefficients.TryGetValue(parameter.Name, out p)) { p = new Parameter(parameter.Name); } parameters.Add(parameter.Name, new Parameter (parameter.Name, parameter.ToDouble(), p.Min, p.Max, p.Variable)); } return(parameters); }
private void Raschot_Click(object sender, EventArgs e) { if ( #region --- (_predel_B1.Text == "") || (_predel_B2.Text == "") || (_predel_B3.Text == "") || (kol_A1_B1.Text == "") || (kol_A1_B2.Text == "") || (kol_A1_B3.Text == "") || (kol_A2_B1.Text == "") || (kol_A2_B2.Text == "") || (kol_A2_B3.Text == "") || (kol_A3_B1.Text == "") || (kol_A3_B2.Text == "") || (kol_A3_B3.Text == "") || (sto_A1.Text == "") || (sto_A2.Text == "") || (sto_A3.Text == "")) #endregion --- { Grafick.Parent = null; MessageBox.Show("Не все поля заполнены!", "Ошибка"); return; } else { Grafick.Parent = tabControl1; chart1.Series[0].Points.Clear(); chart1.Series[1].Points.Clear(); chart1.Series[2].Points.Clear(); H._predel_B1 = Double.Parse(_predel_B1.Text); H._predel_B2 = Double.Parse(_predel_B2.Text); H._predel_B3 = Double.Parse(_predel_B3.Text); H.kol_A1_B1 = Double.Parse(kol_A1_B1.Text); H.kol_A1_B2 = Double.Parse(kol_A1_B2.Text); H.kol_A1_B3 = Double.Parse(kol_A1_B3.Text); H.kol_A2_B1 = Double.Parse(kol_A2_B1.Text); H.kol_A2_B2 = Double.Parse(kol_A2_B2.Text); H.kol_A2_B3 = Double.Parse(kol_A2_B3.Text); H.kol_A3_B1 = Double.Parse(kol_A3_B1.Text); H.kol_A3_B2 = Double.Parse(kol_A3_B2.Text); H.kol_A3_B3 = Double.Parse(kol_A3_B3.Text); H.sto_A1 = Double.Parse(sto_A1.Text); H.sto_A2 = Double.Parse(sto_A2.Text); H.sto_A3 = Double.Parse(sto_A3.Text); List <SolverRow> solverList = new List <SolverRow>(); solverList.Add(new SolverRow { xId = 1, Koef = H.X1 }); solverList.Add(new SolverRow { xId = 2, Koef = H.X2 }); solverList.Add(new SolverRow { xId = 3, Koef = H.X3 }); SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); Set users = new Set(Domain.Any, "users"); Parameter Koef = new Parameter(Domain.Real, "Koef", users); Koef.SetBinding(solverList, "Koef", "xId"); model.AddParameter(Koef); Decision choose = new Decision(Domain.RealNonnegative, "choose", users); model.AddDecisions(choose); model.AddGoal("goal", GoalKind.Minimize, Model.Sum(Model.ForEach(users, xId => choose[xId] * Koef[xId]))); model.AddConstraint("OgranT1", Model.Sum(Model.ForEach(users, xId => H.kol_A1_B1 * H.X1 + H.kol_A2_B1 * H.X2 + H.kol_A3_B1 * H.X3)) <= H._predel_B1); model.AddConstraint("OgranT2", Model.Sum(Model.ForEach(users, xId => H.kol_A1_B2 * H.X1 + H.kol_A2_B2 * H.X2 + H.kol_A3_B2 * H.X3)) <= H._predel_B2); model.AddConstraint("OgranT3", Model.Sum(Model.ForEach(users, xId => H.kol_A1_B3 * H.X1 + H.kol_A2_B3 * H.X2 + H.kol_A3_B3 * H.X3)) <= H._predel_B3); try { Solution solution = context.Solve(); Report report = solution.GetReport(); String reportStr = ""; for (int i = 0; i < solverList.Count; i++) { reportStr += "Значение X" + (i + 1).ToString() + ": " + choose.GetDouble(solverList[i].xId) + "\n"; } reportStr += "\n" + report.ToString(); } catch (Exception ex) { MessageBox.Show("При решении задачи оптимизации возникла исключительная ситуация."); } double X1 = Math.Round(choose.GetDouble(solverList[0].xId), 3); double X2 = Math.Round(choose.GetDouble(solverList[1].xId), 3); double X3 = Math.Round(choose.GetDouble(solverList[2].xId), 3); this.chart1.Series[0].Points.AddXY("", H.X1); this.chart1.Series[1].Points.AddXY("", H.X2); this.chart1.Series[2].Points.AddXY("", H.X3); dataGridView1.Rows.Add(H.X1, H.X2, H.X3); } }
private void FindSolution(IEnumerable <Node> nodes, IEnumerable <Link> links, List <SolverWorker> workers) { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); var nodeSet = new Set(0, nodes.Count(), 1); var workerSet = new Set(0, workers.Count(), 1); //-------------Parameters-------------- var weights = new Parameter(Domain.IntegerNonnegative, "weights", nodeSet); weights.SetBinding(nodes, "Weight", "ID"); var dependencies = new Parameter(Domain.IntegerRange(0, 1), "dependencies", nodeSet, nodeSet); dependencies.SetBinding(links, "isDependent", "Source", "Parent"); model.AddParameters(weights, dependencies); //-------------Decisions-------------- var startTimes = new Decision(Domain.IntegerNonnegative, "starts", nodeSet); var finishTimes = new Decision(Domain.IntegerNonnegative, "finishes", nodeSet); var makespan = new Decision(Domain.IntegerNonnegative, "makespan"); var allocation = new Decision(Domain.IntegerRange(0, 1), "allocation", nodeSet, workerSet); model.AddDecisions(startTimes, finishTimes, makespan, allocation); //-------------Constraints-------------- model.AddConstraint("FinishTime", Model.ForEach(nodeSet, (node) => startTimes[node] + weights[node] == finishTimes[node])); //model.AddConstraint("OneAtATime", Model.ForEach(nodeSet, (n) => // Model.ForEachWhere(nodeSet, (n2) => Model.Or(finishTimes[n] < startTimes[n2], startTimes[n] > finishTimes[n2]), (n2) => n != n2))); model.AddConstraint("Allocatee", Model.ForEach(nodeSet, (n) => Model.Sum(Model.ForEach(workerSet, (w) => allocation[n, w])) == 1)); //model.AddConstraint("Allocatee", Model.ForEach(nodeSet, (n) => Model.ExactlyMofN(1,allocation[n]))); model.AddConstraint("OneAtATime", Model.ForEach(workerSet, (w) => Model.ForEach(nodeSet, (n) => Model.ForEachWhere(nodeSet, (n2) => Model.Implies(Model.And(allocation[n, w] == 1, allocation[n2, w] == 1), Model.Or(finishTimes[n] <= startTimes[n2], startTimes[n] >= finishTimes[n2])), (n2) => n != n2)))); model.AddConstraint("PrecedenceConstraints", Model.ForEach(nodeSet, task => Model.ForEach(nodeSet, parent => Model.Implies(dependencies[task, parent] == 1, startTimes[task] >= finishTimes[parent])))); //model.AddConstraint("ProjectFinish", Model.ForEach(nodeSet, (n) => makespan >= finishTimes[n])); model.AddConstraint("ProjectFinish", makespan == Model.Max(Model.ForEach(nodeSet, (n) => finishTimes[n]))); model.AddGoal("MinMakeSpan", GoalKind.Minimize, makespan); context.CheckModel(); //using (StreamWriter sw = new StreamWriter("Stadium.oml")) { // context.SaveModel(FileFormat.OML, sw); ; //} Solution solution = context.Solve(); Report report = solution.GetReport(); Console.WriteLine(@"===== report ====="); Console.Write("{0}", report); Console.ReadLine(); context.ClearModel(); }