コード例 #1
0
        /// <summary>
        /// Generates all valid binary combinations of all binary configurations options in the given model
        /// </summary>
        /// <param name="vm">The variability model containing the binary options and their constraints.</param>
        /// <returns>Returns a list of configurations, in which a configuration is a list of SELECTED binary options (deselected options are not present)</returns>
        public List <List <BinaryOption> > generateAllVariantsFast(VariabilityModel vm)
        {
            List <List <BinaryOption> > configurations = new List <List <BinaryOption> >();
            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);

            ConstraintSolverSolution soln = S.Solve();


            while (soln.HasFoundSolution)
            {
                List <BinaryOption> config = new List <BinaryOption>();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        config.Add(termToElem[cT]);
                    }
                }
                //THese should always be new configurations
                //  if(!Configuration.containsBinaryConfiguration(configurations, config))
                configurations.Add(config);

                soln.GetNext();
            }
            return(configurations);
        }
コード例 #2
0
        /// <summary>
        /// Generates up to n valid binary combinations of all binary configuration options in the given model.
        /// In case n < 0 all valid binary combinations will be generated.
        /// </summary>
        /// <param name="m">The variability model containing the binary options and their constraints.</param>
        /// <param name="n">The maximum number of samples that will be generated.</param>
        /// <returns>Returns a list of configurations, in which a configuration is a list of SELECTED binary options (deselected options are not present)</returns>
        public List <List <BinaryOption> > GenerateUpToNFast(VariabilityModel m, int n)
        {
            List <List <BinaryOption> > configurations = new List <List <BinaryOption> >();
            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, m);

            ConstraintSolverSolution soln = S.Solve();

            // TODO: Better solution than magic number?
            while (soln.HasFoundSolution && (configurations.Count < n || n < 0))
            {
                List <BinaryOption> config = new List <BinaryOption>();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        config.Add(termToElem[cT]);
                    }
                }
                //THese should always be new configurations
                //  if(!Configuration.containsBinaryConfiguration(configurations, config))
                configurations.Add(config);

                soln.GetNext();
            }
            return(configurations);
        }
コード例 #3
0
        /* public List<List<string>> generateDimacsPseudoRandom(string[] lines,int features, int randomsize, BackgroundWorker worker)
         * {
         *   var cts = new CancellationTokenSource();
         *   var erglist = new List<List<string>>();
         *
         *   var tasks = new Task[features];
         *   var mylock = new object();
         *
         *   for (var i = 0; i < features; i++)
         *   {
         *       var i1 = i;
         *       tasks[i] = Task.Factory.StartNew(() =>
         *       {
         *           Console.WriteLine("Starting: " + i1);
         *           var sw = new Stopwatch();
         *           sw.Start();
         *           var result = generateDimacsSize(lines, i1, randomsize);
         *           sw.Stop();
         *           Console.WriteLine("Done: " + i1 + "\tDuration: " + sw.ElapsedMilliseconds + "\tResults: " + result.Count);
         *           return result;
         *
         *       }, cts.Token).ContinueWith(task =>
         *       {
         *           lock (mylock)
         *           {
         *
         *               erglist.AddRange(task.Result);
         *
         *               Console.WriteLine("Added results: " + i1 + "\tResults now: " + erglist.Count);
         *               counter++;
         *               //worker.ReportProgress((int)(counter * 100.0f / (double)features), erglist.Count);
         *           }
         *       });
         *
         *       if (Task.WaitAny(new[] { tasks[i] }, TimeSpan.FromMilliseconds(60 * 1000)) < 0)
         *       {
         *           cts.Cancel();
         *       }
         *   }
         *
         *   Task.WaitAll(tasks);
         *
         *   return erglist;
         * } */



        /// <summary>
        /// Simulates a simple method to get valid configurations of binary options of a variability model. The randomness is simulated by the modulu value.
        /// We take only the modulu'th configuration into the result set based on the CSP solvers output. If modulu is larger than the number of valid variants, the result set is empty.
        /// </summary>
        /// <param name="vm">The variability model containing the binary options and their constraints.</param>
        /// <param name="treshold">Maximum number of configurations</param>
        /// <param name="modulu">Each configuration that is % modulu == 0 is taken to the result set. Can be less than the maximal (i.e. threshold) specified number of configurations.</param>
        /// <returns>Returns a list of configurations, in which a configuration is a list of SELECTED binary options (deselected options are not present</returns>
        public List <List <BinaryOption> > generateRandomVariants(VariabilityModel vm, int treshold, int modulu)
        {
            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem            S       = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);
            List <List <BinaryOption> > erglist = new List <List <BinaryOption> >();
            ConstraintSolverSolution    soln    = S.Solve();
            int mod = 0;

            while (soln.HasFoundSolution)
            {
                mod++;
                if (mod % modulu != 0)
                {
                    soln.GetNext();
                    continue;
                }
                List <BinaryOption> tempConfig = new List <BinaryOption>();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        tempConfig.Add(termToElem[cT]);
                    }
                }
                if (tempConfig.Contains(null))
                {
                    tempConfig.Remove(null);
                }
                erglist.Add(tempConfig);
                if (erglist.Count == treshold)
                {
                    break;
                }
                soln.GetNext();
            }
            return(erglist);
        }
コード例 #4
0
        /// <summary>
        /// Generates all valid combinations of all configuration options in the given model.
        /// </summary>
        /// <param name="vm">the variability model containing the binary options and their constraints</param>
        /// <param name="optionsToConsider">the options that should be considered. All other options are ignored</param>
        /// <returns>Returns a list of <see cref="Configuration"/></returns>
        public List <Configuration> GenerateAllVariants(VariabilityModel vm, List <ConfigurationOption> optionsToConsider)
        {
            List <Configuration>       allConfigurations = new List <Configuration>();
            Dictionary <CspTerm, bool> variables;
            Dictionary <ConfigurationOption, CspTerm> optionToTerm;
            Dictionary <CspTerm, ConfigurationOption> termToOption;
            ConstraintSystem S = CSPsolver.GetGeneralConstraintSystem(out variables, out optionToTerm, out termToOption, vm);

            ConstraintSolverSolution soln = S.Solve();

            while (soln.HasFoundSolution)
            {
                Dictionary <BinaryOption, BinaryOption.BinaryValue> binOpts = new Dictionary <BinaryOption, BinaryOption.BinaryValue>();
                Dictionary <NumericOption, double> numOpts = new Dictionary <NumericOption, double>();

                foreach (CspTerm ct in variables.Keys)
                {
                    // Ignore all options that should not be considered.
                    if (!optionsToConsider.Contains(termToOption[ct]))
                    {
                        continue;
                    }

                    // If it is a binary option
                    if (variables[ct])
                    {
                        BinaryOption.BinaryValue isSelected = soln.GetIntegerValue(ct) == 1 ? BinaryOption.BinaryValue.Selected : BinaryOption.BinaryValue.Deselected;
                        if (isSelected == BinaryOption.BinaryValue.Selected)
                        {
                            binOpts.Add((BinaryOption)termToOption[ct], isSelected);
                        }
                    }
                    else
                    {
                        numOpts.Add((NumericOption)termToOption[ct], soln.GetIntegerValue(ct));
                    }
                }

                Configuration c = new Configuration(binOpts, numOpts);

                // Check if the non-boolean constraints are satisfied
                if (vm.configurationIsValid(c) && !IsInConfigurationFile(c, allConfigurations) && FulfillsMixedConstraints(c, vm))
                {
                    allConfigurations.Add(c);
                }
                soln.GetNext();
            }

            return(allConfigurations);
        }
コード例 #5
0
        private List <List <BinaryOption> > generateTilSize(int i1, int size, int timeout, VariabilityModel vm)
        {
            var            foundSolutions = new List <List <BinaryOption> >();
            List <CspTerm> variables      = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);

            CspTerm t = S.ExactlyMofN(i1, variables.ToArray());

            S.AddConstraints(new CspTerm[] { t });
            var csp = new ConstraintSolverParams
            {
                TimeLimitMilliSec = timeout * 1000,
            };
            ConstraintSolverSolution soln = S.Solve(csp);

            int counter = 0;

            while (soln.HasFoundSolution)
            {
                List <BinaryOption> tempConfig = (
                    from cT
                    in variables
                    where soln.GetIntegerValue(cT) == 1
                    select termToElem[cT]).ToList();

                if (tempConfig.Contains(null))
                {
                    tempConfig.Remove(null);
                }

                foundSolutions.Add(tempConfig);
                counter++;
                if (counter == size)
                {
                    break;
                }
                soln.GetNext();
            }
            //Console.WriteLine(i1 + "\t" + foundSolutions.Count);
            return(foundSolutions);
        }
コード例 #6
0
        /// <summary>
        /// Simulates a simple method to get valid configurations of binary options of a variability model. The randomness is simulated by the modulu value.
        /// We take only the modulu'th configuration into the result set based on the CSP solvers output. If modulu is larger than the number of valid variants, the result set is empty.
        /// </summary>
        /// <param name="vm">The variability model containing the binary options and their constraints.</param>
        /// <param name="treshold">Maximum number of configurations</param>
        /// <param name="modulu">Each configuration that is % modulu == 0 is taken to the result set</param>
        /// <returns>Returns a list of configurations, in which a configuration is a list of SELECTED binary options (deselected options are not present</returns>
        public List <List <BinaryOption> > GenerateRandomVariants(VariabilityModel vm, int treshold, int modulu)
        {
            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem            S       = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);
            List <List <BinaryOption> > erglist = new List <List <BinaryOption> >();
            ConstraintSolverSolution    soln    = S.Solve();

            List <List <BinaryOption> > allConfigs = new List <List <BinaryOption> >();

            while (soln.HasFoundSolution)
            {
                soln.GetNext();
                List <BinaryOption> tempConfig = new List <BinaryOption>();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        tempConfig.Add(termToElem[cT]);
                    }
                }
                if (tempConfig.Contains(null))
                {
                    tempConfig.Remove(null);
                }
                allConfigs.Add(tempConfig);
            }

            Random r = new Random(modulu);

            for (int i = 0; i < treshold; i++)
            {
                erglist.Add(allConfigs[r.Next(allConfigs.Count)]);
            }
            return(erglist);
        }
コード例 #7
0
        public void GetSolutionsAll(ConstraintSolverSolution solution, int maxSolutions)
        {
            if (solution == null)
            {
                return;
            }

            if (maxSolutions < 1)
            {
                maxSolutions = 1;
            }

            if (solution.HasFoundSolution)
            {
                int no = 1;
                ShiftsForce = new Dictionary <int, List <Models.ShiftForce> >();
                while (solution.HasFoundSolution)
                {
                    if (no > maxSolutions)
                    {
                        break;
                    }
                    var shiftsForce = GetSolutionResults(solution: solution);
                    if (shiftsForce != null)
                    {
                        ShiftsForce.Add(no, shiftsForce);
                    }
                    solution.GetNext();
                    no++;
                }
            }
            else
            {
                ShiftsForce = null;
            }
        }
コード例 #8
0
        /// <summary>
        /// Based on a given (partial) configuration and a variability, we aim at finding all optimally maximal or minimal (in terms of selected binary options) configurations.
        /// </summary>
        /// <param name="config">The (partial) configuration which needs to be expaned to be valid.</param>
        /// <param name="vm">Variability model containing all options and their constraints.</param>
        /// <param name="minimize">If true, we search for the smallest (in terms of selected options) valid configuration. If false, we search for the largest one.</param>
        /// <param name="unwantedOptions">Binary options that we do not want to become part of the configuration. Might be part if there is no other valid configuration without them</param>
        /// <returns>A list of configurations that satisfies the VM and the goal (or null if there is none).</returns>
        public List <List <BinaryOption> > MaximizeConfig(List <BinaryOption> config, VariabilityModel vm, bool minimize, List <BinaryOption> unwantedOptions)
        {
            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);

            //Feature Selection
            if (config != null)
            {
                foreach (BinaryOption binOpt in config)
                {
                    CspTerm term = elemToTerm[binOpt];
                    S.AddConstraints(S.Implies(S.True, term));
                }
            }
            //Defining Goals
            CspTerm[] finalGoals = new CspTerm[variables.Count];
            for (int r = 0; r < variables.Count; r++)
            {
                if (minimize == true)
                {
                    BinaryOption binOpt = termToElem[variables[r]];
                    if (unwantedOptions != null && (unwantedOptions.Contains(binOpt) && !config.Contains(binOpt)))
                    {
                        finalGoals[r] = variables[r] * 10000;
                    }
                    else
                    {
                        // Element is part of an altnerative Group  ... we want to select always the same option of the group, so we give different weights to the member of the group
                        //Functionality deactivated... todo needs further handling

                        /*if (binOpt.getAlternatives().Count != 0)
                         * {
                         *  finalGoals[r] = variables[r] * (binOpt.getID() * 10);
                         * }
                         * else
                         * {*/
                        finalGoals[r] = variables[r] * 1;
                        //}

                        // wenn in einer alternative, dann bekommt es einen wert nach seiner reihenfolge
                        // id mal 10
                    }
                }
                else
                {
                    finalGoals[r] = variables[r] * -1;   // dynamic cost map
                }
            }
            S.TryAddMinimizationGoals(S.Sum(finalGoals));

            ConstraintSolverSolution    soln          = S.Solve();
            List <string>               erg2          = new List <string>();
            List <BinaryOption>         tempConfig    = new List <BinaryOption>();
            List <List <BinaryOption> > resultConfigs = new List <List <BinaryOption> >();

            while (soln.HasFoundSolution && soln.Quality == ConstraintSolverSolution.SolutionQuality.Optimal)
            {
                tempConfig.Clear();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        tempConfig.Add(termToElem[cT]);
                    }
                }
                if (minimize && tempConfig != null)
                {
                    resultConfigs.Add(tempConfig);
                    break;
                }
                if (!Configuration.containsBinaryConfiguration(resultConfigs, tempConfig))
                {
                    resultConfigs.Add(tempConfig);
                }
                soln.GetNext();
            }
            return(resultConfigs);
        }
コード例 #9
0
        /// <summary>
        /// This method searches for a corresponding methods in the dynamically loaded assemblies and calls it if found. It prefers due to performance reasons the Microsoft Solver Foundation implementation.
        /// </summary>
        /// <param name="config">The (partial) configuration which needs to be expaned to be valid.</param>
        /// <param name="vm">Variability model containing all options and their constraints.</param>
        /// <param name="minimize">If true, we search for the smallest (in terms of selected options) valid configuration. If false, we search for the largest one.</param>
        /// <param name="unWantedOptions">Binary options that we do not want to become part of the configuration. Might be part if there is no other valid configuration without them.</param>
        /// <returns>The valid configuration (or null if there is none) that satisfies the VM and the goal.</returns>
        public List <BinaryOption> MinimizeConfig(List <BinaryOption> config, VariabilityModel vm, bool minimize, List <BinaryOption> unWantedOptions)
        {
            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
            ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);


            //Feature Selection
            foreach (BinaryOption binOpt in config)
            {
                CspTerm term = elemToTerm[binOpt];
                S.AddConstraints(S.Implies(S.True, term));
            }

            //Defining Goals
            CspTerm[] finalGoals = new CspTerm[variables.Count];
            for (int r = 0; r < variables.Count; r++)
            {
                if (minimize == true)
                {
                    if (unWantedOptions != null && (unWantedOptions.Contains(termToElem[variables[r]]) && !config.Contains(termToElem[variables[r]])))
                    {
                        finalGoals[r] = variables[r] * 100;
                    }
                    else
                    {
                        finalGoals[r] = variables[r] * 1;
                    }
                }
                else
                {
                    finalGoals[r] = variables[r] * -1;   // dynamic cost map
                }
            }

            S.TryAddMinimizationGoals(S.Sum(finalGoals));

            ConstraintSolverSolution soln       = S.Solve();
            List <string>            erg2       = new List <string>();
            List <BinaryOption>      tempConfig = new List <BinaryOption>();

            while (soln.HasFoundSolution)
            {
                tempConfig.Clear();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        tempConfig.Add(termToElem[cT]);
                    }
                }

                if (minimize && tempConfig != null)
                {
                    break;
                }
                soln.GetNext();
            }
            return(tempConfig);
        }
コード例 #10
0
        /// <summary>
        /// Knapsack enumerator -- enumerate up to "numAnswers" combinations of "weights" such that the sum of the weights is less than the weight limit.
        /// It places the patterns of items inside the list of patterns.  The efficiency parameter ensures that we don't output any which use less than "efficiency" percent
        /// off the weightlimit.
        /// </summary>
        /// <param name="maxAnswers">maximum number of combinations to get out.  Limits runtime.  If zero return all.</param>
        /// <param name="weights">weight of each item to go into the knapsack</param>
        /// <param name="weightLimit">knapsack weight limit</param>
        /// <param name="efficiency">limit patterns to use at least this % of the weight limit (between 0.0 and 1.0) </param>
        /// <param name="patterns">output list of patterns of inclusion of the weights.</param>
        public static void SolveKnapsack(int maxAnswers, int[] weights, int weightLimit, double efficiency, out List <int[]> patterns)
        {
            // convenience value.
            int NumItems            = weights.Length;
            ConstraintSystem solver = ConstraintSystem.CreateSolver();
            CspDomain        dom    = solver.CreateIntegerInterval(0, weightLimit);

            CspTerm knapsackSize = solver.Constant(weightLimit);

            // these represent the quantity of each item.
            CspTerm[] itemQty     = solver.CreateVariableVector(dom, "Quantity", NumItems);
            CspTerm[] itemWeights = new CspTerm[NumItems];

            for (int cnt = 0; cnt < NumItems; cnt++)
            {
                itemWeights[cnt] = solver.Constant(weights[cnt]);
            }

            // contributors to the weight (weight * variable value)
            CspTerm[] contributors = new CspTerm[NumItems];
            for (int cnt = 0; cnt < NumItems; cnt++)
            {
                contributors[cnt] = itemWeights[cnt] * itemQty[cnt];
            }

            // single constraint
            CspTerm knapSackCapacity = solver.GreaterEqual(knapsackSize, solver.Sum(contributors));

            solver.AddConstraints(knapSackCapacity);

            // must be efficient
            CspTerm knapSackAtLeast = solver.LessEqual(knapsackSize * efficiency, solver.Sum(contributors));

            solver.AddConstraints(knapSackAtLeast);

            // start counter and allocate a list for the results.
            int nanswers = 0;

            patterns = new List <int[]>();

            ConstraintSolverSolution sol = solver.Solve();

            while (sol.HasFoundSolution)
            {
                int[] pattern = new int[NumItems];
                // extract this pattern from the enumeration.
                for (int cnt = 0; cnt < NumItems; cnt++)
                {
                    object val;
                    sol.TryGetValue(itemQty[cnt], out val);
                    pattern[cnt] = (int)val;
                }
                // add it to the output.
                patterns.Add(pattern);
                nanswers++;
                // stop if we reach the limit of results.
                if (maxAnswers > 0 && nanswers >= maxAnswers)
                {
                    break;
                }
                sol.GetNext();
            }
        }
コード例 #11
0
        public List <List <BinaryOption> > generateRandomVariantsUntilSeconds(VariabilityModel vm, int seconds,
                                                                              int treshold, int modulu)
        {
            List <List <BinaryOption> > erglist = new List <List <BinaryOption> >();
            var cts = new CancellationTokenSource();

            var task = Task.Factory.StartNew(() =>
            {
                #region task

                List <CspTerm> variables = new List <CspTerm>();
                Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
                Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();
                ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);

                ConstraintSolverSolution soln = S.Solve();
                int mod = 0;
                while (soln.HasFoundSolution)
                {
                    if (cts.IsCancellationRequested)
                    {
                        return(erglist);
                    }
                    mod++;
                    if (mod % modulu != 0)
                    {
                        soln.GetNext();
                        continue;
                    }
                    List <BinaryOption> tempConfig = new List <BinaryOption>();
                    foreach (CspTerm cT in variables)
                    {
                        if (soln.GetIntegerValue(cT) == 1)
                        {
                            tempConfig.Add(termToElem[cT]);
                        }
                    }
                    if (tempConfig.Contains(null))
                    {
                        tempConfig.Remove(null);
                    }
                    erglist.Add(tempConfig);
                    if (erglist.Count == treshold)
                    {
                        break;
                    }
                    soln.GetNext();
                }
                return(erglist);

                #endregion
            }, cts.Token);

            if (Task.WaitAny(new[] { task }, TimeSpan.FromMilliseconds(seconds * 1000)) < 0)
            {
                Console.WriteLine("configsize: " + erglist.Count);
                cts.Cancel();
                return(erglist);
            }

            return(erglist);
        }
コード例 #12
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Seleccione el método por el que desea resolver el problema:\n1 Programación por restricciones\n2 Programación Lineal");
                switch (int.Parse(Console.ReadLine()))
                {
                case 1:
                    SolverContext context = new SolverContext();
                    Model         model   = context.CreateModel();
                    // Creación de variables
                    Decision x1 = new Decision(Domain.Integer, "x1");
                    model.AddDecision(x1);
                    Decision x2 = new Decision(Domain.Integer, "x2");
                    model.AddDecision(x2);
                    Decision x3 = new Decision(Domain.Integer, "x3");
                    model.AddDecision(x3);
                    // Creación de limites
                    model.AddConstraint("limitX1", 50 <= x1 <= 300);
                    model.AddConstraint("limitX2", 100 <= x2 <= 200);
                    model.AddConstraint("limitX3", 20 <= x3 <= 1000);
                    // Creación de restricciones
                    model.AddConstraint("restriccion1", 200 <= (x1 + x2 + x3) <= 280);
                    model.AddConstraint("restriccion2", 100 <= (x1 + (3 * x3)) <= 2000);
                    model.AddConstraint("restriccion3", 50 <= ((2 + x1) + (4 * x3)) <= 1000);
                    // Función objetivo
                    model.AddGoal("maximo", GoalKind.Maximize, -(4 * x1) - (2 * x2) + x3);
                    // Solucion
                    Solution solucion = context.Solve(new SimplexDirective());
                    Report   reporte  = solucion.GetReport();
                    // Imprimir
                    Console.WriteLine(reporte);
                    Console.ReadLine();
                    break;

                case 2:
                    //Solucionador específico
                    ConstraintSystem csp = ConstraintSystem.CreateSolver();
                    // Creacíón de variables
                    CspTerm sx1 = csp.CreateVariable(csp.CreateIntegerInterval(50, 300), "x1");
                    CspTerm sx2 = csp.CreateVariable(csp.CreateIntegerInterval(100, 200), "x2");
                    CspTerm sx3 = csp.CreateVariable(csp.CreateIntegerInterval(20, 1000), "x3");
                    // Creación de restricciones
                    csp.AddConstraints(200 <= (sx1 + sx2 + sx3) <= 280,
                                       100 <= sx1 + (3 * sx2) <= 2000,
                                       50 <= (2 * sx1) + (4 * sx3) <= 1000);

                    // Solución
                    ConstraintSolverSolution cspSolucion = csp.Solve();
                    int numero = 1;
                    while (cspSolucion.HasFoundSolution)
                    {
                        object rx1, rx2, rx3;
                        if (!cspSolucion.TryGetValue(sx1, out rx1) || !cspSolucion.TryGetValue(sx2, out rx2) || !cspSolucion.TryGetValue(sx3, out rx3))
                        {
                            throw new InvalidProgramException("No se encontro solución");
                        }
                        Console.WriteLine(String.Format("Solución {0} :\nx1={1}\nx2={2}\nx3={3}", numero, rx1, rx2, rx3));
                        numero += 1;
                        cspSolucion.GetNext();
                    }

                    /*
                     * //Solucionador específico
                     * SimplexSolver sSolver = new SimplexSolver();
                     * //Creación de variables
                     * int sx1, sx2, sx3;
                     * sSolver.AddVariable("x1", out sx1);
                     * sSolver.SetBounds(sx1, 50, 300);
                     * sSolver.AddVariable("x2", out sx2);
                     * sSolver.SetBounds(sx2, 100, 200);
                     * sSolver.AddVariable("x3", out sx3);
                     * sSolver.SetBounds(sx3,20,1000);
                     * //Creación de restricciones
                     * int r1, r2, r3, goal;
                     * sSolver.AddRow("restriccion1", out r1);
                     * sSolver.SetCoefficient(r1, sx1, 1);
                     * sSolver.SetCoefficient(r1, sx2, 1);
                     * sSolver.SetCoefficient(r1, sx3, 1);
                     * sSolver.SetBounds(r1, 200, 280);
                     * sSolver.AddRow("restriccion2", out r2);
                     * sSolver.SetCoefficient(r2, sx1, 1);
                     * sSolver.SetCoefficient(r2, sx2, 3);
                     * sSolver.SetBounds(r2, 100, 2000);
                     * sSolver.AddRow("restriccion3", out r3);
                     * sSolver.SetCoefficient(r3, sx1, 2);
                     * sSolver.SetCoefficient(r3, sx3, 4);
                     * sSolver.SetBounds(r3, 50, 1000);
                     * //Función objetivo
                     * sSolver.AddRow("objetivo", out goal);
                     * sSolver.SetCoefficient(goal, sx1, -4);
                     * sSolver.SetCoefficient(goal, sx2, -2);
                     * sSolver.SetCoefficient(goal, sx3, 1);
                     * sSolver.SetBounds(goal, Rational.NegativeInfinity,Rational.PositiveInfinity);
                     * sSolver.AddGoal(goal, 1, false);
                     * //Solución
                     * sSolver.Solve(new SimplexSolverParams());
                     * sSolver.GetReport();
                     */
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }
        }
コード例 #13
0
        public static void Run()
        {
            ConstraintSystem S = ConstraintSystem.CreateSolver();

            List <KeyValuePair <CspTerm, string> > termList = new List <KeyValuePair <CspTerm, string> >();

            // create a Term between [1..5], associate it with a name for later ease of display

            NamedTerm namedTerm = delegate(string name) {
                CspTerm x = S.CreateVariable(S.CreateIntegerInterval(1, 5), name);
                termList.Add(new KeyValuePair <CspTerm, string>(x, name));
                return(x);
            };

            // the people and attributes will all be matched via the house they reside in.

            CspTerm English = namedTerm("English"), Spanish = namedTerm("Spanish"), Japanese = namedTerm("Japanese"), Italian = namedTerm("Italian"), Norwegian = namedTerm("Norwegian");
            CspTerm red = namedTerm("red"), green = namedTerm("green"), white = namedTerm("white"), blue = namedTerm("blue"), yellow = namedTerm("yellow");
            CspTerm dog = namedTerm("dog"), snails = namedTerm("snails"), fox = namedTerm("fox"), horse = namedTerm("horse"), zebra = namedTerm("zebra");
            CspTerm painter = namedTerm("painter"), sculptor = namedTerm("sculptor"), diplomat = namedTerm("diplomat"), violinist = namedTerm("violinist"), doctor = namedTerm("doctor");
            CspTerm tea = namedTerm("tea"), coffee = namedTerm("coffee"), milk = namedTerm("milk"), juice = namedTerm("juice"), water = namedTerm("water");

            S.AddConstraints(
                S.Unequal(English, Spanish, Japanese, Italian, Norwegian),
                S.Unequal(red, green, white, blue, yellow),
                S.Unequal(dog, snails, fox, horse, zebra),
                S.Unequal(painter, sculptor, diplomat, violinist, doctor),
                S.Unequal(tea, coffee, milk, juice, water),
                S.Equal(English, red),
                S.Equal(Spanish, dog),
                S.Equal(Japanese, painter),
                S.Equal(Italian, tea),
                S.Equal(1, Norwegian),
                S.Equal(green, coffee),
                S.Equal(1, green - white),
                S.Equal(sculptor, snails),
                S.Equal(diplomat, yellow),
                S.Equal(3, milk),
                S.Equal(1, S.Abs(Norwegian - blue)),
                S.Equal(violinist, juice),
                S.Equal(1, S.Abs(fox - doctor)),
                S.Equal(1, S.Abs(horse - diplomat))
                );

            bool unsolved = true;
            ConstraintSolverSolution soln = S.Solve();

            while (soln.HasFoundSolution)
            {
                unsolved = false;
                System.Console.WriteLine("solved.");
                StringBuilder[] houses = new StringBuilder[5];
                for (int i = 0; i < 5; i++)
                {
                    houses[i] = new StringBuilder(i.ToString());
                }
                foreach (KeyValuePair <CspTerm, string> kvp in termList)
                {
                    string item = kvp.Value;
                    object house;
                    if (!soln.TryGetValue(kvp.Key, out house))
                    {
                        throw new InvalidProgramException("can't find a Term in the solution: " + item);
                    }
                    houses[(int)house - 1].Append(", ");
                    houses[(int)house - 1].Append(item);
                }
                foreach (StringBuilder house in houses)
                {
                    System.Console.WriteLine(house);
                }
                soln.GetNext();
            }
            if (unsolved)
            {
                System.Console.WriteLine("No solution found.");
            }
            else
            {
                System.Console.WriteLine("Solution should have the Norwegian drinking water and the Japanese with the zebra.");
            }
        }