public async void Execute(object?parameter)
        {
            var vm = parameter as DistanceViewModel;

            List <string>[] Savg;
            List <string>[] Smin;

            if (!Directory.Exists(vm?.DistanceParameters.ResultPath))
            {
                Directory.CreateDirectory(vm.DistanceParameters.ResultPath);
            }

            vm.IsDistanceStartButtonEnabled = false;

            EventHandler <int> BaseGeneticOnOnNextIteration()
            {
                return((_, iteration) =>
                {
                    vm.ProgressBarValue++;
                });
            }

            var runs = vm.Runs;
            var seed = vm.CurrentSeed;

            if (vm.RandomSeed)
            {
                var random = new Random();
                seed           = random.Next(1, Int32.MaxValue);
                vm.CurrentSeed = seed;
            }

            vm.CancellationTokenSource = new CancellationTokenSource();
            var ct         = vm.CancellationTokenSource.Token;
            var parameters = vm.DistanceParameters as OptimizationParameters;

            var crossovers = new CrossoverMethod[4];

            crossovers[0] = CrossoverMethod.Aex;
            crossovers[1] = CrossoverMethod.HProX;
            crossovers[2] = CrossoverMethod.HGreX;
            crossovers[3] = CrossoverMethod.HRndX;

            Application.Current.MainWindow.Cursor = Cursors.Wait;


            await Task.Run(() =>
            {
                Directory.CreateDirectory(vm.DistanceParameters.ResultPath + "\\" + seed.ToString());
                //SerializeParameters(vm.DistanceParameters.ResultPath + "\\" + seed + "/parameters.json");


                Optimization.GeneticAlgorithms.BaseGenetic.OnNextIteration += BaseGeneticOnOnNextIteration();
                var operationType = new List <string>();
                var ren           = -1;

                foreach (var dataset in vm.SelectedFiles)
                {
                    vm.DistanceParameters.DataPath = dataset;
                    var datasetName = dataset.Split('\\')[^ 1]
Exemple #2
0
        public BinPackingGenetics(int problemNum, MutationOperator mutationOperator, CrossoverMethod method, SelectionMethod selectionMethod) : base(method, selectionMethod)
        {
            _mutationOperator = mutationOperator;
            CrosMethod        = method;
            string path = "";

            _volumes = new List <int>();
            switch (problemNum)
            {
            case 1: path = "Falkenauer_u120_00.txt"; break;

            case 2: path = "Falkenauer_u250_00.txt"; break;

            case 3: path = "Falkenauer_u500_00.txt"; break;

            case 4: path = "Falkenauer_u1000_00.txt"; break;
            }
            string[] inputArr = System.IO.File.ReadAllLines(path);

            var lines = inputArr.ToList();

            lines.Remove(lines.First()); // first line is n. no need for it in a list
            _containerCapacity = Int32.Parse(lines.First());
            lines.Remove(lines.First()); //
            foreach (var line in lines)
            {
                var volume = Int32.Parse(line);
                _volumes.Add(volume);
            }
            _lowerBound = (int)Math.Ceiling((decimal)(_volumes.Sum() / _containerCapacity));
            MaxFitness  = (uint)(_volumes.Count - _lowerBound);
            bpa         = new BinPackingAlgorithm(_volumes, _containerCapacity);
            _resultBins = new ObservableCollection <List <int> >();
        }
Exemple #3
0
 public KsProblemGenetics(CrossoverMethod crossMethod, SelectionMethod selectionMethod) : base(crossMethod, selectionMethod)
 {
     _capcities  = new List <short>();
     _weights    = new List <uint>();
     _items      = new List <Item>();
     _constrains = new ObservableCollection <short[]>();
 }
Exemple #4
0
        public List <Hypothesis> CrossoverPopulation(List <Hypothesis> population, double crossoverRate, int childPerPair)
        {
            var newPopulation  = new List <Hypothesis>();
            var popToCrossover = Math.Max(1, population.Count * crossoverRate);
            var totalFitness   = population.Sum(h => h.Fitness);
            var minimumFitness = population.Select(h => h.Fitness).Concat(new[] { 0 }).Min();

            if (minimumFitness < 0)
            {
                totalFitness = population.Sum(h => h.Fitness - minimumFitness);
            }
            for (var j = 0; j < popToCrossover; j++)
            {
                var candidateA = FindCrossOverCandidate(population, totalFitness, -minimumFitness);
                var candidateB = FindCrossOverCandidate(population, totalFitness, -minimumFitness);
                if (candidateA != null && candidateB != null)
                {
                    for (var i = 0; i < childPerPair; i++)
                    {
                        newPopulation.Add(CrossoverMethod.Crossover(candidateA, candidateB));
                    }
                }
            }
            return(newPopulation);
        }
 protected GeneticsAlgorithms(CrossoverMethod crossMethod, SelectionMethod selectionMethod)
 {
     Rand                  = new Random();
     Population            = new List <T>();
     Buffer                = new List <T>();
     CrosMethod            = crossMethod;
     SelectMethod          = selectionMethod;
     BestGensHistory       = new List <GenHistory <T> >(BestGensHistoryTargetSize);
     GaMutationFactor      = 1;
     LocalOptSearchEnabled = true;
 }
Exemple #6
0
 public ChilisExpGenetics(CrossoverMethod crossMethod, SelectionMethod selectionMethod, MutationOperator mutationOperator, int k, int upperBound) : base(crossMethod, selectionMethod)
 {
     Population            = new List <SortingNetGen>();
     Buffer                = new List <SortingNetGen>();
     TcPopulation          = new List <TestCaseGen>();
     TcBuffer              = new List <TestCaseGen>();
     VectorSize            = k;
     GaTcPopSize           = 50;
     UppderBound           = upperBound;
     MutationOpt           = mutationOperator;
     MaxFitnessParasite    = Population.Count;
     LocalOptSearchEnabled = true;
     InitBindaryVectors();
 }
Exemple #7
0
 public ClassicGA(int IterationSize, int PopulationSize,
                  CrossoverMethod crossoverMethod, double CrossoverProbability, int dotCrossover,
                  MutationMethod mutationMethod, double MutationProbability, int dotMutation, SelectionMethod selectionMethod,
                  int CountSelected, int CountTour)
     : base(IterationSize, PopulationSize)
 {
     this.crossoverMethod      = crossoverMethod;
     this.CrossoverProbability = CrossoverProbability;
     this.mutationMethod       = mutationMethod;
     this.MutationProbability  = MutationProbability;
     this.dotCrossover         = dotCrossover;
     this.dotMutation          = dotMutation;
     this.selectionMethod      = selectionMethod;
     this.CountSelected        = CountSelected;
     this.CountTour            = CountTour;
 }
Exemple #8
0
 public GeneticAlgorithm(int genomsInGeneration, int generationCount, double mutProb, FirstGenerationGenerator _fgg, CrossoverMethod _cm,
                         MutationMethod _mm, SelectionMethod _sm, FitnessFunction ff)
 {
     this.genomLength        = ff.GetArity();
     this.genomsInGeneration = genomsInGeneration;
     this.fgg = _fgg;
     this.mutationProbability = mutProb;
     this.generationCount     = generationCount;
     Generation = new List <Path>();
     Child      = new List <Path>();
     Buffer     = new List <Path>();
     solution   = new Path(genomLength);
     FitFunc    = ff;
     this.cm    = _cm;
     this.mm    = _mm;
     this.sm    = _sm;
 }
Exemple #9
0
        public static AbstractCrossover ChosenCrossoverMethod(CrossoverMethod crossoverMethod, double CrossoverProbability, int dots)
        {
            AbstractCrossover crossover = null;

            switch (crossoverMethod)
            {
            case CrossoverMethod.OneDot:
                crossover = new OneDotCrossover(CrossoverProbability);
                break;

            case CrossoverMethod.NDot:
                crossover = new NDotCrossover(dots, CrossoverProbability);
                break;
            }

            return(crossover);
        }
        private void choose_crossover_method()
        {
            Console.WriteLine("Please Choose CrossOver Method :");
            var methodsList = Enum.GetValues(typeof(CrossoverMethod)).Cast <CrossoverMethod>().ToList();

            for (int i = 0; i < methodsList.Count; i++)
            {
                Console.WriteLine((i + 1) + ". " + methodsList[i]);
            }
            int input = 0;

            do
            {
                input = get_input();
            } while (input <= 0 || input > methodsList.Count);
            _crossoverMethod = methodsList[input - 1];
        }
Exemple #11
0
        public List <Hypothesis> CrossoverPopulation(List <Hypothesis> population, double crossoverRate, int childPerPair)
        {
            var newPopulation  = new List <Hypothesis>();
            var popToCrossover = Math.Max(1, population.Count * crossoverRate);

            for (var j = 0; j < popToCrossover; j++)
            {
                var candidateA = FindCrossOverCandidate(population);
                var candidateB = FindCrossOverCandidate(population);
                if (candidateA == null || candidateB == null)
                {
                    continue;
                }
                for (var i = 0; i < childPerPair; i++)
                {
                    newPopulation.Add(CrossoverMethod.Crossover(candidateA, candidateB));
                }
            }
            return(newPopulation);
        }
Exemple #12
0
        public static Crossover CreateCrossover(int startingId, CrossoverMethod crossoverMethod,
                                                CrossoverMethod[] crossoverMethods, ConflictResolver resolverConflict, ConflictResolver resolverRandomized, Random random, bool mutateIfSame)
        {
            Crossover crossover = crossoverMethod switch
            {
                CrossoverMethod.Aex => new AexCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.HGreX => new HGreXCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.HRndX => new HRndXCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.HProX => new HProXCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.KPoint => new KPointCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.Cycle => new CycleCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.Order => new OrderCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.MAC => new MACrossover(crossoverMethods, startingId, resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.MRC => new MRCrossover(crossoverMethods, startingId, resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.PMX => new PMXCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.ERX => new ERXCrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                CrossoverMethod.HGA => new HGACrossover(resolverConflict, resolverRandomized, random, mutateIfSame),
                _ => throw new ArgumentException("Wrong crossover method name")
            };

            return(crossover);
        }
Exemple #13
0
 public BaldwinEffect(CrossoverMethod crossMethod, SelectionMethod selectionMethod) : base(crossMethod, selectionMethod)
 {
     _rand           = new Random();
     _targetWasFound = false;
 }
Exemple #14
0
        /// <summary>
        /// Runs the genetic algorithm for the specified number of generations
        /// </summary>
        /// <param name="numGenerations">The number of generations</param>
        /// <returns></returns>
        public void Run()
        {
            ICollection <IGenotype> nextPopulation;
            List <IGenotype>        parents;

            Gene[][]  children;
            IGenotype child;
            double    fitness;
            bool      mutated, solutionFound;

            ParameterCheck();

            if (Population == null)
            {
                InitializePopulation();
            }

            if (AllowDuplicates)
            {
                nextPopulation = new List <IGenotype>(PopulationSize);
            }
            else
            {
                nextPopulation = new SafeHashSet <IGenotype>(MaxRetriesForDuplicates);
            }

            solutionFound = false;

            if (PreserveElitePercent > 0)
            {
                foreach (IGenotype individual in Population.Take((int)(PreserveElitePercent * PopulationSize)).ToList())
                {
                    nextPopulation.Add(individual);
                }
            }

            SelectionMethod.Initialize(Population);

            while (nextPopulation.Count < PopulationSize)
            {
                try
                {
                    parents = SelectionMethod.DoSelection();
                }
                catch (SafeHashSetException)
                {
                    Converged = true;
                    break;
                }

                // Perform crossover
                children = CrossoverMethod.DoCrossover <Gene>(parents);

                // Iterate through each child produced by crossover
                for (int i = 0; i < children.Length; i++)
                {
                    // Calculate fitness of child
                    fitness = FitnessFunction(children[i], out solutionFound);

                    // Perform mutation (but skip if solution has been found)
                    mutated = solutionFound ? false : MutationMethod.DoMutation <Gene>(ref children[i]); // TODO return mutation and use only if better fitness??? Make a parameter to turn on/off

                    // Recalculate fitness if mutation occurred
                    if (mutated)
                    {
                        fitness = FitnessFunction(children[i], out solutionFound);
                    }

                    // Instantiate child
                    child = CreateMethod(children[i], fitness);

                    try
                    {
                        nextPopulation.Add(child);

                        if (solutionFound)
                        {
                            break;
                        }
                    }
                    catch (SafeHashSetException)
                    {
                        Converged = true;
                        break;
                    }
                }

                if (solutionFound || Converged)
                {
                    break;
                }
            }

            GenerationNumber++;
            SolutionFound = solutionFound;
            Population    = nextPopulation.OrderByDescending(x => x.Fitness).ToList();
            BestCurrent   = Population.First();

            FinishedGeneration?.Invoke();

            foreach (Termination.TerminationMethod t in TerminationMethods)
            {
                if (t.CheckTermination(this))
                {
                    Terminated = true;
                    TerminationReached?.Invoke();
                }
            }
        }
Exemple #15
0
 public BinPackingGenetics(List <int> volumes, int containerCapacity, MutationOperator mutationOperator, CrossoverMethod method, SelectionMethod selectionMethod) : base(method, selectionMethod)
 {
     _mutationOperator  = mutationOperator;
     _volumes           = new List <int>(volumes);
     _containerCapacity = containerCapacity;
     _lowerBound        = (int)Math.Ceiling((decimal)(volumes.Sum() / _containerCapacity));
     bpa         = new BinPackingAlgorithm(_volumes, _containerCapacity);
     _resultBins = new ObservableCollection <List <int> >();
     MaxFitness  = (uint)(volumes.Count - _lowerBound);
     Alpha       = (int)MaxFitness / 2;
 }
 public NQueens(int n, MutationOperator mutationOperator, CrossoverMethod method, SelectionMethod selectionMethod) : base(method, selectionMethod)
 {
     _n = n;
     _mutationOperator = mutationOperator;
     MaxFitness        = (uint)(_n * _n); // every queen threat on all the other queens
 }
Exemple #17
0
        static void Main(string[] args)
        {
            FirstGenerationGenerator FGG = new FirstGenerationGenerator();
            CrossoverMethod          CM  = new CrossoverMethod();
            MutationMethod           MM  = new MutationMethod();
            SelectionMethod          SM  = new SelectionMethod();
            double mutationProbability   = 0;
            int    genomsInGeneration    = 0;
            int    generationCount       = 0;
            int    option = 0;

            System.Console.WriteLine("Enter count of genoms");
            genomsInGeneration = Convert.ToInt32(Console.ReadLine());
            System.Console.WriteLine("Enter count of generations");
            generationCount = Convert.ToInt32(Console.ReadLine());
            System.Console.WriteLine("Enter mutation probability");
            mutationProbability = Convert.ToDouble(Console.ReadLine());
            System.Console.WriteLine("Choose first generatioh  generator: 1-Random  2-Nearest neighbor");
            option = Convert.ToInt32(Console.ReadLine());
            if (option == 1)
            {
                FGG = FirstGenerationGenerator.Rand;
            }
            else
            if (option == 2)
            {
                FGG = FirstGenerationGenerator.NearestNeighbor;
            }
            System.Console.WriteLine("Choose crossover method: 1-OX  2-PMX");
            option = Convert.ToInt32(Console.ReadLine());
            if (option == 1)
            {
                CM = CrossoverMethod.OX;
            }
            else
            if (option == 2)
            {
                CM = CrossoverMethod.PMX;
            }
            System.Console.WriteLine("Choose mutation method: 1-Inversion  2-Saltation");
            option = Convert.ToInt32(Console.ReadLine());
            if (option == 1)
            {
                MM = MutationMethod.Inversion;
            }
            else
            if (option == 2)
            {
                MM = MutationMethod.Saltation;
            }
            System.Console.WriteLine("Choose selection method: 1-Tourney  2-Roulette wheel");
            option = Convert.ToInt32(Console.ReadLine());
            if (option == 1)
            {
                SM = SelectionMethod.Tourney;
            }
            else
            if (option == 2)
            {
                SM = SelectionMethod.RouletteWheel;
            }
            FitnessFunction  ff = new FitnessFunction(new Matrix("C:/Users/Ильяс/source/repos/EGA/EGA/m1.txt"));
            GeneticAlgorithm ga = new GeneticAlgorithm(genomsInGeneration, generationCount, mutationProbability, FGG, CM, MM, SM, ff);

            ga.Run();
            System.Console.ReadKey();
        }
 public StringSearch(CrossoverMethod method, SelectionMethod selectionMethod) : base(method, selectionMethod)
 {
     _isBonus   = false;
     MaxFitness = (uint)(90 * StrTarget.Length);
     Alpha      = (int)MaxFitness / 2;
 }