Exemplo n.º 1
0
        public void PMXTest2()
        {
            int populationSize = 120;

            file = root + "\\bays29.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection(5);
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver    solver   = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            List <Candidate> listCand = new List <Candidate>();
            List <int>       GenX     = new List <int>()
            {
                5, 20, 28, 18, 14, 2, 27, 25, 8, 4, 19, 13, 12, 17, 11, 15, 16, 9, 3, 10, 22, 21, 1, 7, 24, 6, 23, 26
            };
            List <int> GenY = new List <int>()
            {
                28, 19, 11, 27, 3, 18, 17, 14, 10, 23, 8, 12, 6, 2, 22, 7, 25, 20, 4, 1, 26, 9, 5, 15, 24, 21, 16, 13
            };
            Candidate parentX = new Candidate(1, GenX, solver, solver.time.ElapsedMilliseconds.ToString());
            Candidate parentY = new Candidate(1, GenY, solver, solver.time.ElapsedMilliseconds.ToString());

            listCand.Add(parentX);
            listCand.Add(parentY);
            crossover.CrossoverPopulation(listCand, 10);
        }
        public void TransportMutationTest1()
        {
            int populationSize = 2000;

            file = root + "\\bays29.xml";
            XDocument             tspFile    = XDocument.Load(file);
            AdjacencyMatrix       testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover          crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection   selector   = new TournamentSelection((int)populationSize / 2);
            TranspositionMutation mutation   = new TranspositionMutation((float)1);

            GeneticSolver solver = new GeneticSolver(testMatrix, mutation, crossover, selector, populationSize, 10);

            List <Candidate> listCand = solver.randomPopulation();

            Candidate parentX = listCand[0];
            Candidate parentY = listCand[1];

            parentX.chromoson = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            parentY.chromoson = new List <int>()
            {
                5, 3, 6, 7, 8, 1, 2, 9, 4,
            };


            mutation.Mutate(parentX);
        }
Exemplo n.º 3
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            Clear();

            int pop_size_factor = Int32.Parse(cmbPopulationSize.Items[cmbPopulationSize.SelectedIndex].ToString());

            CrossoverType crossover_type = CrossoverType.OnePointCrossover;

            switch (cmbCrossoverType.SelectedIndex)
            {
            case 0: crossover_type = CrossoverType.OnePointCrossover; break;

            case 1: crossover_type = CrossoverType.UniformCrossover; break;

            case 2: crossover_type = CrossoverType.PMX; break;
            }

            double elitism_rate = Double.Parse(cmbElitismRate.SelectedItem.ToString());

            gs = new GeneticSolver(1024 * pop_size_factor, 1000, elitism_rate / 10, 0.01, crossover_type);
            gs.GeneratorFunction   = PhraseGenerator;
            gs.FitnessFunction     = CalculateFitness;
            gs.IterationCompleted += Gs_IterationCompleted;
            gs.SolutionFound      += Gs_SolutionFound;

            gs.Evolve();
        }
Exemplo n.º 4
0
        public void OXTest1()
        {
            int populationSize = 120;

            file = root + "\\bays29.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            OXCrossover         crossover  = new OXCrossover((float)(1));
            TournamentSelection selector   = new TournamentSelection(5);
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver    solver   = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            List <Candidate> listCand = solver.randomPopulation();
            Candidate        parentX  = listCand[0];
            Candidate        parentY  = listCand[1];

            parentX.chromoson = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            parentY.chromoson = new List <int>()
            {
                5, 3, 6, 7, 8, 1, 2, 9, 4,
            };



            crossover.Crossover(parentX, parentY);
        }
Exemplo n.º 5
0
        public void SimpleTest()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9000, 100, new List <Item>
            {
                new Item(18, 114, 0), new Item(42, 136, 1), new Item(88, 192, 2), new Item(3, 223, 3)
            });

            IKnapsackSolver solver = new BruteForceSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(473, solve);

            IKnapsackSolver solver2 = new BranchAndBoundSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(473, solve2);

            IKnapsackSolver solver4 = new GeneticSolver(100, 100, new RouletteWheelSelection(), 0.01, 0.8, 0, false, false);

            solver4.Solve(problem);

            IKnapsackSolver solver5 = new FPTASSolver(0.9);

            solver5.Solve(problem);
        }
Exemplo n.º 6
0
 public Candidate(int generation, List <int> genotype, GeneticSolver solver, string time)
 {
     this.time       = time;
     this.generation = generation;
     this.solver     = solver;
     chromoson       = genotype;
     CountFitness();
 }
Exemplo n.º 7
0
 public Candidate(Candidate cand)
 {
     this.time       = cand.time;
     this.generation = cand.generation;
     this.solver     = cand.solver;
     this.chromoson  = new List <int>(cand.chromoson);
     this.CountFitness();
 }
Exemplo n.º 8
0
        public void algo_genetique_test()
        {
            FlightDatabase db = new FlightDatabase(GetFlightDataPath());
            Meeting        m  = new Meeting(5023, db);

            GeneticSolver solver = new GeneticSolver(m, true, 0.4, 150);

            solver.Solve((bestSolution, population) => bestSolution != null && bestSolution.Cost < 100, 1000, 100);
        }
Exemplo n.º 9
0
        public void run_szenario(int times, String sz, String s)
        {
            int render_every = 5120; //model evaluations

            //n mal laufen lassen für empirische Auswertung
            //(bei den direkten Heuristiken (greedy,insertion,savings nicht nötig, daher n = 1)
            for (int i = 0; i < times; i++)
            {
                //solange ein Prozess läuft mache nichts!
                while (optimizer_running)
                {
                    Thread.Sleep(5000);
                }

                String problemInstance = File.ReadAllText(sz + ".json");
                model = new MEPModel.MEP();
                model.LoadModelString(problemInstance);
                scenario = sz + "_" + s + "_" + i;
                Console.WriteLine("Starting Szenario:" + scenario);
                //setze Kontext
                model.AllowTripContinuation     = true;
                model.PermutateOptions          = false;
                model.AllowUnprofitableRequests = true;
                model.AvgTravelSpeed            = 400;
                model.HotelCostPerNight         = -100;
                model.HourlyWage          = -60;
                model.MilageAllowance     = -0.1;
                model.RevenuePerDayOnsite = 2000;

                Solver.Solver so = null;
                switch (s)
                {
                case "Greedy":
                    so = new GreedySolver(model);
                    break;

                case "SA":
                    so = new SimulatedAnnealingSolver(model, 10000, 1600, render_every, 64);    //somit maximal 10.000*16 = 160.000 modell evaluationen!
                    break;

                case "GA":
                    so = new GeneticSolver(model, 19, 5120, 5, render_every);     //somit maximal 100 * 1.600 = 160.000 modell evaluationen!
                    break;

                case "Insertion":
                    so = new NearestInsertionSolver(model);
                    break;

                case "Savings":
                    so = new SavingsSolver(model);
                    break;
                }
                start = DateTime.Now;
                Start_Optimizer(so);
            }
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            var g = new GeneticSolver(1024 * 8, 1000, 0.1, 0.1, CrossoverType.UniformCrossover);

            g.GeneratorFunction   = PhraseGenerator;
            g.FitnessFunction     = CalculateFitness;
            g.IterationCompleted += G_IterationCompleted;
            g.SolutionFound      += G_SolutionFound;
            g.Evolve();
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            var g = new GeneticSolver();

            g.GeneratorFunction   = VariablesGenerator;
            g.FitnessFunction     = CalculateFitness;
            g.IterationCompleted += G_IterationCompleted;
            g.SolutionFound      += G_SolutionFound;
            g.Evolve();
        }
Exemplo n.º 12
0
        private void btnRunAsync_Click(object sender, RoutedEventArgs e)
        {
            output_to_file = false;
            tokensource    = new CancellationTokenSource();
            if (model != null && model.Requests.Count > 0)
            {
                btnRunAsync.IsEnabled = false;
                set_model_parameter();
                //clear optimizer Output:
                txtOptimizerOutput.Text = "";

                Solver.Solver s = null;
                if (rbGeneticAlgorithm.IsChecked == true)
                {
                    s = new GeneticSolver(model, Convert.ToInt32(txtGenerations.Text), Convert.ToInt32(txtPopulationSize.Text), Convert.ToInt32(txtMutationProbability.Text), Convert.ToInt32(txtReportProgress.Text));
                }
                if (rbBruteForce.IsChecked == true)
                {
                    if (model.GetNumberOfElements() > 11)
                    {
                        MessageBox.Show("I´m sorry Dave, I`m afraid I can`t do that!");
                    }
                    else
                    {
                        s = new BruteForceSolver(model);
                    }
                }
                if (rbSimulatedAnnealing.IsChecked == true)
                {
                    s = new SimulatedAnnealingSolver(model, Convert.ToInt32(txtStartTemp.Text), Convert.ToInt32(txtSteps.Text), Convert.ToInt32(txtReportProgress.Text), Convert.ToInt32(txtParallelAnnealings.Text));
                }
                if (rbGreedy.IsChecked == true)
                {
                    s = new GreedySolver(model);
                }
                if (rbInsertion.IsChecked == true)
                {
                    s = new NearestInsertionSolver(model);
                }
                if (rbSavings.IsChecked == true)
                {
                    s = new SavingsSolver(model);
                }

                if (s != null)
                {
                    Start_Optimizer(s);
                }
            }
        }
Exemplo n.º 13
0
        public IPredictionResult Predict <TDistribution>(IHiddenMarkovModel <TDistribution> model, IPredictionRequest request) where TDistribution : IDistribution
        {
            var selectionMethod    = new TournamentSelection(TournamentSize);
            var crossoverAlgorithm = new Crossover(CrossoverProbability);
            var mutationAlgorithm  = new Mutator(MutationProbability);
            var evaluator          = new HmmEvaluator <TDistribution>(model, new ForwardBackward(true));

            var parameters = new GeneticSolverParameters
            {
                CrossOverProbability = CrossoverProbability,
                MutationProbability  = MutationProbability,
                NumberOfGenerations  = NumberOfGenerations,
                PopulationSize       = request.NumberOfDays * 10,
                TournamentSize       = TournamentSize
            };
            var predictions = new PredictionResult {
                Predicted = new double[request.NumberOfDays][]
            };

            var solver = new GeneticSolver(parameters, mutationAlgorithm, crossoverAlgorithm, evaluator, selectionMethod);
            var populationInitializer = new FromTimeSeriesRandomInitializer(request.TrainingSet);
            var population            = populationInitializer.Initialize <decimal>(parameters.PopulationSize, request.NumberOfDays, MutationProbability);

            for (int i = 0; i < population.Count; i++)
            {
                var chromosome = population[i];
                population[i].FintnessValue = evaluator.Evaluate(chromosome);
            }

            var result = solver.Solve(population);
            // Get best fitted chromosome
            var maximumFitness = result[0].FintnessValue;
            var solution       = result[0];

            foreach (var chromosome in result)
            {
                if (maximumFitness <= chromosome.FintnessValue)
                {
                    solution       = chromosome;
                    maximumFitness = chromosome.FintnessValue;
                }
            }
            // Convert it to array
            for (int i = 0; i < solution.Representation.Length; i++)
            {
                predictions.Predicted[i] = Array.ConvertAll(solution.Representation[i].Representation, x => (double)Convert.ChangeType(x, typeof(double)));
            }

            return(predictions);
        }
        public void TournamentTest1()
        {
            int populationSize = 120;

            file = root + "\\bays29.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection(10);
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver solver = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            //  listCand = selector.generateBreedingPool(listCand);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        public ProjectFourViewModel()
        {
            Cities       = new List <City>();
            PlotInfo     = new PlotModel();
            ChangeInfo   = new PlotModel();
            CitySeries   = new ScatterSeries();
            PathSeries   = new LineSeries();
            ChangeSeries = new LineSeries();
            PlotInfo.Series.Add(PathSeries);
            PlotInfo.Series.Add(CitySeries);
            ChangeInfo.Series.Add(ChangeSeries);

            GSolver              = new GeneticSolver();
            GSolver.NewBestTrip += OnNewBestTrip;
            GSolver.DataCleared += OnDataCleared;
        }
        private GeneticSolver getSolver()
        {
            int populationSize = 3000;

            file = root + "\\rbg403.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection((int)(5));
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver solver = new GeneticSolver(
                testMatrix, inv, crossover, selector, populationSize, 60);

            return(solver);
        }
        public void RouletteTests1()
        {
            int populationSize = 1000;

            file = root + "\\bays29.xml";
            XDocument         tspFile    = XDocument.Load(file);
            AdjacencyMatrix   testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover      crossover  = new PMXCrossover((float)(0.80));
            RouletteSelection selector   = new RouletteSelection(100);
            InversionMutation inv        = new InversionMutation((float)0.05);

            GeneticSolver    solver   = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            List <Candidate> listCand = solver.randomPopulation();

            listCand = selector.generateBreedingPool(listCand);
        }
Exemplo n.º 18
0
        public Result(GeneticSolver solver)
        {
            mutationName    = solver.mutation.MutationName;
            selectionName   = solver.selector.SelectionName;
            crossoverName   = solver.crossover.CrossoverName;
            mutationChance  = solver.mutation.mutationChance;
            tspFileName     = solver.matrix.tspFileName;
            overCrossChance = solver.crossover.CrossoverChance;
            time            = solver.time.ElapsedMilliseconds.ToString();
            populationSize  = solver.maxPopulationSize;
            selectionSize   = solver.selector.selectionSize;
            measureName     = tspFileName + "Size" + populationSize + mutationName + mutationChance + selectionName + selectionSize + crossoverName + overCrossChance + "TIME" + solver.MaxTime + "s";

            bestResult  = solver.bestCandidate;
            results     = solver.results;
            TimeResults = solver.bestPerTwoMinutes;
        }
        public void solverTest()
        {
            int populationSize = 3000;

            file = root + "\\rbg403.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection((int)(5));
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver solver = new GeneticSolver(
                testMatrix, inv, crossover, selector, populationSize, 480);
            var result = solver.Solve();

            result.resultToXML();
            result.ToFile();
        }
Exemplo n.º 20
0
        // Use this for initialization
        private void Start()
        {
            m_GeneticSolver = FindObjectOfType <GeneticSolver>();

            if (m_GeneticSolver == null)
            {
                gameObject.SetActive(false);
            }

            m_Dropdown = GetComponent <Dropdown>();

            m_Dropdown.ClearOptions();
            m_Dropdown.AddOptions(Enum.GetNames(typeof(GeneticSolver.PopulationGenerationType)).ToList());

            m_Dropdown.value = (int)m_GeneticSolver.populationGenerationType;

            m_Dropdown.onValueChanged.AddListener(OnDropdownValueChanged);
        }
Exemplo n.º 21
0
        public void Solve_PopulationSizeZero_ZeroSizePopulationReturned()
        {
            var selectionMethod    = new TournamentSelection(TournamentSize);
            var crossoverAlgorithm = new Crossover(CrossoverProbability);
            var mutationAlgorithm  = new Mutator(MutationProbability);

            var model = (HiddenMarkovModelMixtureDistribution)HiddenMarkovModelFactory.GetModel(new ModelCreationParameters <Mixture <IMultivariateDistribution> > {
                Pi = new double[3], TransitionProbabilityMatrix = new double[3][], Emissions = new Mixture <IMultivariateDistribution> [3]
            });
            var evaluator = new HmmEvaluator <Mixture <IMultivariateDistribution> >(model, new ForwardBackward(true));

            var parameters = new GeneticSolverParameters();

            var solver = new GeneticSolver(parameters, mutationAlgorithm, crossoverAlgorithm, evaluator, selectionMethod);

            var result = solver.Solve(new List <IChromosome <decimal> >());

            Assert.AreEqual(result.Count, 0);
        }
Exemplo n.º 22
0
        public void GeneticSolver_AllDependencies_SolverCreatedWithAllDependecnies()
        {
            var selectionMethod    = new TournamentSelection(TournamentSize);
            var crossoverAlgorithm = new Crossover(CrossoverProbability);
            var mutationAlgorithm  = new Mutator(MutationProbability);

            var model = (HiddenMarkovModelMixtureDistribution)HiddenMarkovModelFactory.GetModel(new ModelCreationParameters <Mixture <IMultivariateDistribution> > {
                Pi = new double[3], TransitionProbabilityMatrix = new double[3][], Emissions = new Mixture <IMultivariateDistribution> [3]
            });
            var evaluator = new HmmEvaluator <Mixture <IMultivariateDistribution> >(model, new ForwardBackward(true));

            var parameters = new GeneticSolverParameters();

            var solver = new GeneticSolver(parameters, mutationAlgorithm, crossoverAlgorithm, evaluator, selectionMethod);

            Assert.IsNotNull(solver.MutationAlgorithm);
            Assert.IsNotNull(solver.CrossoverAlgorithm);
            Assert.IsNotNull(solver.EvaluationMethod);
            Assert.IsNotNull(solver.SelectionMethod);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            int[] initial_grid = new int[] { 0, 6, 0, 0, 5, 0, 0, 2, 0,

                                             0, 0, 0, 3, 0, 0, 0, 9, 0,

                                             7, 0, 0, 6, 0, 0, 0, 1, 0,

                                             0, 0, 6, 0, 3, 0, 4, 0, 0,

                                             0, 0, 4, 0, 7, 0, 1, 0, 0,

                                             0, 0, 5, 0, 9, 0, 8, 0, 0,

                                             0, 4, 0, 0, 0, 1, 0, 0, 6,

                                             0, 3, 0, 0, 0, 8, 0, 0, 0,

                                             0, 2, 0, 0, 4, 0, 0, 5, 0 };


            Noyau.Sudoku s   = new Noyau.Sudoku(initial_grid);
            Noyau.Sudoku s_1 = new Noyau.Sudoku();
            Noyau.Sudoku s_2 = new Noyau.Sudoku();

            Console.WriteLine(s.ToString());
            GeneticSolver gs = new GeneticSolver();

            s_1 = gs.Solve(s);
            OrToolsSolver ots = new OrToolsSolver();

            s_2 = ots.Solve(s);

            Console.WriteLine("Genetic Solver");
            Console.WriteLine(s_1.ToString());

            Console.WriteLine("ORToolsSolver");
            Console.WriteLine(s_2.ToString());

            Console.ReadLine();
        }
Exemplo n.º 24
0
        public void Solve_InitialPopulationFromTimeSeriesAndTrainedHmmEvaluator_SolvedPopulation()
        {
            var util   = new TestDataUtils();
            var series = util.GetSvcData(util.GOOGFilePath, new DateTime(2010, 12, 18), new DateTime(2011, 12, 18));
            var test   = util.GetSvcData(util.GOOGFilePath, new DateTime(2011, 12, 18), new DateTime(2012, 01, 18));
            var model  = (HiddenMarkovModelMixtureDistribution)HiddenMarkovModelFactory.GetModel(new ModelCreationParameters <Mixture <IMultivariateDistribution> >()
            {
                NumberOfComponents = NumberOfComponents, NumberOfStates = NumberOfStates
            });

            model.Normalized = true;
            model.Train(series, NumberOfIterations, LikelihoodTolerance);

            var selectionMethod    = new TournamentSelection(TournamentSize);
            var crossoverAlgorithm = new Crossover(CrossoverProbability);
            var mutationAlgorithm  = new Mutator(MutationProbability);

            var evaluator = new HmmEvaluator <Mixture <IMultivariateDistribution> >(model, new ForwardBackward(true));

            var parameters = new GeneticSolverParameters
            {
                CrossOverProbability = CrossoverProbability,
                MutationProbability  = MutationProbability,
                NumberOfGenerations  = 10,
                PopulationSize       = PopulationSize,
                TournamentSize       = TournamentSize
            };
            var populationInitializer = new FromTimeSeriesRandomInitializer(series);
            var population            = populationInitializer.Initialize <decimal>(parameters.PopulationSize, test.Length, MutationProbability);

            for (int i = 0; i < population.Count; i++)
            {
                var chromosome = population[i];
                population[i].FintnessValue = evaluator.Evaluate(chromosome);
            }
            var solver = new GeneticSolver(parameters, mutationAlgorithm, crossoverAlgorithm, evaluator, selectionMethod);

            var result = solver.Solve(population);

            Assert.AreEqual(result.Count, parameters.PopulationSize);
        }
Exemplo n.º 25
0
        private void btnEvolve_Click(object sender, EventArgs e)
        {
            Clear();

            int pop_size_factor = 8;
            int elitism_rate    = 2;
            var crossover_type  = CrossoverType.OnePointCrossover;

            queen_positions = new List <Point>();

            gs = new GeneticSolver(1024 * pop_size_factor, 1000, elitism_rate / 10, 0.01, crossover_type)
            {
                GeneratorFunction = SolutionGenerator,
                FitnessFunction   = CalculateFitness
            };

            gs.IterationCompleted += Gs_IterationCompleted;
            gs.SolutionFound      += Gs_SolutionFound;

            gs.Evolve();
        }
        public void RunSolution()
        {
            if (isMultiThreadChecked)
            {
                solverMultiThread = createNewSolver(true);
                listTask.Add(solverMultiThread);
            }

            if (isSigleThreadChecked)
            {
                solverSingleThread = createNewSolver(false);
                listTask.Add(solverSingleThread);
            }
            var tasks = new List <Task <Result> >();

            foreach (var solver in listTask)
            {
                tasks.Add(Task.Factory.StartNew <Result>(() => solver.Solve()));
            }
            View.solvers = listTask.ToArray();
            View.RunChart();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Processes a TSP and reports errors.
        /// </summary>
        /// <param name="file">File name of TSP being processed.</param>
        private void ProcessTsp(string file)
        {
            System.Diagnostics.Debug.WriteLine($"Loading TSP at path {file} ...\n");

            // Try convert text to TSP
            var success = Interface.TryTextToTsp(file, out var tsp);

            // If conversion was a success
            if (success)
            {
                // Print TSP info to debug console
                tsp.Print();

                // Update name of problem on graph
                this.problemName.Text = tsp.Name;

                // Create solver and event handlers
                Solver solver = null;
                ProgressChangedEventHandler    updateHandler     = null;
                RunWorkerCompletedEventHandler completionHandler = null;
                int drawDelay = 0;

                // Set solvers and event handlers based on the chosen setting
                if (bruteForceRadioButton.IsChecked == true)
                {
                    solver = new BruteForceSolver();

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (bfsRadioButton.IsChecked == true || dfsRadioButton.IsChecked == true)
                {
                    var goal = Convert.ToInt32(searchGoal.Text);

                    if (bfsRadioButton.IsChecked == true)
                    {
                        solver = new BfsSolver();
                    }
                    else
                    {
                        solver = new DfsSolver();
                    }

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (greedyRadioButton.IsChecked == true)
                {
                    solver            = new GreedySolver();
                    updateHandler     = GreedyProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else if (geneticRadioButton.IsChecked == true)
                {
                    solver            = new GeneticSolver();
                    updateHandler     = GeneticProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else
                {
                    MessageBox.Show("No solution method was selected.");
                    return;
                }

                if (progressCheckBox.IsChecked == true)
                {
                    // Update continously
                    solver.ProgressChanged += updateHandler;
                }
                else
                {
                    // Update only at the end
                    solver.RunWorkerCompleted += completionHandler;
                }

                var workerArgs = new Tuple <Tsp, int>(tsp, progressCheckBox.IsChecked == true ? drawDelay : 0);

                // Run solver and draw output
                solver.RunWorkerAsync(workerArgs);
            }
            // If conversion failed
            else
            {
                MessageBox.Show($"Could not convert TSP from text file: \n\n{file}");
            }
        }
        public void StopTest()
        {
            GeneticSolver solver = new GeneticSolver();

            solver.Solve();
        }
        internal GeneticSolver createNewSolver(bool isMultiThread)
        {
            MutationType    mutation  = null;
            CrossoverType   crossover = null;
            SelectionType   selection = null;
            GeneticSolver   solver    = null;//add parameters TO DO
            AdjacencyMatrix matrix    = new AdjacencyMatrix(tspXmlFile);

            switch (mutationIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    mutation = new InversionMutation(mutationChance);
                }
                else
                {
                    mutation = new MultiThreadInversionMutation(mutationChance);
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    mutation = new TranspositionMutation(mutationChance);
                }
                else
                {
                    mutation = new MultiThreadTranspositionMutation(mutationChance);
                }
                break;
            }
            }

            switch (crossoverIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    crossover = new PMXCrossover(crossoverChance);
                }
                else
                {
                    crossover = new MultiThreadPMXCrossover(crossoverChance);          //new PMXCrossover(crossoverChance); //
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    crossover = new OXCrossover(crossoverChance);
                }
                else
                {
                    crossover = new MultiThreadOXCrossover(crossoverChance);
                }
                break;
            }
            }

            switch (selectorIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    selection = new TournamentSelection(selectorSize);
                }
                else
                {
                    selection = new MultiThreadTournamentSelection(selectorSize);
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    selection = new RouletteSelection(selectorSize);
                }
                else
                {
                    selection = new MultiThreadRouletteSelection(selectorSize);
                }
                break;
            }
            }

            if (mutation != null && selection != null && crossover != null)
            {
                if (isMultiThread)
                {
                    MultiTaskOptions.parallelOptCrossover.MaxDegreeOfParallelism = int.Parse(View.tbxLvlCrossover.Text);
                    MultiTaskOptions.parallelOptMutation.MaxDegreeOfParallelism  = int.Parse(View.tbxLvlMutation.Text);
                    MultiTaskOptions.parallelOptSelection.MaxDegreeOfParallelism = int.Parse(View.tbxLvlSelector.Text);
                    solver = new MultiTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS);
                }
                else
                {
                    solver = new SingleTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS);
                }
            }
            return(solver);
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            decimal   frequency = Stopwatch.Frequency;

            if (CommandLine.Parser.Default.ParseArguments(args, Options))
            {
                TextWriter reportWriter = Options.OutputFilePath == null ? Console.Out : new StreamWriter(Options.OutputFilePath);

                VerboseLog("Data parsing ...");

                DataParser parser = new DataParser();
                List <KnapsackProblemModel>          knapsackProblemModels        = parser.ParseProblem(Options.InputFiles);
                Dictionary <int, int>                knownResults                 = null;
                Dictionary <int, Tuple <int, long> > bruteForceResults            = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > costToRatioHeuristicsResults = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > branchAndBoundResults        = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > dynamicByCostResults         = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > fptasResults                 = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > geneticResults               = new Dictionary <int, Tuple <int, long> >();

                if (Options.ResultFiles != null)
                {
                    knownResults = parser.ParseResults(Options.ResultFiles);
                }

                VerboseLog("Done.");

                IKnapsackSolver bruteForceSolver     = new BruteForceSolver();
                IKnapsackSolver ratioHeuristicSolver = new RatioHeuristicSolver();
                IKnapsackSolver branchAndBoundSolver = new BranchAndBoundSolver();
                IKnapsackSolver dynamicByCostSolve   = new DynamicByCostSolver();
                IKnapsackSolver fptasSolver          = null;
                IKnapsackSolver geneticSolver        = null;

                if (Options.FPTAS)
                {
                    fptasSolver = new FPTASSolver(Options.FPTASAccuracy);
                }
                if (Options.Genetics)
                {
                    ISelectionMethod selectionMethod = null;
                    switch (Options.SelectionMethod)
                    {
                    case "roulette": selectionMethod = new RouletteWheelSelection();
                        break;

                    case "rank": selectionMethod = new RankSelection();
                        break;

                    case "elitary": selectionMethod = new EliteSelection();
                        break;

                    default: Console.WriteLine("Wrong selection method for genetics");
                        break;
                    }

                    if (selectionMethod == null)
                    {
                        return;
                    }


                    if (Options.GeneticMetaoptimization)
                    {
                        //Random selection portion
                        for (int i = 0; i < 100; i++)
                        {
                            double randomSelectionPortion = (i * 0.001) + 0;
                            //Crossover rate
                            for (int j = 0; j < 1; j++)
                            {
                                double crossoverRate = (j * 0.03) + 0.22;
                                //Mutation rate
                                for (int k = 0; k < 1; k++)
                                {
                                    double mutationRate = (k * 0.04) + 0.87;

                                    geneticSolver = new GeneticSolver(Options.PopulationSize, Options.IterationsCount, selectionMethod, mutationRate, crossoverRate, randomSelectionPortion, false, false);
                                    geneticResults.Clear();
                                    foreach (KnapsackProblemModel problem in knapsackProblemModels)
                                    {
                                        int result = 0;
                                        try
                                        {
                                            stopwatch.Restart();
                                            result = geneticSolver.Solve(problem);
                                            stopwatch.Stop();
                                        }
                                        catch (Exception ex)
                                        {
                                        }

                                        geneticResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                                    }

                                    decimal totalTime  = 0;
                                    decimal totalError = 0;

                                    foreach (KnapsackProblemModel problem in knapsackProblemModels)
                                    {
                                        int problemId            = problem.ProblemId;
                                        Tuple <int, long> result = geneticResults[problemId];
                                        totalTime  += (result.Item2 / frequency);
                                        totalError += CalculateRelativeError(knownResults[problemId], result.Item1);
                                    }

                                    decimal averageError = totalError / knapsackProblemModels.Count;

                                    reportWriter.WriteLine(randomSelectionPortion + "," + crossoverRate + "," + mutationRate + "," + totalTime + "," + averageError);
                                }
                            }
                        }
                    }

                    geneticSolver = new GeneticSolver(Options.PopulationSize, Options.IterationsCount, selectionMethod, Options.MutationRate, Options.CrossoverRate, Options.RandomSelectionPortion, Options.DiversityCheck, true);
                }

                VerboseLog("Solving JIT instance");
                KnapsackProblemModel jitProblem = new KnapsackProblemModel(-1, 100, new List <Item>
                {
                    new Item(18, 114, 0), new Item(42, 136, 1), new Item(88, 192, 2), new Item(3, 223, 3)
                });

                bruteForceSolver.Solve(jitProblem);
                ratioHeuristicSolver.Solve(jitProblem);
                branchAndBoundSolver.Solve(jitProblem);
                dynamicByCostSolve.Solve(jitProblem);

                if (fptasSolver != null)
                {
                    fptasSolver.Solve(jitProblem);
                }

                if (geneticSolver != null)
                {
                    geneticSolver.Solve(jitProblem);
                }

                VerboseLog("Calculation started");



                foreach (KnapsackProblemModel problem in knapsackProblemModels)
                {
                    VerboseLog("Solving problem:");
                    VerboseLog(problem);

                    int knownResult = -1;
                    if (knownResults != null)
                    {
                        knownResult = knownResults[problem.ProblemId];
                        VerboseLog("Result should be: " + knownResult);
                    }

                    if (Options.BruteForce)
                    {
                        VerboseLog("Brute force solver ...");

                        stopwatch.Restart();
                        int result = bruteForceSolver.Solve(problem);
                        stopwatch.Stop();

                        bruteForceResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));

                        if (knownResult != -1 && result != knownResult)
                        {
                            Console.WriteLine("ERROR - Brute force algorithm not accurate for problem " + problem);
                            Environment.Exit(1);
                        }
                    }

                    if (Options.BranchAndBound)
                    {
                        VerboseLog("Branch and bound solver ...");

                        stopwatch.Restart();
                        int result = branchAndBoundSolver.Solve(problem);
                        stopwatch.Stop();

                        branchAndBoundResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));

                        if (knownResult != -1 && result != knownResult)
                        {
                            Console.WriteLine("ERROR - Branch and bound algorithm not accurate for problem " + problem);
                            Environment.Exit(1);
                        }
                    }

                    if (Options.DynamicByCost)
                    {
                        VerboseLog("Dynamic by cost solver ...");

                        stopwatch.Restart();
                        int result = dynamicByCostSolve.Solve(problem);
                        stopwatch.Stop();

                        dynamicByCostResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));

                        if (knownResult != -1 && result != knownResult)
                        {
                            Console.WriteLine("ERROR - Dynamic by cost algorithm not accurate for problem " + problem);
                            Environment.Exit(1);
                        }
                    }

                    if (Options.CostToRatioHeuristics)
                    {
                        VerboseLog("Ratio heuristics solver ...");

                        stopwatch.Restart();
                        int result = ratioHeuristicSolver.Solve(problem);
                        stopwatch.Stop();

                        costToRatioHeuristicsResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                    }

                    if (Options.FPTAS)
                    {
                        VerboseLog("FPTAS solver ...");

                        if (fptasSolver != null)
                        {
                            stopwatch.Restart();
                            int result = fptasSolver.Solve(problem);
                            stopwatch.Stop();

                            fptasResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                        }
                    }

                    if (Options.Genetics)
                    {
                        VerboseLog("Genetics solver ...");

                        if (geneticSolver != null)
                        {
                            stopwatch.Restart();
                            int result = geneticSolver.Solve(problem);
                            stopwatch.Stop();

                            geneticResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                        }
                    }

                    VerboseLog("Problem solved.");
                }

                reportWriter.Write("Problem ID;Items count");
                if (knownResults != null)
                {
                    reportWriter.Write(";Known result");
                }
                if (Options.BruteForce)
                {
                    reportWriter.Write(";Brute force result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.CostToRatioHeuristics)
                {
                    reportWriter.Write(";Cost to weight ration heuristics result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.BranchAndBound)
                {
                    reportWriter.Write(";Branch and bound result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.DynamicByCost)
                {
                    reportWriter.Write(";Dynamic programming by cost result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.FPTAS)
                {
                    reportWriter.Write(";FPTAS result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error;Max possible error");
                    }
                }
                if (Options.Genetics)
                {
                    reportWriter.Write(";Genetics result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                reportWriter.WriteLine();

                foreach (KnapsackProblemModel problem in knapsackProblemModels)
                {
                    var problemId = problem.ProblemId;
                    reportWriter.Write(problemId);
                    reportWriter.Write(";" + problem.Items.Count);
                    if (knownResults != null)
                    {
                        reportWriter.Write(";" + knownResults[problemId]);
                    }
                    if (Options.BruteForce)
                    {
                        Tuple <int, long> bruteForceResult = bruteForceResults[problemId];
                        reportWriter.Write(";" + bruteForceResult.Item1 + ";" + bruteForceResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], bruteForceResult.Item1));
                        }
                    }
                    if (Options.CostToRatioHeuristics)
                    {
                        Tuple <int, long> heuristicsResult = costToRatioHeuristicsResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    if (Options.BranchAndBound)
                    {
                        Tuple <int, long> heuristicsResult = branchAndBoundResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    if (Options.DynamicByCost)
                    {
                        Tuple <int, long> heuristicsResult = dynamicByCostResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    if (Options.FPTAS)
                    {
                        Tuple <int, long> heuristicsResult = fptasResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                            reportWriter.Write(";" + ((FPTASSolver)fptasSolver).GetMaximumError(problem));
                        }
                    }
                    if (Options.Genetics)
                    {
                        Tuple <int, long> heuristicsResult = geneticResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    reportWriter.WriteLine();
                }

                if (Options.Genetics)
                {
                    decimal totalTime  = 0;
                    decimal totalError = 0;

                    foreach (KnapsackProblemModel problem in knapsackProblemModels)
                    {
                        int problemId            = problem.ProblemId;
                        Tuple <int, long> result = geneticResults[problemId];
                        totalTime  += (result.Item2 / frequency);
                        totalError += CalculateRelativeError(knownResults[problemId], result.Item1);
                    }

                    decimal averageError = totalError / knapsackProblemModels.Count;

                    reportWriter.WriteLine("Aggregate results");
                    reportWriter.WriteLine("Aggregate time");
                    reportWriter.WriteLine(totalTime);
                    reportWriter.WriteLine("Average error");
                    reportWriter.WriteLine(averageError);
                }
            }
            else
            {
                Environment.Exit(1);
            }

            Environment.Exit(0);
        }