//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); }
/// <summary> /// Initialize demand for different rolls /// and some other class fields /// </summary> /// <remarks>Find the initial patterns by producing only one size roll</remarks> public void Initialize() { _patternRolls = new List <PatternItemSize>(); _demands = new List <SizeDemand>(); _patterns = new List <CuttingPattern>(); //demand for rolls: use UNIQUE widths! _demands.Add(new SizeDemand(12, 211)); _demands.Add(new SizeDemand(27, 345)); _demands.Add(new SizeDemand(31, 395)); _demands.Add(new SizeDemand(36, 610)); _demands.Add(new SizeDemand(45, 97)); _demands.Add(new SizeDemand(68, 121)); //Initial number of patterns and its composition //Create one pattern per demanded roll //(each cutting pattern will initially contain a single width roll, //and cut as many items as they fit in the roll's width) //1. Crete one pattern per roll _patternCount = _demands.Count(); for (int i = 0; i < _patternCount; i++) { _patterns.Add(new CuttingPattern() { PatternID = i, Count = 0 }); } //2. add each roll on one pattern _demands.ForEach(demand => AddRollToPatterns(demand)); _context = SolverContext.GetContext(); _setRoll = new Set(Domain.IntegerNonnegative, "Roll"); _shadowPrices = new List <KeyValuePair <int, Rational> >(); Console.WriteLine("Starting with {0} patterns (1 pattern per size, fit as many items as possible, while <={1} [rollWidth]).", _patternCount, _rollWidth); }
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); }
private static void FindForwards(Yield @short, Yield[] yields, double spotTarget, double initialDiff = 0) { var clock = Stopwatch.StartNew(); var context = SolverContext.GetContext(); context.ClearModel(); var model = context.CreateModel(); Console.WriteLine($"Solver-Clean/Create model={clock.ElapsedMilliseconds}"); var forwards = new Decision[yields.Length]; for (var i = 0; i < forwards.Length; i++) { model.AddDecision(forwards[i] = new Decision(Domain.RealNonnegative, null)); } Term fwd = @short.Forward; var spotFactor = Microsoft.SolverFoundation.Services.Model.Power(1d + @short.Spot / 100d, @short.Term / 252d); var diff = new Term[forwards.Length + 1]; diff[0] = initialDiff; for (var i = 0; i < forwards.Length; i++) { var termDelta = yields[i].Term - (i == 0 ? @short.Term : yields[i - 1].Term); var forwardFactor = Microsoft.SolverFoundation.Services.Model.Power(1d + forwards[i] / 100d, termDelta / 252d); spotFactor *= forwardFactor; diff[i + 1] = forwards[i] - (i == 0 ? fwd : forwards[i - 1]); } var spot = (Microsoft.SolverFoundation.Services.Model.Power(spotFactor, 252d / yields.Last().Term) - 1d) * 100d; var diff2 = new Term[diff.Length - 1]; for (var i = 1; i < diff.Length; i++) { diff2[i - 1] = diff[i] - diff[i - 1]; } var diff3 = new Term[diff2.Length - 1]; for (var i = 1; i < diff2.Length; i++) { diff3[i - 1] = diff2[i] - diff2[i - 1]; } var goal = Microsoft.SolverFoundation.Services.Model.Sum(Microsoft.SolverFoundation.Services.Model.Abs(spot - spotTarget), Microsoft.SolverFoundation.Services.Model.Abs(Microsoft.SolverFoundation.Services.Model.Sum(diff3))); model.AddGoal("erro", GoalKind.Minimize, goal); Console.WriteLine($"Solver-create goal={clock.ElapsedMilliseconds}"); context.Solve(); Console.WriteLine($"Solver-solve={clock.ElapsedMilliseconds}"); for (var i = 0; i < forwards.Length; i++) { yields[i].Forward = forwards[i].GetDouble(); } }
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()); }
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(); }
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)); }
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 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 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 BuildRoutesOperation(SolverContext context, Schedule schedule, SolveOptions options, BuildRoutesParameters inputParams) : base(context, schedule, options) { Debug.Assert(inputParams != null); _inputParams = inputParams; }
public SimplexNormal() { this.Context = SolverContext.GetContext(); this.Model = Context.CreateModel(); this.Minimos = 0; this.Maximos = 0; this.CargarCoeficientes(); this.Dispositivos = new Dictionary <string, Inteligente>(); }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public SequenceRoutesOperation(SolverContext context, Schedule schedule, SequenceRoutesParams inputParams, SolveOptions options) : base(context, schedule, options) { Debug.Assert(inputParams != null); _inputParams = inputParams; }
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 AssignOrdersReqBuilder(SolverContext context, ICollection<Order> unlockedOrdersToAssign, ICollection<Route> unlockedTargetRoutes, bool setAssignmentSpec) : base(context) { _unlockedOrdersToAssign = unlockedOrdersToAssign; _unlockedTargetRoutes = unlockedTargetRoutes; _setAssignmentSpec = setAssignmentSpec; }
public Report GetReport(SolverContext context, Solution solution, SolutionMapping solutionMapping) { PluginSolutionMapping pluginSolutionMapping = solutionMapping as PluginSolutionMapping; if (pluginSolutionMapping == null && solutionMapping != null) { throw new ArgumentException("solutionMapping is not a LinearSolutionMapping", "solutionMapping"); } return(new Z3TermSolverReport(context, this, solution, pluginSolutionMapping)); }
/// <summary> /// Metod dlya polucheniya smeshannoy strategii. /// </summary> /// <param name="arr"></param> /// <returns></returns> private static (double q1, double q2, double v) GeMixedStrategy(int[,] arr) { const string q1Param = "q1"; const string p2Param = "q2"; const string vParam = "v"; const string eq1Param = "eq1"; const string eq2Param = "eq2"; const string eq3Param = "eq3"; var context = SolverContext.GetContext(); var model = context.CreateModel(); var q1Dec = new Decision(Domain.Real, q1Param); var q2Dec = new Decision(Domain.Real, p2Param); var vDec = new Decision(Domain.Real, vParam); model.AddDecisions(q1Dec, q2Dec, vDec); model.AddConstraint(eq1Param, arr[0, 0] * q1Dec + arr[0, 1] * q2Dec == vDec); model.AddConstraint(eq2Param, arr[1, 0] * q1Dec + arr[1, 1] * q2Dec == vDec); model.AddConstraint(eq3Param, q1Dec + q2Dec == 1); var solution = context.Solve(); double q1 = 0; double q2 = 0; double v = 0; foreach (var decision in solution.Decisions) { switch (decision.Name) { case q1Param: q1 = (double)(decision.GetValues() .FirstOrDefault() ?.FirstOrDefault() ?? 0); break; case p2Param: q2 = (double)(decision.GetValues() .FirstOrDefault() ?.FirstOrDefault() ?? 0); break; case vParam: v = (double)(decision.GetValues() .FirstOrDefault() ?.FirstOrDefault() ?? 0); break; } } context.ClearModel(); return(q1, q2, v); }
private static void FindForwards(Yield @short, Yield[] yields, double spotTarget) { var context = SolverContext.GetContext(); context.ClearModel(); var model = context.CreateModel(); var forwards = new Decision[yields.Length]; for (var i = 0; i < forwards.Length; i++) { model.AddDecision(forwards[i] = new Decision(Domain.RealNonnegative, null)); } Term fwd = @short.Forward; var spotFactor = Model.Power(1d + @short.Spot / 100d, @short.Term / 252d); var diff = new Term[forwards.Length + 1]; diff[0] = 0; for (var i = 0; i < forwards.Length; i++) { var termDelta = yields[i].Term - (i == 0 ? @short.Term : yields[i - 1].Term); var forwardFactor = Model.Power(1d + forwards[i] / 100d, termDelta / 252d); spotFactor *= forwardFactor; diff[i + 1] = forwards[i] - (i == 0 ? fwd : forwards[i - 1]); } var spot = (Model.Power(spotFactor, 252d / yields.Last().Term) - 1d) * 100d; var diff2 = new Term[diff.Length - 1]; for (var i = 1; i < diff.Length; i++) { diff2[i - 1] = diff[i] - diff[i - 1]; } var diff3 = new Term[diff2.Length - 1]; for (var i = 1; i < diff2.Length; i++) { diff3[i - 1] = diff2[i] - diff2[i - 1]; } var goal = Model.Sum(Model.Abs(spot - spotTarget), Model.Abs(Model.Sum(diff3))); model.AddGoal("erro", GoalKind.Minimize, goal); context.Solve(); for (var i = 0; i < forwards.Length; i++) { yields[i].Forward = forwards[i].GetDouble(); } }
public ConfiguratorSession CreateConfiguratorSession(Model model) { // Create a ConfigurationInstance and SolverContext ConfigurationInstance configInstance = _configInstanceBLOFactory.Create_ConfigurationInstance_FromModel(model); SolverContext solverContext = new SolverContext(model); // Create a new ConfiguratorSession ConfiguratorSession newSession = new ConfiguratorSession(configInstance, model.CustomRules, solverContext); return(newSession); }
public Deck() { solver = SolverContext.GetContext(); random = new Random(); deck = new List <int>(40); for (int i = 0; i < 40; i++) { deck.Add(i); } }
static int NumberSolutions(SolverContext problem) { int ct = 0; Solution soln = problem.Solve(); while (soln.Quality == SolverQuality.Feasible) { ++ct; soln.GetNext(); } return(ct); }
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)); }
/// <summary> /// Creates orders assigning operation result without solving. /// </summary> /// <param name="context">Solve operation context.</param> /// <param name="requestData">Solve operation request data.</param> /// <param name="violations">Violations found upon request building.</param> /// <returns>Result of the solve for the specified request.</returns> public static SolveResult CreateResultWithoutSolve( SolverContext context, SolveRequestData requestData, IEnumerable<Violation> violations) { foreach (var route in requestData.Routes) { context.Project.Schedules.ClearRouteResults(route); } return new SolveResult(null, violations.ToArray(), false); }
public Dictionary <Action, double> GetValue(State s, FriendQTable q) { var context = SolverContext.GetContext(); var model = context.CreateModel(); var actionDecisions = new List <Decision>(); foreach (var action in Enum.GetNames(typeof(Action))) { var decision = new Decision(Domain.RealNonnegative, action); model.AddDecisions(decision); actionDecisions.Add(decision); } var valueDecision = new Decision(Domain.RealNonnegative, "value"); model.AddDecisions(valueDecision); model.AddConstraint("probSumConst", actionDecisions[0] + actionDecisions[1] + actionDecisions[2] + actionDecisions[3] + actionDecisions[4] == 1.0); int constCount = 0; foreach (Action playerOneAction in Enum.GetValues(typeof(Action))) { var qConstraintValues = new List <double>(); foreach (Action playerTwoAction in Enum.GetValues(typeof(Action))) { qConstraintValues.Add(q.GetQValue(s, playerOneAction, playerTwoAction)); } model.AddConstraint("Const" + constCount, qConstraintValues[0] * actionDecisions[0] + qConstraintValues[1] * actionDecisions[1] + qConstraintValues[2] * actionDecisions[2] + qConstraintValues[3] * actionDecisions[3] + qConstraintValues[4] * actionDecisions[4] <= valueDecision); ++constCount; } model.AddGoal("MinimizeV", GoalKind.Minimize, valueDecision); context.Solve(new SimplexDirective()); var pi_s = new Dictionary <Action, double>(); foreach (var actionDec in actionDecisions) { pi_s[(Action)Enum.Parse(typeof(Action), actionDec.Name)] = actionDec.GetDouble(); } context.ClearModel(); return(pi_s); }
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 Deck(List <int> cards) { solver = SolverContext.GetContext(); random = new Random(); deck = new List <int>(40 - cards.Count); for (int i = 0; i < 40; i++) { if (!cards.Contains(i)) { deck.Add(i); } } }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public AssignOrdersStep2(SolverContext context, Schedule schedule, SolveRequestData reqData, AssignOrdersParams inputParams, IList<RouteResult> prevRouteResults, IList<Violation> prevViolations, SolveOptions options) : base(context, schedule, options) { _reqData = reqData; _inputParams = inputParams; _prevRouteResults = prevRouteResults; _prevViolations = prevViolations; }
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(); }
public BuildRoutesOperation(SolverContext context, Schedule schedule, SolveOptions options, SolveRequestData reqData, List<Violation> violations, BuildRoutesParameters inputParams) : base(context, schedule, options) { Debug.Assert(reqData != null); Debug.Assert(violations != null); Debug.Assert(inputParams != null); _reqData = reqData; _violations = violations; _inputParams = inputParams; }
/// <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); }
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(); }
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); }
static void Main(string[] args) { var solver = SolverContext.GetContext(); var model = solver.CreateModel(); double pArroz = 20; double pAceite = 280; double pHabichuela = 25; double presupuesto = 1500; var decisionX = new Decision(Domain.IntegerNonnegative, "Arroz"); var decisionY = new Decision(Domain.IntegerNonnegative, "Aceite"); var decisionZ = new Decision(Domain.IntegerNonnegative, "Habichuela"); model.AddDecision(decisionX); model.AddDecision(decisionY); model.AddDecision(decisionZ); var tGoal = (pArroz * decisionX) + (pAceite * decisionY) + (pHabichuela * decisionZ); model.AddGoal("Meta", GoalKind.Maximize, tGoal); model.AddConstraint("cantminX", decisionX >= 20); model.AddConstraint("cantmaxX", decisionX <= 40); model.AddConstraint("cantminY", decisionY >= 1); model.AddConstraint("cantmaxY", decisionY <= 3); model.AddConstraint("cantminZ", decisionZ >= 1); model.AddConstraint("cantmaxZ", decisionZ <= 3); model.AddConstraint("Total", tGoal >= 1); model.AddConstraint("Solucion", tGoal <= presupuesto); solver.CheckModel(); var solution = solver.Solve(); var qa = solution.Quality; var gls = solution.Goals; double x = decisionX.GetDouble(); double y = decisionY.GetDouble(); double z = decisionZ.GetDouble(); double total = (x * pArroz) + (y * pAceite) + (z * pHabichuela); Console.WriteLine("Cantidades Máximas: "); Console.WriteLine("Arroz: " + x + " - Aceite: " + y + " - Habichuela: " + z); Console.WriteLine("Solución: " + total); Report r = solution.GetReport(); using (StreamWriter sw = new StreamWriter("ejemplo1.txt")) { solver.SaveModel(FileFormat.FreeMPS, sw); } }
static void LoadModel(SolverContext context, string fileName) { string ext = Path.GetExtension(fileName).ToLower(); if (ext == ".mps") { context.LoadModel(FileFormat.MPS, Path.GetFullPath(fileName)); } else if (ext == ".smps") { context.LoadModel(FileFormat.SMPS, Path.GetFullPath(fileName)); } else if (ext == ".oml") { context.LoadModel(FileFormat.OML, Path.GetFullPath(fileName)); } else { throw new NotSupportedException("This file format hasn't been supported."); } }
/// <summary> /// Checks if orders for the specified schedule could be assigned /// without solving. /// </summary> /// <param name="context">Solve operation context.</param> /// <param name="schedule">Schedule to take orders from.</param> /// <returns>True if and only if orders for the specified schedule /// could be assigned without solving</returns> public static bool CanGetResultWithoutSolve( SolverContext context, Schedule schedule) { // get orders planned on schedule's date var dayOrders = context.Project.Orders.Search( (DateTime)schedule.PlannedDate); // check if we have at least one geocoded order bool haveGeocodedOrders = false; foreach (var order in dayOrders) { if (order.IsGeocoded) { haveGeocodedOrders = true; break; } } return !haveGeocodedOrders; }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public SequenceRoutesReqBuilder(SolverContext context) : base(context) { }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public BuildRoutesReqBuilder(SolverContext context) : base(context) { }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Constructor. /// </summary> /// <param name="context">The reference to the solver context object.</param> public VrpRequestBuilder(SolverContext context) { _context = context; }
public Report GetReport(SolverContext context, Solution solution, SolutionMapping solutionMapping) { LinearSolutionMapping lpSolutionMapping = solutionMapping as LinearSolutionMapping; if (lpSolutionMapping == null && solutionMapping != null) throw new ArgumentException("solutionMapping is not a LinearSolutionMapping", "solutionMapping"); return new Z3LinearSolverReport(context, this, solution, lpSolutionMapping); }
public Z3LinearSolverReport(SolverContext context, ISolver solver, Solution solution, LinearSolutionMapping solutionMapping) : base(context, solver, solution, solutionMapping) { }
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); }
public Z3TermSolverReport(SolverContext context, ISolver solver, Solution solution, PluginSolutionMapping pluginSolutionMapping) : base(context, solver, solution, pluginSolutionMapping) { }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <c>RouteRequestBuilder</c> class. /// </summary> /// <param name="context">Solver context.</param> public RouteRequestBuilder(SolverContext context) { _context = context; }