public override void Evolve() { int individualsToEliminate = (int)(_generationGap * _populationSize); // A single generation is when GenerationGap % of population is eliminated and replaced IList <T> offspringPopulation = new List <T>(); while (offspringPopulation.Count < individualsToEliminate) { IList <T> matingPool = new List <T>(CrossoverOperator.NumberOfParents); for (int j = 0; j < CrossoverOperator.NumberOfParents; j++) { T mate = SelectionOperator.Execute(_population); matingPool.Add(mate); } IList <T> children = CrossoverOperator.Execute(matingPool); for (int j = 0; j < children.Count; j++) { MutationOperator.Execute(children[j]); _problem.Evaluate(children[j]); offspringPopulation.Add(children[j]); } } offspringPopulation = offspringPopulation.Take(individualsToEliminate).ToList(); _population = ReplacementOperator.Execute(_population, offspringPopulation); UpdateState(); }
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> >(); }
public override Chromosome RandomNeighbourSolution(Chromosome chromosome, MutationOperator neighbourhood) { int size = chromosome.Size(); IGene[] newGenes = new IGene[size]; Array.Copy(chromosome.Genes, newGenes, size); neighbourhood.Run(newGenes); Chromosome result = new Solution(chromosome.Problem as VrptwProblem, newGenes); return(result); }
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; }
/// <summary> /// Runs a random walk of n steps along a landscape defined by a mutation operator and returns its results. /// </summary> /// <param name="steps">Number of steps.</param> /// <param name="searchOperator">Operator defining a neighbourhood.</param> /// <returns></returns> public RandomWalk RandomWalk(int steps, MutationOperator searchOperator) { RandomWalk statistics = new RandomWalk(steps); Chromosome currentSolution = ChromosomeFactory.RandomSolution(Problem.GeneCount(), Problem); GatherData(currentSolution, 0, statistics); for (int i = 1; i < steps; ++i) { searchOperator.Run(ref currentSolution); GatherData(currentSolution, i, statistics); } return(statistics); }
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(); }
protected virtual IEnumerable <IDeploymentChromosome> Mutate(IEnumerable <IDeploymentChromosome> offspring) { foreach (var child in offspring) { if (RandomProvider.GetRandom() <= MutationProbability) { yield return(MutationOperator.Mutate(child)); } else { yield return(child); } } }
private void choose_mutations_operator() { Console.WriteLine("Please Choose Mutation Operator :"); var mutationList = Enum.GetValues(typeof(MutationOperator)).Cast <MutationOperator>().ToList(); for (int i = 0; i < mutationList.Count; i++) { Console.WriteLine((i + 1) + ". " + mutationList[i]); } int input = 0; do { input = get_input(); } while (input <= 0 || input > mutationList.Count); _mutationOperator = mutationList[input - 1]; }
private void CreateNextGeneration() { var startingIndex = UsingElitism ? NumberOfElite : 0; if (UsingElitism) { Population.SortByFitness(); for (int i = 0; i < NumberOfElite; i++) { Population.AddChromosome(i, Population.Chromosomes[i]); } startingIndex = NumberOfElite; } var populationSize = Population.PopulationSize; for (int i = startingIndex; i < populationSize; i++) { // TODO -> Should I make sure that both parents are different ?? // selection operation var fatherChromosome = SelectionOperator.PopulationSelection(Population); var motherChromosome = SelectionOperator.PopulationSelection(Population); // TODO -> return more than one child always!!! // crossover operation var childChromosome = CrossoverOperator.Crossover(fatherChromosome, motherChromosome); // TODO -> some crossovers can return more than one child // mutate operation MutationOperator.Mutate(childChromosome); // add child chromsome to the next generation population CalculateFitness(childChromosome); Population.AddChromosome(i, childChromosome); } // prepare for next evolution Population.SetNextGeneration(); SelectionOperator.SetNextGeneration(); Generation++; }
public GeneticAlgorithm( int populationSize, int paramsCount, double generationGapPart, ISelection selection, CrossoverOperator crossoverOperator, MutationOperator mutationOperator, IFitnessFunc fitnessFunc, FloatRange range) { chromosomes = new List <IntChromosome>(populationSize); this.generationGapPart = generationGapPart; this.selection = selection; this.crossoverOperator = crossoverOperator; this.mutationOperator = mutationOperator; this.fitnessFunc = fitnessFunc; this.paramsCount = paramsCount; this.range = range; generatePopulationInt = new GeneratePopulationInt(); random = new Random(); bitCountForIntCoding = Coder.BitCountForIntCoding(range); GeneratePopulation(); }
public override void Evolve() { IList <T> offspringPopulation = new List <T>(); // Let elites survive to next generation int numberOfElites = (int)(_elitismRate * _populationSize); IList <T> elites = _population .OrderByDescending(c => c, _problem.FitnessComparer) .Take(numberOfElites).ToList(); foreach (T individual in elites) { offspringPopulation.Add(individual); } while (offspringPopulation.Count < _populationSize) { IList <T> matingPool = new List <T>(CrossoverOperator.NumberOfParents); for (int i = 0; i < CrossoverOperator.NumberOfParents; i++) { matingPool.Add(SelectionOperator.Execute(_population)); } IList <T> children = CrossoverOperator.Execute(matingPool); for (int i = 0; i < children.Count; i++) { MutationOperator.Execute(children[i]); _problem.Evaluate(children[i]); offspringPopulation.Add(children[i]); } } // When there is some excess chromosomes, discard them by taking only the needed ones _population = offspringPopulation.Take(_populationSize).ToList(); UpdateState(); }
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 }
/// <summary> /// Sets the options and other configuration used in the GA. /// </summary> private void ApplyOptions() { /*** setting the selection operator to the specified type ***/ var selectionType = GaOptions.SelectionType; if (selectionType == SelectionType.None) { throw new Exception("Selection method cannot be none when setting the method."); } var populationSize = Population.PopulationSize; switch (selectionType) { case SelectionType.Rws: SelectionOperator = new RouletteWheelSelection <T>(populationSize, Random); break; case SelectionType.Tos: // the tournamnet selection percentage is hardcoded for now to 2%, TODO => this must be passed in the GA Options SelectionOperator = new TournamentSelection <T>(populationSize, Random, 0.02); break; } /*** setting the selection operator to the specified type ***/ /*** setting the crossover operator to the specified type ***/ var crossoverType = GaOptions.CrossoverType; if (crossoverType == CrossoverType.None) { throw new Exception("Crossover method cannot be none when setting the method."); } switch (crossoverType) { case CrossoverType.OrderOne: CrossoverOperator = new OrderOne <T>(Random); break; case CrossoverType.Cycle: CrossoverOperator = new CycleCrossover <T>(Random); break; } /*** setting the crossover operator to the specified type ***/ /*** setting the mutation operator to the specified type ***/ var mutationType = GaOptions.MutationType; if (mutationType == MutationType.None) { throw new Exception("Mutation method cannot be none when setting the method."); } switch (mutationType) { case MutationType.SingleSwap: MutationOperator = new SingleSwapMutation <T>(Random); break; case MutationType.InversionMutation: MutationOperator = new InversionMutation <T>(Random, GaOptions.MutationRate); break; } /*** setting the mutation operator to the specified type ***/ /*** setting the stopping criteria for the algorithm ***/ var stoppingCriteriaOptions = GaOptions.StoppingCriteriaOptions; var stoppingCriteriaType = stoppingCriteriaOptions.StoppingCriteriaType; switch (stoppingCriteriaType) { case StoppingCriteriaType.TimeBased: var minutesPassed = stoppingCriteriaOptions.MinutesPassed; if (minutesPassed <= 0) { throw new Exception($"When using {stoppingCriteriaType}, the minutes passed must be larger than 0."); } StoppingCriteria = new TimeBaseStoppingCriteria(minutesPassed); break; case StoppingCriteriaType.SpecifiedIterations: var maximumIterations = stoppingCriteriaOptions.MaximumIterations; if (maximumIterations <= 0) { throw new Exception($"When using {stoppingCriteriaType}, the max iterations must be larger than 0."); } StoppingCriteria = new IterationStoppingCriteria(maximumIterations); break; } /*** setting the stopping criteria for the algorithm ***/ }
public static async Task <Chromosome> DoMa(string filename, CrossoverOperator crossOp, MutationOperator mutOp) { var problem = new VrptwProblemReader().ReadFromFile(filename); var parameters = new Parameters() { ChromosomeFactory = new SolutionFactory(), ConvergenceLimit = 0.15f, CrossoverOperators = new List <CrossoverOperator> { crossOp }, CrossoverProbability = 0.9f, EliteChildrenCount = 4, Fitness = new FitnessFunction(200000, 1), FitnessStrategy = FitnessStrategy.MINIMIZE, GeneCount = problem.GeneCount(), Heuristics = new SimulatedAnnealing(), HeuristicsParameters = new float[] { 100, 0.90f, 50 }, MaxIterations = 300, MutationOperators = new List <MutationOperator> { mutOp }, MutationProbability = 0.15f, PopulationSize = 200, PreservedChromosomesNumber = 4, Selection = new TournamentSelection() }; MemeticAlgorithm ma = new MemeticAlgorithm(); Chromosome sol = await ma.Run(problem, parameters, CallBackMa, crossOp.GetId() + "-" + mutOp.GetId()); return(sol); }
public abstract Chromosome RandomNeighbourSolution(Chromosome chromosome, MutationOperator neighbourhood);
public void Test1() { AbstractChromosomeFactory factory = new SolutionFactory(); int[] routeWeights = new int[] { 20000, 50000, 120000, 200000, 350000 }; int distanceWeight = 1; string[] customerTypes = new string[] { "C1", "C2", "R1", "R2", "RC1", "RC2" }; Dictionary <string, int> customerNumbers = new Dictionary <string, int>() { { "2", 20000 }, { "4", 50000 }, { "6", 120000 }, { "8", 200000 }, { "10", 350000 } }; string[] customerInstances = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; CrossoverOperator[] crossoverOps = new CrossoverOperator[] { new OrderCrossover(), new PartiallyMatchedCrossover(), new CycleCrossover(), new UniformBasedOrderCrossover() }; MutationOperator[] mutationOps = new MutationOperator[] { new SwapOperator(), new InsertionOperator(), new InversionOperator(), new DisplacementOperator() }; int randomWalkNumber = 2000, randomWalkSteps = 5000; string floatPattern = "0.000", separator = ","; float epsilon = 0.05f; foreach (var type in customerTypes) { foreach (var number in customerNumbers) { foreach (var instance in customerInstances) { string instanceId = type + '_' + number.Key + '_' + instance; VrptwProblem problem = reader.ReadFromFile(FILE_PATH + @"\" + instanceId + ".txt"); FitnessFunction ff = new FitnessFunction(number.Value, distanceWeight); Landscape landscape = new Landscape(problem, factory, ff); foreach (var op in crossoverOps) { string path = RESULT_PATH + @"\" + instanceId + "_" + op.GetId() + ".csv"; if (!File.Exists(path)) { File.Create(path).Close(); File.ReadAllText(path); using (TextWriter tw = new StreamWriter(path)) { tw.WriteLine("AC, IC, PIC, DBI"); for (int i = 0; i < randomWalkNumber; ++i) { var rwResult = landscape.RandomWalk(randomWalkSteps, op); float ac = Autocorrelation.Run(rwResult); float ic = InformationContent.Run(rwResult, epsilon); float pic = PartialInformationContent.Run(rwResult, epsilon); float dbi = DensityBasinInformation.Run(rwResult, epsilon); string line = ac.ToString(floatPattern) + separator + ic.ToString(floatPattern) + separator + pic.ToString(floatPattern) + separator + dbi.ToString(floatPattern); tw.WriteLine(line); } } } } } } } }