コード例 #1
0
 private static SolutionTable ConvertToSolutionTable(
     ConstraintSolverSolution solution,
     ZebraPuzzleConstraints constraints)
 {
     return(new SolutionTable(constraints.HouseNumbers.Select(
                                  houseNumber => new SolutionRow
                                  (
                                      houseNumber + 1,
                                      (HouseColour)DetermineTermFromSolution(solution,
                                                                             constraints.ColourMatrix, houseNumber,
                                                                             constraints.HouseNumbers),
                                      (Drink)DetermineTermFromSolution(solution,
                                                                       constraints.DrinkMatrix, houseNumber,
                                                                       constraints.HouseNumbers),
                                      (Nationality)DetermineTermFromSolution(solution,
                                                                             constraints.NationalityMatrix, houseNumber,
                                                                             constraints.HouseNumbers),
                                      (Smoke)DetermineTermFromSolution(solution,
                                                                       constraints.SmokeMatrix, houseNumber,
                                                                       constraints.HouseNumbers),
                                      (Pet)DetermineTermFromSolution(solution,
                                                                     constraints.PetMatrix, houseNumber,
                                                                     constraints.HouseNumbers)
                                  )).ToList()));
 }
コード例 #2
0
        /// <summary>
        /// Checks whether the boolean selection is valid w.r.t. the variability model. Does not check for numeric options' correctness.
        /// </summary>
        /// <param name="config">The list of binary options that are SELECTED (only selected options must occur in the list).</param>
        /// <param name="vm">The variability model that represents the context of the configuration.</param>
        /// <param name="partialConfiguration">Whether the given list of options represents only a partial configuration. This means that options not in config might be additionally select to obtain a valid configuration.</param>
        /// <returns>True if it is a valid selection w.r.t. the VM, false otherwise</returns>
        public bool checkConfigurationSAT(List <BinaryOption> config, VariabilityModel vm, bool partialConfiguration)
        {
            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 binayOpt in elemToTerm.Keys)
            {
                CspTerm term = elemToTerm[binayOpt];
                if (config.Contains(binayOpt))
                {
                    S.AddConstraints(S.Implies(S.True, term));
                }
                else if (!partialConfiguration)
                {
                    S.AddConstraints(S.Implies(S.True, S.Not(term)));
                }
            }

            ConstraintSolverSolution sol = S.Solve();

            if (sol.HasFoundSolution)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #3
0
        static int DetermineTermFromSolution(
            ConstraintSolverSolution solution,
            CspTerm[][] terms,
            int currentHouseNumber,
            IEnumerable <int> houseNubmers)
        {
            if (solution == null)
            {
                throw new ArgumentNullException("solution");
            }
            if (terms == null)
            {
                throw new ArgumentNullException("terms");
            }

            foreach (var houseNumber in houseNubmers)
            {
                object term;
                solution.TryGetValue(terms[currentHouseNumber][houseNumber],
                                     out term);

                if ((int)term == 1)
                {
                    return(houseNumber);
                }
            }
            return(0);
        }
コード例 #4
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);
        }
コード例 #5
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);
        }
コード例 #6
0
        /// <summary>
        ///  The method aims at finding a configuration which is similar to the given configuration, but does not contain the optionToBeRemoved. If further options need to be removed from the given configuration, they are outputed in removedElements.
        /// Idea: Encode this as a CSP problem. We aim at finding a configuration that maximizes a goal. Each option of the given configuration gets a large value assigned. All other options of the variability model gets a negative value assigned.
        /// We will further create a boolean constraint that forbids selecting the optionToBeRemoved. Now, we find an optimal valid configuration.
        /// </summary>
        /// <param name="optionToBeRemoved">The binary configuration option that must not be part of the new configuration.</param>
        /// <param name="originalConfig">The configuration for which we want to find a similar one.</param>
        /// <param name="removedElements">If further options need to be removed from the given configuration to build a valid configuration, they are outputed in this list.</param>
        /// <param name="vm">The variability model containing all options and their constraints.</param>
        /// <returns>A configuration that is valid, similar to the original configuration and does not contain the optionToBeRemoved.</returns>
        public List <BinaryOption> GenerateConfigWithoutOption(BinaryOption optionToBeRemoved, List <BinaryOption> originalConfig, out List <BinaryOption> removedElements, VariabilityModel vm)
        {
            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);

            removedElements = new List <BinaryOption>();

            //Forbid the selection of this configuration option
            CspTerm optionToRemove = elemToTerm[optionToBeRemoved];

            S.AddConstraints(S.Implies(S.True, S.Not(optionToRemove)));

            //Defining Goals
            CspTerm[] finalGoals = new CspTerm[variables.Count];
            int       r          = 0;

            foreach (var term in variables)
            {
                if (originalConfig.Contains(termToElem[term]))
                {
                    finalGoals[r] = term * -1000; //Since we minimize, we put a large negative value of an option that is within the original configuration to increase chances that the option gets selected again
                }
                else
                {
                    finalGoals[r] = variables[r] * 10000;//Positive number will lead to a small chance that an option gets selected when it is not in the original configuration
                }
                r++;
            }

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

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

            if (soln.HasFoundSolution && soln.Quality == ConstraintSolverSolution.SolutionQuality.Optimal)
            {
                tempConfig.Clear();
                foreach (CspTerm cT in variables)
                {
                    if (soln.GetIntegerValue(cT) == 1)
                    {
                        tempConfig.Add(termToElem[cT]);
                    }
                }
                //Adding the options that have been removed from the original configuration
                foreach (var opt in originalConfig)
                {
                    if (!tempConfig.Contains(opt))
                    {
                        removedElements.Add(opt);
                    }
                }
                return(tempConfig);
            }

            return(null);
        }
コード例 #7
0
        public void Solve(int?[,] field)
        {
            ConstraintSystem S = ConstraintSystem.CreateSolver();
            CspDomain        Z = S.CreateIntegerInterval(1, 9);

            CspTerm[][] sudoku = S.CreateVariableArray(Z, "cell", 9, 9);
            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    if (field[row, col] > 0)
                    {
                        S.AddConstraints(S.Equal(field[row, col] ?? 0, sudoku[row][col]));
                    }
                }
                S.AddConstraints(S.Unequal(GetSlice(sudoku, row, row, 0, 8)));
            }
            for (int col = 0; col < 9; col++)
            {
                S.AddConstraints(S.Unequal(GetSlice(sudoku, 0, 8, col, col)));
            }
            for (int a = 0; a < 3; a++)
            {
                for (int b = 0; b < 3; b++)
                {
                    S.AddConstraints(S.Unequal(GetSlice(sudoku, a * 3, a * 3 + 2, b * 3, b * 3 + 2)));
                }
            }
            ConstraintSolverSolution soln = S.Solve();

            if (!soln.HasFoundSolution)
            {
                throw new NoSolutionException("Для поставленной цифры нет решение!");
            }


            object[] h = new object[9];
            for (int row = 0; row < 9; row++)
            {
                if ((row % 3) == 0)
                {
                    System.Console.WriteLine();
                }
                for (int col = 0; col < 9; col++)
                {
                    soln.TryGetValue(sudoku[row][col], out h[col]);
                }
                System.Console.WriteLine("{0}{1}{2} {3}{4}{5} {6}{7}{8}", h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7], h[8]);
            }
        }
コード例 #8
0
        /// <summary>
        /// This method has the objective to sample a configuration where n features are selected
        /// </summary>
        /// <returns>The first fitting configuration.</returns>
        /// <param name="vm">The variability model.</param>
        /// <param name="numberSelectedFeatures">The number of features that should be selected.</param>
        /// <param name="featureWeight">The weight of the features to minimize.</param>
        public List <BinaryOption> GenerateConfigurationFromBucket(VariabilityModel vm, int numberSelectedFeatures, Dictionary <List <BinaryOption>, int> featureWeight, List <BinaryOption> desiredOptions)
        {
            if (desiredOptions != null)
            {
                throw new NotImplementedException();
            }
            if (this._constraintSystemCache == null)
            {
                this._constraintSystemCache = new Dictionary <int, ConstraintSystemCache>();
            }

            List <CspTerm> variables;
            Dictionary <CspTerm, BinaryOption> termToElem;
            ConstraintSystem S;

            if (!this._constraintSystemCache.Keys.Contains(numberSelectedFeatures))
            {
                InitializeCache(vm, numberSelectedFeatures);
            }

            variables  = _constraintSystemCache[numberSelectedFeatures].GetVariables();
            termToElem = _constraintSystemCache[numberSelectedFeatures].GetTermToElemMapping();
            S          = _constraintSystemCache[numberSelectedFeatures].GetConstraintSystem();

            S.ResetSolver();
            S.RemoveAllMinimizationGoals();

            // Next, solve the constraint system
            ConstraintSolverSolution soln = S.Solve();

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

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

            return(tempConfig);
        }
コード例 #9
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);
        }
コード例 #10
0
        /// <summary>
        /// Checks whether the boolean selection is valid w.r.t. the variability model. Does not check for numeric options' correctness.
        /// </summary>
        /// <param name="config">The list of binary options that are SELECTED (only selected options must occur in the list).</param>
        /// <param name="vm">The variability model that represents the context of the configuration.</param>
        /// <param name="exact">Checks also the number of selected options such that it returns only true if exactly the given configuration is valid
        /// (e.g., if we need to select more features to get a valid config, it returns false if exact is set to true).
        /// <returns>True if it is a valid selection w.r.t. the VM, false otherwise</returns>
        public bool checkConfigurationSAT(List <BinaryOption> config, VariabilityModel vm, bool exact)
        {
            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 binayOpt in elemToTerm.Keys)
            {
                CspTerm term = elemToTerm[binayOpt];
                if (config.Contains(binayOpt))
                {
                    S.AddConstraints(S.Implies(S.True, term));
                }
                else
                {
                    if (exact)
                    {
                        S.AddConstraints(S.Implies(S.True, S.Not(term)));
                    }
                }
            }

            ConstraintSolverSolution sol = S.Solve();

            if (sol.HasFoundSolution)
            {
                int count = 0;
                foreach (CspTerm cT in variables)
                {
                    if (sol.GetIntegerValue(cT) == 1)
                    {
                        count++;
                    }
                }
                //Needs testing TODO
                if (count != config.Count && exact == true)
                {
                    return(false);
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #11
0
        static void Main(string[] args)
        {
            ConstraintSystem s1 = ConstraintSystem.CreateSolver();

            // () and ()
            CspTerm p1 = s1.CreateBoolean("p1");
            CspTerm p2 = s1.CreateBoolean("p2");
            CspTerm p3 = s1.CreateBoolean("p3");
            CspTerm p4 = s1.CreateBoolean("p4");

            var x = new CspDomain();

            CspTerm test = s1.And(s1.Or(p1, s1.And(s1.Neg(p3)), s1.Neg(p1)), s1.And(p2, s1.Neg(s1.Difference(p1, p2))));

            CspTerm tOr12 = s1.Or(s1.Neg(t1), s1.Neg(t2));
            CspTerm tOr13 = s1.Or(s1.Neg(t1), s1.Neg(t3));
            CspTerm tOr14 = s1.Or(s1.Neg(t1), s1.Neg(t4));

            CspTerm tOr23 = s1.Or(s1.Neg(t2), s1.Neg(t3));
            CspTerm tOr24 = s1.Or(s1.Neg(t2), s1.Neg(t4));

            CspTerm tOr34 = s1.Or(s1.Neg(t3), s1.Neg(t4));

            CspTerm tOr = s1.Or(t1, t2, t3, t4);

            s1.AddConstraints(tOr12);
            s1.AddConstraints(tOr13);
            s1.AddConstraints(tOr14);
            s1.AddConstraints(tOr23);
            s1.AddConstraints(tOr24);
            s1.AddConstraints(tOr34);
            s1.AddConstraints(tOr);

            ConstraintSolverSolution solution1 = s1.Solve();

            if (solution1.HasFoundSolution)
            {
                Console.WriteLine("Is Satisfiable");
            }
            else
            {
                Console.WriteLine("Not satisfiable");
            }

            Console.ReadKey();
        }
コード例 #12
0
        protected List <Models.ShiftForce> GetSolutionResults(ConstraintSolverSolution solution)
        {
            if (solution == null || !solution.HasFoundSolution || ShiftsX == null || ShiftsX.Count == 0)
            {
                return(null);
            }

            int force;
            List <Models.ShiftForce> shiftsForce = new List <Models.ShiftForce>();

            foreach (var entry in ShiftsX)
            {
                force = solution.GetIntegerValue(entry.Value);
                var shiftForce = new Models.ShiftForce(entry.Key, force);
                shiftsForce.Add(shiftForce);
            }
            return(shiftsForce);
        }
コード例 #13
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);
        }
コード例 #14
0
        /// <summary>
        /// Creates a sample of configurations, by iteratively adding a configuration that has the maximal manhattan distance
        /// to the configurations that were previously selected.
        /// </summary>
        /// <param name="vm">The domain for sampling.</param>
        /// <param name="minimalConfiguration">A minimal configuration that will be used as starting point.</param>
        /// <param name="numberToSample">The number of configurations that should be sampled.</param>
        /// <param name="optionWeight">Weight assigned to optional binary options.</param>
        /// <returns>A list of distance maximized configurations.</returns>
        public List <List <BinaryOption> > DistanceMaximization(VariabilityModel vm, List <BinaryOption> minimalConfiguration, int numberToSample, int optionWeight)
        {
            List <Configuration>        sample          = new List <Configuration>();
            List <List <BinaryOption> > convertedSample = new List <List <BinaryOption> >();

            sample.Add(new Configuration(minimalConfiguration));
            convertedSample.Add(minimalConfiguration);

            List <CspTerm> variables = new List <CspTerm>();
            Dictionary <BinaryOption, CspTerm> elemToTerm = new Dictionary <BinaryOption, CspTerm>();
            Dictionary <CspTerm, BinaryOption> termToElem = new Dictionary <CspTerm, BinaryOption>();


            while (sample.Count < numberToSample)
            {
                ConstraintSystem S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);
                addDistanceMaximiationGoal(sample, vm, elemToTerm, S, optionWeight);
                ConstraintSolverSolution sol = S.Solve();
                if (sol.HasFoundSolution)
                {
                    List <BinaryOption> solution = new List <BinaryOption>();
                    foreach (CspTerm cT in variables)
                    {
                        if (sol.GetIntegerValue(cT) == 1)
                        {
                            solution.Add(termToElem[cT]);
                        }
                    }
                    S.ResetSolver();
                    convertedSample.Add(solution);
                    sample.Add(new Configuration(solution));
                }
                else
                {
                    GlobalState.logInfo.logLine("No more solutions available.");
                    return(convertedSample);
                }
            }

            return(convertedSample);
        }
コード例 #15
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);
        }
コード例 #16
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);
        }
コード例 #17
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;
            }
        }
コード例 #18
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);
        }
コード例 #19
0
        /// <summary>
        /// This method has the objective to sample a configuration where n features are selected
        /// </summary>
        /// <returns>The first fitting configuration.</returns>
        /// <param name="vm">The variability model.</param>
        /// <param name="numberSelectedFeatures">The number of features that should be selected.</param>
        /// <param name="featureWeight">The weight of the features to minimize.</param>
        /// <param name="sampledConfigurations">The sampled configurations until now.</param>
        public List <BinaryOption> GenerateConfigurationFromBucket(VariabilityModel vm, int numberSelectedFeatures, Dictionary <List <BinaryOption>, int> featureWeight, Configuration lastSampledConfiguration)
        {
            if (this._constraintSystemCache == null)
            {
                this._constraintSystemCache = new Dictionary <int, ConstraintSystemCache>();
            }

            List <CspTerm> variables;
            Dictionary <BinaryOption, CspTerm> elemToTerm;
            Dictionary <CspTerm, BinaryOption> termToElem;
            ConstraintSystem S;

            if (this._constraintSystemCache.Keys.Contains(numberSelectedFeatures))
            {
                variables  = _constraintSystemCache[numberSelectedFeatures].GetVariables();
                elemToTerm = _constraintSystemCache[numberSelectedFeatures].GetElemToTermMapping();
                termToElem = _constraintSystemCache[numberSelectedFeatures].GetTermToElemMapping();
                S          = _constraintSystemCache[numberSelectedFeatures].GetConstraintSystem();

                S.ResetSolver();
                S.RemoveAllMinimizationGoals();

                // Add the missing configurations
                AddBinaryConfigurationsToConstraintSystem(vm, S, lastSampledConfiguration, elemToTerm);
            }
            else
            {
                variables  = new List <CspTerm>();
                elemToTerm = new Dictionary <BinaryOption, CspTerm>();
                termToElem = new Dictionary <CspTerm, BinaryOption>();

                // Build the constraint system
                S = CSPsolver.getConstraintSystem(out variables, out elemToTerm, out termToElem, vm);

                // The first goal of this method is, to have an exact number of features selected
                S.AddConstraints(S.ExactlyMofN(numberSelectedFeatures, variables.ToArray()));

                if (lastSampledConfiguration != null)
                {
                    // Add the previous configurations as constraints
                    AddBinaryConfigurationsToConstraintSystem(vm, S, lastSampledConfiguration, elemToTerm);
                }

                this._constraintSystemCache.Add(numberSelectedFeatures, new ConstraintSystemCache(S, variables, elemToTerm, termToElem));
            }

            // Next, solve the constraint system
            ConstraintSolverSolution soln = S.Solve();

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

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

            return(tempConfig);
        }
コード例 #20
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.");
            }
        }
コード例 #21
0
        protected static void CCN_CSP()
        {
            int param1 = ReadSelectionInt("Max agents", 100, min: 1, max: 1000);
            var param2 = ReadSelectionInt("Max solutions", 100, min: 1, max: 5000);
            var param3 = ReadSelectionInt("Max time\"", 120, min: 10, max: 1200);

            //Set agent shifts
            var      solveShifts = new CSP.ShiftsPlanner(param1);
            TimeSpan ts8h        = GetTimeSpanHours(8);
            TimeSpan ts9h        = GetTimeSpanHours(9);
            TimeSpan ts10h       = GetTimeSpanHours(10);
            TimeSpan ts30mi      = GetTimeSpanMinutes(30);

            var shifts = new List <CSP.Models.Shift>();

            shifts.Add(new CSP.Models.Shift(name: "A", start: GetTimeSpanHours(7), duration: ts8h));
            shifts.Add(new CSP.Models.Shift(name: "B", start: GetTimeSpanHours(9), duration: ts8h));
            shifts.Add(new CSP.Models.Shift(name: "E", start: GetTimeSpanHours(11), duration: ts8h));
            shifts.Add(new CSP.Models.Shift(name: "D", start: GetTimeSpanHours(13), duration: ts8h));
            shifts.Add(new CSP.Models.Shift(name: "C", start: GetTimeSpanHours(15), duration: ts8h));
            shifts.Add(new CSP.Models.Shift(name: "H", start: GetTimeSpanHours(17), duration: ts8h));
            solveShifts.Shifts = shifts;

            //Set requirements per shift
            int[]    liveData     = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 10, 20, 29, 45, 51, 57, 61, 61, 61, 58, 58, 56, 54, 51, 48, 50, 43, 43, 41, 38, 37, 37, 35, 31, 27, 29, 24, 23, 18, 14, 13, 9, 6, 4 };
            var      requirements = new List <CSP.Models.HalfHourRequirement>();
            TimeSpan ts           = GetTimeSpanHours(0);

            for (int i = 0; i < liveData.Length; i++)
            {
                requirements.Add(new CSP.Models.HalfHourRequirement(start: ts, requiredForce: liveData[i]));
                ts = ts.Add(ts30mi);
            }
            solveShifts.HalfHourRequirements = requirements;

            var S = solveShifts.PrepareCspSolver();
            //S.Parameters.EnumerateInterimSolutions = false;
            //S.Parameters.Algorithm = ConstraintSolverParams.CspSearchAlgorithm.TreeSearch;
            //S.Parameters.Solving = () => { Console.WriteLine("Solving"); } ;
            //S.Parameters.TimeLimitMilliSec = (param3.Value - 5) * 1000;
            ConstraintSolverSolution solution = null;

            Task taskSolve = new Task(() =>
            {
                solution = S.Solve();
            });
            Stopwatch timer = new Stopwatch();

            timer.Start();
            taskSolve.Start();

            TimeSpan limit = new TimeSpan(hours: 0, minutes: 0, seconds: param3);

            while (!taskSolve.IsCompleted)
            {
                if (!S.Parameters.Abort)
                {
                    Console.SetCursorPosition(0, Console.CursorTop);
                    Console.Write("  {0:hh}:{0:mm}:{0:ss}", timer.Elapsed);
                    Thread.Sleep(millisecondsTimeout: 500);
                }
                if (timer.Elapsed > limit && !S.Parameters.Abort)
                {
                    S.Parameters.Abort = true;
                    Console.WriteLine("\n  time limit - aborting...");
                }
            }
            Console.WriteLine("\n");

            //solveShifts.Solve(maxSolutions: param2.GetValueOrDefault());
            timer.Stop();

            solveShifts.GetSolutionsAll(solution: solution, maxSolutions: param2);

            if (solveShifts.ShiftsForce != null && solveShifts.ShiftsForce.Count > 0)
            {
                //solveShifts.ShowSolution(no: 1, shiftsForce: solveShifts.ShiftsForce.First().Value, showAgents: true, showSlots: false);
                foreach (var shift in solveShifts.ShiftsForce)
                {
                    solveShifts.ShowSolution(shift.Key, shift.Value, showAgents: true, showSlots: true);
                }
                Console.WriteLine(" solved in {0}", timer.Elapsed);
            }
            else
            {
                Console.WriteLine(" no solution found", timer.Elapsed);
            }
        }
コード例 #22
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();
            }
        }
コード例 #23
0
        public static void Run(int teamsNo)
        {
            // schedule N teams to play N-1 matches (one against every other team) with a difference
            //   of no more than 1 extra game away or home.  Note that N must be even (since every team
            //   must be paired every week).

            ConstraintSystem S = ConstraintSystem.CreateSolver();

            // The teams are numbered 0 to N-1 for simplicity in index lookups,
            //    since our arrays are zero-based.
            CspDomain Teams = S.CreateIntegerInterval(0, teamsNo - 1);


            CspTerm[][] matches = S.CreateVariableArray(Teams, "opponents", teamsNo, teamsNo - 1);

            CspTerm[][] atHome = S.CreateBooleanArray("atHome", teamsNo, teamsNo - 1);

            // each row represents the N-1 games the teams play.  The 0th week has an even-odd
            //  assignment since by symmetry that is equivalent to any other assignment and
            //  we thereby eliminate redundant solutions being enumerated.

            for (int t = 0; t < teamsNo; t++)
            {
                CspTerm atHomeSum = S.Sum(atHome[t]);
                S.AddConstraints(
                    S.Unequal(t, matches[t]),                                         // don't play self, and play every other team
                    S.LessEqual(teamsNo / 2 - 1, atHomeSum, S.Constant(teamsNo / 2)), // a balance of atHomes
                    S.Equal(t ^ 1, matches[t][0])                                     // even-odd pairing in the initial round
                    );
            }

            for (int w = 0; w < teamsNo - 1; w++)
            {
                S.AddConstraints(
                    S.Unequal(GetColumn(matches, w))              // every team appears once each week
                    );
                for (int t = 0; t < teamsNo; t++)
                {
                    S.AddConstraints(
                        S.Equal(t, S.Index(matches, matches[t][w], w)),           // Each team's pair's pair must be itself.
                        S.Equal(atHome[t][w], !S.Index(atHome, matches[t][w], w)) // Each pair is Home-Away or Away-Home.
                        );
                }
            }

            // That's it!  The problem is delivered to the solver.
            // Now to get an answer...

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

            if (soln.HasFoundSolution)
            {
                //unsolved = false;

                Console.Write("       | ");
                for (int w = 0; w < teamsNo - 1; w++)
                {
                    Console.Write("{1}Wk{0,2}", w + 1, w == 0 ? "" : " | ");
                }
                Console.WriteLine();
                Console.Write("       | ");
                for (int w = 0; w < teamsNo - 1; w++)
                {
                    Console.Write("{1}OP H", w + 1, w == 0 ? "" : " | ");
                }
                Console.WriteLine();
                Console.WriteLine("       {0}", "|" + new String('-', teamsNo * 6));
                for (int t = 0; t < teamsNo; t++)
                {
                    StringBuilder line = new StringBuilder();
                    line.AppendFormat("Team {0,2}| ", t + 1);
                    for (int w = 0; w < teamsNo - 1; w++)
                    {
                        object opponent, home;
                        if (!soln.TryGetValue(matches[t][w], out opponent))
                        {
                            throw new InvalidProgramException(matches[t][w].Key.ToString());
                        }
                        if (!soln.TryGetValue(atHome[t][w], out home))
                        {
                            throw new InvalidProgramException(atHome[t][w].Key.ToString());
                        }
                        line.AppendFormat("{2}{0,2} {1}",
                                          ((int)opponent) + 1,
                                          (int)home == 1 ? "*" : " ",
                                          w == 0 ? "" : " | "
                                          );
                        //line.Append(opponent.ToString());
                        //line.Append(((int)home == 1) ? " H," : " A,");
                    }
                    System.Console.WriteLine(line.ToString());
                }
                System.Console.WriteLine();
            }
            else
            {
                System.Console.WriteLine("No solution found.");
            }
        }
コード例 #24
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();
            }
        }
コード例 #25
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);
        }
コード例 #26
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);
        }
コード例 #27
0
        ///// <summary> Helper function for reading the Bus Driver data file
        ///// </summary>
        //static List<string> Numerals(string line)
        //{
        //    List<string> result = new List<string>();
        //    int left = 0;
        //    while (left < line.Length)
        //    {
        //        char c = line[left];
        //        if (('0' <= c) && (c <= '9'))
        //        {
        //            int right = left + 1;
        //            while ((right < line.Length) && ('0' <= line[right]) && (line[right] <= '9'))
        //                right++;
        //            result.Add(line.Substring(left, right - left));
        //            left = right + 1;
        //        }
        //        else
        //            left++;
        //    }
        //    return result;
        //}

        /// <summary> Bus Drivers.  Data taken from data files of London bus companies, with the
        ///           problem being to find the cheapest, complete, non-overlapping set of task
        ///           assignments that will give a feasible schedule.
        /// </summary>
        public static void BusDrivers(string sourceFilePath)
        {
            // http://www-old.cs.st-andrews.ac.uk/~ianm/CSPLib/prob/prob022/index.html

            ConstraintSystem S = ConstraintSystem.CreateSolver();

            List <CspTerm> driverCosts  = new List <CspTerm>();
            List <int[]>   driversTasks = new List <int[]>();
            int            nTasks       = 0;

            // Read the data file.  Each row specifies a driver cost, a count of tasks, and the task numbers

            try
            {
                using (StreamReader sr = new StreamReader(sourceFilePath))
                {
                    String line;

                    while ((line = sr.ReadLine()) != null)
                    {
                        int[] tasks;
                        driverCosts.Add(S.Constant(ReadDriver(line, out tasks)));
                        nTasks += tasks.Length;
                        Array.Sort <int>(tasks);
                        driversTasks.Add(tasks);
                    }
                }
                int nDrivers = driversTasks.Count;

                // create a master list of tasks by sorting the raw union and then compressing out duplicates.

                int[] allTasks = new int[nTasks];
                nTasks = 0;
                foreach (int[] tasks in driversTasks)
                {
                    foreach (int x in tasks)
                    {
                        allTasks[nTasks++] = x;
                    }
                }
                Array.Sort <int>(allTasks);
                nTasks = 0;
                for (int i = 1; i < allTasks.Length; i++)
                {
                    if (allTasks[nTasks] < allTasks[i])
                    {
                        allTasks[++nTasks] = allTasks[i];
                    }
                }
                nTasks++;
                Array.Resize <int>(ref allTasks, nTasks);

                // We now have an array of all the tasks, and a list of all the drivers.

                // The problem statement comes down to:
                //    - each task must be assigned exactly once
                //    - minimize the cost of drivers

                // We add a boolean vector representing the drivers, true if the driver is to be used.

                CspTerm[] driversUsed = S.CreateBooleanVector("drivers", nDrivers);   // these are the Decision Variables

                //  We now create an array which maps which tasks are in which drivers.
                //  In addition to this static map, we create a dynamic map of the usage and the costs.

                CspTerm[][] taskActualUse    = new CspTerm[nTasks][];
                CspTerm[]   driverActualCost = new CspTerm[nDrivers];
                for (int t = 0; t < nTasks; t++)
                {
                    taskActualUse[t] = new CspTerm[nDrivers];
                    for (int r = 0; r < nDrivers; r++)
                    {
                        taskActualUse[t][r] = (0 <= Array.BinarySearch <int>(driversTasks[r], allTasks[t])) ? driversUsed[r] : S.False;
                    }
                    S.AddConstraints(
                        S.ExactlyMofN(1, taskActualUse[t])  // this task appears exactly once
                        );
                }

                // set the goal

                for (int r = 0; r < nDrivers; r++)
                {
                    driverActualCost[r] = driversUsed[r] * driverCosts[r];   // dynamic cost map
                }
                S.TryAddMinimizationGoals(S.Sum(driverActualCost));

                // now run the Solver and print the solutions

                int solnId = 0;
                ConstraintSolverSolution soln = S.Solve();
                if (soln.HasFoundSolution)
                {
                    System.Console.WriteLine("Solution #" + solnId++);
                    for (int d = 0; d < driversUsed.Length; d++)
                    {
                        object isUsed;
                        if (!soln.TryGetValue(driversUsed[d], out isUsed))
                        {
                            throw new InvalidProgramException("can't find drive in the solution: " + d.ToString());
                        }

                        // Take only the decision variables which turn out true.
                        // For each true row, print the row number and the list of tasks.

                        if (1 == (int)isUsed)
                        {
                            StringBuilder line = new StringBuilder(d.ToString());
                            line.Append(": ");
                            foreach (int x in driversTasks[d])
                            {
                                line.Append(x.ToString()).Append(", ");
                            }
                            System.Console.WriteLine(line.ToString());
                        }
                    }
                }
                if (solnId == 0)
                {
                    System.Console.WriteLine("No solution found.");
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
コード例 #28
0
        public static void Run(string parameters)
        {
            // http://www-old.cs.st-andrews.ac.uk/~ianm/CSPLib/prob/prob022/index.html

            ConstraintSystem S = ConstraintSystem.CreateSolver();

            List <CspTerm> driverCosts  = new List <CspTerm>();
            List <int[]>   driversTasks = new List <int[]>();
            int            nTasks       = 0;

            // Read the data file.  Each row specifies a driver cost, a count of tasks, and the task numbers
            try
            {
                //parse parameters to extract data
                //<line no> = bus driver no-1 (eg line 1 = driver0)
                //1 4 3 4 16 17
                //1 = cost of driver
                // 4 = number of bus routes (tasks)
                // 3, 4, 16, 17 = the bus routes (tasks) for the driver
                var lines = Regex.Split(parameters, "\r\n|\r|\n");
                foreach (var line in lines)
                {
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }

                    int[] tasks;
                    driverCosts.Add(S.Constant(ReadDriver(line, out tasks)));
                    nTasks += tasks.Length;
                    Array.Sort <int>(tasks);
                    driversTasks.Add(tasks);
                }
                int nDrivers = driversTasks.Count;

                // create a master list of unique tasks (bus routes) that be assigned to drivers
                List <int> tasksU = new List <int>();
                driversTasks.ForEach(x => tasksU.AddRange(x));
                int[] allTasks = tasksU.OrderBy(x => x).Distinct().ToArray();
                nTasks = allTasks.Length;


                // We now have an array of all the tasks, and a list of all the drivers.

                // The problem statement comes down to:
                //    - each task must be assigned exactly once
                //    - minimize the cost of drivers

                // We add a boolean vector representing the drivers, true if the driver is to be used.

                CspTerm[] driversUsed = S.CreateBooleanVector("drivers", nDrivers);   // these are the Decision Variables

                //  We now create an array which maps which tasks are in which drivers.
                //  In addition to this static map, we create a dynamic map of the usage and the costs.
                CspTerm[][] taskActualUse    = new CspTerm[nTasks][];
                CspTerm[]   driverActualCost = new CspTerm[nDrivers];
                for (int t = 0; t < nTasks; t++)              //for each task / bus route
                {
                    taskActualUse[t] = new CspTerm[nDrivers]; //for each route, array of all bus drivers (used to flag who may drive the route)
                    for (int r = 0; r < nDrivers; r++)        //for each driver
                    {
                        taskActualUse[t][r] = (0 <= Array.BinarySearch <int>(driversTasks[r], allTasks[t])) ? driversUsed[r] : S.False;
                    }
                    S.AddConstraints(
                        S.ExactlyMofN(1, taskActualUse[t])  // this task appears exactly once
                        );
                }

                // set the goal: minimize total driver's cost
                for (int r = 0; r < nDrivers; r++)
                {
                    driverActualCost[r] = driversUsed[r] * driverCosts[r];   // dynamic cost map
                }
                S.TryAddMinimizationGoals(S.Sum(driverActualCost));

                // now run the Solver and print the solutions
                int solnId = 0;
                ConstraintSolverSolution soln = S.Solve();
                if (soln.HasFoundSolution)
                {
                    System.Console.WriteLine("Solution #" + solnId++);
                    for (int d = 0; d < driversUsed.Length; d++)
                    {
                        object isUsed;
                        if (!soln.TryGetValue(driversUsed[d], out isUsed))
                        {
                            throw new InvalidProgramException("can't find drive in the solution: " + d.ToString());
                        }

                        // Take only the decision variables which turn out true.
                        // For each true row, print the row number and the list of tasks.

                        if (1 == (int)isUsed)
                        {
                            StringBuilder line = new StringBuilder(d.ToString());
                            line.Append(": ");
                            foreach (int x in driversTasks[d])
                            {
                                line.Append(x.ToString()).Append(", ");
                            }
                            System.Console.WriteLine(line.ToString());
                        }
                    }
                }
                if (solnId == 0)
                {
                    System.Console.WriteLine("No solution found.");
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
コード例 #29
0
        public ConstraintSolverSolution SolveB(int maxSolutions = 100)
        {
            ConstraintSystem S = ConstraintSystem.CreateSolver();

            //Define how many agents may work per shift
            CspDomain cspShiftsForceDomain = S.CreateIntegerInterval(first: 0, last: MaxAgents);

            //Decision variables, one per shift, that will hold the result of how may agents must work per shift to fullfil requirements
            CspTerm[] cspShiftsForce = S.CreateVariableVector(domain: cspShiftsForceDomain, key: "force", length: Shifts.Count);

            //index shifts, their variable CspTerm by the shift's relative no (0=first, 1=second, etc)
            ShiftsX = new Dictionary <Models.Shift, CspTerm>();
            int i = 0;

            Shifts.ForEach(x => { ShiftsX.Add(x, cspShiftsForce[i]); i++; });

            //Constraint - Agents on every half hour must be >= requirement for that half hour
            List <CspTerm> cspHalfHourExcess = new List <CspTerm>();

            foreach (var halfHourRq in HalfHourRequirements)
            {
                //find shifts including that halftime, and calculate their sum of force
                List <CspTerm> cspActive = new List <CspTerm>();
                foreach (var entry in ShiftsX)
                {
                    if (entry.Key.IncludesHalfHour(halfHourRq.Start))
                    {
                        cspActive.Add(entry.Value);
                    }
                }

                //add constraint for sum of force of active shifts on that halfhour
                //if we need agents but no shifts exists for a halfhour, do not add a constraint
                if (cspActive.Count > 0)
                {
                    var s = S.Sum(cspActive.ToArray()) - S.Constant(halfHourRq.RequiredForce);
                    S.AddConstraints(
                        S.LessEqual(constant: 0, inputs: s)
                        );
                    cspHalfHourExcess.Add(s);
                }
            }

            //var goal = S.Sum(shiftsX.Values.ToArray());
            //bool ok = S.TryAddMinimizationGoals(goal);

            var  goalMinExcess = S.Sum(cspHalfHourExcess.ToArray());
            bool ok            = S.TryAddMinimizationGoals(goalMinExcess);

            ConstraintSolverSolution solution = S.Solve();

            Console.WriteLine();
            GetSolutionsAll(solution: solution, maxSolutions: maxSolutions);
            if (ShiftsForce == null || ShiftsForce.Count == 0)
            {
                Console.WriteLine("No solution found");
            }

            if (ShiftsForce != null)
            {
                foreach (var shiftForceEntry in ShiftsForce)
                {
                    ShowSolution(no: shiftForceEntry.Key, shiftsForce: shiftForceEntry.Value, showAgents: true, showSlots: false);
                }
            }

            return(solution);
        }