Esempio n. 1
0
        /// <summary>
        /// Takes the decision domain as a parameter and builds LP/MIP model
        /// depending on the domain
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        private Model BuildMasterModel(Domain domain)
        {
            _context.ClearModel();
            Model masterModel = _context.CreateModel();

            //Creating the sets
            Set setPattern = new Set(domain: Domain.IntegerNonnegative, name: "Pattern");

            //parameter for demanded sizes
            Parameter paramDemands = new Parameter(domain: Domain.IntegerNonnegative, name: "ParamDemands", indexSets: _setRoll);

            paramDemands.SetBinding(binding: _demands, valueField: "Demand", indexFields: "Width");

            //parameter for number that each pattern must be applied to get all sizes and their demanded quantityv
            Parameter paramPatternRolls = new Parameter(domain: Domain.IntegerNonnegative, name: "paramPatternRolls", indexSets: new Set[] { setPattern, _setRoll });

            paramPatternRolls.SetBinding(binding: _patternRolls, valueField: "Count", indexFields: new string[] { "PatternID", "Width" });

            //Add both parameters to model
            masterModel.AddParameters(paramDemands, paramPatternRolls);

            //Decision: Created, bind data and add to the model
            //This is where the solver will place values (how many times to cut each pattern)
            Decision decisionPatternCounts = new Decision(domain: domain, name: "PatternCounts", indexSets: setPattern);

            decisionPatternCounts.SetBinding(binding: _patterns, valueField: "Count", indexFields: "PatternID");
            masterModel.AddDecision(decision: decisionPatternCounts);

            //Adding the demand constraint
            masterModel.AddConstraint(_demandConstraintName, Model.ForEach
                                      (
                                          _setRoll, roll =>                     //from _setRoll, run for each roll
                                          //sum of (pattern items for given roll) * (pattern count) >= (demandf for size)
                                          Model.Sum
                                          (
                                              Model.ForEach
                                              (
                                                  setPattern, pattern =>                       //from setPattern, run for each pattern
                                                  decisionPatternCounts[pattern] * paramPatternRolls[pattern, roll]
                                              )
                                          )
                                          >= paramDemands[roll]
                                      ));

            //Minize the total cuts
            masterModel.AddGoal("TotalRolls", GoalKind.Minimize, Model.Sum(Model.ForEach(setPattern, pattern => decisionPatternCounts[pattern])));
            return(masterModel);
        }
Esempio n. 2
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();
        }
        /// <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);
        }
Esempio n. 4
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());
        }
Esempio n. 5
0
        public static Tuple <double, List <double> > PlayerBStrategy(List <List <int> > matrix)
        {
            SolverContext context = SolverContext.GetContext();

            context.ClearModel();
            Model model = context.CreateModel();

            List <Decision> decicionList = new List <Decision>();

            for (int j = 0; j < matrix[0].Count; j++)
            {
                decicionList.Add(new Decision(Domain.RealNonnegative, "B" + j));
            }

            foreach (var decision in decicionList)
            {
                model.AddDecision(decision);
            }

            for (int i = 0; i < matrix.Count; i++)
            {
                SumTermBuilder rowSum = new SumTermBuilder(decicionList.Count);

                for (int j = 0; j < decicionList.Count; j++)
                {
                    rowSum.Add(decicionList[j] * matrix[i][j]);
                }

                model.AddConstraint("con" + i, rowSum.ToTerm() <= 1);
            }

            SumTermBuilder decisionSum = new SumTermBuilder(decicionList.Count);

            for (int j = 0; j < decicionList.Count; j++)
            {
                model.AddConstraint("nonneg" + j, decicionList[j] >= 0);
                decisionSum.Add(decicionList[j]);
            }

            model.AddGoal("max", GoalKind.Maximize, decisionSum.ToTerm());

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

            double        gameValue          = 1 / solution.Goals.First().ToDouble();
            List <double> parsedDecicionList = new List <double>();

            foreach (var decision in decicionList)
            {
                parsedDecicionList.Add(decision.ToDouble() * gameValue);
            }

            return(new Tuple <double, List <double> >(gameValue, parsedDecicionList));
        }
Esempio n. 6
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());
        }
Esempio n. 7
0
        /// <summary>Create the model.
        /// </summary>
        /// <param name="project">The project to be scheduled.</param>
        public void Initialize(Project project)
        {
            context = SolverContext.GetContext();
            context.ClearModel();
            model = context.CreateModel();

            int eventCount = project.Tasks.Count;

            // we will fill these in in the remainder of the post.
            InitializeSets(project.Tasks.Count, eventCount, project.Resources.Count);
            InitializeParameters(project.Tasks, project.Resources);
            InitializeDecisions();
            InitializeGoal();
            InitializeConstraints(project, eventCount);
        }
Esempio n. 8
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
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            try
            {
                //https://nathanbrixius.wordpress.com/2009/04/24/modeling-a-production-planning-problem-using-solver-foundation/
                SolverContext context = SolverContext.GetContext();
                context.ClearModel();
                Model model = context.CreateModel();

                Set fabricas       = new Set(Domain.Any, "fabricas");
                Set distribuidores = new Set(Domain.Any, "distribuidores");

                Parameter demanda = new Parameter(Domain.Integer, "demanda", distribuidores);
                demanda.SetBinding(getDemanda().AsEnumerable(), "Demanda", "Distribuidor");

                Parameter costos = new Parameter(Domain.Integer, "costos", fabricas, distribuidores);
                costos.SetBinding(getCostos().AsEnumerable(), "Costo", "Fabrica", "Distribuidor");

                Parameter disponibilidad = new Parameter(Domain.Integer, "disponibilidad", fabricas);
                disponibilidad.SetBinding(getDisponibilidad().AsEnumerable(), "Disponibilidad", "Fabrica");

                model.AddParameters(demanda, costos, disponibilidad);

                Decision x = new Decision(Domain.RealNonnegative, "x", fabricas, distribuidores);
                model.AddDecision(x);

                model.AddConstraint("Disponibilidad", Model.ForEach(fabricas, f => Model.Sum(Model.ForEach(distribuidores, d => x[f, d])) <= disponibilidad[f]));
                model.AddConstraint("Demanda", Model.ForEach(distribuidores, d => Model.Sum(Model.ForEach(fabricas, f => x[f, d])) >= demanda[d]));

                model.AddGoal("Meta", GoalKind.Minimize, Model.Sum(Model.ForEach(fabricas, f => Model.ForEach(distribuidores, d => costos[f, d] * x[f, d]))));

                Solution solution = context.Solve(new SimplexDirective());
                Report   report   = solution.GetReport();
                Console.WriteLine(report);
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
Esempio n. 10
0
        static void ExecuteZ3(string fileName, Z3BaseDirective directive)
        {
            SolverContext context = SolverContext.GetContext();

            try
            {
                LoadModel(context, fileName);

                Solution solution = context.Solve(directive);
                Report   report   = solution.GetReport();
                Console.Write("{0}", report);
            }
            catch (Exception e)
            {
                Console.WriteLine("Skipping unsolvable instance in {0} with error message '{1}'.", fileName, e.Message);
            }
            finally
            {
                context.ClearModel();
            }
        }
Esempio n. 11
0
        public string[,] Calculate()
        {
            Solution solution = context.Solve();
            Report   report   = solution.GetReport();

            Console.WriteLine(solution.Quality);

            string[,] decisionsValues = new string[model.Decisions.Count(), 2];

            for (int i = 0; i < model.Decisions.Count(); i++)
            {
                Decision d = model.Decisions.ElementAt(i);
                decisionsValues[i, 0] = d.Name;
                decisionsValues[i, 1] = d.GetDouble().ToString();
            }
            context.ClearModel();



            return(decisionsValues);
        }
Esempio n. 12
0
        static void ConvertToSMT2(string fileName, Z3BaseDirective directive)
        {
            SolverContext context = SolverContext.GetContext();

            try
            {
                LoadModel(context, fileName);

                if (context.CurrentModel.Goals.Any())
                {
                    directive.SMT2LogFile = Path.ChangeExtension(fileName, ".smt2");
                    context.Solve(() => true, directive);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Skipping unconvertable instance in {0} with error message '{1}'.", fileName, e.Message);
            }
            finally
            {
                context.ClearModel();
            }
        }
        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();
        }
Esempio n. 14
0
        /// <summary>
        /// Handles the given action, which may result in a synchronized transition.
        /// </summary>
        public bool HandleAction(ActionType type, string channel, Dictionary <string, object> parameters)
        {
            Log.Debug(this, nameof(HandleAction) + " Type: " + type + " Channel: " + channel + " Parameters:\n" + string.Join("\n", parameters.Select(x => x.Key + ": " + x.Value).ToArray()));

            List <SymbolicTransition> validTransitions = new List <SymbolicTransition>();

            foreach (SymbolicTransition transition in Transitions)
            {
                // Transition must come from the current state.
                if (transition.From != State)
                {
                    continue;
                }
                // Transition must have the same type (input or output).
                if (transition.Type != type)
                {
                    continue;
                }
                // Transition must have the same channel name.
                if (transition.Channel != channel)
                {
                    continue;
                }

                bool valid = true;
                try
                {
                    SolverContext solver = SolverContext.GetContext();

                    if (!modelCache.TryGetValue(transition, out Model model))
                    {
                        solver.ClearModel();
                        model = solver.CreateModel();
                        modelCache.Add(transition, model);

                        Log.Debug(this, "Created new model: " + model);

                        // Add location variables, and interaction variables.
                        //model.AddParameters(Variables.ToArray());
                        model.AddDecisions(transition.Variables.ToArray());

                        // Let the transition add its guard expression.
                        transition.Guard(model, Variables, transition.Variables);
                    }
                    else
                    {
                        Log.Debug(this, "Re-using existing model: " + model);

                        solver.ClearModel();
                        solver.CurrentModel = model;
                    }

                    // Does it solve?
                    Solution solution = solver.Solve(new HybridLocalSearchDirective()
                    {
                        TimeLimit = 1000,
                    });

                    Log.Debug(this, "Succesfully solved: " + transition);
                    foreach (Decision decision in transition.Variables)
                    {
                        Log.Debug(this, string.Format("<Decision> {0}: {1}", decision.Name, decision));
                    }

                    Report report = solution.GetReport();
                    Log.Debug(this, string.Format("{0}", report));

                    solver.ClearModel();
                }
                catch (Exception e)
                {
                    Log.Error(this, "Exception solving: " + transition + "\n" + e);
                    valid = false;
                }

                // Transition must have the same parameters (but order does not matter).
                //if (!transition.Parameters.SetEquals(new HashSet<string>(parameters.Keys))) continue;
                // Transition guard function must evaluate to true.
                //if (!transition.GuardFunction(Variables, parameters)) continue;

                // All checks passed!
                if (valid)
                {
                    validTransitions.Add(transition);
                }
            }

            Log.Debug(this, "Valid transitions:\n" + string.Join("\n", validTransitions.Select(x => x.ToString()).ToArray()));

            if (validTransitions.Count == 0)
            {
                return(false);
            }

            // DEBUG: For testing, we pick the first compatible transition, not a random one. (TPE)
            SymbolicTransition chosenTransition = validTransitions.First();

            Log.Debug(this, "Chosen transition:\n" + chosenTransition);

            chosenTransition.Update(Variables, chosenTransition.Variables);

            Log.Debug(this, "From: " + State + " To: " + chosenTransition.To);
            State = chosenTransition.To;

            return(true);
        }
Esempio n. 15
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();
        }
Esempio n. 16
0
        public IActionResult Result(double TempVhod, double FeOVhod, double TempExit, double Osnovnoct, double FeOExit, int dsfsdfdsfdsf)
        {
            ViewData["Message"] = "Your application description page.";

            RashetShlak cls = new RashetShlak(TempVhod, FeOVhod, TempExit, Osnovnoct, FeOExit);

            ViewBag.rashet = cls;

            // Расчеты

            #region расчеты СЛАУ
            string[]    str    = new string[4];
            int         p      = 0;
            XmlReader   reader = XmlReader.Create(@"phones_.xml");
            XmlDocument doc    = new XmlDocument();

            XmlReaderSettings settings = new XmlReaderSettings();
            //settings.
            //doc = new XmlReader();
            {
                //doc.Load("phones_.xml");
                doc.Load(reader);
                foreach (XmlNode node in doc.SelectNodes("phones"))
                {
                    foreach (XmlNode child in node.ChildNodes)
                    {
                        str[p] = (string.Format(child.InnerText)).ToString();
                        p++;
                    }
                }
            }
            Char     delimiter = '/';
            double[] x         = new double[6];

            double[,] y = new double[3, 6];
            for (int u = 0; u < 4; u++)
            {
                String[] subn = str[u].Split(delimiter);
                if (u == 0)
                {
                    for (int j = 0; j < 6; j++)
                    {
                        x[j] = double.Parse(subn[j]);
                    }
                }
                else
                {
                    for (int j = 0; j < 6; j++)
                    {
                        y[u - 1, j] = double.Parse(subn[j]);
                    }
                }
            }

            double[,] results = new double[3, 6];

            SolverContext context = SolverContext.GetContext();

            for (int i = 0; i < y.GetLength(0); i++)
            {
                Decision a = new Decision(Domain.Real, "a");
                Decision b = new Decision(Domain.Real, "b");
                Decision c = new Decision(Domain.Real, "c");
                Decision d = new Decision(Domain.Real, "d");
                Decision e = new Decision(Domain.Real, "e");
                Decision f = new Decision(Domain.Real, "f");

                Microsoft.SolverFoundation.Services.Model model = context.CreateModel();

                model.AddDecisions(a, b, c, d, e, f);

                model.AddConstraint("eqA1", y[i, 0] == ((Math.Pow(x[0], 1)) * a + (Math.Pow(x[0], 2)) * b + (Math.Pow(x[0], 3)) * c + (Math.Pow(x[0], 4)) * d + (Math.Pow(x[0], 5)) * e + f));
                model.AddConstraint("eqA2", y[i, 1] == ((Math.Pow(x[1], 1)) * a + (Math.Pow(x[1], 2)) * b + (Math.Pow(x[1], 3)) * c + (Math.Pow(x[1], 4)) * d + (Math.Pow(x[1], 5)) * e + f));
                model.AddConstraint("eqA3", y[i, 2] == ((Math.Pow(x[2], 1)) * a + (Math.Pow(x[2], 2)) * b + (Math.Pow(x[2], 3)) * c + (Math.Pow(x[2], 4)) * d + (Math.Pow(x[2], 5)) * e + f));
                model.AddConstraint("eqA4", y[i, 3] == ((Math.Pow(x[3], 1)) * a + (Math.Pow(x[3], 2)) * b + (Math.Pow(x[3], 3)) * c + (Math.Pow(x[3], 4)) * d + (Math.Pow(x[3], 5)) * e + f));
                model.AddConstraint("eqA5", y[i, 4] == ((Math.Pow(x[4], 1)) * a + (Math.Pow(x[4], 2)) * b + (Math.Pow(x[4], 3)) * c + (Math.Pow(x[4], 4)) * d + (Math.Pow(x[4], 5)) * e + f));
                model.AddConstraint("eqA6", y[i, 5] == ((Math.Pow(x[5], 1)) * a + (Math.Pow(x[5], 2)) * b + (Math.Pow(x[5], 3)) * c + (Math.Pow(x[5], 4)) * d + (Math.Pow(x[5], 5)) * e + f));

                Solution solution = context.Solve();
                string   result   = solution.GetReport().ToString();

                results[i, 0] = a.ToDouble();
                results[i, 1] = b.ToDouble();
                results[i, 2] = c.ToDouble();
                results[i, 3] = d.ToDouble();
                results[i, 4] = e.ToDouble();
                results[i, 5] = f.ToDouble();

                context.ClearModel();
            }

            double[] temps = { cls.TempVhod, cls.TempExit };
            double[,] koefs = new double[2, 3];

            for (int i = 0; i < 2; i++)
            {
                Decision a = new Decision(Domain.Real, "a");
                Decision b = new Decision(Domain.Real, "b");
                Decision c = new Decision(Domain.Real, "c");

                Microsoft.SolverFoundation.Services.Model model = context.CreateModel();

                model.AddDecisions(a, b, c);

                double ta = results[0, 5] +
                            results[0, 0] * Math.Pow(temps[i], 1) +
                            results[0, 1] * Math.Pow(temps[i], 2) +
                            results[0, 2] * Math.Pow(temps[i], 3) +
                            results[0, 3] * Math.Pow(temps[i], 4) +
                            results[0, 4] * Math.Pow(temps[i], 5);
                double tb = results[1, 5] +
                            results[1, 0] * Math.Pow(temps[i], 1) +
                            results[1, 1] * Math.Pow(temps[i], 2) +
                            results[1, 2] * Math.Pow(temps[i], 3) +
                            results[1, 3] * Math.Pow(temps[i], 4) +
                            results[1, 4] * Math.Pow(temps[i], 5);
                double tc = results[2, 5] +
                            results[2, 0] * Math.Pow(temps[i], 1) +
                            results[2, 1] * Math.Pow(temps[i], 2) +
                            results[2, 2] * Math.Pow(temps[i], 3) +
                            results[2, 3] * Math.Pow(temps[i], 4) +
                            results[2, 4] * Math.Pow(temps[i], 5);

                //MessageBox.Show(ta.ToString() + "..." + tb.ToString() + "..." + tc.ToString());

                model.AddConstraint("eqA1", ta == 0 * a + 0 * b + c);
                model.AddConstraint("eqA2", tb == 6.0 * a + 36.0 * b + c);
                model.AddConstraint("eqA3", tc == 12.0 * a + 144.0 * b + c);

                Solution solution = context.Solve();
                // string result = solution.GetReport().ToString();

                koefs[i, 0] = a.ToDouble();
                koefs[i, 1] = b.ToDouble();
                koefs[i, 2] = c.ToDouble();

                context.ClearModel();
            }
            #endregion

            cls.VisVhod     = koefs[0, 2] + koefs[0, 0] * cls.FeOVhod + koefs[0, 1] * cls.FeOVhod * cls.FeOVhod;
            cls.VisExit     = koefs[1, 2] + koefs[1, 0] * cls.FeOExit + koefs[1, 1] * cls.FeOExit * cls.FeOExit;
            cls.VisOcnVhod  = cls.VisVhod + 196 * (cls.Osnovnoct - 1);
            cls.VisOsnExit  = cls.VisExit + 4 * (cls.Osnovnoct - 1);
            cls.KoffB       = (Math.Log10(Math.Log10(cls.VisOsnExit)) - Math.Log10(Math.Log10(cls.VisOcnVhod))) / (cls.TempExit - cls.TempVhod);
            cls.KoffA       = Math.Log10(Math.Log10(cls.VisOcnVhod)) - cls.TempVhod * cls.KoffB;
            cls.Vis1180     = Math.Pow(10, Math.Pow(10, cls.KoffA + cls.KoffB * cls.TempVhod));
            cls.Vis1200     = Math.Pow(10, Math.Pow(10, cls.KoffA + cls.KoffB * 1200));
            cls.Vis1250     = Math.Pow(10, Math.Pow(10, cls.KoffA + cls.KoffB * 1250));
            cls.Vis1275     = Math.Pow(10, Math.Pow(10, cls.KoffA + cls.KoffB * 1275));
            cls.Vis1300     = Math.Pow(10, Math.Pow(10, cls.KoffA + cls.KoffB * 1300));
            cls.TempKristal = (cls.KoffA - Math.Log10(Math.Log10(25))) / ((-1) * cls.KoffB);


            #region Excel

            // Открываем приложение
            application = new Application
            {
                DisplayAlerts = false
            };

            // Файл шаблона
            const string template = "shlak2.xlsx";

            // Открываем книгу
            workBook = application.Workbooks.Open(Path.Combine(Environment.CurrentDirectory, template));

            // Получаем активную таблицу
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[1];//.get_Item(2);
            // Записываем данные
            worksheet.Range["C22"].Value = cls.TempVhod;
            worksheet.Range["C23"].Value = cls.FeOVhod;
            worksheet.Range["C24"].Value = cls.TempExit;
            worksheet.Range["C25"].Value = cls.FeOExit;
            worksheet.Range["C26"].Value = cls.Osnovnoct;
            //ВВОД данных и р-т
            double VisVhodEX     = double.Parse(worksheet.Range["C27"].Value.ToString());
            double VisExitEX     = double.Parse(worksheet.Range["C28"].Value.ToString());
            double VisOcnVhodEX  = double.Parse(worksheet.Range["C29"].Value.ToString());
            double VisOsnExitEX  = double.Parse(worksheet.Range["C30"].Value.ToString());
            double KoffAEX       = double.Parse(worksheet.Range["C31"].Value.ToString());
            double KoffBEX       = double.Parse(worksheet.Range["C32"].Value.ToString());
            double Vis1180EX     = double.Parse(worksheet.Range["C33"].Value.ToString());
            double Vis1200EX     = double.Parse(worksheet.Range["C34"].Value.ToString());
            double Vis1250EX     = double.Parse(worksheet.Range["C35"].Value.ToString());
            double Vis1275EX     = double.Parse(worksheet.Range["C36"].Value.ToString());
            double Vis1300EX     = double.Parse(worksheet.Range["C37"].Value.ToString());
            double TempKristalEX = double.Parse(worksheet.Range["C38"].Value.ToString());
            // Показываем приложение

            workBook.Save();

            cls.pogr = Math.Round((((Math.Abs(((Math.Abs(VisVhodEX) - Math.Abs(cls.VisVhod)) / Math.Abs(VisVhodEX))) +
                                     Math.Abs(((Math.Abs(VisExitEX) - Math.Abs(cls.VisExit)) / Math.Abs(VisExitEX))) +
                                     Math.Abs(((Math.Abs(VisOcnVhodEX) - Math.Abs(cls.VisOcnVhod)) / Math.Abs(VisOcnVhodEX))) +
                                     Math.Abs(((Math.Abs(VisOsnExitEX) - Math.Abs(cls.VisOsnExit)) / Math.Abs(VisOsnExitEX))) +
                                     Math.Abs(((Math.Abs(Vis1250EX) - Math.Abs(cls.Vis1250)) / Math.Abs(Vis1250EX))) +
                                     Math.Abs(((Math.Abs(Vis1275EX) - Math.Abs(cls.Vis1275)) / Math.Abs(Vis1275EX))) +
                                     Math.Abs(((Math.Abs(Vis1300EX) - Math.Abs(cls.Vis1300)) / Math.Abs(Vis1300EX))) +
                                     Math.Abs(((Math.Abs(TempKristalEX) - Math.Abs(cls.TempExit)) / Math.Abs(TempKristalEX))) +
                                     Math.Abs(((Math.Abs(KoffAEX) - Math.Abs(cls.KoffA)) / Math.Abs(KoffAEX))) +
                                     Math.Abs(((Math.Abs(KoffBEX) - Math.Abs(cls.KoffB)) / Math.Abs(KoffBEX))) +
                                     Math.Abs(((Math.Abs(Vis1180EX) - Math.Abs(cls.Vis1180)) / Math.Abs(Vis1180EX))) +
                                     Math.Abs(((Math.Abs(Vis1200EX) - Math.Abs(cls.Vis1200)) / Math.Abs(Vis1200EX))))) / 12) * 100, 2);

            #endregion
            workBook.Close(false, Type.Missing, Type.Missing);
            application.Quit();
            return(View());
        }
Esempio n. 17
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;
                }
            }
        }
Esempio n. 18
0
        //Sampling a card distribution considering which suits the players have
        //It uses a CSP from Microsoft SolverFoundation
        public List <List <int> > SampleHands(Dictionary <int, List <int> > suitHasPlayer, int[] playerIDs, ref List <List <int> > hands)
        {
            int[] handSizes = new int[] { hands[0].Capacity - hands[0].Count, hands[1].Capacity - hands[1].Count, hands[2].Capacity - hands[2].Count };
            if (deck.Count != handSizes[0] + handSizes[1] + handSizes[2])
            {
                //Remover este bocado de codigo se o erro nunca mais ocorrer
                Console.WriteLine("[" + System.Threading.Thread.CurrentThread.ManagedThreadId + "] - PROBLEM! - deck.Count: " + deck.Count + " P0: " + handSizes[0] + " P1: " + handSizes[1] + " P2: " + handSizes[2] + " deck: " + deckToString());
                Console.Out.Flush();
                //System.Environment.Exit(1);
            }

            deck = shuffle(deck);

            lock (thisLock)
            {
                var                model = solver.CreateModel();
                List <Decision>    decisions = new List <Decision>(deck.Count);
                List <List <int> > players = getDomains(playerIDs, handSizes);
                List <int>         player1 = players[0];
                List <int>         player1Copy = new List <int>(player1);
                List <int>         player2 = players[1];
                List <int>         player3 = players[2];
                List <int>         player3Copy = new List <int>(player3);
                Domain             domain1 = null, domain2 = null, domain3 = null, domain12 = null, domain23 = null, domain13 = null, domain123 = null;

                if (player1.Count > 0)
                {
                    domain1 = Domain.Set(player1.ToArray());
                }
                if (player2.Count > 0)
                {
                    domain2 = Domain.Set(player2.ToArray());
                }
                if (player3.Count > 0)
                {
                    domain3 = Domain.Set(player3.ToArray());
                }
                if (player1.Count > 0 && player2.Count > 0)
                {
                    player1.AddRange(player2);
                    domain12 = Domain.Set(player1.ToArray());
                }
                if (player2.Count > 0 && player3.Count > 0)
                {
                    player2.AddRange(player3);
                    domain23 = Domain.Set(player2.ToArray());
                }
                if (player1.Count > 0 && player3.Count > 0)
                {
                    player3.AddRange(player1Copy);
                    domain13 = Domain.Set(player3.ToArray());
                }
                if (player1.Count > 0 && player2.Count > 0 && player3.Count > 0)
                {
                    player1.AddRange(player3Copy);
                    domain123 = Domain.Set(player1.ToArray());
                }


                for (int i = 0; i < deck.Count; i++)
                {
                    int        card = deck[i];
                    List <int> playersThatHaveSuit = suitHasPlayer[Card.GetSuit(card)];
                    Decision   d;

                    if (playersThatHaveSuit.Count == 3 && domain123 != null)
                    {
                        d = new Decision(domain123, "c" + card);
                    }
                    else if (playersThatHaveSuit.Count >= 2 && playersThatHaveSuit.Contains(playerIDs[0]) && playersThatHaveSuit.Contains(playerIDs[1]) && domain12 != null)
                    {
                        d = new Decision(domain12, "c" + card);
                    }
                    else if (playersThatHaveSuit.Count >= 2 && playersThatHaveSuit.Contains(playerIDs[0]) && playersThatHaveSuit.Contains(playerIDs[2]) && domain13 != null)
                    {
                        d = new Decision(domain13, "c" + card);
                    }
                    else if (playersThatHaveSuit.Count >= 2 && playersThatHaveSuit.Contains(playerIDs[1]) && playersThatHaveSuit.Contains(playerIDs[2]) && domain23 != null)
                    {
                        d = new Decision(domain23, "c" + card);
                    }
                    else if (playersThatHaveSuit.Count >= 1 && playersThatHaveSuit.Contains(playerIDs[0]) && domain1 != null)
                    {
                        d = new Decision(domain1, "c" + card);
                    }
                    else if (playersThatHaveSuit.Count >= 1 && playersThatHaveSuit.Contains(playerIDs[1]) && domain2 != null)
                    {
                        d = new Decision(domain2, "c" + card);
                    }
                    else if (playersThatHaveSuit.Count >= 1 && playersThatHaveSuit.Contains(playerIDs[2]) && domain3 != null)
                    {
                        d = new Decision(domain3, "c" + card);
                    }
                    else
                    {
                        solver.ClearModel();
                        return(null);
                    }

                    decisions.Add(d);
                    model.AddDecision(d);
                }

                model.AddConstraint("allDiff", Model.AllDifferent(decisions.ToArray()));
                var solution = solver.Solve();


                if (solution.Quality != SolverQuality.Feasible)
                {
                    Console.Write("CSP Problem - solution {0}", solution.Quality);
                    return(null);
                }

                List <List <int> > cardsPerPlayer = new List <List <int> >(3);
                cardsPerPlayer.Add(new List <int>(handSizes[0]));
                cardsPerPlayer.Add(new List <int>(handSizes[1]));
                cardsPerPlayer.Add(new List <int>(handSizes[2]));

                for (int i = 0; i < deck.Count; i++)
                {
                    int decision = Convert.ToInt16(decisions[i].ToString());
                    decision = decision / 10;
                    if (decision == playerIDs[0])
                    {
                        hands[0].Add(deck[i]);
                    }
                    else if (decision == playerIDs[1])
                    {
                        hands[1].Add(deck[i]);
                    }
                    else if (decision == playerIDs[2])
                    {
                        hands[2].Add(deck[i]);
                    }
                    else
                    {
                        Console.WriteLine("Deck::SampleHands(with CSP) >> Unkown decision");
                    }
                }
                solver.ClearModel();
            }
            return(hands);
        }
        public string Solve()
        {
            /***************************
            /*Construction of the model*
            /***************************/
            SolverContext context = SolverContext.GetContext();
            //For repeating the solution with other minimum returns
            context.ClearModel();

            //Create an empty model from context
            Model portfolio = context.CreateModel();

            //Create a string set with stock names
            Set setStocks = new Set(Domain.Any, "Stocks");

            /****Decisions*****/

            //Create decisions bound to the set. There will be as many decisions as there are values in the set
            Decision allocations = new Decision(Domain.RealNonnegative, "Allocations", setStocks);
            allocations.SetBinding(StocksHistory, "Allocation", "Stock");
            portfolio.AddDecision(allocations);

            /***Parameters***/

            //Create parameters bound to Covariant matrix
            Parameter pCovariants = new Parameter(Domain.Real, "Covariants", setStocks, setStocks);
            pCovariants.SetBinding(Covariants, "Variance", "StockI", "StockJ");

            //Create parameters bound to mean performance of the stocks over 12 month period
            Parameter pMeans = new Parameter(Domain.Real, "Means", setStocks);
            pMeans.SetBinding(StocksHistory, "Mean", "Stock");

            portfolio.AddParameters(pCovariants, pMeans);

            /***Constraints***/

            //Portion of a stock should be between 0 and 1
            portfolio.AddConstraint("portion", Model.ForEach(setStocks, stock => 0 <= allocations[stock] <= 1));

            //Sum of all allocations should be equal to unity
            portfolio.AddConstraint("SumPortions", Model.Sum(Model.ForEach(setStocks, stock => allocations[stock])) == 1);

            //Expected minimum return
            portfolio.AddConstraint("ROI", Model.Sum(Model.ForEach(setStocks, stock => Model.Product(allocations[stock], pMeans[stock]))) >= MinROI);

            /***Goals***/

            portfolio.AddGoal("Variance", GoalKind.Minimize, Model.Sum
                                                             (
                                                                Model.ForEach
                                                                (
                                                                    setStocks, stockI =>
                                                                    Model.ForEach
                                                                    (
                                                                        setStocks, stockJ =>
                                                                       Model.Product(pCovariants[stockI, stockJ], allocations[stockI], allocations[stockJ])
                                                                    )
                                                                )
                                                            )
                             );
            /************************************************
           /*Add SolveEvent to watch the solving progress  *
           /************************************************/

            EventHandler<SolvingEventArgs> handler = new EventHandler<SolvingEventArgs>(SolvingEventHandler);            
            
            // ensure the handler is registered only once when hit the Solve button again.
            context.Solving -= handler;
            context.Solving += handler;           

            /*******************
            /*Solve the model  *
            /*******************/

            //Use IPM algorithm
            Solution solution = context.Solve(new InteriorPointMethodDirective());

            //Save the decisions back to the array
            if (solution.Quality == SolverQuality.Optimal)
                context.PropagateDecisions();

            using (TextWriter tw = new StreamWriter("portfolio.qps"))
            {
                context.SaveModel(FileFormat.MPS, tw);
            }

            Report report = solution.GetReport();
            return report.ToString();
        }
Esempio n. 20
0
        private void CreateModel()
        {
            context = SolverContext.GetContext();
            context.ClearModel();
            model = context.CreateModel();
            items = new Set(Domain.Any, "items");

            cost = new Parameter(Domain.Integer, "cost", items);
            cost.SetBinding(Round.Players, "Cost", "Name");

            score = new Parameter(Domain.Integer, "score", items);
            score.SetBinding(Round.Players, "Score", "Name");

            team = new Parameter(Domain.IntegerNonnegative, "team", items);
            team.SetBinding(Round.Players, "TeamId", "Name");

            dummy = new Parameter(Domain.Boolean, "dummy", items);
            dummy.SetBinding(Round.Players, "IsDummyPlayer", "Name");

            model.AddParameters(cost, score, team, dummy);

            choose = new Decision(Domain.IntegerRange(0, 1), "choose", items);
            choose.SetBinding(Round.Players, "SelectedValue", "Name");
            model.AddDecision(choose);
        }
Esempio n. 21
0
        static void ValidateZ3(string fileName, Z3BaseDirective directive)
        {
            SolverContext context = SolverContext.GetContext();

            try
            {
                LoadModel(context, fileName);

                if (context.CurrentModel.Goals.Any())
                {
                    var msfDirective = (directive is Z3MILPDirective) ? (Directive) new MixedIntegerProgrammingDirective()
                    {
                        TimeLimit = 10000
                    }
                                            : (Directive) new Directive()
                    {
                        TimeLimit = 10000
                    };
                    var sol1 = context.Solve(msfDirective);

                    Console.WriteLine("Solved the model using MSF.");
                    Console.Write("{0}", sol1.GetReport());
                    var expectedGoals = sol1.Goals.Select(x => x.ToDouble());
                    context.ClearModel();

                    context.LoadModel(FileFormat.OML, Path.GetFullPath(fileName));
                    directive.SMT2LogFile = Path.ChangeExtension(fileName, ".smt2");
                    var sol2 = context.Solve(directive);
                    //Console.Write("{0}", sol2.GetReport());
                    var actualGoals = sol2.Goals.Select(x => x.ToDouble());

                    Console.WriteLine("Solved the model using Z3.");
                    var  goalPairs = expectedGoals.Zip(actualGoals, (expected, actual) => new { expected, actual }).ToArray();
                    bool validated = goalPairs.All(p => Math.Abs(p.expected - p.actual) <= 0.0001);
                    if (validated)
                    {
                        Console.WriteLine("INFO: Two solvers give approximately the same results.");
                    }
                    else
                    {
                        Console.Error.WriteLine("ERROR: Discrepancy found between results.");
                        if (!validated && File.Exists(directive.SMT2LogFile))
                        {
                            var sb = new StringBuilder();
                            for (int i = 0; i < goalPairs.Length; i++)
                            {
                                sb.AppendFormat("\n(echo \"Goal {0}: actual |-> {1:0.0000}, expected |-> {2:0.0000}\")",
                                                i + 1, goalPairs[i].actual, goalPairs[i].expected);
                            }
                            Console.Error.WriteLine(sb.ToString());
                            File.AppendAllText(directive.SMT2LogFile, sb.ToString());
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Ignoring this instance without having any goal.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Skipping unsolvable instance in {0} with error message '{1}'.",
                                  fileName, e.Message);
            }
            finally
            {
                context.ClearModel();
            }
        }
Esempio n. 22
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            context.ClearModel();
            Model model = context.CreateModel();

            List <Decision> decisions = new List <Decision>();

            var    formula = "";
            string con     = "";

            foreach (var item in dataGridVars.Items)
            {
                string li       = "L" + (item as Invester).Line;
                double maxValue = Double.Parse((item as Invester).MaxValue) * Double.Parse(Value.Text) / 100f;
                String contrain = li + " <= " + maxValue;
                ParseContrain(contrain);
                con += " " + li + " +";
                Decision dc = new Decision(Domain.RealRange(0, maxValue), li);
                decisions.Add(dc);
                model.AddDecision(dc);
            }
            ParseContrain(con.Substring(0, con.Length - 1) + " >= " + Value.Text);
            foreach (var item in dataGridVars.Items)
            {
                formula += " " + Double.Parse((item as Invester).Interest) + " * L" + (item as Invester).Line;
                if ((item as Invester).Line <= dataGridVars.Items.Count - 1)
                {
                    formula += " +";
                }
                String contrain = "L" + (item as Invester).Line + " >= 0 ";
                ParseContrain(contrain);
            }
            TargetFormula = formula.Substring(1, formula.Length - 2);

            FormulaTB.Text = TargetFormula;

            foreach (var list in ListOfContrains)
            {
                string c = "";
                for (int i = 0; i < list.Capacity; i++)
                {
                    if (i != 0 && i < list.Capacity - 1)
                    {
                        c += list[i] >= 0 ? " + " : " - ";
                    }
                    if (i == list.Capacity - 1)
                    {
                        c += " " + listOfStringContrains[ListOfContrains.IndexOf(list)] + " " + list[i];
                    }
                    else
                    {
                        c += Math.Abs(list[i]) + " * L" + i;
                    }
                }
                model.AddConstraint("C" + ListOfContrains.IndexOf(list), c);

                Console.WriteLine(c);
            }
            model.AddGoal("Goal", GoalKind.Minimize, TargetFormula);
            var directive = new SimplexDirective()
            {
                IterationLimit = -1,
                TimeLimit      = -1,
                Arithmetic     = Arithmetic.Exact,
                GetSensitivity = true
            };
            Solution solution = context.Solve(directive);

            Quality.Text = solution.Quality.ToString();
            Console.WriteLine(solution.GetReport().ToString());
            if (solution.Quality != SolverQuality.Optimal)
            {
                return;
            }

            context.PropagateDecisions();

            for (int i = 0; i < decisions.Count; i++)
            {
                var old = (dataGridVars.Items[i] as Invester);
                old.SelectedValue     = decisions[i].ToDouble().ToString();
                dataGridVars.Items[i] = old;
            }
            dataGridVars.Items.Refresh();
            dataGridVars.UpdateLayout();
        }
Esempio n. 23
0
        private void Solv_Click(object sender, EventArgs e)
        {
            //Coded by : Mohammed Al Sayed
            //Zagzig university ,Group B section 13
            if (Objtxt.Text == "")
            {
                MessageBox.Show("Please Enter The Object Function", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }
            try
            {
                Objtxt.Text = Objtxt.Text.ToLower().TrimEnd(Environment.NewLine.ToCharArray());//triming newline at the end
                string objectfunction = Objtxt.Text;

                //begin Setting object function

                Model model = context.CreateModel();//Creating Linear Programming Model

                for (int i = 0; i < objectfunction.Length; i++)
                {                                             //extracting Variables and adding decisions
                    if (char.IsNumber(objectfunction[i]) && char.IsLetter(objectfunction[i + 1]))
                    {
                        objectfunction = objectfunction.Insert(i + 1, "*");//Parsing text into an acceptable Term like 2*x+3*y  >> 2x become 2*x
                    }
                    else if (char.IsLetter(objectfunction[i]))

                    {
                        //Adding Decisions(Variables) into model
                        model.AddDecision(new Decision(Domain.RealNonnegative, objectfunction[i].ToString()));//each literal represent a variable
                    }
                }
                //end setting object function

                //begin SettingConstrains
                if (Cnstrntxt.Text == "")
                {
                    MessageBox.Show("Please Enter The Constrains", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
                }

                Cnstrntxt.Text = Cnstrntxt.Text.ToLower().TrimEnd(Environment.NewLine.ToCharArray()); //removing newline at the end of the text
                string constrainsRaw = Cnstrntxt.Text;
                //parsing text into an acceptable MOL term ,, something like that 2*x+4*y a programatic equation
                for (int i = 0; i < constrainsRaw.Length - 1; i++)
                {
                    if (char.IsNumber(constrainsRaw[i]) && char.IsLetter(constrainsRaw[i + 1])) //2X
                    {
                        constrainsRaw = constrainsRaw.Insert(i + 1, "*");                       //2*x
                    }
                }
                //spliting constrains
                string[] constrains = constrainsRaw.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i <= constrains.GetUpperBound(0); i++)
                {
                    model.AddConstraint("Constrain_" + i.ToString(), constrains[i]);//each line represent a constrain
                }
                //end setting constrains

                //begin setting goal
                GoalKind goal;                //defining a goal
                if (tpcom.SelectedIndex == 1) //goal type
                {
                    goal = GoalKind.Minimize;
                }
                else
                {
                    goal = GoalKind.Maximize;
                }

                model.AddGoal("target", goal, objectfunction);
                //end setting goal

                //begin solving

                SimplexDirective simplxReactor = new SimplexDirective();            ///solver object
                if (Chksensitivity.Checked)
                {
                    simplxReactor.GetSensitivity = true;                         //sensitivity
                }
                if (ChkInfeasibility.Checked)
                {
                    simplxReactor.GetInfeasibility = true;                           //infeasibility
                }
                if (cmbAlgorithm.SelectedIndex == 1)
                {
                    simplxReactor.Algorithm = SimplexAlgorithm.Dual;                                  //Algorithm used
                }
                Solution solution = context.Solve(simplxReactor);


                Report report = solution.GetReport(); //defining a report


                if (ChkFullReport.Checked)
                {
                    txtreport.Text = report.ToString(); //presenting the report in report textbox
                }
                ResultTextbox.Text = "";                //removing old values if existed
                ResultTextbox.Text = solution.Goals.First().ToDouble().ToString();

                VarResultTextbox.Text = "";
                foreach (Decision d in model.Decisions) //adding decisions(variables) and they production size in variable textbox
                {
                    VarResultTextbox.Text += d.Name + " = " + d.ToString() + Environment.NewLine;
                }

                //Duals aka shadow prices
                if (chkdual.Checked)
                {
                    txtdual.Text = "";                                                                       //removing old values if existed
                    LinearReport lin = ((LinearReport)solution.GetReport());                                 //generating a linear programming report out of the solution report

                    foreach (Microsoft.SolverFoundation.Services.Constraint constraint in model.Constraints) //getting constrains from the model
                    {
                        foreach (var dual in lin.GetShadowPrices(constraint))                                //getting the shadow prices for each constrain
                        {
                            txtdual.Text += dual.Key + " = " + dual.Value.ToDouble().ToString() + Environment.NewLine;
                        }
                    }
                }
                //end shadowprices

                //begin Sensitivity Analysis
                if (Chksensitivity.Checked)
                {
                    txtbound.Text = "";                                                                      //removing old values if existed
                    LinearReport lin = ((LinearReport)solution.GetReport());                                 //generating a linear programming report out of the solution report

                    foreach (Microsoft.SolverFoundation.Services.Constraint constraint in model.Constraints) //getting constrains from the model
                    {
                        foreach (var bound in lin.GetConstraintBoundsSensitivity(constraint))                //getting the boundaries prices for each constrain
                        {
                            //parsing the boundaries into intervals
                            //opening the interval if infinity existed
                            txtbound.Text += bound.Key + " = " + bound.Value.Current.ToDouble().ToString() + Environment.NewLine +
                                             (Double.IsInfinity(bound.Value.Lower.ToDouble()) ? "]" : "[") + bound.Value.Lower.ToDouble().ToString() + " , " + bound.Value.Upper.ToDouble().ToString() + (Double.IsInfinity(bound.Value.Upper.ToDouble()) ? "[" : "]")
                                             + Environment.NewLine + Environment.NewLine
                            ;
                        }
                    }
                }
                context.ClearModel();//killing the model object so we can create a new one

                //end solving

                //begin handling errors
            }

            catch (Exception ex)
            {
                context.ClearModel();
                txtreport.Text = "An Error have occured  If you're sure about you entries  "
                                 + "Please Send this report to the programmer" + Environment.NewLine + Environment.NewLine;
                txtreport.Text += Objtxt.Text + Environment.NewLine + Environment.NewLine;
                txtreport.Text += Cnstrntxt.Text + Environment.NewLine + Environment.NewLine;


                txtreport.Text     += ex.Message;
                txtreport.ForeColor = Color.Red;
                MessageBox.Show("Error,Please Check your entries" + Environment.NewLine + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            tabControl1.SelectedIndex = 1;
            //end handling errors
        }
Esempio n. 24
0
        public ZeroCouponCurve BuildZeroCouponCurve()
        {
            // 1. Linear interpolate the market curve
            double gap = 1.0 / (double)CouponFrequency;
            SortedDictionary <double, double> interpMarketCurve = new SortedDictionary <double, double>();
            List <double> xs = marketCurve.Keys.ToList <double>();
            List <double> ys = marketCurve.Values.ToList <double>();

            for (double x = gap; x <= 50; x += gap)
            {
                interpMarketCurve.Add(x, LinearInterpolation(x, xs, ys));
            }

            // 2. Find discount factors with a bootstrap method
            List <double> discountFactors = new List <double>();
            List <double> couponRates     = interpMarketCurve.Values.Select(x => x / (double)CouponFrequency).ToList <double>();

            for (int i = 0; i < interpMarketCurve.Count; i++)
            {
                double couponRate           = couponRates[i];
                Func <Decision, Term> error = (df) =>
                {
                    Term guess = 0;
                    for (int j = 0; j < i; j++)
                    {
                        guess += couponRate * discountFactors[j];
                    }
                    guess += (1 + couponRate) * df;

                    return((guess - 1) * (guess - 1));
                };

                // Create solver context and model
                SolverContext context = SolverContext.GetContext();
                Model         model   = context.CreateModel();

                Decision df = new Decision(Domain.RealNonnegative, "df");
                df.SetInitialValue(1.0);
                model.AddDecision(df);

                model.AddGoal("error", GoalKind.Minimize, error(df));

                Solution solution = context.Solve();

                discountFactors.Add(df.GetDouble());
                context.ClearModel();
            }

            // 3. Calculate a zero coupon curve by discount factors
            SortedDictionary <double, double> zeroCouponCurve = new SortedDictionary <double, double>();
            List <double> yearFracs = interpMarketCurve.Keys.ToList <double>();

            for (int i = 0; i < interpMarketCurve.Count; i++)
            {
                double discountFactor = discountFactors[i];
                double yearFrac       = yearFracs[i];
                double zeroCouponRate = Math.Pow(1 / discountFactor, 1 / yearFrac) - 1;
                zeroCouponCurve.Add(yearFrac, zeroCouponRate);
            }

            return(new ZeroCouponCurve(zeroCouponCurve));
        }
Esempio n. 25
0
        public static Dictionary <string, MySolver.Parameter> Solve(double[] Xvals, double[] Yvals,
                                                                    string formula, Dictionary <string, MySolver.Parameter> coefficients)
        {
            if (formula.StartsWith("If[FRAP"))//Send to frapa model and return the result
            {
                return(FRAPA_Model.AllModels.Solve(formula, Xvals, Yvals, coefficients));
            }

            // create solver model
            SolverContext solver = SolverContext.GetContext();

            solver.ClearModel();
            Model model = solver.CreateModel();

            foreach (var parameter in coefficients)
            {
                if (parameter.Value.Variable)//add variable
                {
                    //m.AddDecision(new Decision(Domain.IntegerRange(0, 100), "b"));
                    //Decision des = new Decision(Domain.Real, parameter.Key);
                    Decision des = new Decision(Domain.RealRange(parameter.Value.Min, parameter.Value.Max), parameter.Key);
                    des.SetInitialValue(parameter.Value.Value);
                    model.AddDecision(des);
                }
                else // add scalar
                {
                    Microsoft.SolverFoundation.Services.Parameter par =
                        new Microsoft.SolverFoundation.Services.Parameter(
                            Domain.Real, parameter.Key);
                    //par.SetBinding(new double[] { parameter.Value.Value }, parameter.Key);
                    par.SetBinding((double)parameter.Value.Value);
                    model.AddParameters(par);
                }
            }

            //operators: https://msdn.microsoft.com/en-us/library/gg261757(v=vs.93).aspx
            string theTerm = "((" + formula.Replace("t", Xvals[0].ToString()).Replace("Sqr" + Xvals[0].ToString(), "Sqrt") + ") - " + Yvals[0].ToString() + ") ^ 2";

            for (int i = 1; i < Xvals.Length && i < Yvals.Length; i++)
            {
                theTerm += " + ((" + formula.Replace("t", Xvals[i].ToString()).Replace("Sqr" + Xvals[i].ToString(), "Sqrt") + ") - " + Yvals[i].ToString() + ") ^ 2";
            }

            //
            // define optimization type and give objective function SUM(e^2) to be minimized

            model.AddGoal("SumOfSquaredErrors", GoalKind.Minimize, theTerm);
            //
            // solve model and transfer results (optimized decision variables) from
            // model into a dictionary object which will be returned for the caller
            Solution solution = solver.Solve();
            //return the result
            Dictionary <string, MySolver.Parameter> parameters = new Dictionary <string, MySolver.Parameter>();

            foreach (Decision parameter in model.Decisions)
            {
                MySolver.Parameter p;

                if (!coefficients.TryGetValue(parameter.Name, out p))
                {
                    p = new Parameter(parameter.Name);
                }

                parameters.Add(parameter.Name, new Parameter
                                   (parameter.Name, parameter.ToDouble(), p.Min, p.Max, p.Variable));
            }

            return(parameters);
        }
Esempio n. 26
0
        public void SetUp()
        {
            SolverContext context = SolverContext.GetContext();

            context.ClearModel();
        }
Esempio n. 27
0
        public static Decision SBFF()
        {
            // -----------------------------Game Matrix-------------------------------------------
            IEnumerable <TheModelStructure> pStrategies = new List <TheModelStructure>()
            {
                new TheModelStructure()
                {
                    tName = "T1", uDC = 5, uAU = 5, uDU = -20, uAC = -24, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T2", uDC = 2, uAU = 2, uDU = -8, uAC = -12, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T3", uDC = 6, uAU = 6, uDU = -24, uAC = -28, dMS = 0.09
                },
                new TheModelStructure()
                {
                    tName = "T4", uDC = 2, uAU = 1, uDU = -8, uAC = -12, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T5", uDC = 4, uAU = 4, uDU = -16, uAC = -20, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T6", uDC = 3, uAU = 3, uDU = -9, uAC = -13, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T7", uDC = 3, uAU = 3, uDU = -12, uAC = -16, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T8", uDC = 8, uAU = 7, uDU = -32, uAC = -36, dMS = 0.35
                },
                new TheModelStructure()
                {
                    tName = "T9", uDC = 2, uAU = 2, uDU = -8, uAC = -12, dMS = 0.07
                },
                new TheModelStructure()
                {
                    tName = "T10", uDC = 6, uAU = 6, uDU = -24, uAC = -28, dMS = 0.07
                }
                //new TheModelStructure() {tableName = "Table11", tableValue = 5},
                //new TheModelStructure() {tableName = "Table12", tableValue = 3},
                //new TheModelStructure() {tableName = "Table13", tableValue = 4},
                //new TheModelStructure() {tableName = "Table14", tableValue = 3},
                //new TheModelStructure() {tableName = "Table15", tableValue = 4},
                //new TheModelStructure() {tableName = "Table16", tableValue = 7},
                //new TheModelStructure() {tableName = "Table17", tableValue = 5},
                //new TheModelStructure() {tableName = "Table18", tableValue = 8},
                //new TheModelStructure() {tableName = "Table19", tableValue = 4},
                //new TheModelStructure() {tableName = "Table20", tableValue = 5}
            };

            //---------------------------Intilizing the solver----------------------------------------------
            SolverContext context        = SolverContext.GetContext();
            Model         model          = context.CreateModel();
            Set           modelStructure = new Set(Domain.Any, "game");

            //----------------------------Game parameters----------------------------------------------------
            Parameter uDC = new Parameter(Domain.Integer, "uDC", modelStructure);

            uDC.SetBinding(pStrategies, "uDC", "tName"); // bind to the  field.
            model.AddParameters(uDC);

            Parameter uDU = new Parameter(Domain.Integer, "uDU", modelStructure);

            uDU.SetBinding(pStrategies, "uDU", "tName"); // bind to the  field.
            model.AddParameters(uDU);


            Parameter uAU = new Parameter(Domain.Integer, "uAU", modelStructure);

            uAU.SetBinding(pStrategies, "uAU", "tName"); // bind to the  field.
            model.AddParameters(uAU);

            Parameter uAC = new Parameter(Domain.Integer, "uAC", modelStructure);

            uAC.SetBinding(pStrategies, "uAC", "tName"); // bind to the  field.
            model.AddParameters(uAC);


            Parameter dMS = new Parameter(Domain.Real, "dMS", modelStructure);

            dMS.SetBinding(pStrategies, "dMS", "tName"); // bind to the  field.
            model.AddParameters(dMS);


            //---------------------------Decision Variables------------------------------------------------
            Decision fMS = new Decision(Domain.RealRange(0.03, 0.40), "fMS", modelStructure);

            model.AddDecision(fMS);



            //----------------------------Objective function----------------------------------------------

            model.AddGoal("aGoal", GoalKind.Maximize, Model.Sum(
                              Model.ForEach(modelStructure, i => fMS[i] * dMS[i] * uAC[i] + (1 - fMS[i]) * (1 - dMS[i]) * uAU[i])));



            model.AddConstraint("fms",
                                Model.Sum(Model.ForEach(modelStructure, i => fMS[i])) == 1);



            //-------------------------------Solvig the game------------------------------------
            try
            {
                var solution = context.Solve();
            }
            catch (Exception e)
            {
                throw e;
            }

            context.ClearModel();

            return(fMS);
        }
Esempio n. 28
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);
                }
            }
        }
Esempio n. 29
0
        private Dictionary <String, double> solve(List <BinaryOption> variables, List <double> results, List <List <BinaryOption> > configurations, List <Interaction> interactions)
        {
            Dictionary <String, double> optionInfluences = new Dictionary <string, double>();

            foreach (BinaryOption elem in variables)
            {
                optionInfluences.Add(elem.Name, 0);
            }
            if (interactions != null)
            {
                foreach (Interaction inter in interactions)
                {
                    optionInfluences.Add(inter.Name, 0);
                }
            }

            //Building the OML model
            StringBuilder omlModel = new StringBuilder();

            omlModel.Append("Model[");

            String decisions = generateDecisionOML(variables, results);

            omlModel.Append(decisions + ",");
            String constraints = generateConstraintOML(variables, configurations, interactions, results);

            omlModel.Append(constraints + ",");

            String goal = generateGoalOML(results.Count);

            omlModel.Append(goal + "]");

            Console.WriteLine(omlModel);
            SolverContext context = SolverContext.GetContext();

            context.ClearModel();
            //String model = "Model[Decisions[Reals[0,Infinity], f1,f2,y1,y2,y3],Constraints[f1+y1==1,f1+f2+y2==4,f2+y3==3],Goals[Minimize[y1+y2+y3]]]";
            //String model = "Model[Decisions[Reals[0,Infinity],fp1,fn1,fp2,fn2,yp1,yn1,yp2,yn2,yp3,yn3],Constraints[fp1-fn1+yp1-yn1==1,fp1-fn1+fp2-fn2+yp2-yn2==0,fp2-fn2+yp3-yn3==-1],Goals[Minimize[yp1+yn1+yp2+yn2+yp3+yn3]]]";
            //Console.WriteLine(omlModel.ToString());
            context.LoadModel(FileFormat.OML, new StringReader(omlModel.ToString()));

            //List<double> erglist = new List<double>();


            //Solve the optimization problem
            if (context.CheckModel().IsValid)
            {
                Solution      solution = context.Solve();
                StringBuilder sb       = new StringBuilder();

                foreach (Decision d in solution.Decisions)
                {
                    sb.Append(d.ToString() + "; ");

                    //Constructing feature Values
                    string option = d.Name.Substring(0, d.Name.Length - 2);
                    if (d.Name.EndsWith("_p"))
                    {
                        optionInfluences[option] += d.ToDouble();
                    }
                    else if (d.Name.EndsWith("_n"))
                    {
                        optionInfluences[option] -= d.ToDouble();
                    }
                }

                /*if (this.withStandardDeviation && this.standardDeviation != 0)
                 * {
                 *  foreach (BinaryOption elem in variables)
                 *  {
                 *       if(featureValues[elem.Name] == 0)
                 *           continue;
                 *      int configNb = 0;
                 *      foreach (List<BinaryOption> config in configurations)
                 *      {
                 *          bool derivativeRequired = true;
                 *          foreach(Element parent in elem.getDerivativeParents())
                 *          {
                 *              if(config.Contains(parent) == false)
                 *              {
                 *                  derivativeRequired = false;
                 *                  break;
                 *              }
                 *          }
                 *          if(derivativeRequired)
                 *          {
                 *              double equationValue = results[configNb];
                 *              if (Math.Abs(featureValues[elem.Name]) < Math.Abs(equationValue * this.standardDeviation / 100))
                 *              {
                 *                  featureValues[elem.Name] = 0;
                 *                  break;
                 *              }
                 *          }
                 *          configNb++;
                 *      }
                 *  }
                 * }*/
            }
            return(optionInfluences);
        }
Esempio n. 30
0
        private void btnCalc_Click(object sender, EventArgs e)
        {
            if (
                #region ---
                (txtRashod_PG_base_DP_1.Text == "") ||
                (txtRashod_PG_base_DPmin_1.Text == "") ||
                (txtRashod_PG_base_DPmax_1.Text == "") ||
                (txtRashod_K_base_DP_1.Text == "") ||
                (txtRashod_K_base_DP_E_1.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_1.Text == "") ||
                (txtTeor_t_base_DP_1.Text == "") ||
                (txtTeor_t_base_DPmin_1.Text == "") ||
                (txtTeor_t_base_DPmax_1.Text == "") ||
                (txtProiz_chug_iz_PG_DP_1.Text == "") ||
                (txtProiz_chug_uvel_K_DP_1.Text == "") ||
                (txtIz_t_uvel_pg_DP_1.Text == "") ||

                (txtRashod_PG_base_DP_2.Text == "") ||
                (txtRashod_PG_base_DPmin_2.Text == "") ||
                (txtRashod_PG_base_DPmax_2.Text == "") ||
                (txtRashod_K_base_DP_2.Text == "") ||
                (txtRashod_K_base_DP_E_2.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_2.Text == "") ||
                (txtTeor_t_base_DP_2.Text == "") ||
                (txtTeor_t_base_DPmin_2.Text == "") ||
                (txtTeor_t_base_DPmax_2.Text == "") ||
                (txtProiz_chug_iz_PG_DP_2.Text == "") ||
                (txtProiz_chug_uvel_K_DP_2.Text == "") ||
                (txtIz_t_uvel_pg_DP_2.Text == "") ||

                (txtRashod_PG_base_DP_3.Text == "") ||
                (txtRashod_PG_base_DPmin_3.Text == "") ||
                (txtRashod_PG_base_DPmax_3.Text == "") ||
                (txtRashod_K_base_DP_3.Text == "") ||
                (txtRashod_K_base_DP_E_3.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_3.Text == "") ||
                (txtTeor_t_base_DP_3.Text == "") ||
                (txtTeor_t_base_DPmin_3.Text == "") ||
                (txtTeor_t_base_DPmax_3.Text == "") ||
                (txtProiz_chug_iz_PG_DP_3.Text == "") ||
                (txtProiz_chug_uvel_K_DP_3.Text == "") ||
                (txtIz_t_uvel_pg_DP_3.Text == "") ||

                (txtRashod_PG_base_DP_4.Text == "") ||
                (txtRashod_PG_base_DPmin_4.Text == "") ||
                (txtRashod_PG_base_DPmax_4.Text == "") ||
                (txtRashod_K_base_DP_4.Text == "") ||
                (txtRashod_K_base_DP_E_4.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_4.Text == "") ||
                (txtTeor_t_base_DP_4.Text == "") ||
                (txtTeor_t_base_DPmin_4.Text == "") ||
                (txtTeor_t_base_DPmax_4.Text == "") ||
                (txtProiz_chug_iz_PG_DP_4.Text == "") ||
                (txtProiz_chug_uvel_K_DP_4.Text == "") ||
                (txtIz_t_uvel_pg_DP_4.Text == "") ||

                (txtRashod_PG_base_DP_5.Text == "") ||
                (txtRashod_PG_base_DPmin_5.Text == "") ||
                (txtRashod_PG_base_DPmax_5.Text == "") ||
                (txtRashod_K_base_DP_5.Text == "") ||
                (txtRashod_K_base_DP_E_5.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_5.Text == "") ||
                (txtTeor_t_base_DP_5.Text == "") ||
                (txtTeor_t_base_DPmin_5.Text == "") ||
                (txtTeor_t_base_DPmax_5.Text == "") ||
                (txtProiz_chug_iz_PG_DP_5.Text == "") ||
                (txtProiz_chug_uvel_K_DP_5.Text == "") ||
                (txtIz_t_uvel_pg_DP_5.Text == "") ||

                (txtRashod_PG_base_DP_6.Text == "") ||
                (txtRashod_PG_base_DPmin_6.Text == "") ||
                (txtRashod_PG_base_DPmax_6.Text == "") ||
                (txtRashod_K_base_DP_6.Text == "") ||
                (txtRashod_K_base_DP_E_6.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_6.Text == "") ||
                (txtTeor_t_base_DP_6.Text == "") ||
                (txtTeor_t_base_DPmin_6.Text == "") ||
                (txtTeor_t_base_DPmax_6.Text == "") ||
                (txtProiz_chug_iz_PG_DP_6.Text == "") ||
                (txtProiz_chug_uvel_K_DP_6.Text == "") ||
                (txtIz_t_uvel_pg_DP_6.Text == "") ||

                (txtRashod_PG_base_DP_7.Text == "") ||
                (txtRashod_PG_base_DPmin_7.Text == "") ||
                (txtRashod_PG_base_DPmax_7.Text == "") ||
                (txtRashod_K_base_DP_7.Text == "") ||
                (txtRashod_K_base_DP_E_7.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_7.Text == "") ||
                (txtTeor_t_base_DP_7.Text == "") ||
                (txtTeor_t_base_DPmin_7.Text == "") ||
                (txtTeor_t_base_DPmax_7.Text == "") ||
                (txtProiz_chug_iz_PG_DP_7.Text == "") ||
                (txtProiz_chug_uvel_K_DP_7.Text == "") ||
                (txtIz_t_uvel_pg_DP_7.Text == "") ||

                (txtRashod_PG_base_DP_8.Text == "") ||
                (txtRashod_PG_base_DPmin_8.Text == "") ||
                (txtRashod_PG_base_DPmax_8.Text == "") ||
                (txtRashod_K_base_DP_8.Text == "") ||
                (txtRashod_K_base_DP_E_8.Text == "") ||
                (txtProizvoditelnost_chug_base_DP_8.Text == "") ||
                (txtTeor_t_base_DP_8.Text == "") ||
                (txtTeor_t_base_DPmin_8.Text == "") ||
                (txtTeor_t_base_DPmax_8.Text == "") ||
                (txtProiz_chug_iz_PG_DP_8.Text == "") ||
                (txtProiz_chug_uvel_K_DP_8.Text == "") ||
                (txtIz_t_uvel_pg_DP_8.Text == ""))
            #endregion ---
            {
                tPGraph.Parent = null;
                MessageBox.Show("Не все поля заполнены!", "Ошибка");
                return;
            }
            //очищаем
            chart1.Series[0].Points.Clear();
            chart1.Series[1].Points.Clear();

            //при нажатии на кнопку, открывается вкладка
            tPGraph.Parent = tab;

            List <ModelDP> modelDPs = new List <ModelDP>();
            #region -- Загрузка первоначальных значений

            // ДП-1
            _mdp.Rashod_PG_base_DP_1    = Double.Parse(txtRashod_PG_base_DP_1.Text);
            _mdp.Rashod_PG_base_DPmin_1 = Double.Parse(txtRashod_PG_base_DPmin_1.Text);
            _mdp.Rashod_PG_base_DPmax_1 = Double.Parse(txtRashod_PG_base_DPmax_1.Text);
            _mdp.Rashod_K_base_DP_1     = Double.Parse(txtRashod_K_base_DP_1.Text);


            _mdp.Rashod_K_base_DP_E_1            = Double.Parse(txtRashod_K_base_DP_E_1.Text);
            _mdp.Proizvoditelnost_chug_base_DP_1 = Double.Parse(txtProizvoditelnost_chug_base_DP_1.Text);
            _mdp.Teor_t_base_DP_1    = Double.Parse(txtTeor_t_base_DP_1.Text);
            _mdp.Teor_t_base_DPmin_1 = Double.Parse(txtTeor_t_base_DPmin_1.Text);
            _mdp.Teor_t_base_DPmax_1 = Double.Parse(txtTeor_t_base_DPmax_1.Text);

            _mdp.Proiz_chug_iz_PG_DP_1  = Double.Parse(txtProiz_chug_iz_PG_DP_1.Text);
            _mdp.Proiz_chug_uvel_K_DP_1 = Double.Parse(txtProiz_chug_uvel_K_DP_1.Text);
            _mdp.Iz_t_uvel_pg_DP_1      = Double.Parse(txtIz_t_uvel_pg_DP_1.Text);



            // ДП-2
            _mdp.Rashod_PG_base_DP_2    = Double.Parse(txtRashod_PG_base_DP_2.Text);
            _mdp.Rashod_PG_base_DPmin_2 = Double.Parse(txtRashod_PG_base_DPmin_2.Text);
            _mdp.Rashod_PG_base_DPmax_2 = Double.Parse(txtRashod_PG_base_DPmax_2.Text);
            _mdp.Rashod_K_base_DP_2     = Double.Parse(txtRashod_K_base_DP_2.Text);


            _mdp.Rashod_K_base_DP_E_2            = Double.Parse(txtRashod_K_base_DP_E_2.Text);
            _mdp.Proizvoditelnost_chug_base_DP_2 = Double.Parse(txtProizvoditelnost_chug_base_DP_2.Text);
            _mdp.Teor_t_base_DP_2    = Double.Parse(txtTeor_t_base_DP_2.Text);
            _mdp.Teor_t_base_DPmin_2 = Double.Parse(txtTeor_t_base_DPmin_2.Text);
            _mdp.Teor_t_base_DPmax_2 = Double.Parse(txtTeor_t_base_DPmax_2.Text);

            _mdp.Proiz_chug_iz_PG_DP_2  = Double.Parse(txtProiz_chug_iz_PG_DP_2.Text);
            _mdp.Proiz_chug_uvel_K_DP_2 = Double.Parse(txtProiz_chug_uvel_K_DP_2.Text);
            _mdp.Iz_t_uvel_pg_DP_2      = Double.Parse(txtIz_t_uvel_pg_DP_2.Text);


            // ДП-3
            _mdp.Rashod_PG_base_DP_3    = Double.Parse(txtRashod_PG_base_DP_3.Text);
            _mdp.Rashod_PG_base_DPmin_3 = Double.Parse(txtRashod_PG_base_DPmin_3.Text);
            _mdp.Rashod_PG_base_DPmax_3 = Double.Parse(txtRashod_PG_base_DPmax_3.Text);
            _mdp.Rashod_K_base_DP_3     = Double.Parse(txtRashod_K_base_DP_3.Text);


            _mdp.Rashod_K_base_DP_E_3            = Double.Parse(txtRashod_K_base_DP_E_3.Text);
            _mdp.Proizvoditelnost_chug_base_DP_3 = Double.Parse(txtProizvoditelnost_chug_base_DP_3.Text);
            _mdp.Teor_t_base_DP_3    = Double.Parse(txtTeor_t_base_DP_3.Text);
            _mdp.Teor_t_base_DPmin_3 = Double.Parse(txtTeor_t_base_DPmin_3.Text);
            _mdp.Teor_t_base_DPmax_3 = Double.Parse(txtTeor_t_base_DPmax_3.Text);

            _mdp.Proiz_chug_iz_PG_DP_3  = Double.Parse(txtProiz_chug_iz_PG_DP_3.Text);
            _mdp.Proiz_chug_uvel_K_DP_3 = Double.Parse(txtProiz_chug_uvel_K_DP_3.Text);
            _mdp.Iz_t_uvel_pg_DP_3      = Double.Parse(txtIz_t_uvel_pg_DP_3.Text);

            // ДП-4
            _mdp.Rashod_PG_base_DP_4    = Double.Parse(txtRashod_PG_base_DP_4.Text);
            _mdp.Rashod_PG_base_DPmin_4 = Double.Parse(txtRashod_PG_base_DPmin_4.Text);
            _mdp.Rashod_PG_base_DPmax_4 = Double.Parse(txtRashod_PG_base_DPmax_4.Text);
            _mdp.Rashod_K_base_DP_4     = Double.Parse(txtRashod_K_base_DP_4.Text);


            _mdp.Rashod_K_base_DP_E_4            = Double.Parse(txtRashod_K_base_DP_E_4.Text);
            _mdp.Proizvoditelnost_chug_base_DP_4 = Double.Parse(txtProizvoditelnost_chug_base_DP_4.Text);
            _mdp.Teor_t_base_DP_4    = Double.Parse(txtTeor_t_base_DP_4.Text);
            _mdp.Teor_t_base_DPmin_4 = Double.Parse(txtTeor_t_base_DPmin_4.Text);
            _mdp.Teor_t_base_DPmax_4 = Double.Parse(txtTeor_t_base_DPmax_4.Text);

            _mdp.Proiz_chug_iz_PG_DP_4  = Double.Parse(txtProiz_chug_iz_PG_DP_4.Text);
            _mdp.Proiz_chug_uvel_K_DP_4 = Double.Parse(txtProiz_chug_uvel_K_DP_4.Text);
            _mdp.Iz_t_uvel_pg_DP_4      = Double.Parse(txtIz_t_uvel_pg_DP_4.Text);

            // ДП-5
            _mdp.Rashod_PG_base_DP_5    = Double.Parse(txtRashod_PG_base_DP_5.Text);
            _mdp.Rashod_PG_base_DPmin_5 = Double.Parse(txtRashod_PG_base_DPmin_5.Text);
            _mdp.Rashod_PG_base_DPmax_5 = Double.Parse(txtRashod_PG_base_DPmax_5.Text);
            _mdp.Rashod_K_base_DP_5     = Double.Parse(txtRashod_K_base_DP_5.Text);


            _mdp.Rashod_K_base_DP_E_5            = Double.Parse(txtRashod_K_base_DP_E_5.Text);
            _mdp.Proizvoditelnost_chug_base_DP_5 = Double.Parse(txtProizvoditelnost_chug_base_DP_5.Text);
            _mdp.Teor_t_base_DP_5    = Double.Parse(txtTeor_t_base_DP_5.Text);
            _mdp.Teor_t_base_DPmin_5 = Double.Parse(txtTeor_t_base_DPmin_5.Text);
            _mdp.Teor_t_base_DPmax_5 = Double.Parse(txtTeor_t_base_DPmax_5.Text);

            _mdp.Proiz_chug_iz_PG_DP_5  = Double.Parse(txtProiz_chug_iz_PG_DP_5.Text);
            _mdp.Proiz_chug_uvel_K_DP_5 = Double.Parse(txtProiz_chug_uvel_K_DP_5.Text);
            _mdp.Iz_t_uvel_pg_DP_5      = Double.Parse(txtIz_t_uvel_pg_DP_5.Text);
            // ДП-6
            _mdp.Rashod_PG_base_DP_6    = Double.Parse(txtRashod_PG_base_DP_6.Text);
            _mdp.Rashod_PG_base_DPmin_6 = Double.Parse(txtRashod_PG_base_DPmin_6.Text);
            _mdp.Rashod_PG_base_DPmax_6 = Double.Parse(txtRashod_PG_base_DPmax_6.Text);
            _mdp.Rashod_K_base_DP_6     = Double.Parse(txtRashod_K_base_DP_6.Text);


            _mdp.Rashod_K_base_DP_E_6            = Double.Parse(txtRashod_K_base_DP_E_6.Text);
            _mdp.Proizvoditelnost_chug_base_DP_6 = Double.Parse(txtProizvoditelnost_chug_base_DP_6.Text);
            _mdp.Teor_t_base_DP_6    = Double.Parse(txtTeor_t_base_DP_6.Text);
            _mdp.Teor_t_base_DPmin_6 = Double.Parse(txtTeor_t_base_DPmin_6.Text);
            _mdp.Teor_t_base_DPmax_6 = Double.Parse(txtTeor_t_base_DPmax_6.Text);

            _mdp.Proiz_chug_iz_PG_DP_6  = Double.Parse(txtProiz_chug_iz_PG_DP_6.Text);
            _mdp.Proiz_chug_uvel_K_DP_6 = Double.Parse(txtProiz_chug_uvel_K_DP_6.Text);
            _mdp.Iz_t_uvel_pg_DP_6      = Double.Parse(txtIz_t_uvel_pg_DP_6.Text);
            // ДП-7
            _mdp.Rashod_PG_base_DP_7    = Double.Parse(txtRashod_PG_base_DP_7.Text);
            _mdp.Rashod_PG_base_DPmin_7 = Double.Parse(txtRashod_PG_base_DPmin_7.Text);
            _mdp.Rashod_PG_base_DPmax_7 = Double.Parse(txtRashod_PG_base_DPmax_7.Text);
            _mdp.Rashod_K_base_DP_7     = Double.Parse(txtRashod_K_base_DP_7.Text);


            _mdp.Rashod_K_base_DP_E_7            = Double.Parse(txtRashod_K_base_DP_E_7.Text);
            _mdp.Proizvoditelnost_chug_base_DP_7 = Double.Parse(txtProizvoditelnost_chug_base_DP_7.Text);
            _mdp.Teor_t_base_DP_7    = Double.Parse(txtTeor_t_base_DP_7.Text);
            _mdp.Teor_t_base_DPmin_7 = Double.Parse(txtTeor_t_base_DPmin_7.Text);
            _mdp.Teor_t_base_DPmax_7 = Double.Parse(txtTeor_t_base_DPmax_7.Text);

            _mdp.Proiz_chug_iz_PG_DP_7  = Double.Parse(txtProiz_chug_iz_PG_DP_7.Text);
            _mdp.Proiz_chug_uvel_K_DP_7 = Double.Parse(txtProiz_chug_uvel_K_DP_7.Text);
            _mdp.Iz_t_uvel_pg_DP_7      = Double.Parse(txtIz_t_uvel_pg_DP_7.Text);
            // ДП-8
            _mdp.Rashod_PG_base_DP_8    = Double.Parse(txtRashod_PG_base_DP_8.Text);
            _mdp.Rashod_PG_base_DPmin_8 = Double.Parse(txtRashod_PG_base_DPmin_8.Text);
            _mdp.Rashod_PG_base_DPmax_8 = Double.Parse(txtRashod_PG_base_DPmax_8.Text);
            _mdp.Rashod_K_base_DP_8     = Double.Parse(txtRashod_K_base_DP_8.Text);


            _mdp.Rashod_K_base_DP_E_8            = Double.Parse(txtRashod_K_base_DP_E_8.Text);
            _mdp.Proizvoditelnost_chug_base_DP_8 = Double.Parse(txtProizvoditelnost_chug_base_DP_8.Text);
            _mdp.Teor_t_base_DP_8    = Double.Parse(txtTeor_t_base_DP_8.Text);
            _mdp.Teor_t_base_DPmin_8 = Double.Parse(txtTeor_t_base_DPmin_8.Text);
            _mdp.Teor_t_base_DPmax_8 = Double.Parse(txtTeor_t_base_DPmax_8.Text);

            _mdp.Proiz_chug_iz_PG_DP_8  = Double.Parse(txtProiz_chug_iz_PG_DP_8.Text);
            _mdp.Proiz_chug_uvel_K_DP_8 = Double.Parse(txtProiz_chug_uvel_K_DP_8.Text);
            _mdp.Iz_t_uvel_pg_DP_8      = Double.Parse(txtIz_t_uvel_pg_DP_8.Text);

            //параметры
            _mdp.Stoimoct_k       = Double.Parse(txtStoimoct_k.Text);
            _mdp.Stoimoct_pg      = Double.Parse(txtStoimoct_pg.Text);
            _mdp.Rezerf_rashod_pg = Double.Parse(txtRezerf_rashod_pg.Text);
            _mdp.Zapas_k          = Double.Parse(txtZapas_k.Text);
            _mdp.Treb_proiz_chug  = Double.Parse(txtTreb_proiz_chug.Text);

            #endregion -- Загрузка первоначальных значений
            #region ---
            //Для ДП1
            modelDPs.Add(new ModelDP {
                xId                  = 1,
                Koef                 = (_mdp.Rashod_K_base_DP_E_1 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_1),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_1 + 0.001 * _mdp.Rashod_PG_base_DP_1 * _mdp.Rashod_K_base_DP_E_1),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_1 - _mdp.Rashod_K_base_DP_E_1 * _mdp.Proiz_chug_uvel_K_DP_1,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_1 * _mdp.Proiz_chug_iz_PG_DP_1 + _mdp.Rashod_K_base_DP_E_1 * _mdp.Rashod_PG_base_DP_1 * _mdp.Proiz_chug_uvel_K_DP_1 + _mdp.Proizvoditelnost_chug_base_DP_1,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_1 + _mdp.Rashod_PG_base_DP_1 * _mdp.Iz_t_uvel_pg_DP_1 - _mdp.Teor_t_base_DP_1) / _mdp.Iz_t_uvel_pg_DP_1,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_1 + _mdp.Rashod_PG_base_DP_1 * _mdp.Iz_t_uvel_pg_DP_1 - _mdp.Teor_t_base_DP_1) / _mdp.Iz_t_uvel_pg_DP_1,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_1,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_1,
            });
            //Для ДП2
            modelDPs.Add(new ModelDP
            {
                xId                  = 2,
                Koef                 = (_mdp.Rashod_K_base_DP_E_2 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_2),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_2 + 0.001 * _mdp.Rashod_PG_base_DP_2 * _mdp.Rashod_K_base_DP_E_2),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_2 - _mdp.Rashod_K_base_DP_E_2 * _mdp.Proiz_chug_uvel_K_DP_2,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_2 * _mdp.Proiz_chug_iz_PG_DP_2 + _mdp.Rashod_K_base_DP_E_2 * _mdp.Rashod_PG_base_DP_2 * _mdp.Proiz_chug_uvel_K_DP_2 + _mdp.Proizvoditelnost_chug_base_DP_2,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_2 + _mdp.Rashod_PG_base_DP_2 * _mdp.Iz_t_uvel_pg_DP_2 - _mdp.Teor_t_base_DP_2) / _mdp.Iz_t_uvel_pg_DP_2,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_2 + _mdp.Rashod_PG_base_DP_2 * _mdp.Iz_t_uvel_pg_DP_2 - _mdp.Teor_t_base_DP_2) / _mdp.Iz_t_uvel_pg_DP_2,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_2,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_2
            });

            //Для ДП3
            modelDPs.Add(new ModelDP
            {
                xId                  = 3,
                Koef                 = (_mdp.Rashod_K_base_DP_E_3 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_3),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_3 + 0.001 * _mdp.Rashod_PG_base_DP_3 * _mdp.Rashod_K_base_DP_E_3),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_3 - _mdp.Rashod_K_base_DP_E_3 * _mdp.Proiz_chug_uvel_K_DP_3,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_3 * _mdp.Proiz_chug_iz_PG_DP_3 + _mdp.Rashod_K_base_DP_E_3 * _mdp.Rashod_PG_base_DP_3 * _mdp.Proiz_chug_uvel_K_DP_3 + _mdp.Proizvoditelnost_chug_base_DP_3,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_3 + _mdp.Rashod_PG_base_DP_3 * _mdp.Iz_t_uvel_pg_DP_3 - _mdp.Teor_t_base_DP_3) / _mdp.Iz_t_uvel_pg_DP_3,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_3 + _mdp.Rashod_PG_base_DP_3 * _mdp.Iz_t_uvel_pg_DP_3 - _mdp.Teor_t_base_DP_3) / _mdp.Iz_t_uvel_pg_DP_3,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_3,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_3
            });

            //Для ДП4
            modelDPs.Add(new ModelDP
            {
                xId                  = 4,
                Koef                 = (_mdp.Rashod_K_base_DP_E_4 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_4),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_4 + 0.001 * _mdp.Rashod_PG_base_DP_4 * _mdp.Rashod_K_base_DP_E_4),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_4 - _mdp.Rashod_K_base_DP_E_4 * _mdp.Proiz_chug_uvel_K_DP_4,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_4 * _mdp.Proiz_chug_iz_PG_DP_4 + _mdp.Rashod_K_base_DP_E_4 * _mdp.Rashod_PG_base_DP_4 * _mdp.Proiz_chug_uvel_K_DP_4 + _mdp.Proizvoditelnost_chug_base_DP_4,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_4 + _mdp.Rashod_PG_base_DP_4 * _mdp.Iz_t_uvel_pg_DP_4 - _mdp.Teor_t_base_DP_4) / _mdp.Iz_t_uvel_pg_DP_4,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_4 + _mdp.Rashod_PG_base_DP_4 * _mdp.Iz_t_uvel_pg_DP_4 - _mdp.Teor_t_base_DP_4) / _mdp.Iz_t_uvel_pg_DP_4,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_4,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_4
            });

            //Для ДП5
            modelDPs.Add(new ModelDP
            {
                xId                  = 5,
                Koef                 = (_mdp.Rashod_K_base_DP_E_5 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_5),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_5 + 0.001 * _mdp.Rashod_PG_base_DP_5 * _mdp.Rashod_K_base_DP_E_5),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_5 - _mdp.Rashod_K_base_DP_E_5 * _mdp.Proiz_chug_uvel_K_DP_5,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_5 * _mdp.Proiz_chug_iz_PG_DP_5 + _mdp.Rashod_K_base_DP_E_5 * _mdp.Rashod_PG_base_DP_5 * _mdp.Proiz_chug_uvel_K_DP_5 + _mdp.Proizvoditelnost_chug_base_DP_5,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_5 + _mdp.Rashod_PG_base_DP_5 * _mdp.Iz_t_uvel_pg_DP_5 - _mdp.Teor_t_base_DP_5) / _mdp.Iz_t_uvel_pg_DP_5,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_5 + _mdp.Rashod_PG_base_DP_5 * _mdp.Iz_t_uvel_pg_DP_5 - _mdp.Teor_t_base_DP_5) / _mdp.Iz_t_uvel_pg_DP_5,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_5,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_5
            });

            //Для ДП6
            modelDPs.Add(new ModelDP
            {
                xId                  = 6,
                Koef                 = (_mdp.Rashod_K_base_DP_E_6 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_6),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_6 + 0.001 * _mdp.Rashod_PG_base_DP_6 * _mdp.Rashod_K_base_DP_E_6),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_6 - _mdp.Rashod_K_base_DP_E_6 * _mdp.Proiz_chug_uvel_K_DP_6,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_6 * _mdp.Proiz_chug_iz_PG_DP_6 + _mdp.Rashod_K_base_DP_E_6 * _mdp.Rashod_PG_base_DP_6 * _mdp.Proiz_chug_uvel_K_DP_6 + _mdp.Proizvoditelnost_chug_base_DP_6,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_6 + _mdp.Rashod_PG_base_DP_6 * _mdp.Iz_t_uvel_pg_DP_6 - _mdp.Teor_t_base_DP_6) / _mdp.Iz_t_uvel_pg_DP_6,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_6 + _mdp.Rashod_PG_base_DP_6 * _mdp.Iz_t_uvel_pg_DP_6 - _mdp.Teor_t_base_DP_6) / _mdp.Iz_t_uvel_pg_DP_6,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_6,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_6
            });

            //Для ДП7
            modelDPs.Add(new ModelDP
            {
                xId                  = 7,
                Koef                 = (_mdp.Rashod_K_base_DP_E_7 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_7),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_7 + 0.001 * _mdp.Rashod_PG_base_DP_7 * _mdp.Rashod_K_base_DP_E_7),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_7 - _mdp.Rashod_K_base_DP_E_7 * _mdp.Proiz_chug_uvel_K_DP_7,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_7 * _mdp.Proiz_chug_iz_PG_DP_7 + _mdp.Rashod_K_base_DP_E_7 * _mdp.Rashod_PG_base_DP_7 * _mdp.Proiz_chug_uvel_K_DP_7 + _mdp.Proizvoditelnost_chug_base_DP_7,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_7 + _mdp.Rashod_PG_base_DP_7 * _mdp.Iz_t_uvel_pg_DP_7 - _mdp.Teor_t_base_DP_7) / _mdp.Iz_t_uvel_pg_DP_7,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_7 + _mdp.Rashod_PG_base_DP_7 * _mdp.Iz_t_uvel_pg_DP_7 - _mdp.Teor_t_base_DP_7) / _mdp.Iz_t_uvel_pg_DP_7,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_7,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_7
            });

            //Для ДП8
            modelDPs.Add(new ModelDP
            {
                xId                  = 8,
                Koef                 = (_mdp.Rashod_K_base_DP_E_8 * _mdp.Stoimoct_k - _mdp.Stoimoct_pg),
                KoefNerav1           = (-0.001 * _mdp.Rashod_K_base_DP_E_8),
                KoefNerav11          = (_mdp.Rashod_K_base_DP_8 + 0.001 * _mdp.Rashod_PG_base_DP_8 * _mdp.Rashod_K_base_DP_E_8),
                KoefNerav2           = _mdp.Proiz_chug_iz_PG_DP_8 - _mdp.Rashod_K_base_DP_E_8 * _mdp.Proiz_chug_uvel_K_DP_8,
                KoefNerav22          = -_mdp.Rashod_PG_base_DP_8 * _mdp.Proiz_chug_iz_PG_DP_8 + _mdp.Rashod_K_base_DP_E_8 * _mdp.Rashod_PG_base_DP_8 * _mdp.Proiz_chug_uvel_K_DP_8 + _mdp.Proizvoditelnost_chug_base_DP_8,
                KoefNerav3           = (_mdp.Teor_t_base_DPmin_8 + _mdp.Rashod_PG_base_DP_8 * _mdp.Iz_t_uvel_pg_DP_8 - _mdp.Teor_t_base_DP_8) / _mdp.Iz_t_uvel_pg_DP_8,
                KoefNerav33          = (_mdp.Teor_t_base_DPmax_8 + _mdp.Rashod_PG_base_DP_8 * _mdp.Iz_t_uvel_pg_DP_8 - _mdp.Teor_t_base_DP_8) / _mdp.Iz_t_uvel_pg_DP_8,
                Rashod_PG_base_DPmin = _mdp.Rashod_PG_base_DPmin_8,
                Rashod_PG_base_DPmax = _mdp.Rashod_PG_base_DPmax_8
            });


            #endregion ---

            SolverContext context = SolverContext.GetContext();
            context.ClearModel();
            Model model = context.CreateModel();
            Set   users = new Set(Domain.Any, "users");

            Parameter Koef                 = new Parameter(Domain.Real, "Koef", users);
            Parameter KoefNerav1           = new Parameter(Domain.Real, "KoefNerav1", users);
            Parameter KoefNerav11          = new Parameter(Domain.Real, "KoefNerav11", users);
            Parameter KoefNerav2           = new Parameter(Domain.Real, "KoefNerav2", users);
            Parameter KoefNerav22          = new Parameter(Domain.Real, "KoefNerav22", users);
            Parameter KoefNerav3           = new Parameter(Domain.Real, "KoefNerav3", users);
            Parameter KoefNerav33          = new Parameter(Domain.Real, "KoefNerav33", users);
            Parameter Rashod_PG_base_DPmin = new Parameter(Domain.Real, "Rashod_PG_base_DPmin", users);
            Parameter Rashod_PG_base_DPmax = new Parameter(Domain.Real, "Rashod_PG_base_DPmax", users);

            Koef.SetBinding(modelDPs, "Koef", "xId");
            KoefNerav1.SetBinding(modelDPs, "KoefNerav1", "xId");
            KoefNerav11.SetBinding(modelDPs, "KoefNerav11", "xId");
            KoefNerav2.SetBinding(modelDPs, "KoefNerav2", "xId");
            KoefNerav22.SetBinding(modelDPs, "KoefNerav22", "xId");
            KoefNerav3.SetBinding(modelDPs, "KoefNerav3", "xId");
            KoefNerav33.SetBinding(modelDPs, "KoefNerav33", "xId");
            Rashod_PG_base_DPmin.SetBinding(modelDPs, "Rashod_PG_base_DPmin", "xId");
            Rashod_PG_base_DPmax.SetBinding(modelDPs, "Rashod_PG_base_DPmax", "xId");

            model.AddParameters(
                Koef,
                KoefNerav1,
                KoefNerav11,
                KoefNerav2,
                KoefNerav22,
                KoefNerav3,
                KoefNerav33,
                Rashod_PG_base_DPmin,
                Rashod_PG_base_DPmax
                );

            Decision choose = new Decision(Domain.RealNonnegative, "choose", users);
            model.AddDecision(choose);

            model.AddGoal("Z", GoalKind.Maximize, Model.Sum(Model.ForEach(users, xId => choose[xId] * Koef[xId])));

            model.AddConstraint("Z1", Model.ForEach(users, xId => (Rashod_PG_base_DPmin[xId] <= choose[xId] <= Rashod_PG_base_DPmax[xId])));
            model.AddConstraint("Z2", Model.Sum(Model.ForEach(users, xId => choose[xId])) <= _mdp.Rezerf_rashod_pg);
            model.AddConstraint("Nerav1", Model.Sum(Model.ForEach(users, xId => choose[xId] * KoefNerav1[xId] + KoefNerav11[xId])) <= _mdp.Zapas_k);
            model.AddConstraint("Nerav2", Model.Sum(Model.ForEach(users, xId => choose[xId] * KoefNerav2[xId] + KoefNerav22[xId])) >= _mdp.Treb_proiz_chug);
            model.AddConstraint("Nerav3", Model.ForEach(users, xId => KoefNerav33[xId] <= choose[xId] <= KoefNerav3[xId]));

            try
            {
                Solution solution = context.Solve();
                Report   report   = solution.GetReport();

                String reportStr = "";

                for (int i = 0; i < modelDPs.Count; i++)
                {
                    reportStr += "Значение X" + (i + 1).ToString() + ": " + choose.GetDouble(modelDPs[i].xId) + "\n";
                }
                reportStr += "\n" + report.ToString();

                //MessageBox.Show(reportStr);
            }
            catch (Exception ex)
            {
                MessageBox.Show("При решении задачи оптимизации возникла исключительная ситуация.");
            }

            _mdp.DP1 = Math.Round(choose.GetDouble(modelDPs[0].xId), 2);
            _mdp.DP2 = Math.Round(choose.GetDouble(modelDPs[1].xId), 2);
            _mdp.DP3 = Math.Round(choose.GetDouble(modelDPs[2].xId), 2);
            _mdp.DP4 = Math.Round(choose.GetDouble(modelDPs[3].xId), 2);
            _mdp.DP5 = Math.Round(choose.GetDouble(modelDPs[4].xId), 2);
            _mdp.DP6 = Math.Round(choose.GetDouble(modelDPs[5].xId), 2);
            _mdp.DP7 = Math.Round(choose.GetDouble(modelDPs[6].xId), 2);
            _mdp.DP8 = Math.Round(choose.GetDouble(modelDPs[7].xId), 2);

            txtDP1.Text = _mdp.DP1.ToString();
            txtDP2.Text = _mdp.DP2.ToString();
            txtDP3.Text = _mdp.DP3.ToString();
            txtDP4.Text = _mdp.DP4.ToString();
            txtDP5.Text = _mdp.DP5.ToString();
            txtDP6.Text = _mdp.DP6.ToString();
            txtDP7.Text = _mdp.DP7.ToString();
            txtDP8.Text = _mdp.DP8.ToString();

            double z = 0;
            for (int i = 0; i < 8; i++)
            {
                double a = choose.GetDouble(modelDPs[i].xId);
                double b = modelDPs[i].Koef;
                z += a * b;
            }
            txtZ.Text = z.ToString();

            //график
            this.chart1.Series[0].Points.AddXY("ДП1", txtRashod_PG_base_DP_1.Text);
            this.chart1.Series[0].Points.AddXY("ДП2", txtRashod_PG_base_DP_2.Text);
            this.chart1.Series[0].Points.AddXY("ДП3", txtRashod_PG_base_DP_3.Text);
            this.chart1.Series[0].Points.AddXY("ДП4", txtRashod_PG_base_DP_4.Text);
            this.chart1.Series[0].Points.AddXY("ДП5", txtRashod_PG_base_DP_5.Text);
            this.chart1.Series[0].Points.AddXY("ДП6", txtRashod_PG_base_DP_6.Text);
            this.chart1.Series[0].Points.AddXY("ДП7", txtRashod_PG_base_DP_7.Text);
            this.chart1.Series[0].Points.AddXY("ДП8", txtRashod_PG_base_DP_8.Text);

            this.chart1.Series[1].Points.AddXY("ДП1", choose.GetDouble(modelDPs[0].xId));
            this.chart1.Series[1].Points.AddXY("ДП2", choose.GetDouble(modelDPs[1].xId));
            this.chart1.Series[1].Points.AddXY("ДП3", choose.GetDouble(modelDPs[2].xId));
            this.chart1.Series[1].Points.AddXY("ДП4", choose.GetDouble(modelDPs[3].xId));
            this.chart1.Series[1].Points.AddXY("ДП5", choose.GetDouble(modelDPs[4].xId));
            this.chart1.Series[1].Points.AddXY("ДП6", choose.GetDouble(modelDPs[5].xId));
            this.chart1.Series[1].Points.AddXY("ДП7", choose.GetDouble(modelDPs[6].xId));
            this.chart1.Series[1].Points.AddXY("ДП8", choose.GetDouble(modelDPs[7].xId));
        }