public override void Execute(ref IOrganism organism) { var chromosome = (IGEPChromosome)organism[0]; var main = chromosome.Main; var activeAlleleDNA = main.GetActiveAllele().DNA; activeAlleleDNA.DecrementNucleotide(activeAlleleDNA.RandomIndex()); }
public Tuple<IOrganism, IOrganism> CrossLink(IOrganism parent1, IOrganism parent2) { if (parent1.Chromosomes.Count != parent2.Chromosomes.Count) { throw new InvalidOperationException("Parents must have the same number of chromosomes"); } IOrganism child1 = parent1.Clone(); IOrganism child2 = parent2.Clone(); for (int chromosomeIndex = 0; chromosomeIndex <= parent1.Chromosomes.Count - 1; chromosomeIndex++) { if (rand.NextDouble() > this.CrossLinkProbability) { continue; } var child1Genes = child1.Chromosomes[chromosomeIndex].GetGenes(); var child2Genes = child2.Chromosomes[chromosomeIndex].GetGenes(); int matchIndex = rand.Next(Math.Min(child1Genes.Count(), child2Genes.Count())); Chromosome match1 = child1Genes.ElementAt(matchIndex); Chromosome match2 = child2Genes.ElementAt(matchIndex); this.SwapGenes(child1.Chromosomes[chromosomeIndex], match1, match2); this.SwapGenes(child2.Chromosomes[chromosomeIndex], match1, match2); } return new Tuple<IOrganism, IOrganism>(child1, child2); }
public void Start() { int iteration = 0; while (iteration < Iterations) { Console.WriteLine($"Generation {iteration}"); iteration++; var scoredOrganisms = Population.Organisms.Select(o => new { Score = o.Score(), Organism = o }) .ToArray(); //Sort the organisms by score var sortedOrganisms = scoredOrganisms .OrderBy(o => o.Score) .Select(o => o.Organism) .ToArray(); //Keep track of the absolute best organism. var currentBestOrganism = sortedOrganisms.First(); if (AbsoluteBestOrganism == null || currentBestOrganism.Score() < AbsoluteBestOrganism.Score()) { AbsoluteBestOrganism = currentBestOrganism; } //Keep the best organisms var matePopulation = new HashSet <IOrganism>(sortedOrganisms[0..MatePopulationCutoff]);
public void Mutate(IOrganism organism) { foreach (Chromosome chromosome in organism.Chromosomes) { int index = rand.Next(chromosome.Length); chromosome[index] = !chromosome[index]; } }
public Tuple <IOrganism, IOrganism> CrossLink(IOrganism parent1, IOrganism parent2) { if (parent1.Chromosomes.Count != parent2.Chromosomes.Count) { throw new InvalidOperationException("Parents must have the same number of chromosomes"); } IOrganism child1 = parent1.Clone(); IOrganism child2 = parent2.Clone(); for (int i = 0; i <= parent1.Chromosomes.Count - 1; i++) { if (rand.NextDouble() > this.CrossLinkProbability) { continue; } int crossLinkIndex1 = rand.Next(Math.Min(parent1.Chromosomes[i].Length, parent2.Chromosomes[i].Length) - 1); int crossLinkIndex2 = rand.Next(crossLinkIndex1 + 1, Math.Min(parent1.Chromosomes[i].Length, parent2.Chromosomes[i].Length)); child1.Chromosomes[i].OverWrite(crossLinkIndex1, parent2.Chromosomes[i].Bits.Skip(crossLinkIndex1).Take(crossLinkIndex2 - crossLinkIndex1).ToArray()); child2.Chromosomes[i].OverWrite(crossLinkIndex1, parent1.Chromosomes[i].Bits.Take(crossLinkIndex2 - crossLinkIndex1).ToArray()); } return(new Tuple <IOrganism, IOrganism>(child1, child2)); }
public void Eat(IOrganism organism, List <IOrganism> toDelete) { AudioController.PlayEat(); AddHealth(organism.Health); toDelete.Add(organism); Move(2); }
public Tuple <IOrganism, IOrganism> CrossLink(IOrganism parent1, IOrganism parent2) { if (parent1.Chromosomes.Count != parent2.Chromosomes.Count) { throw new InvalidOperationException("Parents must have the same number of chromosomes"); } IOrganism child1 = parent1.Clone(); IOrganism child2 = parent2.Clone(); for (int chromosomeIndex = 0; chromosomeIndex <= parent1.Chromosomes.Count - 1; chromosomeIndex++) { if (rand.NextDouble() > this.CrossLinkProbability) { continue; } var child1Genes = child1.Chromosomes[chromosomeIndex].GetGenes(); var child2Genes = child2.Chromosomes[chromosomeIndex].GetGenes(); int matchIndex = rand.Next(Math.Min(child1Genes.Count(), child2Genes.Count())); Chromosome match1 = child1Genes.ElementAt(matchIndex); Chromosome match2 = child2Genes.ElementAt(matchIndex); this.SwapGenes(child1.Chromosomes[chromosomeIndex], match1, match2); this.SwapGenes(child2.Chromosomes[chromosomeIndex], match1, match2); } return(new Tuple <IOrganism, IOrganism>(child1, child2)); }
private double CalculateFitness(IOrganism o) { List <City> cities = this.cityInfo.Select(c => c.Name).ToList(); var numbers = o.Chromosomes[0].GetGenes().Select((g, i) => Convert.ToInt32(g.ToString(), 2)).ToList(); double totalDistance = 0; City lastCity = City.Unknown; numbers.ForEach(i => { City currentCity = cities[i]; cities.RemoveAt(i); if (lastCity == City.Unknown) { lastCity = currentCity; } else { totalDistance += this.GetDistance(lastCity, currentCity); lastCity = currentCity; } }); return(1 / totalDistance); }
public void Mutate(IOrganism organism) { foreach (Chromosome chromosome in organism.Chromosomes) { if (chromosome.Length % this.geneLength != 0) { //Throw New InvalidOperationException("The element must be a multiple of gene length") } int gene1Index = rand.Next(Convert.ToInt32(Math.Floor((double)chromosome.Length / this.geneLength)) - 1); int gene2Index = gene1Index + 1; bool[] temp = new bool[this.geneLength + 1]; for (int i = 0; i <= this.geneLength - 1; i++) { temp[i] = chromosome[gene1Index * this.geneLength + i]; } for (int i = 0; i <= this.geneLength - 1; i++) { chromosome[gene1Index * this.geneLength + i] = chromosome[gene2Index * this.geneLength + i]; chromosome[gene2Index * this.geneLength + i] = temp[i]; } } }
public void Move(IOrganism obj, Point oldPoint, Point newPoint) { var o = Matrix[oldPoint.X, oldPoint.Y]; Matrix[oldPoint.X, oldPoint.Y] = null; Matrix[newPoint.X, newPoint.Y] = o; }
private static void GetPopulationUsingVar(IOrganism organism) { double population = 0; // Switch on passed organism using var pattern matching. switch (organism) { // Assign organism to new bee variable, if population is roughly equal to 30 trillion. case var bee when Math.Abs(bee.Population - 30e12) <= 1: population = bee.Population; break; // Assign organism to new human variable, if object type Name is "Human." case var human when human.GetType().Name == "Human": population = human.Population; break; default: // Output alert if organism type is unknown. Logging.Log($"Unknown organism type ({organism.GetType().Name}), or population exceeds all known estimates."); return; } // Output retrieved population estimate. Logging.Log($"Estimated number of {organism.GetType().Name.ToLower()}s on Earth: {population:n0}."); }
public void Clone(IOrganism parent) { var parentCast = (IncrementingBoard)parent; for (int i = 0; i < GeneInfo.Length; i++) { GeneInfo[i] = parentCast.GeneInfo[i]; } }
public void Mutate(IOrganism organism) { foreach (Chromosome chromosome in organism.Chromosomes) { int index = rand.Next(chromosome.Length - 1); bool temp = chromosome[index]; chromosome[index] = chromosome[index + 1]; chromosome[index + 1] = temp; } }
/// <summary> /// Removes the current occupant from the <see cref="VehicleSeat"/>. /// </summary> public void Clear() { if (!IsOccupied) { return; } Occupant = null; }
/// <summary> /// Gets the IMetrics of the IOrganism. /// /// Calls OnEvaluationStart on start and calls OnEvaluationEnd on end. /// </summary> /// <returns></returns> public override IMetrics GetMetrics(IOrganism organism) { this.OnEvaluationStart(new StartMetricsEvaluationEventArgs()); var metrics = this.GetMetricsDelegate(organism: organism); this.OnEvaluationEnd(new EndMetricsEvaluationEventArgs()); return metrics; }
public void Mutate(IOrganism organism) { for (int i = 0; i <= organism.Chromosomes.Count - 1; i++) { int index = rand.Next(organism.Chromosomes[i].Length); Chromosome mutated = new Chromosome(organism.Chromosomes[i].GeneLength, organism.Chromosomes[i].Length - 1); Array.Copy(organism.Chromosomes[i].Bits, 0, mutated.Bits, 0, index); Array.Copy(organism.Chromosomes[i].Bits, index + 1, mutated.Bits, index, organism.Chromosomes[i].Length - index - 1); organism.Chromosomes[i] = mutated; } }
public void Clone(IOrganism parent) { var p = (Warehouse)parent; //Copy the shelves for (int i = 0; i < Shelves.Length; i++) { SetShelf(i, p.Shelves[i]); } }
public void Mutate(IOrganism organism) { if (this.Mutators.Count == 0) { throw new ArgumentException("Mutators"); } if (rand.NextDouble() < this.MutationProbability) { int index = rand.Next(this.Mutators.Count); this.Mutators[index].Mutate(organism); } }
public override void Execute(ref IOrganism organism) { var chromosome = (IGEPChromosome)organism[0]; var main = chromosome.Main; var dna = main.GetActiveAllele().DNA; var nucleotidesToMutateCount = Randomizer.Next(this.MinimumNucleotidesToMutate, this.MaximumNucleotidesToMutate + 1); for (var i = 0; i < nucleotidesToMutateCount; i++) dna.RandomlyFlipNucleotide(); }
/// <summary> /// Kills the <see cref="Organism"/>, specifying the killer. /// </summary> /// <param name="killer">The killer.</param> public void Kill(IOrganism killer) { if (IsDead) { return; } IsAlive = false; SetHealth(0); OnKilled(); }
private IOrganism CorrectEncoding(IOrganism o) { var genes = o.Chromosomes[0].GetGenes(); var geneCount = genes.Count(); for (int geneId = 0; geneId < geneCount; geneId++) { o.Chromosomes[0].Gene(geneId, new Chromosome(geneLength, Convert.ToString(Convert.ToInt32(o.Chromosomes[0].Gene(geneId).ToString(), 2) % (genes.Count() - geneId), 2).PadLeft(geneLength, '0'))); } return(o); }
/// <summary> /// Revives the <see cref="Organism"/>, specifying the reviver. /// </summary> /// <param name="reviver">The reviver.</param> public void Revive(IOrganism reviver) { if (!IsDead) { return; } IsAlive = true; SetHealth(Template.MaxHealth); OnRevived(); }
private void addIOrganism(IOrganism organism) { organism.Position = Position.GenerateRandomEmptyPosition(this.Terrarium); organism.LastPosition = new Position(organism.Position.X, organism.Position.Y); organism.Terrarium = this.Terrarium; if (organism is Plant) { Plant plant = (Plant)organism; Terrarium.RenderPlant(plant); } this.Terrarium.Organisms.Add(organism); }
public void Add(IOrganism obj, Point point) { var o = Matrix[point.X, point.Y]; if (o == null) { Organisms.Add(obj); LiveOrganisms.Add(obj); Matrix[point.X, point.Y] = obj; } }
protected override void ConstructFromOrganism(IOrganism organism) { this.Clear(); var chromosomeIndex = 0; foreach (IGEPChromosome chromosome in organism) { var geneLevel = 0; this.FillGenomeUnits(currentGene: chromosome.Main, chromosomeIndex: chromosomeIndex, geneLevel: ref geneLevel); chromosomeIndex++; } }
public void Mutate(IOrganism organism) { for (int i = 0; i <= organism.Chromosomes.Count - 1; i++) { int index = rand.Next(organism.Chromosomes[i].Length); bool newElement = rand.NextDouble() > 0.5; bool[] mutated = new bool[organism.Chromosomes[i].Length + 1]; Array.Copy(organism.Chromosomes[i].Bits, 0, mutated, 0, index); mutated[index] = newElement; Array.Copy(organism.Chromosomes[i].Bits, index, mutated, index + 1, organism.Chromosomes[i].Length - index); organism.Chromosomes[i] = new Chromosome(organism.Chromosomes[i].GeneLength, mutated); } }
/// <summary> /// Occupies the <see cref="VehicleSeat"/> with the specified creature. /// </summary> /// <param name="newOccupant">The creature to occupy the seat with.</param> /// <param name="force">Whether to boot the current occupant out.</param> public void Occupy(IOrganism newOccupant, bool force = true) { if (IsOccupied) { if (force) { Occupant = newOccupant; } return; } Occupant = newOccupant; }
public override void ConstructFromOrganism(IOrganism organism, ISurroundings surroundings) { base.ConstructFromOrganism(organism: organism, surroundings: surroundings); var o = (IGEPOrganism) organism; var gepSurroundings = (IGEPSurroundings) surroundings; foreach(IGEPChromosome chromosome in o.GetChromosomes()) { var debuggableChromosome = chromosome.ToDebuggableChromosome(new GEPChromosomeSurroundings(gepSurroundings)); this.Chromosomes.Add(debuggableChromosome); } }
/// <summary> /// Heals the <see cref="Organism"/>, specifying the healer. /// </summary> /// <param name="healer">The healer.</param> /// <param name="amount">The healing amount (hp).</param> public void Heal(IOrganism healer, int amount) { if (IsDead) { return; } if (Health + amount > Template.MaxHealth) { SetHealth(Template.MaxHealth); return; } SetHealth(Health + amount); OnHealed(); }
public void Mate(IOrganism parent1, IOrganism parent2) { var parent1Cast = (IncrementingBoard)parent1; var parent2Cast = (IncrementingBoard)parent2; var cutoff = Rng.Next(1, parent1Cast.GeneInfo.Length - 1); for (int i = 0; i < cutoff; i++) { GeneInfo[i] = parent1Cast.GeneInfo[i]; } for (int i = cutoff; i < parent2Cast.GeneInfo.Length; i++) { GeneInfo[i] = parent2Cast.GeneInfo[i]; } }
private string WritePath(IOrganism o) { List <City> cities = this.cityInfo.Select(c => c.Name).ToList(); var numbers = o.Chromosomes[0].GetGenes().Select((g, i) => Convert.ToInt32(g.ToString(), 2) % (cities.Count - i)).ToList(); City[] output = new City[cities.Count + 1]; int counter = 0; numbers.ForEach(i => { output[counter] = cities[i]; cities.RemoveAt(i); counter += 1; }); return(string.Join(",", output)); }
public void Fight(IOrganism organism, List <IOrganism> toDelete) { // Cast to animal to use add health Animal animal = (Animal)organism; //Console.WriteLine("Carnivore fought with Carnivore"); if (organism.Health > Health) { toDelete.Add(this); animal.AddHealth(Health); } else if (organism.Health <= Health) { toDelete.Add(organism); AddHealth(animal.Health); Move(2); } AudioController.PlayFight(); }
public void TravellingSalesmanTest() { int populationSize = 100; IRandom rand = new Rand(); this.geneLength = 6; this.cityInfo = this.BuildCityInfo(); Population candidates = RandomPopulationGenerator.GeneratePopulation(rand, populationSize, 1, geneLength, this.cityInfo.Count, this.cityInfo.Count, new List <Chromosome>(), new List <Chromosome>(), CorrectEncoding); GeneticAlgorithm ga = new GeneticAlgorithm(rand, candidates, CalculateFitness); ga.encodingCorrector = CorrectEncoding; IOrganism solution = ga.FindSolution(); string path = WritePath(solution); double totalDistance = 1 / CalculateFitness(solution); Assert.IsTrue(totalDistance <= 25000); }
public Tuple<IOrganism, IOrganism> CrossLink(IOrganism parent1, IOrganism parent2) { if (parent1.Chromosomes.Count != parent2.Chromosomes.Count) { throw new InvalidOperationException("Parents must have the same number of chromosomes"); } IOrganism child1 = parent1.Clone(); IOrganism child2 = parent2.Clone(); for (int i = 0; i <= parent1.Chromosomes.Count - 1; i++) { if (rand.NextDouble() > this.CrossLinkProbability) { continue; } int crossLinkIndex = rand.Next(Math.Min(parent1.Chromosomes[i].Length, parent2.Chromosomes[i].Length)); child1.Chromosomes[i].OverWrite(crossLinkIndex, parent2.Chromosomes[i].Bits.Skip(crossLinkIndex).ToArray()); child2.Chromosomes[i].OverWrite(crossLinkIndex, parent1.Chromosomes[i].Bits.Take(child2.Chromosomes[i].Length - crossLinkIndex).ToArray()); } return new Tuple<IOrganism, IOrganism>(child1, child2); }
public virtual void PlaceOrganisms(IOrganism organism, int count, int index) { do { Point p = new Point(); p.X = Rand.Next(0, Size); p.Y = Rand.Next(0, Size); if (Matrix[p.X, p.Y] != null) { continue; } var obj = organism.Create(this, BaseCore, p, index); Add(obj, p); count--; } while (count > 0); }
private static void GetPopulationUsingType(IOrganism organism) { double population = 0; // Switch on passed organism using type pattern matching. switch (organism) { case Bee bee: population = bee.Population; break; case Human human when(human.Population < 1e7): // If a Human is passed and the population is too low, panic! Logging.Log($"The human population is too low at {human.Population:n0}! Apocalypse!"); return; case Human human: // If the Human population is alright, proceed as normal. population = human.Population; break; case Insect insect: population = insect.Population; break; case Mammal mammal: population = mammal.Population; break; default: // Output alert if organism type is unknown. Logging.Log($"Unknown organism type ({organism.GetType().Name}), or population exceeds all known estimates."); return; } // Output retrieved population estimate. Logging.Log($"Estimated number of {organism.GetType().Name.ToLower()}s on Earth: {population:n0}."); }
public void Fight(IOrganism organism, List <IOrganism> toDelete) { // Cast to animal to use add health Animal animal = (Animal)organism; if (organism is Human) { if (organism.Health >= Health) { toDelete.Add(this); animal.AddHealth(Health); } else if (organism.Health < Health) { toDelete.Add(organism); AddHealth(animal.Health); Move(2); } } else // If other carnivore { if (organism.Health > Health) { toDelete.Add(this); animal.AddHealth(Health); } else if (organism.Health < Health) { toDelete.Add(organism); AddHealth(animal.Health); Move(2); } } AudioController.PlayFight(); }
/// <summary> /// Gets the percentage that IOrganism one and IOrganism two are similar. /// 100% would be identical and 0% would indicate that the IOrganisms share nothing. /// </summary> /// <param name="one">The first IOrganism to compare.</param> /// <param name="two">The second IOrganism to compare.</param> /// <returns>The percentage that IOrganism one and IOrganism two are similar. /// 100% would be identical and 0% would indicate that the IOrganisms share nothing.</returns> public abstract double GetPercentageIOrganismSimilarity(IOrganism one, IOrganism two);
private IOrganism CorrectEncoding(IOrganism o) { var genes = o.Chromosomes[0].GetGenes(); var geneCount = genes.Count(); for (int geneId = 0; geneId < geneCount; geneId++) { o.Chromosomes[0].Gene(geneId, new Chromosome(geneLength, Convert.ToString(Convert.ToInt32(o.Chromosomes[0].Gene(geneId).ToString(), 2) % (genes.Count() - geneId), 2).PadLeft(geneLength, '0'))); } return o; }
private string WritePath(IOrganism o) { List<City> cities = this.cityInfo.Select(c => c.Name).ToList(); var numbers = o.Chromosomes[0].GetGenes().Select((g, i) => Convert.ToInt32(g.ToString(), 2) % (cities.Count - i)).ToList(); City[] output = new City[cities.Count + 1]; int counter = 0; numbers.ForEach(i => { output[counter] = cities[i]; cities.RemoveAt(i); counter += 1; }); return string.Join(",", output); }
/// <summary> /// Executes the Mutation on the given IOrganism. /// </summary> /// <param name="organism">The IOrganism to mutate.</param> public abstract void Execute(ref IOrganism organism);
private IMetrics MetricsFunction(IOrganism organism) { var o = (IGEPOrganism) organism; var value = this.GetValue(o, this.GetInputRegistry(o, 1), this.GetInputRegistry(o, 2), this.GetInputRegistry(o, 3), this.GetInputRegistry(o, 4), this.GetInputRegistry(o, 5), this.GetInputRegistry(o, 6), this.GetInputRegistry(o, 8), this.GetInputRegistry(o, 9) ); const double worstFitness = 15000; if (double.IsNaN(value) || double.IsInfinity(value)) value = worstFitness; return new Metrics() {Value = new MetricsValue() {Value = value}}; }
public void Add(IOrganism member) { this.Members.Add(member); }
public void Remove(IOrganism member) { this.Members.Remove(member); }
public override void ConstructFromOrganism(IOrganism organism, GeneticFaraday.Contracts.Organisms.OrganismBehavior.Surroundings.ISurroundings surroundings) { this.Chromosomes = new List<IDebuggableChromosome>(); }
public override void Execute(ref IOrganism organism) { var chromosome = (IGEPChromosome) organism[0]; var main = chromosome.Main; main.GetActiveAllele().DNA.RandomlyFlipNucleotide(); }
/// <summary> /// Gets the IMetrics of the IOrganism. /// /// Calls EvaluationStart at its beginning and EvaluationEnd at its end. /// </summary> /// <returns></returns> public abstract IMetrics GetMetrics(IOrganism organism);
private double CalculateFitness(IOrganism o) { List<City> cities = this.cityInfo.Select(c => c.Name).ToList(); var numbers = o.Chromosomes[0].GetGenes().Select((g, i) => Convert.ToInt32(g.ToString(), 2)).ToList(); double totalDistance = 0; City lastCity = City.Unknown; numbers.ForEach(i => { City currentCity = cities[i]; cities.RemoveAt(i); if (lastCity == City.Unknown) { lastCity = currentCity; } else { totalDistance += this.GetDistance(lastCity, currentCity); lastCity = currentCity; } }); return 1 / totalDistance; }
public virtual void RespondTo(IOrganism organism) { }
/// <summary> /// The provided IOrganism must be an IGEPOrganism. /// </summary> /// <param name="item"></param> new public void Add(IOrganism item) { this.Add((IGEPOrganism) item); }
/// <summary> /// Gets the percentage that IOrganism one and IOrganism two are similar. /// 100% would be identical and 0% would indicate that the IOrganisms share nothing. /// </summary> /// <param name="one">The first IOrganism to compare.</param> /// <param name="two">The second IOrganism to compare.</param> /// <returns>The percentage that IOrganism one and IOrgnaism two are similar. /// 100% would be identical and 0% would indicate that the IOrganisms share nothing.</returns> public override double GetPercentageIOrganismSimilarity(IOrganism one, IOrganism two) { return this.GetPercentageIOrganismSimilarityDelegate(one: one, two: two); }
public void Mutate(IOrganism organism) { this.MutationCount += 1; }