/// <summary> /// Invokes the mutation method on all agents in the population. /// </summary> /// <param name="mutator">The mutation method that defines how the population should be mutated.</param> /// <param name="mutationProbability">The probability for an agent to be mutated.</param> /// <param name="mutationProbilityGene">The probability for a gene to be mutated.</param> /// <param name="random">The random generator that produces random numbers used in the method to determine /// if an agent or a gene should be mutated.</param> public void MakeMutations(IMutator mutator, double mutationProbability, double mutationProbilityGene, IRandomNumberGenerator random) { // Mutate all agents in population for (int i = 0; i < Agents.Count; i++) { // Check if agent should be mutated double randomDouble = random.GetDouble(0, 1); if (randomDouble < mutationProbability) { Agents[i].Mutate(mutator, mutationProbilityGene, random); } } }
/// <summary> /// Goes through every gene and randomize the gene if probabilty hit. /// </summary> /// <param name="genes"></param> /// <param name="mutationProbabilityGene"></param> /// <param name="random"></param> /// <returns></returns> public Gene[] MakeMutation(Gene[] genes, double mutationProbabilityGene, IRandomNumberGenerator random) { for (int i = 0; i < genes.Length; i++) { // Check if this gene should be mutated double randomDouble = random.GetDouble(0, 1); if (randomDouble < mutationProbabilityGene) { // Overwrite with new random gene genes[i] = new Gene(random); } } return(genes); }
/// <summary> /// Returns selected agents based on the Roulette wheel selection method. /// </summary> /// <param name="agents"></param> /// <param name="selectionSize"></param> /// <param name="random"></param> /// <returns></returns> public List <Agent> MakeSelection(List <Agent> agents, int selectionSize, IRandomNumberGenerator random) { double totalFitness = 0; List <double> agentProbabilities = new List <double>(); List <Agent> selectedAgents = new List <Agent>(); // Get total fitnes for (int i = 0; i < agents.Count; i++) { // Sum fitness values totalFitness += agents[i].Fitness; } // Make agent probabilities for (int i = 0; i < agents.Count; i++) { agentProbabilities.Add(agents[i].Fitness / totalFitness); } double randomNumber = 0; double total = 0; int counter = 0; bool agentFound = false; for (int i = 0; i < selectionSize; i++) { // Get new random number randomNumber = random.GetDouble(0, 1); // Find angent match for (int j = 0; j < agents.Count && !agentFound; j++) { total += agentProbabilities[j]; if (total >= randomNumber) { selectedAgents.Add(agents[j]); agentFound = true; } } Debug.WriteLine(++counter); total = 0; agentFound = false; } return(selectedAgents); }
/// <summary> /// Makes a random gene. /// </summary> /// <param name="random"></param> public Gene(IRandomNumberGenerator random) { Value = random.GetDouble(-1, 1); }