Пример #1
0
        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();
        }
Пример #2
0
    //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);
    }
Пример #3
0
        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 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 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));
        }
Пример #6
0
        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);
        }
Пример #7
0
        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);
        }
Пример #8
0
        /// <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);
        }
Пример #9
0
        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());
        }
Пример #10
0
        private void InitializeDecisions()
        {
            makespan = new Decision(Domain.RealNonnegative, "makespan");
            isActive = new Decision(Domain.IntegerRange(0, 1), "isActive", tasks, events);
            start    = new Decision(Domain.RealNonnegative, "start", events);

            machineSpeed = new Decision(Domain.Set(1, 2), "machineSpeed", events);

            model.AddDecisions(makespan, isActive, start, machineSpeed);
        }
Пример #11
0
        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());
        }
        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();
        }
Пример #14
0
        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
        }
Пример #15
0
        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));
        }
Пример #16
0
        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);
        }
Пример #17
0
        private void button1_Click(object sender, EventArgs e)
        {
            SolverContext context = SolverContext.GetContext();
            Model         model   = context.CreateModel();

            Decision x11 = new Decision(Domain.IntegerNonnegative, "x11");
            Decision x12 = new Decision(Domain.IntegerNonnegative, "x12");
            Decision x13 = new Decision(Domain.IntegerNonnegative, "x13");
            Decision x14 = new Decision(Domain.IntegerNonnegative, "x14");
            Decision x15 = new Decision(Domain.IntegerNonnegative, "x15");
            Decision x21 = new Decision(Domain.IntegerNonnegative, "x21");
            Decision x22 = new Decision(Domain.IntegerNonnegative, "x22");
            Decision x23 = new Decision(Domain.IntegerNonnegative, "x23");
            Decision x24 = new Decision(Domain.IntegerNonnegative, "x24");
            Decision x25 = new Decision(Domain.IntegerNonnegative, "x25");
            Decision x31 = new Decision(Domain.IntegerNonnegative, "x31");
            Decision x32 = new Decision(Domain.IntegerNonnegative, "x32");
            Decision x33 = new Decision(Domain.IntegerNonnegative, "x33");
            Decision x34 = new Decision(Domain.IntegerNonnegative, "x34");
            Decision x35 = new Decision(Domain.IntegerNonnegative, "x35");
            Decision x41 = new Decision(Domain.IntegerNonnegative, "x41");
            Decision x42 = new Decision(Domain.IntegerNonnegative, "x42");
            Decision x43 = new Decision(Domain.IntegerNonnegative, "x43");
            Decision x44 = new Decision(Domain.IntegerNonnegative, "x44");
            Decision x45 = new Decision(Domain.IntegerNonnegative, "x45");
            Decision x51 = new Decision(Domain.IntegerNonnegative, "x51");
            Decision x52 = new Decision(Domain.IntegerNonnegative, "x52");
            Decision x53 = new Decision(Domain.IntegerNonnegative, "x53");
            Decision x54 = new Decision(Domain.IntegerNonnegative, "x54");
            Decision x55 = new Decision(Domain.IntegerNonnegative, "x55");

            model.AddDecisions(x11, x12, x13, x14, x15,
                               x21, x22, x23, x24, x25,
                               x31, x32, x33, x34, x35,
                               x41, x42, x43, x44, x45,
                               x51, x52, x53, x54, x55);

            model.AddConstraint("Row1", x11 + x12 + x13 + x14 + x15 >= 70);
            model.AddConstraint("Row2", x21 + x22 + x23 + x24 + x25 >= 80);
            model.AddConstraint("Row3", x31 + x32 + x33 + x34 + x35 >= 90);
            model.AddConstraint("Row4", x41 + x42 + x43 + x44 + x45 >= 85);
            model.AddConstraint("Row5", x51 + x52 + x53 + x54 + x55 >= 90);
            model.AddConstraint("Row6", x11 + x21 + x31 + x41 + x51 >= 110);
            model.AddConstraint("Row7", x12 + x22 + x32 + x42 + x52 >= 120);
            model.AddConstraint("Row8", x13 + x23 + x33 + x43 + x53 >= 130);
            model.AddConstraint("Row9", x14 + x24 + x34 + x44 + x54 >= 120);
            model.AddConstraint("Row10", x15 + x25 + x35 + x45 + x55 >= 100);


            model.AddGoal("Goal", GoalKind.Minimize, x11 + x12 + x13 + x14 + x15 +
                          x21 + x22 + x23 + x24 + x25 +
                          x31 + x32 + x33 + x34 + x35 +
                          x41 + x42 + x43 + x44 + x45 +
                          x51 + x52 + x53 + x54 + x55);

            Solution solution = context.Solve(new SimplexDirective());

            Report report = solution.GetReport();

            MessageBox.Show("x11=" + x11.ToString() + ",x12=" + x12.ToString());

            Console.WriteLine("x1: {0}, x2: {1}, x3: {2}", x11, x12, x13, x14, x15,
                              x21, x22, x23, x24, x25,
                              x31, x32, x33, x34, x35,
                              x41, x42, x43, x44, x45,
                              x51, x52, x53, x54, x55);
            Console.Write("{0}", report);
            Console.ReadLine();
        }
Пример #18
0
        private void bt_Ras_Click(object sender, EventArgs e)
        {
            if (
                #region ---
                (tb_Cu1.Text == "") ||
                (tb_Cu2.Text == "") ||
                (tb_Sn1.Text == "") ||
                (tb_Sn2.Text == "") ||
                (tb_Zn1.Text == "") ||
                (tb_Zn2.Text == "") ||
                (tb_St1.Text == "") ||
                (tb_St2.Text == ""))
            #endregion ---
            {
                Grafick.Parent = null;
                MessageBox.Show("Не все поля заполнены!", "Ошибка");
                return;
            }
            else
            {
                Grafick.Parent = tabControl1;

                chart1.Series[0].Points.Clear();
                chart1.Series[1].Points.Clear();

                st.Cu1 = Double.Parse(tb_Cu1.Text);
                st.Cu2 = Double.Parse(tb_Cu2.Text);
                st.Sn1 = Double.Parse(tb_Sn1.Text);
                st.Sn2 = Double.Parse(tb_Sn1.Text);
                st.Zn1 = Double.Parse(tb_Zn1.Text);
                st.Zn2 = Double.Parse(tb_Zn2.Text);
                st.St1 = Double.Parse(tb_St1.Text);
                st.St2 = Double.Parse(tb_St2.Text);


                List <SolverRow> solverList = new List <SolverRow>();
                solverList.Add(new SolverRow {
                    xId = 1, Koef = st.Ras_Sp1
                });
                solverList.Add(new SolverRow {
                    xId = 2, Koef = st.Ras_Sp2
                });


                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("Ogran1", Model.Sum(Model.ForEach(users, xId => (st.Cu1 * st.Ras_Sp1 + st.Cu2 * st.Ras_Sp2) * 0.01)) <= 2);
                model.AddConstraint("Ogran2", Model.Sum(Model.ForEach(users, xId => (st.Sn1 * st.Ras_Sp1 + st.Sn2 * st.Ras_Sp2) * 0.01)) <= 1000);
                model.AddConstraint("Ogran3", Model.Sum(Model.ForEach(users, xId => (st.Zn1 * st.Ras_Sp1 + st.Zn2 * st.Ras_Sp2) * 0.01)) <= 12.8);


                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 Ras_Sp1 = Math.Round(choose.GetDouble(solverList[0].xId), 3);
                double Ras_Sp2 = Math.Round(choose.GetDouble(solverList[1].xId), 3);


                this.chart1.Series[0].Points.AddXY("", st.Ras_Sp1);
                this.chart1.Series[1].Points.AddXY("", st.Ras_Sp2);

                dataGridView1.Rows.Add(st.Ras_Sp1, st.Ras_Sp2, st.Ras_O_St);
            }
        }
Пример #19
0
        public DecisionesCiudad(Model model, string prefix)
        {
            Transporte = new DecisionesMovimiento(model, prefix);

            AgrandarAlmacen = new Decision(Domain.Boolean, prefix + "_agrandarAlmacen");
            AlmacenamientoPropio = new Decision(Domain.IntegerNonnegative, prefix + "_almacenPropio");
            Detencion = new Decision(Domain.IntegerNonnegative, prefix + "_Detencion");
            model.AddDecisions((Decision)AgrandarAlmacen, (Decision)AlmacenamientoPropio, (Decision)Detencion);
        }
Пример #20
0
        public DecisionesMovimiento(Model model, string prefix)
        {
            Aereo = new Decision(Domain.IntegerNonnegative, prefix + "_transporte_Aereo");
            Terrestre = new Decision(Domain.IntegerNonnegative, prefix + "_transporte_Terrestre");

            model.AddDecisions((Decision)Aereo, (Decision)Terrestre);
        }
Пример #21
0
        public DecisionesSemanales(Model model, string prefix, string monopolis, string bipolis, string tripolis, string tetrapolis, string metropolis)
        {
            AgrandarAlmacen = new Decision(Domain.Boolean, prefix + "_agrandarAlmacen");
            AlquilarAlmacen = new Decision(Domain.Boolean, prefix + "_alquilarAlmacen");
            UnidadesAProducir = new Decision(Domain.IntegerNonnegative, prefix + "_unidadesAProducir");

            model.AddDecisions((Decision)AgrandarAlmacen, (Decision)AlquilarAlmacen, (Decision)UnidadesAProducir);

            Alternic = new DecisionesMateriaPrima(model, prefix + "_alternic");
            Nikelen = new DecisionesMateriaPrima(model, prefix + "_nikelen");
            Progesic = new DecisionesMateriaPrima(model, prefix + "_progesic");

            Monopolis = new DecisionesCiudad(model, prefix + "_" + monopolis);
            Bipolis = new DecisionesCiudad(model, prefix + "_" + bipolis);
            Tripolis = new DecisionesCiudad(model, prefix + "_" + tripolis);
            Tetrapolis = new DecisionesCiudad(model, prefix + "_" + tetrapolis);
            Metropolis = new DecisionesCiudad(model, prefix + "_" + metropolis);

            model.AddConstraint(prefix + "_constraint_unidadesAProducir", UnidadesAProducir <= 3370);
        }
Пример #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            Stenka_Model sm = new Stenka_Model();

            if (Tb_l_ogn.Text == "" || Tb_l_1.Text == "" || Tb_l_2.Text == "" || Tb_C1.Text == "" || Tb_C2.Text == "" || Tb_x0.Text == "" || Tb_trab.Text == "" || Tb_tokr.Text == "" || Tb_tnp.Text == "" || Tb_anar.Text == "" || Tb_arab.Text == "")
            {
                MessageBox.Show("Не все поля заполнены!", "Ошибка");
                return;
            }
            else
            {
                tp_Graph.Parent = Tab_cont;
                chart1.Series[0].Points.Clear();
                chart1.Series[1].Points.Clear();
                sm.l_ogn = Double.Parse(Tb_l_ogn.Text);
                sm.l_1   = Double.Parse(Tb_l_1.Text);
                sm.l_2   = Double.Parse(Tb_l_2.Text);
                sm.c1    = Double.Parse(Tb_C1.Text);
                sm.c2    = Double.Parse(Tb_C2.Text);
                sm.x0    = Double.Parse(Tb_x0.Text);
                sm.t_rab = Double.Parse(Tb_trab.Text);
                sm.t_okr = Double.Parse(Tb_tokr.Text);
                sm.t_np  = Double.Parse(Tb_tnp.Text);
                sm.a_nar = Double.Parse(Tb_anar.Text);
                sm.a_rab = Double.Parse(Tb_arab.Text);
                List <SolverRow> solverList = new List <SolverRow>();
                solverList.Add(new SolverRow {
                    xId = 1, Koef_C = sm.c1
                });
                solverList.Add(new SolverRow {
                    xId = 2, Koef_C = sm.c2
                });
                SolverContext cntxt = SolverContext.GetContext();
                cntxt.ClearModel();
                Model model = cntxt.CreateModel();
                Set   users = new Set(Domain.Any, "users");

                //Parameter l_ogn = new Parameter(Domain.Real, "l_ogn", users);
                //l_ogn.SetBinding ()
                Parameter Koef_C = new Parameter(Domain.Real, "Koef_C", users);
                Koef_C.SetBinding(solverList, "Koef_C", "xId");
                model.AddParameter(Koef_C);

                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_C[xId])));

                //model.AddConstraint("c_choose", Model.ForEach(users, xId => (min[xId] <= choose[xId] <= max[xId])));

                model.AddConstraint("X1", choose[1] >= 0);
                model.AddConstraint("X2", choose[2] >= 0);
                model.AddConstraint("X_Sum", Model.Sum(Model.ForEach(users, xId => choose[xId])) <= sm.x0 / 1000d);
                model.AddConstraint("Temp", sm.t_okr <= sm.t_np);
                model.AddConstraint("K_sigma", (sm.t_np - (sm.t_okr + ((sm.t_rab - sm.t_okr) / (((1 / sm.a_rab) + (choose[1] / sm.l_1) + (choose[2] / sm.l_2) + (1 / sm.a_nar)) * sm.a_nar)))) >= 0);

                try
                {
                    Solution solution = cntxt.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();

                    //MessageBox.Show(reportStr);
                }
                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);
                this.chart1.Series[0].Points.AddXY("Толщина стенок, м", x1);
                this.chart1.Series[1].Points.AddXY("Толщина стенок, м", x2);
                if (dataGridView1.RowCount == 1)
                {
                    dataGridView1[0, 0].Value = x1;
                    dataGridView1[1, 0].Value = x2;
                }
                else
                {
                    dataGridView1.Rows.Add(x1, x2);
                }
            }
        }
Пример #23
0
        public DecisionesAlmacenMP(Model model, string prefix)
        {
            AlmacenPropio = new Decision(Domain.IntegerNonnegative, prefix + "_AlmacenPropio");
            AlmacenAlquilado = new Decision(Domain.IntegerNonnegative, prefix + "_AlmacenAlquilado");
            Detencion = new Decision(Domain.IntegerNonnegative, prefix + "_Detencion");

            model.AddDecisions((Decision)AlmacenPropio, (Decision)AlmacenAlquilado, (Decision)Detencion);
        }
Пример #24
0
        public void PerformSimplex()
        {
            IEnumerable <Event> events     = _eventService.FindEventsWithBlobs();
            List <string>       ids        = new List <string>();
            List <ulong>        size       = new List <ulong>();
            List <int>          attendees  = new List <int>();
            List <DateTime>     createDate = new List <DateTime>();
            List <DateTime>     startDate  = new List <DateTime>();

            if (events.Count() > 0)
            {
                foreach (Event e in events)
                {
                    foreach (Post p in e.Posts)
                    {
                        if (p.MediaItem != null)
                        {
                            ids.Add(p.MediaItem.FooCDNBlob);
                            size.Add(p.MediaItem.Size);
                            if (e.RSVPs != null && e.RSVPs.Count > 0)
                            {
                                attendees.Add(e.RSVPs.Count(r => r.Response == RSVPStatus.Yes));
                                createDate.Add(e.CreationTime);
                                startDate.Add(e.EventTime.StartTime);
                            }
                        }
                    }
                }

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

                //string[] ids = { "1", "2", "3" };
                string[] types = { "MEMCACHE", "DISK", "TAPE" };

                //ulong[] size = { 334, 567, 278 }; // in bytes
                //int[] invitees = { 20, 12, 14 };
                //DateTime[] createDate = { new DateTime(2014, 4, 20), new DateTime(2014, 4, 18), new DateTime(2014, 4, 22) };
                //DateTime[] eventDate = { new DateTime(2014, 4, 26), new DateTime(2014, 4, 21), new DateTime(2014, 4, 24) };
                int[] scores = new int[ids.Count];
                for (int i = 0; i < scores.Length; i++)
                {
                    scores[i] = GetScores(attendees[i], createDate[i], startDate[i]);
                }
                Decision[][] decs = new Decision[ids.Count][];
                for (int i = 0; i < ids.Count; i++)
                {
                    decs[i] = new Decision[3];
                    for (int j = 0; j < 3; j++)
                    {
                        decs[i][j] = new Decision(Domain.IntegerNonnegative, String.Format("dec_{0}_{1}", i, j));
                    }
                    model.AddDecisions(decs[i][0], decs[i][1], decs[i][2]);
                    model.AddConstraint(String.Format("con_{0}", i), decs[i][0] + decs[i][1] + decs[i][2] == 1);
                }
                double[] storageCosts     = { .000000000025, .0000000000025, 0 };
                double[] servingcosts     = { .0000000003, .0000000001, 0 };
                int[]    typeWeights      = { 10, 4, 1 };
                string   constraintString = String.Format("{0} * {1} * {2} + {0} * {1} * {3} * {4} + {5} * {1} * {6} + {5} * {1} * {3} * {7} + {8} * {1} * {9} + {8} * {1} * {3} * {10}", decs[0][0].Name, size[0], storageCosts[0], scores[0], servingcosts[0], decs[0][1].Name, storageCosts[1], servingcosts[1], decs[0][2].Name, storageCosts[2], servingcosts[2]);
                string   goalString       = String.Format("{1} * {0} * {2} + {3} * {0} * {4} + {5} * {0} * {6}", scores[0], decs[0][0].Name, typeWeights[0], decs[0][1].Name, typeWeights[1], decs[0][2].Name, typeWeights[2]);
                for (int i = 1; i < decs.Length; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        constraintString = String.Format("{0} + {1} * {2} * {3} + {1} * {2} * {4} * {5}", constraintString, decs[i][j].Name, size[i], storageCosts[j], scores[i], servingcosts[j]);
                        goalString       = String.Format("{0} + {1} * {2} * {3}", goalString, decs[i][j].Name, scores[i], typeWeights[j]);
                    }
                }
                constraintString = String.Format("{0} <= 15", constraintString);
                model.AddConstraint("money_con", constraintString);
                model.AddGoal("goal", GoalKind.Maximize, goalString);

                Solution solution = context.Solve(new SimplexDirective());
                for (int i = 0; i < ids.Count; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (decs[i][j].GetDouble() == 1)
                        {
                            _fooCDNService.PutBlob(ids[i], types[j]);
                        }
                    }
                }
            }
        }
Пример #25
0
        /// <summary>
        /// Контроллер вывода результатов расчетов
        /// </summary>
        /// <returns>Результаты расчета</returns>
        public IActionResult Results(InputValues data)
        {
            double FullMassComponents = data.FullMassComponents;

            data.FullMassComponents = 100;
            double Cof = FullMassComponents / 100; // Коофицент для интерполяции массы от 100
            ////////////////// Поиск решений
            SolverContext problem = SolverContext.GetContext();
            Model         model   = problem.CreateModel();

            Decision[] component = new Decision[8];

            for (int i = 0; i < 7; i++)
            {
                // Задаем данные модели
                component[i] = new Decision(Domain.Real, $"Num{i}");
            }

            // Общая стоимость
            component[7] = new Decision(Domain.Real, $"Cost");

            // Связываем модель и данные
            model.AddDecisions(component);

            // Ограничения
            for (int i = 0; i < 7; i++)
            {
                // Ограничение диапазон значений компонента
                model.AddConstraint($"DiaOgrEl1{i}", component[i] / (data.FullMassComponents / 100) > data.ComponentInputValues[i].MinPercent & component[i] / (data.FullMassComponents / 100) < data.ComponentInputValues[i].MaxPercent);
            }

            // Чему равна общая стоимость всех компонентов
            model.AddConstraint($"DiaOgrCost", component[7] ==
                                (
                                    component[0] * data.ComponentInputValues[0].Cost +
                                    component[1] * data.ComponentInputValues[1].Cost +
                                    component[2] * data.ComponentInputValues[2].Cost +
                                    component[3] * data.ComponentInputValues[3].Cost +
                                    component[4] * data.ComponentInputValues[4].Cost +
                                    component[5] * data.ComponentInputValues[5].Cost +
                                    component[6] * data.ComponentInputValues[6].Cost
                                ));
            // Ограничение суммы компонентов
            model.AddConstraint($"DiaOgrSumm", (component[0] + component[1] + component[2] + component[3] + component[4] + component[5] + component[6]) == data.FullMassComponents);

            // Общие Содержание Si
            model.AddConstraint($"DiaOgrSi",
                                (
                                    (component[0] * data.ComponentInputValues[0].PercentSi / 100)
                                    + (component[1] * data.ComponentInputValues[1].PercentSi / 100)
                                    + (component[2] * data.ComponentInputValues[2].PercentSi / 100)
                                    + (component[3] * data.ComponentInputValues[3].PercentSi / 100)
                                    + (component[4] * data.ComponentInputValues[4].PercentSi / 100)
                                    + (component[5] * data.ComponentInputValues[5].PercentSi / 100)
                                    + (component[6] * data.ComponentInputValues[6].PercentSi / 100)
                                ) / (data.FullMassComponents / 100)
                                > data.MinPercentSi &
                                (
                                    (component[0] * data.ComponentInputValues[0].PercentSi / 100)
                                    + (component[1] * data.ComponentInputValues[1].PercentSi / 100)
                                    + (component[2] * data.ComponentInputValues[2].PercentSi / 100)
                                    + (component[3] * data.ComponentInputValues[3].PercentSi / 100)
                                    + (component[4] * data.ComponentInputValues[4].PercentSi / 100)
                                    + (component[5] * data.ComponentInputValues[5].PercentSi / 100)
                                    + (component[6] * data.ComponentInputValues[6].PercentSi / 100)
                                )
                                < data.MaxPercentSi);

            // Общие Содержание Mn
            model.AddConstraint($"DiaOgrMn",
                                (
                                    (component[0] * data.ComponentInputValues[0].PercentMn / 100)
                                    + (component[1] * data.ComponentInputValues[1].PercentMn / 100)
                                    + (component[2] * data.ComponentInputValues[2].PercentMn / 100)
                                    + (component[3] * data.ComponentInputValues[3].PercentMn / 100)
                                    + (component[4] * data.ComponentInputValues[4].PercentMn / 100)
                                    + (component[5] * data.ComponentInputValues[5].PercentMn / 100)
                                    + (component[6] * data.ComponentInputValues[6].PercentMn / 100)
                                ) / (data.FullMassComponents / 100)
                                > data.MinPercentMn &
                                (
                                    (component[0] * data.ComponentInputValues[0].PercentMn / 100)
                                    + (component[1] * data.ComponentInputValues[1].PercentMn / 100)
                                    + (component[2] * data.ComponentInputValues[2].PercentMn / 100)
                                    + (component[3] * data.ComponentInputValues[3].PercentMn / 100)
                                    + (component[4] * data.ComponentInputValues[4].PercentMn / 100)
                                    + (component[5] * data.ComponentInputValues[5].PercentMn / 100)
                                    + (component[6] * data.ComponentInputValues[6].PercentMn / 100)
                                )
                                < data.MaxPercentMn);

            // Найти минимальную цену
            model.AddGoal("goal", GoalKind.Minimize, component[7]);

            // Расчет
            Solution solution = problem.Solve();
            //////////////////// Конец поиска решений

            // Начало теста
            Results results = new Results();

            for (int i = 0; i < 7; i++)
            {
                results.ComponentResults.Add(new ComponentResult()
                {
                    Name = data.ComponentInputValues[i].Name, Cost = component[i].ToDouble() * Cof * data.ComponentInputValues[i].Cost, PercentMass = component[i].ToDouble() * Cof / (data.FullMassComponents / 100), FullMass = component[i].ToDouble() * Cof, MnMass = (component[i].ToDouble() * Cof * data.ComponentInputValues[i].PercentMn / 100) / (data.FullMassComponents / 100), SiMass = (component[i].ToDouble() * Cof * data.ComponentInputValues[i].PercentSi / 100) / (data.FullMassComponents / 100)
                });
            }
            results.AllComponentResult = results.AllResult();
            // Конец теста

            return(View(results));
        }
Пример #26
0
        public void Solve(GrilleSudoku s)
        {
            SolverContext problem = SolverContext.GetContext();
            Model         model   = problem.CreateModel();

            Decision[][] grid = new Decision[9][]; // 0-based indices, 1-based values
            for (int r = 0; r < 9; ++r)
            {
                grid[r] = new Decision[9];
            }

            for (int r = 0; r < 9; ++r)
            {
                for (int c = 0; c < 9; ++c)
                {
                    grid[r][c] = new Decision(Domain.IntegerRange(1, 9), "grid" + r + c);
                }
            }

            for (int r = 0; r < 9; ++r)
            {
                model.AddDecisions(grid[r]);
            }

            //for (int r = 0; r < 9; ++r) // alternative to above
            //  for (int c = 0; c < 9; ++c)
            //    model.AddDecisions(grid[r][c]);

            Console.WriteLine("\nCreating generic row constraints");
            for (int r = 0; r < 9; ++r)
            {
                model.AddConstraint("rowConstraint" + r, Model.AllDifferent(grid[r]));
            }

            Console.WriteLine("Creating generic column constraints");
            for (int c = 0; c < 9; ++c)
            {
                for (int first = 0; first < 8; ++first)
                {
                    for (int second = first + 1; second < 9; ++second)
                    {
                        model.AddConstraint("colConstraint" + c + first + second, grid[first][c] != grid[second][c]);
                    }
                }
            }

            Console.WriteLine("Creating generic sub-cube constraints");
            // cube constraints for grid[a][b] and grid[x][y]
            for (int r = 0; r < 9; r += 3)
            {
                for (int c = 0; c < 9; c += 3)
                {
                    for (int a = r; a < r + 3; ++a)
                    {
                        for (int b = c; b < c + 3; ++b)
                        {
                            for (int x = r; x < r + 3; ++x)
                            {
                                for (int y = c; y < c + 3; ++y)
                                {
                                    if ((x == a && y > b) || (x > a))
                                    { // xy > ab
                                        model.AddConstraint("cubeConstraint" + a + b + x + y, grid[a][b] != grid[x][y]);
                                    }
                                } // y
                            }     // x
                        }         // b
                    }             // a
                }                 // c
            }                     // r

            Console.WriteLine("Creating problem specific data constraints");

            // brute force approach:
            //model.AddConstraint("v02", grid[0][2] == 6);
            //model.AddConstraint("v03", grid[0][3] == 2);
            //model.AddConstraint("v07", grid[0][7] == 8);

            //model.AddConstraint("v12", grid[1][2] == 8);
            //model.AddConstraint("v13", grid[1][3] == 9);
            //model.AddConstraint("v14", grid[1][4] == 7);

            //model.AddConstraint("v22", grid[2][2] == 4);
            //model.AddConstraint("v23", grid[2][3] == 8);
            //model.AddConstraint("v24", grid[2][4] == 1);
            //model.AddConstraint("v26", grid[2][6] == 5);

            //model.AddConstraint("v34", grid[3][4] == 6);
            //model.AddConstraint("v38", grid[3][8] == 2);

            //model.AddConstraint("v41", grid[4][1] == 7);
            //model.AddConstraint("v47", grid[4][7] == 3);

            //model.AddConstraint("v50", grid[5][0] == 6);
            //model.AddConstraint("v54", grid[5][4] == 5);

            //model.AddConstraint("v62", grid[6][2] == 2);
            //model.AddConstraint("v64", grid[6][4] == 4);
            //model.AddConstraint("v65", grid[6][5] == 7);
            //model.AddConstraint("v66", grid[6][6] == 1);

            //model.AddConstraint("v72", grid[7][2] == 3);
            //model.AddConstraint("v74", grid[7][4] == 2);
            //model.AddConstraint("v75", grid[7][5] == 8);
            //model.AddConstraint("v76", grid[7][6] == 4);

            //model.AddConstraint("v81", grid[8][1] == 5);
            //model.AddConstraint("v85", grid[8][5] == 1);
            //model.AddConstraint("v86", grid[8][6] == 2);
            ////model.AddConstraint("v86", grid[8][6] == 4); // creates unsolvable problem

            AddDataConstraints(s, model, grid); // more elegant approach

            Console.WriteLine("\nSolving. . . ");

            int numSolutions = NumberSolutions(problem);

            Console.WriteLine("\nThere is/are " + numSolutions + " Solution(s)\n");

            Solution solution = problem.Solve();

            //ShowAnswer(grid); // alternative to below

            for (int r = 0; r < 9; ++r)
            {
                for (int c = 0; c < 9; ++c)
                {
                    double v = grid[r][c].GetDouble();
                    //Console.Write(" " + v);
                    s.SetCell(r, c, (int)v);
                }
            }
        }
Пример #27
0
        static void Main(string[] args)
        {
            try
            {
                /*CREACIÓN DEL PROBLEMA*/
                Console.WriteLine("CREACIÓN DEL PROBLEMA");

                //Crea una instancia de SolverContext bajo el patron de diseño Singleton
                SolverContext contexto = SolverContext.GetContext();

                //Esta variable almacena todo el modelo mátematico del problema
                Model model = contexto.CreateModel();

                /*VARIABLES DEL PROBLEMA*/
                Console.WriteLine("VARIABLES DEL PROBLEMA");

                //Se define el dominio de las variables del problema y su nombre
                Decision x1a = new Decision(Domain.IntegerNonnegative, "x1a");
                Decision x1b = new Decision(Domain.IntegerNonnegative, "x1b");
                Decision x1c = new Decision(Domain.IntegerNonnegative, "x1c");
                Decision x2a = new Decision(Domain.IntegerNonnegative, "x2a");
                Decision x2b = new Decision(Domain.IntegerNonnegative, "x2b");
                Decision x2c = new Decision(Domain.IntegerNonnegative, "x2c");
                Decision x3a = new Decision(Domain.IntegerNonnegative, "x3a");
                Decision x3b = new Decision(Domain.IntegerNonnegative, "x3b");
                Decision x3c = new Decision(Domain.IntegerNonnegative, "x3c");

                //Las variables creadas son adicionadas al modelo del problema
                model.AddDecisions(new Decision[] { x1a, x1b, x1c, x2a, x2b, x2c, x3a, x3b, x3c });

                /*RESTRICCIONES DEL PROBLEMA*/
                Console.WriteLine("RESTRICCIONES DEL PROBLEMA");

                //Restricciones de capacidad en toneladas de las bodegas
                //X1A + X1B + X1C ≤ 2000
                model.AddConstraint("rCapacidadToneladasX1", x1a + x1b + x1c <= 100);
                //X2A + X2B + X2C ≤ 1500
                model.AddConstraint("rCapacidadToneladasX2", x2a + x2b + x2c <= 110);
                //X3A + X3B + X3C ≤ 3000
                model.AddConstraint("rCapacidadToneladasX3", x3a + x3b + x3c <= 120);

                //Restricciones de capacidad en volumen de las bodegas
                //60X1A + 50X1B + 25X1C ≤ 100000
                model.AddConstraint("rCapacidadVolumenX1", 60 * x1a + 50 * x1b + 25 * x1c <= 1600);
                //60X2A + 50X2B + 25X2C ≤ 300000
                model.AddConstraint("rCapacidadVolumenX2", 60 * x2a + 50 * x2b + 25 * x2c <= 1700);
                //60X3A + 50X3B + 25X3C ≤ 135000
                model.AddConstraint("rCapacidadVolumenX3", 60 * x3a + 50 * x3b + 25 * x3c <= 5000);

                //Restricciones de oferta en toneladas de cada tipo de carga
                //X1A + X2A + X3A ≤ 6000
                model.AddConstraint("rToneladasTipoCarga1", x1a + x2a + x3a <= 50);
                //X1B + X2B + X3B ≤ 4000
                model.AddConstraint("rToneladasTipoCarga2", x1b + x2b + x3b <= 120);
                //X1C + X2C + X3C ≤ 2000
                model.AddConstraint("rToneladasTipoCarga3", x1c + x2c + x3c <= 100);

                //Restricciones de porcentaje igual
                //3X1A + 3X1B + 3X1C - 4X2A - 4X2B - 4X2C = 0
                model.AddConstraint("Porcentaje1", 11 * (x1a + x1b + x1c) - 10 * (x2a + x2b + x2c) == 0);
                //3X1A + 3X1B + 3X1C - 2X3A - 2X3B - 2X3C = 0
                model.AddConstraint("Porcentaje2", 6 * (x1a + x1b + x1c) - 5 * (x3a + x3b + x3c) == 0);

                /*OPTIMIZACIÓN DEL PROBLEMA*/

                model.AddGoal("Maximo", GoalKind.Maximize, 6 * (x1a + x1b + x1c) + 8 * (x2a + x2b + x2c) + 5 * (x3a + x3b + x3c));

                /*SOLUCIÓN*/
                Console.WriteLine("SOLUCIÓN");

                var solucion = contexto.Solve();

                /*PRESENTACIÓN DE VALORES*/
                Console.WriteLine("PRESENTACIÓN DE VALORES");

                Console.WriteLine("La solución hallada tiene una consideración : " + solucion.Quality.ToString());
                foreach (var i in solucion.Goals)
                {
                    Console.WriteLine("MÁXIMO= " + i.ToDouble());
                }

                Console.WriteLine("VARIABLES");
                foreach (var i in model.Decisions)
                {
                    Console.WriteLine(i.Name + "=" + i.ToDouble());
                }

                Console.WriteLine("RESTRICCIONES");
                foreach (var i in model.Constraints)
                {
                    Console.WriteLine(i.Name + ":\t\t" + i.Expression);
                }

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }
        }
Пример #28
0
        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();
        }
Пример #29
0
        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);
            }
        }
        public void SolverNewItem()
        {
            SolverContext solverContext = SolverContext.GetContext();
            Model         solverModel   = solverContext.CreateModel();

            Parameter id = new Parameter(Domain.IntegerRange(1, 2), nameof(id));

            id.SetBinding(2);
            solverModel.AddParameter(id);

            string[] guids = new string[] { "c87354e7-888b-4a7f-a337-d5e24324b4f1", "10d0e86d-1d6e-4c4e-80c0-2cea387d98a5" };
            Decision guid  = new Decision(Domain.Enum(guids), nameof(guid));

            string[] systemNames = new string[] { "human_nld_fire_bevelvoerder", "object_firetool_watergun" };
            Decision systemName  = new Decision(Domain.Enum(systemNames), nameof(systemName));

            string[] positions = new string[] { "(0,0,0)", "(1,1,1)" };
            Decision position  = new Decision(Domain.Enum(positions), nameof(position));

            string[] rotations = new string[] { "(0,0,0,1)" };
            Decision rotation  = new Decision(Domain.Enum(rotations), nameof(rotation));

            string[] modelGroups = new string[] { "group_12", "default" };
            Decision modelGroup  = new Decision(Domain.Enum(modelGroups), nameof(modelGroup));

            string[] models = new string[] { "asset_human_nld_ic1_fire_bevelvoerder_12", "asset_object_int_fire_watergun" };
            Decision model  = new Decision(Domain.Enum(models), nameof(model));

            int[]    modelVersions = new int[] { 24, 18 };
            Decision modelVersion  = new Decision(Domain.Set(modelVersions), nameof(modelVersion));

            string[] parents = new string[] { "null" };
            Decision parent  = new Decision(Domain.Enum(parents), nameof(parent));

            solverModel.AddDecisions(guid, systemName, position, rotation, modelGroup, model, modelVersion, parent);

            Term guard =
                Model.If(id == 1,
                         guid == guids[0] &
                         systemName == systemNames[0] &
                         position == positions[0] &
                         rotation == rotations[0] &
                         modelGroup == modelGroups[0] &
                         model == models[0] &
                         modelVersion == modelVersions[0] &
                         parent == parents[0],
                         Model.If(id == 2,
                                  guid == guids[1] &
                                  systemName == systemNames[1] &
                                  position == positions[1] &
                                  rotation == rotations[0] &
                                  modelGroup == modelGroups[1] &
                                  model == models[1] &
                                  modelVersion == modelVersions[1] &
                                  parent == parents[0],
                                  false));

            solverModel.AddConstraint(nameof(guard), guard);

            Solution solution = solverContext.Solve(new HybridLocalSearchDirective());

            Report report = solution.GetReport();

            Console.WriteLine("{0}: {1}", nameof(id), id);
            Console.WriteLine("{0}: {1}", nameof(guid), guid);
            Console.WriteLine("{0}: {1}", nameof(systemName), systemName);
            Console.WriteLine("{0}: {1}", nameof(position), position);
            Console.WriteLine("{0}: {1}", nameof(rotation), rotation);
            Console.WriteLine("{0}: {1}", nameof(modelGroup), modelGroup);
            Console.WriteLine("{0}: {1}", nameof(model), model);
            Console.WriteLine("{0}: {1}", nameof(modelVersion), modelVersion);
            Console.WriteLine("{0}: {1}", nameof(parent), parent);
            Console.Write("{0}", report);
        }
Пример #31
0
        public void solve()
        {
            minU = Convert.ToDouble(minUTB.Text);
            maxU = Convert.ToDouble(maxUTB.Text);

            double[,] A;
            double[] U;

            FileInfo newFile = new FileInfo(filePath);

            using (ExcelPackage xlPackage = new ExcelPackage(newFile))
            {
                SolverContext context = SolverContext.GetContext();
                context.ClearModel();
                Model model = context.CreateModel();
                textBlock.Text = "";

                ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];

                A = Parcer.A(worksheet);
                textBlock.Text += Printer.TwoDimensial(A, true);
                U = Parcer.Ust(worksheet);
                textBlock.Text += "\nСтационарные потенциалы:\n" + Printer.OneDimensial(U);


                Decision[] decs = new Decision[A.GetLength(1)];
                for (int i = 0; i < decs.Length; i++)
                {
                    decs[i] = new Decision(Domain.RealNonnegative, "I" + i.ToString());
                }
                model.AddDecisions(decs);

                textBlock.Text += "\nСистема уравнений:\n";
                for (int i = 0; i < A.GetLength(0); i++)
                {
                    string expression = "";
                    string max        = (minU + "<=").Replace(',', '.');
                    string min        = ("<=" + maxU).Replace(',', '.');

                    for (int h = 0; h < decs.Length; h++)
                    {
                        expression += A[i, h] + "*I" + h + "+";
                    }
                    expression += U[i];

                    model.AddConstraint("U" + i, max + expression.Replace(',', '.') + min);
                    textBlock.Text += "КИП" + i + ": U" + i + "=" + expression + "\n";
                }
                model.AddGoal("minI", GoalKind.Minimize, Model.Sum(decs));

                Solution solution = context.Solve(new Directive());
                textBlock.Text += "\nРезультат расчетов:\n";
                for (int h = 0; h < decs.Length; h++)
                {
                    textBlock.Text += decs[h].Name + "=" + decs[h].ToDouble().ToString() + "\n";
                }

                textBlock.Text += "\nПри этом достигаются следующие потенциалы:\n";
                for (int i = 0; i < A.GetLength(0); i++)
                {
                    double Uf = 0;
                    for (int h = 0; h < decs.Length; h++)
                    {
                        Uf += A[i, h] * decs[h].GetDouble();
                    }
                    Uf += U[i];

                    currUChart.Add(new KeyValuePair <string, double>("КИП" + i, Uf));
                    maxUChart.Add(new KeyValuePair <string, double>("КИП" + i, 1.5));
                    minUChart.Add(new KeyValuePair <string, double>("КИП" + i, 0.9));
                    textBlock.Text += "U" + i + " = " + Uf + "\n";
                }

                textBlock.Text += "\nВремя вычисления: " + solution.GetReport().SolveTime.ToString() + "мс\n";
                if (currUChart.Count > 10)
                {
                    chart.Width = 80 * currUChart.Count;
                }
                else
                {
                    chart.Width = double.NaN;
                }
            }
        }
        public void OptFunc(double[,] Forcurve, double[,] injectionVol, double[,] withdrawal)
        {
            double[,] PriceArray   = Forcurve;
            double[,] InjectionVol = injectionVol;
            double[,] Withdrawal   = withdrawal;

            //is a combination from the price spread array....
            double[,] monthspread = new double[12, 12];
            double results = 0;

            for (int row = 0; row < PriceArray.GetLength(0); row++)
            {
                int sprow = row; int i = 1;

                for (int col = sprow; col < PriceArray.GetLength(0) - 1; col++)
                {
                    results = Math.Round(((PriceArray[row + i, 1] - con.Widthdrawl) - (PriceArray[row, 1] + con.Injection)), 5);
                    monthspread[row, sprow + 1] = results;

                    sprow++;
                    i++;
                }
                ;
            }

            Term goal;

            Term[,] ty;
            Term[,] tv;


            SolverContext context = SolverContext.GetContext();                 // Get context environment
            Model         model   = context.CreateModel();                      // Create a new model

            #region decision and constraints
            //need 12 decisions for every month remaining in the year......
            Decision I1  = new Decision(Domain.RealNonnegative, "I1");
            Decision W1  = new Decision(Domain.RealNonnegative, "W1");
            Decision I2  = new Decision(Domain.RealNonnegative, "I2");
            Decision I3  = new Decision(Domain.RealNonnegative, "I3");
            Decision I4  = new Decision(Domain.RealNonnegative, "I4");
            Decision I5  = new Decision(Domain.RealNonnegative, "I5");
            Decision I6  = new Decision(Domain.RealNonnegative, "I6");
            Decision I7  = new Decision(Domain.RealNonnegative, "I7");
            Decision I8  = new Decision(Domain.RealNonnegative, "I8");
            Decision I9  = new Decision(Domain.RealNonnegative, "I9");
            Decision I10 = new Decision(Domain.RealNonnegative, "I10");
            Decision I11 = new Decision(Domain.RealNonnegative, "I11");
            Decision I12 = new Decision(Domain.RealNonnegative, "I12");
            Decision W2  = new Decision(Domain.RealNonnegative, "W2");
            Decision W3  = new Decision(Domain.RealNonnegative, "W3");
            Decision W4  = new Decision(Domain.RealNonnegative, "W4");
            Decision W5  = new Decision(Domain.RealNonnegative, "W5");
            Decision W6  = new Decision(Domain.RealNonnegative, "W6");
            Decision W7  = new Decision(Domain.RealNonnegative, "W7");
            Decision W8  = new Decision(Domain.RealNonnegative, "W8");
            Decision W9  = new Decision(Domain.RealNonnegative, "W9");
            Decision W10 = new Decision(Domain.RealNonnegative, "W10");
            Decision W11 = new Decision(Domain.RealNonnegative, "W11");
            Decision W12 = new Decision(Domain.RealNonnegative, "W12");
            model.AddDecisions(I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, W11, W12);                                     // Add these to the model (this is where the outputs will be stored)

            model.AddConstraints("limits",
                                 //monthly injection withdrawl constraints
                                 W1 + Withdrawal[9, 1] <= con.JulExport,    //13333333.2,
                                 I1 + InjectionVol[9, 1] == con.JanImport,  //0
                                 W2 + Withdrawal[10, 1] <= con.FebExport,   //11999999.88,
                                 I2 + InjectionVol[10, 1] == con.FebImport, //0,
                                 W3 + Withdrawal[11, 1] <= con.MarExport,   //5333333.28,
                                 I3 + InjectionVol[11, 1] == con.MarImport, //0,
                                 W4 + Withdrawal[0, 1] == con.AprExport,    //0,
                                 I4 + InjectionVol[0, 1] == con.AprImport,  //0,
                                 W5 + Withdrawal[1, 1] == con.MayExport,    //0,
                                 I5 + InjectionVol[1, 1] <= con.MayImport,  //3000000,
                                 W6 + Withdrawal[2, 1] == con.JunExport,    //0,
                                 I6 + InjectionVol[2, 1] <= con.JunImport,  //16800000,
                                 W7 + Withdrawal[3, 1] == con.JulExport,    //0,
                                 I7 + InjectionVol[3, 1] <= con.JulImport,  //16800000,
                                 W8 + Withdrawal[4, 1] == con.AugExport,    //0,
                                 I8 + InjectionVol[4, 1] <= con.AugImport,  //12600000,
                                 W9 + Withdrawal[5, 1] == con.SeptExport,   //0,
                                 I9 + InjectionVol[5, 1] <= con.SeptImport, //10800000,
                                 W10 + Withdrawal[6, 1] <= con.OctExport,   //6000000,
                                 I10 + InjectionVol[6, 1] == con.OctImport, //0,
                                 W11 + Withdrawal[7, 1] <= con.NovExport,   //6000000,
                                 I11 + InjectionVol[7, 1] == con.NovImport, //0,
                                 W12 + Withdrawal[8, 1] <= con.DecExport,   //17333333,
                                 I12 + InjectionVol[8, 1] == con.DecImport, //0,

                                                                            //maximum capacity constraints...
                                 I4 -  -W4 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 + I1 - W1 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 + I1 - W1 + I2 - W2 <= con.MaxCap,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 + I1 - W1 + I2 - W2 + I3 - W3 <= con.MaxCap,
                                 //minimum capacity constraints
                                 //you need to take into account any volumes currently in storage...
                                 I4 - W4 >= 0,
                                 I4 - W4 + I5 - W5 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 + I1 - W1 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 + I1 - W1 + I2 - W2 >= 0,
                                 I4 - W4 + I5 - W5 + I6 - W6 + I7 - W7 + I8 - W8 + I9 - W9 + I10 - W10 + I11 - W11 + I12 - W12 + I1 - W1 + I2 - W2 + I3 - W3 == 0
                                 );

            #endregion

            ty = matrix(monthspread);
            tv = new Term[, ] {
                { (I4 - W4), (I5 - W5), (I6 - W6), (I7 - W7), (I8 - W8), (I9 - W9), (I10 - W10), (I11 - W11), (I12 - W12), (I1 - W1), (I2 - W2), (I3 - W3) }
            };

            //to create the goal we need to find the volumes for each month, if injection greater than
            //withdrawals vol is positive vica versa, then multiply by spread and reverse sign to find profit, which is what we want to maximise
            //goal = matMult(matSubtract(tx, tw), ty)[0, 0];
            goal = matMult(tv, ty)[0, 0];
            model.AddGoal("goal", GoalKind.Minimize, goal);

            // Specifying the IPM solver, as we have a quadratic goal
            Solution solution = context.Solve(new InteriorPointMethodDirective());


            //Profit calculation section, you need to store decisions and profit figures......

            //  DataSet SimulationResults = new DataSet();
            #region Fill DataSet

            DataRow rowinfo = Withtable.NewRow();

            rowinfo[0]  = Convert.ToDouble(W4.GetDouble());
            rowinfo[1]  = Convert.ToDouble(W5.GetDouble());
            rowinfo[2]  = Convert.ToDouble(W6.GetDouble());
            rowinfo[3]  = Convert.ToDouble(W7.GetDouble());
            rowinfo[4]  = Convert.ToDouble(W8.GetDouble());
            rowinfo[5]  = Convert.ToDouble(W9.GetDouble());
            rowinfo[6]  = Convert.ToDouble(W10.GetDouble());
            rowinfo[7]  = Convert.ToDouble(W11.GetDouble());
            rowinfo[8]  = Convert.ToDouble(W12.GetDouble());
            rowinfo[9]  = Convert.ToDouble(W1.GetDouble());
            rowinfo[10] = Convert.ToDouble(W2.GetDouble());
            rowinfo[11] = Convert.ToDouble(W3.GetDouble());
            SimulationResults.Tables[1].Rows.Add(rowinfo);

            rowinfo     = Imptable.NewRow();
            rowinfo[0]  = Convert.ToDouble(I4.GetDouble());
            rowinfo[1]  = Convert.ToDouble(I5.GetDouble());
            rowinfo[2]  = Convert.ToDouble(I6.GetDouble());
            rowinfo[3]  = Convert.ToDouble(I7.GetDouble());
            rowinfo[4]  = Convert.ToDouble(I8.GetDouble());
            rowinfo[5]  = Convert.ToDouble(I9.GetDouble());
            rowinfo[6]  = Convert.ToDouble(I10.GetDouble());
            rowinfo[7]  = Convert.ToDouble(I11.GetDouble());
            rowinfo[8]  = Convert.ToDouble(I12.GetDouble());
            rowinfo[9]  = Convert.ToDouble(I1.GetDouble());
            rowinfo[10] = Convert.ToDouble(I2.GetDouble());
            rowinfo[11] = Convert.ToDouble(I3.GetDouble());
            SimulationResults.Tables[2].Rows.Add(rowinfo);

            rowinfo     = Proftable.NewRow();
            rowinfo[0]  = (Convert.ToDouble(W4.GetDouble()) - Convert.ToDouble(I4.GetDouble())) * PriceArray[0, 1] / 100;
            rowinfo[1]  = (Convert.ToDouble(W5.GetDouble()) - Convert.ToDouble(I5.GetDouble())) * PriceArray[1, 1] / 100;
            rowinfo[2]  = (Convert.ToDouble(W6.GetDouble()) - Convert.ToDouble(I6.GetDouble())) * PriceArray[2, 1] / 100;
            rowinfo[3]  = (Convert.ToDouble(W7.GetDouble()) - Convert.ToDouble(I7.GetDouble())) * PriceArray[3, 1] / 100;
            rowinfo[4]  = (Convert.ToDouble(W8.GetDouble()) - Convert.ToDouble(I8.GetDouble())) * PriceArray[4, 1] / 100;
            rowinfo[5]  = (Convert.ToDouble(W9.GetDouble()) - Convert.ToDouble(I9.GetDouble())) * PriceArray[5, 1] / 100;
            rowinfo[6]  = (Convert.ToDouble(W10.GetDouble()) - Convert.ToDouble(I10.GetDouble())) * PriceArray[6, 1] / 100;
            rowinfo[7]  = (Convert.ToDouble(W11.GetDouble()) - Convert.ToDouble(I11.GetDouble())) * PriceArray[7, 1] / 100;
            rowinfo[8]  = (Convert.ToDouble(W12.GetDouble()) - Convert.ToDouble(I12.GetDouble())) * PriceArray[8, 1] / 100;
            rowinfo[9]  = (Convert.ToDouble(W1.GetDouble()) - Convert.ToDouble(I1.GetDouble())) * PriceArray[9, 1] / 100;
            rowinfo[10] = (Convert.ToDouble(W2.GetDouble()) - Convert.ToDouble(I2.GetDouble())) * PriceArray[10, 1] / 100;
            rowinfo[11] = (Convert.ToDouble(W3.GetDouble()) - Convert.ToDouble(I3.GetDouble())) * PriceArray[11, 1] / 100;
            rowinfo[12] = ((double)rowinfo[0] + (double)rowinfo[1] + (double)rowinfo[2] + (double)rowinfo[3] + (double)rowinfo[4] + (double)rowinfo[5] + (double)rowinfo[6] + (double)rowinfo[7] + (double)rowinfo[8] + (double)rowinfo[9] + (double)rowinfo[10] + (double)rowinfo[11]);
            SimulationResults.Tables[4].Rows.Add(rowinfo);

            rowinfo     = ForCurvetable.NewRow();
            rowinfo[0]  = PriceArray[0, 1];
            rowinfo[1]  = PriceArray[1, 1];
            rowinfo[2]  = PriceArray[2, 1];
            rowinfo[3]  = PriceArray[3, 1];
            rowinfo[4]  = PriceArray[4, 1];
            rowinfo[5]  = PriceArray[5, 1];
            rowinfo[6]  = PriceArray[6, 1];
            rowinfo[7]  = PriceArray[7, 1];
            rowinfo[8]  = PriceArray[8, 1];
            rowinfo[9]  = PriceArray[9, 1];
            rowinfo[10] = PriceArray[10, 1];
            rowinfo[11] = PriceArray[11, 1];
            SimulationResults.Tables[0].Rows.Add(rowinfo);

            rowinfo     = Positiontable.NewRow();
            rowinfo[0]  = (Convert.ToDouble(I4.GetDouble()) - Convert.ToDouble(W4.GetDouble()));
            rowinfo[1]  = (double)rowinfo[0] + (Convert.ToDouble(I5.GetDouble()) - Convert.ToDouble(W5.GetDouble()));
            rowinfo[2]  = (double)rowinfo[1] + (Convert.ToDouble(I6.GetDouble()) - Convert.ToDouble(W6.GetDouble()));
            rowinfo[3]  = (double)rowinfo[2] + (Convert.ToDouble(I7.GetDouble()) - Convert.ToDouble(W7.GetDouble()));
            rowinfo[4]  = (double)rowinfo[3] + (Convert.ToDouble(I8.GetDouble()) - Convert.ToDouble(W8.GetDouble()));
            rowinfo[5]  = (double)rowinfo[4] + (Convert.ToDouble(I9.GetDouble()) - Convert.ToDouble(W9.GetDouble()));
            rowinfo[6]  = (double)rowinfo[5] + (Convert.ToDouble(I10.GetDouble()) - Convert.ToDouble(W10.GetDouble()));
            rowinfo[7]  = (double)rowinfo[6] + (Convert.ToDouble(I11.GetDouble()) - Convert.ToDouble(W11.GetDouble()));
            rowinfo[8]  = (double)rowinfo[7] + (Convert.ToDouble(I12.GetDouble()) - Convert.ToDouble(W12.GetDouble()));
            rowinfo[9]  = (double)rowinfo[8] + (Convert.ToDouble(I1.GetDouble()) - Convert.ToDouble(W1.GetDouble()));
            rowinfo[10] = (double)rowinfo[9] + (Convert.ToDouble(I2.GetDouble()) - Convert.ToDouble(W2.GetDouble()));
            rowinfo[11] = (double)rowinfo[10] + (Convert.ToDouble(I3.GetDouble()) - Convert.ToDouble(W3.GetDouble()));
            SimulationResults.Tables[3].Rows.Add(rowinfo);
            #endregion

            //  System.Diagnostics.Process.GetCurrentProcess().Kill();
            context.ClearModel();
        }