Beispiel #1
0
        public MplsAllocationSolverImpl(SolverParameters parameters)
        {
            this.parameters = parameters;

            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (this.parameters.Machines == null || this.parameters.Machines.Length == 0)
            {
                throw new ArgumentException("No Machines where provided as parameters");
            }

            if (this.parameters.ContainerSpecs == null || this.parameters.ContainerSpecs.Length == 0)
            {
                throw new ArgumentException("No Container Specs where provided as parameters");
            }

            this.averageAvailableResource = new double[this.ResourceCount];

            this.resourceWeight = new double[this.ResourceCount];
            for (int i = 0; i < this.ResourceCount; i++)
            {
                this.resourceWeight[i] = 1;
            }

            this.desiredContainerInstanceCounts = parameters.ContainerSpecs
                                                  .Select(c => c.DesiredInstanceCount)
                                                  .ToArray();

            if (parameters.HardConstraintResource.HasValue)
            {
                this.IdentifyHardConstraint(parameters.HardConstraintResource.Value, parameters.OptimizeResources);
            }

            if (parameters.MaximizeResourceUsageFor.HasValue)
            {
                this.AssignInstancesToMaximizeResourceUtilization();
            }

            bool allMachineResourcesListed = parameters.Machines.All(c => c.AvailableResources.Length == parameters.Machines[0].AvailableResources.Length);

            if (!allMachineResourcesListed)
            {
                throw new ArgumentException("All Machines should list the exact same resources, and specify zero when not required.");
            }

            bool allContainerResourceUsagesListed = parameters.ContainerSpecs.All(c => c.ResourceUsages.Length == parameters.ContainerSpecs[0].ResourceUsages.Length);

            if (!allContainerResourceUsagesListed)
            {
                throw new ArgumentException("All Container Specs should list the exact same resources, and specify zero when not required.");
            }

            this.machineConstraintsPerResource    = parameters.Machines.Select(c => c.AvailableResources.Select(x => x.Value).ToArray()).ToArray().Rotate();
            this.containerCoefficientsPerResource = parameters.ContainerSpecs.Select(c => c.ResourceUsages.Select(d => d.Value).ToArray()).ToArray().Rotate();

            this.currentDeallocationCount = new int[this.Columns];
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
//            var solver = new Solver<Values.MyThing, int>(new DefaultGenomeFactory<MyThing>(), new MyThingGenomeEvaluator(), new MyThingGenomeDescription(), new MyThingSolverLogger(), new SolverParameters(1000));

            var coefficientsToMatch = new Coefficients.Coefficients
            {
                FifthLevel  = 0,
                FourthLevel = 3.9,
                ThirdLevel  = -34.5,
                SecondLevel = -9.8,
                FirstLevel  = 11.9
            };
            var pointsToMatch = Enumerable.Range(-1000, 1000).Select(x => new Point(x, coefficientsToMatch.Calc(x)));
            var evaluator     = new CoefficientsGenomeEvaluator(pointsToMatch);

            var solverParameters = new SolverParameters(
                1000,
                2000,
                0.3);

//            var tasks = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
//                tasks.Add(Task.Run(() => LaunchEvolutionRun(genomeDescriptions, solverParameters, defaultGenomeFactory, evaluator)));
                LaunchEvolutionRun(solverParameters, evaluator);
            }

//            Task.WaitAll(tasks.ToArray());

//            TestBellCurve();
            Console.WriteLine("Finished");
            Console.ReadKey();
        }
Beispiel #3
0
        public SolverResult Solve(SolverParameters parameters)
        {
            MplsAllocationSolverImpl solver   = new MplsAllocationSolverImpl(parameters);
            SolverResult             solution = solver.Solve();

            return(solution);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            var maxEliteSize     = 1000;
            var solverParameters = new SolverParameters(
                maxEliteSize,
                2 * maxEliteSize,
                0.3);

            var expressionGenerator = ExpressionGeneratorFactory.CreateExpressionGenerator();

            // TestExpressionGenerator(expressionGenerator);

//            var tasks = new List<Task>();
            for (int i = 0; i < 5; i++)
            {
//                tasks.Add(Task.Run(() => LaunchEvolutionRun(genomeDescriptions, solverParameters, defaultGenomeFactory, evaluator)));
                LaunchEvolutionRun(solverParameters, expressionGenerator);
            }

//            Task.WaitAll(tasks.ToArray());

//            TestBellCurve();
            Console.WriteLine("Finished");
            Console.ReadLine();
        }
Beispiel #5
0
        public SharpEngine(
            PhysicsEngineParameters simulationParameters,
            CollisionEngineParameters collisionEngineParameters,
            SolverParameters solverParameters)
        {
            SolverParameters     = solverParameters;
            CollisionEngineParam = collisionEngineParameters;
            EngineParameters     = simulationParameters;

            // Default solver
            SetSolverType(SolverType.ProjectedGaussSeidel);

            Shapes = new IShape[0];

            CollisionEngine = new CollisionDetectionEngine(
                collisionEngineParameters,
                EngineParameters.CollisionDistance);

            contactPartitioningEngine = new ContactPartitioningEngine();

            CollisionShapes          = new List <ICollisionShape>();
            CollisionJoints          = new List <ICollisionJoint>();
            Joints                   = new List <IConstraint> ();
            HsGenerator              = new HashGenerator();
            LinearSystemBuilder      = new LinearProblemBuilderEngine(EngineParameters);
            IntegrateVelocityEngine  = new IntegrateVelocity(EngineParameters);
            IntegratePositionEngine  = new IntegratePosition(EngineParameters);
            contactConstraintBuilder = new ContactConstraintBuilder(EngineParameters);
            rayCastEngine            = new RayCastingEngine();
            warmStartEngine          = new WarmStartEngine(EngineParameters);
            ccdEngine                = new ConservativeAdvancement();
        }
Beispiel #6
0
        public static void SimpleAllocationCase <T>() where T : IAllocationSolver, new()
        {
            Console.WriteLine($"Allocating with Solver: {typeof(T).Name}");

            MachineBuilder machineBuilder = new MachineBuilder();

            Machine[] machines =
                machineBuilder.WithCpu(20).WithMemory(20).BuildMany(93).Union(
                    machineBuilder.WithCpu(5).WithMemory(5).BuildMany(51)
                    ).Union(
                    machineBuilder.WithCpu(1).WithMemory(1).BuildMany(84)
                    ).ToArray();

            ContainerBuilder containerBuilder = new ContainerBuilder();

            ContainerSpec[] containers =
                containerBuilder.WithCpu(1).WithMemory(1).WithInstanceCount(24).BuildMany(1);

            SolverParameters parameters = new SolverParameters
            {
                Machines = machines, ContainerSpecs = containers, FullScanIterations = 2, InitialRandomGuessIterations = 2
            };

            IAllocationSolver solver   = new T();
            SolverResult      solution = solver.Solve(parameters);

            Console.WriteLine($"Solution Quality: {solution.SolutionQuality.ToString()}");

            var allocatedMachines = solution.NewAllocations.Select(c => new { c.Machine.Name }).ToArray();

            foreach (var allocation in solution.Allocations)
            {
                Console.WriteLine($"{allocation.Machine.Name} <- {allocation.ContainerSpec.Name}");
            }
        }
Beispiel #7
0
    private static long Solve(long num_buses_check = 0)
    {
        SolverParameters sPrm = new SolverParameters();

        sPrm.compress_trail = 0;
        sPrm.trace_level    = 0;
        sPrm.profile_level  = 0;
        Solver solver = new Solver("OrTools", sPrm);

        //this works
        // IntVar[,] x = solver.MakeIntVarMatrix(2,2, new int[] {-2,0,1,2}, "x");

        //this doesn't work
        IntVar[,] x = solver.MakeIntVarMatrix(2, 2, new int[] { 0, 1, 2 }, "x");

        for (int w = 0; w < 2; w++)
        {
            IntVar[] b = new IntVar[2];
            for (int i = 0; i < 2; i++)
            {
                b[i] = solver.MakeIsEqualCstVar(x[w, i], 0);
            }
            solver.Add(solver.MakeSumGreaterOrEqual(b, 2));
        }

        IntVar[]        x_flat = x.Flatten();
        DecisionBuilder db     = solver.MakePhase(x_flat,
                                                  Solver.CHOOSE_FIRST_UNBOUND,
                                                  Solver.ASSIGN_MIN_VALUE);

        solver.NewSearch(db);
        while (solver.NextSolution())
        {
            Console.WriteLine("x: ");
            for (int j = 0; j < 2; j++)
            {
                Console.Write("worker" + (j + 1).ToString() + ":");
                for (int i = 0; i < 2; i++)
                {
                    Console.Write(" {0,2} ", x[j, i].Value());
                }
                Console.Write("\n");
            }
            Console.WriteLine("End   at---->" + DateTime.Now);
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
        return(1);
    }
        protected override GeneticAlgorithm GetGA(SolverParameters parameters)
        {
            var population =
                new Population(parameters.Population, parameters.Population, new FiveHousesChromosome());

            return(new GeneticAlgorithm(
                       population,
                       FitnessProvider,
                       new TournamentSelection(),
                       new UniformCrossover(),
                       new TraitGroupMutation()));
        }
        public SubspaceMinimization(SolverParameters solverParameters)
        {
            solverParam = solverParameters;

            var gaussSeidelSolverParam = new SolverParameters(
                25,
                solverParam.ErrorTolerance,
                solverParam.SOR,
                solverParam.MaxThreadNumber);

            gaussSeidelSolver = new ProjectedGaussSeidel(gaussSeidelSolverParam);
        }
Beispiel #10
0
    private static long Solve(long num_buses_check = 0)
    {
        SolverParameters sPrm = new SolverParameters();
        sPrm.compress_trail = 0;
        sPrm.trace_level = 0;
        sPrm.profile_level = 0;
        Solver solver = new Solver("OrTools",sPrm);

        //this works
        // IntVar[,] x = solver.MakeIntVarMatrix(2,2, new int[] {-2,0,1,2}, "x");

        //this doesn't work
        IntVar[,] x = solver.MakeIntVarMatrix(2, 2, new int[] { 0, 1, 2 }, "x");

        for (int w = 0; w < 2; w++)
        {
          IntVar[] b = new IntVar[2];
          for (int i = 0; i < 2; i++)
          {
        b[i] = solver.MakeIsEqualCstVar(x[w, i], 0);
          }
          solver.Add(solver.MakeSumGreaterOrEqual(b, 2));
        }

        IntVar[] x_flat = x.Flatten();
        DecisionBuilder db = solver.MakePhase(x_flat,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);
        solver.NewSearch(db);
        while (solver.NextSolution())
        {
          Console.WriteLine("x: ");
          for (int j = 0; j < 2; j++)
          {
        Console.Write("worker" + (j + 1).ToString() + ":");
        for (int i = 0; i < 2; i++)
        {
          Console.Write(" {0,2} ", x[j, i].Value());
        }
        Console.Write("\n");
          }
          Console.WriteLine("End   at---->" + DateTime.Now);
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
        return 1;
    }
        public async Task Initialise()
        {
            // Just want to get back gen 0 so we can see the problem
            var param0 = new SolverParameters {
                Generations = 0, Population = 2
            };

            await RunSolver(param0);

            if (cssClass == "m-hidden")
            {
                cssClass = "m-fadeIn";
            }
        }
        protected override GeneticAlgorithm GetGA(SolverParameters parameters)
        {
            var adamChromosome = new GeniusSquareChromosome();

            var population =
                new Population(parameters.Population, parameters.Population, adamChromosome);

            return(new GeneticAlgorithm(
                       population,
                       FitnessProvider,
                       new EliteSelection(),
                       new UniformCrossover(),
                       new IntMutation()));
        }
Beispiel #13
0
        protected override GeneticAlgorithm GetGA(SolverParameters parameters)
        {
            var adamChromosome = new PasswordChromosome(PasswordLength);

            var population =
                new Population(parameters.Population, parameters.Population, adamChromosome);

            return(new GeneticAlgorithm(
                       population,
                       FitnessProvider,
                       new EliteSelection(),
                       new UniformCrossover(),
                       new StringMutation()));
        }
        protected override GeneticAlgorithm GetGA(SolverParameters parameters)
        {
            var adamChromosome = new IntChromosome(0.To(NumQueens - 1).ToArray());

            var population =
                new Population(parameters.Population, parameters.Population, adamChromosome);

            return(new GeneticAlgorithm(
                       population,
                       FitnessProvider,
                       new EliteSelection(),
                       new OrderedCrossover(),
                       new ReverseSequenceMutation()));
        }
Beispiel #15
0
        protected override GeneticAlgorithm GetGA(SolverParameters parameters)
        {
            // First node is fixed
            var adamChromosome = new IntChromosome(1.To(NumPoints - 1).ToArray());

            var population =
                new Population(parameters.Population, parameters.Population, adamChromosome);

            return(new GeneticAlgorithm(
                       population,
                       FitnessProvider,
                       new TournamentSelection(),
                       new OrderedCrossover(),
                       new ReverseSequenceMutation()));
        }
Beispiel #16
0
        public ClassicTumblerParameters()
        {
            var solver = new SolverParameters();

            FakePuzzleCount = solver.FakePuzzleCount;
            RealPuzzleCount = solver.RealPuzzleCount;

            var promise = new PromiseParameters();

            FakeTransactionCount = promise.FakeTransactionCount;
            RealTransactionCount = promise.RealTransactionCount;
            FakeFormat           = promise.FakeFormat;

            Denomination   = Money.Coins(1.0m);
            Fee            = Money.Coins(0.01m);
            CycleGenerator = new OverlappedCycleGenerator();
        }
Beispiel #17
0
        private static void LaunchEvolutionRun(SolverParameters solverParameters, ExpressionGenerator <GameState> expressionGenerator)
        {
            var cache                 = new FitnessCache <GameAgentLogicGenome, double>(2000 * solverParameters.MaxEliteSize);
            var evaluator             = new GameAgentEvaluator <GameAgentLogicGenome>(cache, genome => new GameAgentWithLogic(genome));
            var bellWeightedRandom    = new CyclableBellWeightedRandom(10.0, 3.0, 1.0, 0.5, 0.1);
            var genomeDescriptions    = new GameAgentLogicGenomeDescription(bellWeightedRandom, expressionGenerator);
            var defaultGenomeFactory  = new GeneticSolver.Genome.DefaultGenomeFactory <GameAgentLogicGenome>(genomeDescriptions);
            var mutationProbabilities = new Cyclable <double>(new[] { 0.3, 0.9, 1.0 });
            var mutator               = new GenomeMutator <GameAgentLogicGenome>(genomeDescriptions, mutationProbabilities, new UnWeightedRandom());
            var logger                = new GameAgentWithLogicSolverLogger();
            var solver                = new Solver <GameAgentLogicGenome, double>(
                defaultGenomeFactory,
                evaluator,
                logger,
                solverParameters,
                new IEarlyStoppingCondition <GameAgentLogicGenome, double>[]
            {
                // new GeneticSolver.EarlyStoppingConditions.FitnessThresholdReachedEarlyStopCondition<GameAgentMultipliers, double>(fitness => fitness < 1e-6),
                new GeneticSolver.EarlyStoppingConditions.ProgressStalledEarlyStoppingCondition <GameAgentLogicGenome, double>(10, 0.5, 0.8),
                new GeneticSolver.EarlyStoppingConditions.FitnessNotImprovingEarlyStoppingCondition <GameAgentLogicGenome>(1, 100),
            },
                new IGenomeReproductionStrategy <GameAgentLogicGenome>[]
            {
                new CyclableReproductionStrategy <GameAgentLogicGenome>(new IGenomeReproductionStrategy <GameAgentLogicGenome>[]
                {
                    new SexualGenomeReproductionStrategy <GameAgentLogicGenome, double>(mutator, new StratifiedBreedingStrategy(),
                                                                                        defaultGenomeFactory, genomeDescriptions, evaluator, 40, 2),
                    new SexualGenomeReproductionStrategy <GameAgentLogicGenome, double>(mutator, new GeneticSolver.PairingStrategies.RandomBreedingStrategy(),
                                                                                        defaultGenomeFactory, genomeDescriptions, evaluator, 40, 2),
                    new AsexualGenomeReproductionStrategy <GameAgentLogicGenome>(new GenomeMutator <GameAgentLogicGenome>(genomeDescriptions, 1.0, new UnWeightedRandom())),
                }),
                new AsexualGenomeReproductionStrategy <GameAgentLogicGenome>(new GenomeMutator <GameAgentLogicGenome>(genomeDescriptions, 0.4, new UnWeightedRandom())),
            });

            solver.NewGeneration += (s, e) => bellWeightedRandom.CycleStdDev();
            solver.NewGeneration += (s, e) => mutationProbabilities.Cycle();
            solver.NewGeneration += (sender, e) => cache.ClearExcept(e.OrderedGenomes.Select(g => g.GenomeInfo.Genome));

            logger.Start();
            var best = solver.Evolve(1000);

            logger.LogGeneration(best);
            logger.End();
        }
        private async Task RunSolver(SolverParameters parameters)
        {
            StopSolver();

            if (fitnessChart != null)
            {
                await fitnessChart.Clear();
            }

            token = new CancellationTokenSource();

            stopwatch.Restart();
            IsSolving = true;

            try
            {
                var results = Solver.GetResults(token, parameters).WithCancellation(token.Token);

                await foreach (var result in results)
                {
                    HandleResult(result);
                }
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Task cancelled by user");
            }
            catch (Exception e)
            {
                error = e.Message;

                Console.WriteLine($"Error: {e.Message}");
            }
            finally
            {
                IsSolving = false;
                stopwatch.Stop();

                StateHasChanged();
            }
        }
Beispiel #19
0
        public async IAsyncEnumerable <Result <T> > Solve(
            SolverParameters parameters,
            [EnumeratorCancellation] CancellationToken token = default)
        {
            int generations = parameters.Generations;

            var ga = GetGeneticAlgorithm(parameters);

            ga.Start();

            double bestFitness = 0;

            // Run one generation and then yield result before resuming
            for (int i = 0; i <= generations; i++)
            {
                token.ThrowIfCancellationRequested();

                var result = GetResult(ga.Population, ga.TimeEvolving, i);

                // Only publish improved result or every nth result
                if (result.Fitness > bestFitness || i % StepSize == 0)
                {
                    bestFitness = result.Fitness;


                    yield return(result);

                    await Task.Delay(1); // TODO: Determine if this is optimal

                    if (ga.BestChromosome.Fitness >= 1.0)
                    {
                        yield break;
                    }
                }

                await Task.Yield();

                ga.Termination = new GenerationNumberTermination(i + 1);
                ga.Resume();
            }
        }
Beispiel #20
0
        private static void LaunchEvolutionRun(SolverParameters solverParameters, CoefficientsGenomeEvaluator evaluator)
        {
            var mutationProbabilities = new Cyclable <double>(new [] { 0.3, 0.9, 1.0 });
            var bellWeightedRandom    = new CyclableBellWeightedRandom(10.0, 3.0, 1.0, 0.5, 0.1);
            var genomeDescriptions    = new CoefficientsGenomeDescriptions(bellWeightedRandom);
            var defaultGenomeFactory  = new DefaultGenomeFactory <Coefficients.Coefficients>(genomeDescriptions);
            var mutator = new GenomeMutator <Coefficients.Coefficients>(genomeDescriptions, mutationProbabilities, new UnWeightedRandom());
            var logger  = new CoefficientsSolverLogger();
            var solver  = new Solver <Coefficients.Coefficients, double>(
                defaultGenomeFactory,
                evaluator,
                logger,
                solverParameters,
                new IEarlyStoppingCondition <Coefficients.Coefficients, double>[]
            {
                new FitnessThresholdReachedEarlyStopCondition <Coefficients.Coefficients, double>(fitness => fitness < 1e-6),
                new ProgressStalledEarlyStoppingCondition <Coefficients.Coefficients, double>(10, 0.5, 0.8),
                new FitnessNotImprovingEarlyStoppingCondition <Coefficients.Coefficients>(1e-7, 10),
            },
                new IGenomeReproductionStrategy <Coefficients.Coefficients>[]
            {
//                    new SexualGenomeReproductionStrategy<Coefficients.Coefficients, double>(mutator, new HaremBreedingStrategy(),
//                        defaultGenomeFactory, genomeDescriptions, evaluator, 100, 2),
                new SexualGenomeReproductionStrategy <Coefficients.Coefficients, double>(mutator, new StratifiedBreedingStrategy(),
                                                                                         defaultGenomeFactory, genomeDescriptions, evaluator, 100, 2),
                new SexualGenomeReproductionStrategy <Coefficients.Coefficients, double>(mutator, new RandomBreedingStrategy(),
                                                                                         defaultGenomeFactory, genomeDescriptions, evaluator, 100, 2),
//                    new AsexualGenomeReproductionStrategy<Coefficients.Coefficients>(mutator),
            });

            solver.NewGeneration += (s, e) => mutationProbabilities.Cycle();
            solver.NewGeneration += (s, e) => bellWeightedRandom.CycleStdDev();

            logger.Start();
            var best = solver.Evolve(1000);

            logger.LogGeneration(best);
            logger.End();
        }
Beispiel #21
0
        public GeneticAlgorithm GetGeneticAlgorithm(SolverParameters parameters)
        {
            var ga = GetGA(parameters);

            ga.Population.GenerationStrategy = new PerformanceGenerationStrategy();

            ga.CrossoverProbability = parameters.CrossoverProbability;
            ga.MutationProbability  = parameters.MutationProbability;

            ga.Selection = parameters.Selection switch
            {
                SolverParameters.SolverSelection.Elite => new EliteSelection(),
                SolverParameters.SolverSelection.Tournament => new TournamentSelection(),
                SolverParameters.SolverSelection.Roulette => new RouletteWheelSelection(),
                _ => throw new InvalidOperationException(
                          $"Unknow selection strategy: {parameters.Selection}")
            };

            ga.Termination = new GenerationNumberTermination(0);

            return(ga);
        }
Beispiel #22
0
    //  We don't need helper functions here
    //  Csharp syntax is easier than C++ syntax!

    private static void CPisFun (int kBase, int time_limit_param, bool print)
    {

        // Use some profiling and change the default parameters of the solver
        SolverParameters solver_params = new SolverParameters();
        // Change the profile level
        solver_params.profile_level = SolverParameters.NORMAL_PROFILING;

        //  Constraint Programming engine
        Solver solver = new Solver ("CP is fun!", solver_params);

        // Decision variables
        IntVar c = solver.MakeIntVar (1, kBase - 1, "C");
        IntVar p = solver.MakeIntVar (0, kBase - 1, "P");
        IntVar i = solver.MakeIntVar (1, kBase - 1, "I");
        IntVar s = solver.MakeIntVar (0, kBase - 1, "S");
        IntVar f = solver.MakeIntVar (1, kBase - 1, "F");
        IntVar u = solver.MakeIntVar (0, kBase - 1, "U");
        IntVar n = solver.MakeIntVar (0, kBase - 1, "N");
        IntVar t = solver.MakeIntVar (1, kBase - 1, "T");
        IntVar r = solver.MakeIntVar (0, kBase - 1, "R");
        IntVar e = solver.MakeIntVar (0, kBase - 1, "E");

        // We need to group variables in a vector to be able to use
        // the global constraint AllDifferent
        IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e};

        // Check if we have enough digits
        if (kBase < letters.Length) {
          throw new Exception("kBase < letters.Length");
        }

        //  Constraints
        solver.Add (letters.AllDifferent ());

        // CP + IS + FUN = TRUE
        solver.Add (p + s + n + kBase * (c + i + u) + kBase * kBase * f ==
               e + kBase * u + kBase * kBase * r + kBase * kBase * kBase * t);

        SolutionCollector all_solutions = solver.MakeAllSolutionCollector();
        //  Add the interesting variables to the SolutionCollector
        all_solutions.Add(letters);

        //  Decision Builder: hot to scour the search tree
        DecisionBuilder db = solver.MakePhase (letters,
                                               Solver.CHOOSE_FIRST_UNBOUND,
                                               Solver.ASSIGN_MIN_VALUE);

        // Add some time limit
        SearchLimit time_limit = solver.MakeTimeLimit(time_limit_param);

        solver.Solve(db, all_solutions, time_limit);

        //  Retrieve the solutions
        int numberSolutions = all_solutions.SolutionCount();
        Console.WriteLine ("Number of solutions: " + numberSolutions);

        if (print) {
            for (int index = 0; index < numberSolutions; ++index) {
                Console.Write ("C=" + all_solutions.Value(index, c));
                Console.Write (" P=" + all_solutions.Value(index, p));
                Console.Write (" I=" + all_solutions.Value(index, i));
                Console.Write (" S=" + all_solutions.Value(index, s));
                Console.Write (" F=" + all_solutions.Value(index, f));
                Console.Write (" U=" + all_solutions.Value(index, u));
                Console.Write (" N=" + all_solutions.Value(index, n));
                Console.Write (" T=" + all_solutions.Value(index, t));
                Console.Write (" R=" + all_solutions.Value(index, r));
                Console.Write (" E=" + all_solutions.Value(index, e));
                Console.WriteLine ();
            }
        }

        // Save profile in file
        solver.ExportProfilingOverview("profile.txt");
    }
        private void RoundTrip(ref SolverClientSession client, SolverParameters parameters)
        {
            var clone = Serializer.Clone(client.GetInternalState());

            client = new SolverClientSession(parameters, clone);
        }
        public void TestPuzzleSolver()
        {
            RsaKey         key = TestKeys.Default;
            PuzzleSolution expectedSolution = null;
            Puzzle         puzzle           = key.PubKey.GeneratePuzzle(ref expectedSolution);

            var parameters = new SolverParameters
            {
                FakePuzzleCount = 50,
                RealPuzzleCount = 10,
                ServerKey       = key.PubKey
            };
            SolverClientSession client = new SolverClientSession(parameters);
            SolverServerSession server = new SolverServerSession(key, parameters);

            var clientEscrow = new Key();
            var serverEscrow = new Key();

            var escrow            = CreateEscrowCoin(clientEscrow.PubKey, serverEscrow.PubKey);
            var redeemDestination = new Key().ScriptPubKey;

            client.ConfigureEscrowedCoin(escrow, clientEscrow, redeemDestination);
            client.AcceptPuzzle(puzzle.PuzzleValue);
            RoundTrip(ref client, parameters);
            Assert.True(client.GetInternalState().RedeemDestination == redeemDestination);
            PuzzleValue[] puzzles = client.GeneratePuzzles();
            RoundTrip(ref client, parameters);
            RoundTrip(ref puzzles);

            server.ConfigureEscrowedCoin(escrow, serverEscrow);
            var commitments = server.SolvePuzzles(puzzles);

            RoundTrip(ref server, parameters, key);
            RoundTrip(ref commitments);

            var revelation = client.Reveal(commitments);

            RoundTrip(ref client, parameters);
            RoundTrip(ref revelation);

            SolutionKey[] fakePuzzleKeys = server.CheckRevelation(revelation);
            RoundTrip(ref server, parameters, key);
            RoundTrip(ref fakePuzzleKeys);


            BlindFactor[] blindFactors = client.GetBlindFactors(fakePuzzleKeys);
            RoundTrip(ref client, parameters);
            RoundTrip(ref blindFactors);

            var offerInformation = server.CheckBlindedFactors(blindFactors, FeeRate);

            RoundTrip(ref server, parameters, key);

            var clientOfferSig = client.SignOffer(offerInformation);


            //Verify if the scripts are correctly created
            var fulfill     = server.FulfillOffer(clientOfferSig, new Key().ScriptPubKey, FeeRate);
            var offerRedeem = client.CreateOfferRedeemTransaction(FeeRate);

            var offerTransaction = server.GetSignedOfferTransaction();
            var offerCoin        = offerTransaction.Transaction.Outputs.AsCoins().First();
            var resigned         = offerTransaction.ReSign(client.EscrowedCoin);

            TransactionBuilder txBuilder = new TransactionBuilder();

            txBuilder.AddCoins(client.EscrowedCoin);
            Assert.True(txBuilder.Verify(resigned));

            resigned  = fulfill.ReSign(offerCoin);
            txBuilder = new TransactionBuilder();
            txBuilder.AddCoins(offerCoin);
            Assert.True(txBuilder.Verify(resigned));

            var offerRedeemTx = offerRedeem.ReSign(offerCoin);

            txBuilder = new TransactionBuilder();
            txBuilder.AddCoins(offerCoin);
            Assert.True(txBuilder.Verify(offerRedeemTx));


            client.CheckSolutions(fulfill.Transaction);
            RoundTrip(ref client, parameters);

            var clientEscapeSignature = client.SignEscape();
            var escapeTransaction     = server.GetSignedEscapeTransaction(clientEscapeSignature, FeeRate, new Key().ScriptPubKey);

            txBuilder = new TransactionBuilder();
            txBuilder.AddCoins(client.EscrowedCoin);
            Assert.True(txBuilder.Verify(escapeTransaction));

            var solution = client.GetSolution();

            RoundTrip(ref client, parameters);
            Assert.True(solution == expectedSolution);
        }
        private void RoundTrip(ref SolverServerSession server, SolverParameters parameters, RsaKey key)
        {
            var clone = Serializer.Clone(server.GetInternalState());

            server = new SolverServerSession(key, parameters, clone);
        }
 public IAsyncEnumerable <Result <FiveHousesSolution> > GetResults(
     CancellationTokenSource token,
     SolverParameters parameters) =>
 SolverService.GetFiveHousesSolution(token, parameters);
Beispiel #27
0
    //  We don't need helper functions here
    //  Csharp syntax is easier than C++ syntax!

    private static void CPisFun(int kBase, int time_limit_param, bool print)
    {
        // Use some profiling and change the default parameters of the solver
        SolverParameters solver_params = new SolverParameters();

        // Change the profile level
        solver_params.profile_level = SolverParameters.NORMAL_PROFILING;

        //  Constraint Programming engine
        Solver solver = new Solver("CP is fun!", solver_params);

        // Decision variables
        IntVar c = solver.MakeIntVar(1, kBase - 1, "C");
        IntVar p = solver.MakeIntVar(0, kBase - 1, "P");
        IntVar i = solver.MakeIntVar(1, kBase - 1, "I");
        IntVar s = solver.MakeIntVar(0, kBase - 1, "S");
        IntVar f = solver.MakeIntVar(1, kBase - 1, "F");
        IntVar u = solver.MakeIntVar(0, kBase - 1, "U");
        IntVar n = solver.MakeIntVar(0, kBase - 1, "N");
        IntVar t = solver.MakeIntVar(1, kBase - 1, "T");
        IntVar r = solver.MakeIntVar(0, kBase - 1, "R");
        IntVar e = solver.MakeIntVar(0, kBase - 1, "E");

        // We need to group variables in a vector to be able to use
        // the global constraint AllDifferent
        IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e };

        // Check if we have enough digits
        if (kBase < letters.Length)
        {
            throw new Exception("kBase < letters.Length");
        }

        //  Constraints
        solver.Add(letters.AllDifferent());

        // CP + IS + FUN = TRUE
        solver.Add(p + s + n + kBase * (c + i + u) + kBase * kBase * f ==
                   e + kBase * u + kBase * kBase * r + kBase * kBase * kBase * t);

        SolutionCollector all_solutions = solver.MakeAllSolutionCollector();

        //  Add the interesting variables to the SolutionCollector
        all_solutions.Add(letters);

        //  Decision Builder: hot to scour the search tree
        DecisionBuilder db = solver.MakePhase(letters,
                                              Solver.CHOOSE_FIRST_UNBOUND,
                                              Solver.ASSIGN_MIN_VALUE);

        // Add some time limit
        SearchLimit time_limit = solver.MakeTimeLimit(time_limit_param);

        solver.Solve(db, all_solutions, time_limit);

        //  Retrieve the solutions
        int numberSolutions = all_solutions.SolutionCount();

        Console.WriteLine("Number of solutions: " + numberSolutions);

        if (print)
        {
            for (int index = 0; index < numberSolutions; ++index)
            {
                Console.Write("C=" + all_solutions.Value(index, c));
                Console.Write(" P=" + all_solutions.Value(index, p));
                Console.Write(" I=" + all_solutions.Value(index, i));
                Console.Write(" S=" + all_solutions.Value(index, s));
                Console.Write(" F=" + all_solutions.Value(index, f));
                Console.Write(" U=" + all_solutions.Value(index, u));
                Console.Write(" N=" + all_solutions.Value(index, n));
                Console.Write(" T=" + all_solutions.Value(index, t));
                Console.Write(" R=" + all_solutions.Value(index, r));
                Console.Write(" E=" + all_solutions.Value(index, e));
                Console.WriteLine();
            }
        }

        // Save profile in file
        solver.ExportProfilingOverview("profile.txt");
    }
Beispiel #28
0
 public IAsyncEnumerable <Result <PasswordSolution> > GetResults(
     CancellationTokenSource token,
     SolverParameters parameters) =>
 SolverService.GetPasswordSolution(token, password, parameters);
Beispiel #29
0
 public bool Check(SolverParameters solverParams)
 {
     return(solverParams.FakePuzzleCount == FakePuzzleCount &&
            solverParams.RealPuzzleCount == RealPuzzleCount);
 }
Beispiel #30
0
 public IAsyncEnumerable <Result <EightQueensSolution> > GetResults(
     CancellationTokenSource token,
     SolverParameters parameters) =>
 SolverService.GetEightQueensSolution(token, numQueens, parameters);
Beispiel #31
0
 public static extern void GetSolverParameters(IntPtr solver, ref SolverParameters parameters);
Beispiel #32
0
 public static extern void GetSolverParameters(IntPtr solver, [MarshalAs(UnmanagedType.Struct)] ref SolverParameters parameters);