/// <summary> /// Mutates each bit of a <see cref="ListEntityBase{T}"/> if it meets a certain /// probability. /// </summary> /// <param name="entity"><see cref="ListEntityBase{T}"/> to be mutated.</param> /// <returns>True if a mutation occurred; otherwise, false.</returns> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> protected override bool GenerateMutation(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } bool isMutated = false; ListEntityBase <bool> bsEntity = (ListEntityBase <bool>)entity; for (int i = 0; i < bsEntity.Length; i++) { if (RandomNumberService.Instance.GetDouble() <= this.MutationRate) { isMutated = true; if (!bsEntity[i]) { bsEntity[i] = true; } else { bsEntity[i] = false; } } } return(isMutated); }
public override Task <double> EvaluateFitnessAsync(GeneticEntity entity) { this.DoEvaluateFitnessCallCount++; MockEntity mockEntity = (MockEntity)entity; return(Task.FromResult(Double.Parse(mockEntity.Identifier))); }
/// <summary> /// Migrates the <see cref="GeneticEntity"/> objects with the best fitness between populations. /// </summary> protected virtual void OnMigrate() { this.AssertIsInitialized(); IList <Population> populations = this.Environment !.Populations; // Build a list of migrant genetic entities from the first population List <GeneticEntity> migrantGeneticEntities = new List <GeneticEntity>(this.MigrantCount); for (int i = 0; i < this.MigrantCount; i++) { GeneticEntity[] sortedEntities = populations[0].Entities.GetEntitiesSortedByFitness( this.SelectionOperator !.SelectionBasedOnFitnessType, this.FitnessEvaluator !.EvaluationMode).ToArray(); migrantGeneticEntities.Add(sortedEntities[sortedEntities.Length - i - 1]); } // Migrate genetic entities between populations for (int populationIndex = 1; populationIndex < populations.Count; populationIndex++) { Population population = populations[populationIndex]; List <GeneticEntity> sortedEntities = population.Entities.GetEntitiesSortedByFitness( this.SelectionOperator !.SelectionBasedOnFitnessType, this.FitnessEvaluator !.EvaluationMode).ToList(); for (int entityIndex = 0; entityIndex < this.MigrantCount; entityIndex++) { // Add new migrant population.Entities.Add(migrantGeneticEntities[entityIndex]); sortedEntities.Add(migrantGeneticEntities[entityIndex]); // Set entity to be replaced as a new migrant for next population. GeneticEntity migrant = sortedEntities[sortedEntities.Count - entityIndex - 2]; migrantGeneticEntities[entityIndex] = migrant; // Remove the replaced entity. population.Entities.Remove(migrant); sortedEntities.Remove(migrant); } } Population firstPopulation = populations[0]; List <GeneticEntity> firstPopulationSortedEntities = firstPopulation.Entities.GetEntitiesSortedByFitness( this.SelectionOperator !.SelectionBasedOnFitnessType, this.FitnessEvaluator !.EvaluationMode).ToList(); // Use the migrants from the last population and migrate them to the first population. for (int entityIndex = 0; entityIndex < this.MigrantCount; entityIndex++) { // Add new migrant firstPopulation.Entities.Add(migrantGeneticEntities[entityIndex]); firstPopulationSortedEntities.Add(migrantGeneticEntities[entityIndex]); GeneticEntity replacedEntity = firstPopulationSortedEntities[firstPopulationSortedEntities.Count - entityIndex - 2]; // Remove the replaced entity. firstPopulation.Entities.Remove(replacedEntity); firstPopulationSortedEntities.Remove(replacedEntity); } }
/// <summary> /// Mutates each bit of a <see cref="IntegerListEntity"/> if it meets a certain /// probability. /// </summary> /// <param name="entity"><see cref="IntegerListEntity"/> to be mutated.</param> /// <returns>True if a mutation occurred; otherwise, false.</returns> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> protected override bool GenerateMutation(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } bool isMutated = false; IntegerListEntity listEntity = (IntegerListEntity)entity; for (int i = 0; i < listEntity.Length; i++) { if (RandomNumberService.Instance.GetDouble() <= this.MutationRate) { int currentValue = listEntity[i]; int randomValue = currentValue; while (randomValue == currentValue) { randomValue = RandomNumberService.Instance.GetRandomValue(listEntity.MinElementValue, listEntity.MaxElementValue + 1); } listEntity[i] = randomValue; isMutated = true; } } return(isMutated); }
/// <summary> /// Mutates each element of a <see cref="ListEntityBase"/> if it meets a certain /// probability. /// </summary> /// <param name="entity"><see cref="ListEntityBase"/> to be mutated.</param> /// <returns>True if a mutation occurred; otherwise, false.</returns> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> protected override bool GenerateMutation(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } ListEntityBase listEntity = (ListEntityBase)entity; if (RandomNumberService.Instance.GetDouble() <= this.MutationRate) { int firstPosition = RandomNumberService.Instance.GetRandomValue(listEntity.Length - 1); int secondPosition; do { secondPosition = RandomNumberService.Instance.GetRandomValue(listEntity.Length - 1); } while (secondPosition == firstPosition); object?firstValue = listEntity.GetValue(firstPosition); listEntity.SetValue(firstPosition, listEntity.GetValue(secondPosition)); listEntity.SetValue(secondPosition, firstValue); return(true); } return(false); }
public override Task <double> EvaluateFitnessAsync(GeneticEntity entity) { BinaryStringEntity binStrEntity = (BinaryStringEntity)entity; // The entity's fitness is equal to the number of "true" bits (a bit representing a 1 value) // it contains. return(Task.FromResult <double>(binStrEntity.Count(bit => bit == true))); }
/// <summary> /// Initializes a new instance of the <see cref="WheelSlice"/> class. /// </summary> /// <param name="entity">The <see cref="GeneticEntity"/> belonging to the wheel slice.</param> /// <param name="size">The value indicating how large the slice is on the wheel.</param> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="size"/> is less than.</exception> public WheelSlice(GeneticEntity entity, double size) { if (size < 0) { throw new ArgumentException(Resources.ErrorMsg_InvalidWheelSliceSize, nameof(size)); } this.Entity = entity ?? throw new ArgumentNullException(nameof(entity)); this.Size = size; }
// Start is called before the first frame update void Start() { GeneticEntity.SeedRandom(seed); soil = GetComponent <Soil>(); newBeds = new List <Bed>(); ResetPopulation(false); EventQueue.Subscribe(EventQueue.EventType.Plot_Start, EvolvePopulation); }
/// <summary> /// Returns the fitness value to base termination on. /// </summary> /// <param name="entity">The <see cref="GeneticEntity"/> whose appropriate fitness value should be returned.</param> /// <returns>The fitness value to base termination on.</returns> private double GetFitnessValue(GeneticEntity entity) { if (this.FitnessType == FitnessType.Raw) { return(entity.RawFitnessValue); } else { return(entity.ScaledFitnessValue); } }
public void ResetPopulation(bool shouldResetSeed) { if (shouldResetSeed) { GeneticEntity.SeedRandom(seed); } newBeds.Clear(); newBeds = CreateBeds(); generationNumber = 0; EventQueue.QueueEvent(EventQueue.EventType.Plot_Reset, this, new TimeArgs(Time.realtimeSinceStartup)); }
/// <summary> /// Copies the state from this object> to <paramref name="entity"/>. /// </summary> /// <param name="entity"><see cref="GeneticEntity"/> to which state is to be copied.</param> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> public override void CopyTo(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } TreeEntityBase treeEntity = (TreeEntityBase)entity; treeEntity.rootNode = this.rootNode?.Clone(treeEntity, null); base.CopyTo(entity); }
/// <summary> /// Sets the <see cref="GeneticEntity.ScaledFitnessValue"/> property of each entity /// in the <paramref name="population"/> by raising it to the power of <see cref="ScalingPower"/>. /// </summary> /// <param name="population"><see cref="Population"/> containing the <see cref="GeneticEntity"/> objects.</param> /// <exception cref="ArgumentNullException"><paramref name="population"/> is null.</exception> protected override void UpdateScaledFitnessValues(Population population) { if (population == null) { throw new ArgumentNullException(nameof(population)); } for (int i = 0; i < population.Entities.Count; i++) { GeneticEntity entity = population.Entities[i]; entity.ScaledFitnessValue = Math.Pow(entity.RawFitnessValue, this.ScalingPower); } }
/// <summary> /// Returns the sigma scaled fitness value of <paramref name="geneticEntity"/>. /// </summary> private double GetSigmaScaleValue(GeneticEntity geneticEntity, double mean, double standardDeviation) { // Goldberg, 1989 double val = geneticEntity.RawFitnessValue - (mean - this.Multiplier * standardDeviation); if (val < 0) { return(0); } else { return(val); } }
/// <summary> /// Mutates each bit of a <see cref="ListEntityBase"/> if it meets a certain /// probability. /// </summary> /// <param name="entity"><see cref="ListEntityBase"/> to be mutated.</param> /// <returns>True if a mutation occurred; otherwise, false.</returns> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> protected override bool GenerateMutation(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } ListEntityBase listEntity = (ListEntityBase)entity; if (RandomNumberService.Instance.GetDouble() <= this.MutationRate) { int firstPosition = RandomNumberService.Instance.GetRandomValue(listEntity.Length); int secondPosition; do { secondPosition = RandomNumberService.Instance.GetRandomValue(listEntity.Length); } while (secondPosition == firstPosition); if (firstPosition < secondPosition) { object?currentMovingValue = listEntity.GetValue(firstPosition); for (int i = firstPosition + 1; i <= secondPosition; i++) { object?savedValue = listEntity.GetValue(i); listEntity.SetValue(i, currentMovingValue); currentMovingValue = savedValue; } listEntity.SetValue(firstPosition, currentMovingValue); } else { object?currentMovingValue = listEntity.GetValue(firstPosition); for (int i = firstPosition - 1; i >= secondPosition; i--) { object?savedValue = listEntity.GetValue(i); listEntity.SetValue(i, currentMovingValue); currentMovingValue = savedValue; } listEntity.SetValue(firstPosition, currentMovingValue); } return(true); } return(false); }
/*public void FillBeds(int[] pChromosome = null) * { * for (int i = 0; i < beds.Count; i++) * { * int[] chromosome = pChromosome == null ? GeneticEntity.GenerateRandomChromosome(new Vector2Int(0, 4), patches.Length, seed) : pChromosome; * beds[i] = new Bed(chromosome, 0.0f, patches); * } * }*/ public List <Bed> CreateBeds(int[] pChromosome = null) { List <Bed> firstBeds = new List <Bed>(); for (int i = 0; i < numberOfBeds; i++) { Vector2Int alleleRange = new Vector2Int((int)testbench.AlleleLower, (int)testbench.AlleleUpper); int[] chromosome = pChromosome == null?GeneticEntity.GenerateRandomChromosome(alleleRange, patches.Length, seed) : pChromosome; firstBeds.Add(new Bed(chromosome, alleleRange, this, patches)); } initialised = true; //Debug.Log("Create " + firstBeds.Count + " beds."); return(firstBeds); }
/// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The /// return value has the following meanings: /// * Less than zero: This object is less than <paramref name="other"/>. /// * Zero: This object is equal to <paramref name="other"/>. /// * Greater than zero: This object is greater than <paramref name="other"/>. /// </returns> public override int CompareTo(GeneticEntity other) { if (other is null) { return(1); } if (!(other is ListEntityBase listEntityBase)) { throw new ArgumentException(StringUtil.GetFormattedString( Resources.ErrorMsg_ObjectIsWrongType, typeof(ListEntityBase)), nameof(other)); } return(ComparisonHelper.CompareLists(this, listEntityBase)); }
/// <summary> /// Copies the state from this object to <paramref name="entity"/>. /// </summary> /// <param name="entity"><see cref="GeneticEntity"/> to which state is to be copied.</param> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> public override void CopyTo(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } this.AssertIsInitialized(); base.CopyTo(entity); BinaryStringEntity binStrEntity = (BinaryStringEntity)entity; binStrEntity.genes = (BitArray)this.genes.Clone(); binStrEntity.UpdateStringRepresentation(); }
public void MutationOperator_Mutate() { GeneticAlgorithm algorithm = GetAlgorithm(.03); MockMutationOperator op = new MockMutationOperator(); op.Initialize(algorithm); GeneticEntity entity = new MockEntity(); entity.Initialize(algorithm); entity.Age = 10; GeneticEntity mutant = op.Mutate(entity); Assert.NotSame(entity, mutant); Assert.Equal(entity.Age, mutant.Age); Assert.Equal(1, op.DoMutateCallCount); }
public void InversionOperator_Mutate() { GeneticAlgorithm algorithm = new MockGeneticAlgorithm { SelectionOperator = new MockSelectionOperator(), PopulationSeed = new MockPopulation(), FitnessEvaluator = new MockFitnessEvaluator(), GeneticEntitySeed = new BinaryStringEntity { MinimumStartingLength = 4, MaximumStartingLength = 4 }, MutationOperator = new InversionOperator { MutationRate = 1 } }; algorithm.GeneticEntitySeed.Initialize(algorithm); InversionOperator op = (InversionOperator)algorithm.MutationOperator; op.Initialize(algorithm); BinaryStringEntity entity = (BinaryStringEntity)algorithm.GeneticEntitySeed.CreateNewAndInitialize(); entity.Age = 10; entity.Initialize(algorithm); entity[0] = true; entity[1] = true; entity[2] = false; entity[3] = true; FakeRandomUtil randomUtil = new FakeRandomUtil(); RandomNumberService.Instance = randomUtil; randomUtil.RandomValue = 1; GeneticEntity mutant = op.Mutate(entity); Assert.Equal("1011", mutant.Representation); Assert.Equal(0, mutant.Age); }
/// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The /// return value has the following meanings: /// * Less than zero: This object is less than <paramref name="other"/>. /// * Zero: This object is equal to <paramref name="other"/>. /// * Greater than zero: This object is greater than <paramref name="other"/>. /// </returns> public override int CompareTo(GeneticEntity other) { if (other is null) { return(1); } if (!(other is TreeEntityBase treeEntityBase)) { throw new ArgumentException(StringUtil.GetFormattedString( Resources.ErrorMsg_ObjectIsWrongType, typeof(TreeEntityBase)), nameof(other)); } List <TreeNode> thisTree = this.GetPrefixTree().ToList(); List <TreeNode> otherTree = treeEntityBase.GetPrefixTree().ToList(); return(ComparisonHelper.CompareLists( (IList)thisTree.Select(n => n.Value).ToList(), (IList)otherTree.Select(n => n.Value).ToList())); }
public override Task <double> EvaluateFitnessAsync(GeneticEntity entity) { BinaryStringEntity binaryEntity = (BinaryStringEntity)entity; int totalBitDiffs = 0; int minLength = Math.Min(binaryEntity.Length, this.TargetBinary.Length); for (int i = 0; i < minLength; i++) { bool bitValue = this.TargetBinary[i] == '0' ? false : true; if (binaryEntity[i] != bitValue) { totalBitDiffs++; } } // add the difference in size as part of the difference in bits totalBitDiffs += Math.Abs(binaryEntity.Length - this.TargetBinary.Length); return(Task.FromResult <double>(totalBitDiffs)); }
public void FitnessSharingScalingStrategy_Scale() { double scalingCurvature = .8; double scalingDistance = 3; GeneticAlgorithm algorithm = GetAlgorithm(scalingCurvature, scalingDistance); FakeFitnessSharingScalingStrategy strategy = (FakeFitnessSharingScalingStrategy)algorithm.FitnessScalingStrategy; strategy.Initialize(algorithm); SimplePopulation population = new SimplePopulation(); population.Initialize(algorithm); GeneticEntity entity1 = AddEntity(algorithm, population, 5); GeneticEntity entity2 = AddEntity(algorithm, population, 6); GeneticEntity entity3 = AddEntity(algorithm, population, 9); GeneticEntity entity4 = AddEntity(algorithm, population, 11.5); GeneticEntity entity5 = AddEntity(algorithm, population, 20); GeneticEntity entity6 = AddEntity(algorithm, population, 25); strategy.Scale(population); ValidateScale(entity1, 3.16); ValidateScale(entity2, 3.79); ValidateScale(entity3, 7.92); ValidateScale(entity4, 10.13); ValidateScale(entity5, 20); ValidateScale(entity6, 25); // Change the population size to verify fitness distances are recalculated GeneticEntity entity7 = AddEntity(algorithm, population, 10); strategy.Scale(population); ValidateScale(entity1, 1.84); ValidateScale(entity2, 2.21); ValidateScale(entity3, 5.37); ValidateScale(entity4, 4.73); ValidateScale(entity5, 20); ValidateScale(entity6, 25); ValidateScale(entity7, 4.6); }
public async Task UniformBitMutationOperator_Mutate() { MockGeneticAlgorithm algorithm = new MockGeneticAlgorithm { PopulationSeed = new MockPopulation(), SelectionOperator = new MockSelectionOperator(), FitnessEvaluator = new MockFitnessEvaluator2(), GeneticEntitySeed = new BinaryStringEntity { MinimumStartingLength = 4, MaximumStartingLength = 4 }, MutationOperator = new UniformBitMutationOperator { MutationRate = 1 } }; await algorithm.InitializeAsync(); UniformBitMutationOperator op = new UniformBitMutationOperator { MutationRate = 1 }; op.Initialize(algorithm); BinaryStringEntity entity = new BinaryStringEntity { MinimumStartingLength = 4, MaximumStartingLength = 4 }; entity.Age = 10; entity.Initialize(algorithm); entity[0] = true; entity[1] = true; entity[2] = false; entity[3] = true; GeneticEntity mutant = op.Mutate(entity); Assert.Equal("0010", mutant.Representation); Assert.Equal(0, mutant.Age); }
public void UniformIntegerMutationOperatorTest_Mutate() { MockGeneticAlgorithm algorithm = new MockGeneticAlgorithm { PopulationSeed = new MockPopulation(), SelectionOperator = new MockSelectionOperator(), FitnessEvaluator = new MockFitnessEvaluator(), GeneticEntitySeed = new IntegerListEntity { MinimumStartingLength = 4, MaximumStartingLength = 4, MaxElementValue = 2, MinElementValue = 1 }, MutationOperator = new UniformIntegerMutationOperator { MutationRate = 1 } }; UniformIntegerMutationOperator op = new UniformIntegerMutationOperator { MutationRate = 1 }; op.Initialize(algorithm); IntegerListEntity entity = new IntegerListEntity { MinimumStartingLength = 4, MaximumStartingLength = 4, MaxElementValue = 2, MinElementValue = 1 }; entity.Age = 10; entity.Initialize(algorithm); entity[0] = 1; entity[1] = 1; entity[2] = 2; entity[3] = 1; GeneticEntity mutant = op.Mutate(entity); Assert.Equal("2, 2, 1, 2", mutant.Representation); Assert.Equal(0, mutant.Age); }
public void RouletteWheelSampler_GetEntity_NoSizes() { MockGeneticAlgorithm algorithm = new MockGeneticAlgorithm { GeneticEntitySeed = new MockEntity(), SelectionOperator = new MockSelectionOperator(), FitnessEvaluator = new MockFitnessEvaluator(), PopulationSeed = new MockPopulation() }; List <WheelSlice> slices = new List <WheelSlice>(); MockEntity entity1 = new MockEntity(); entity1.Initialize(algorithm); MockEntity entity2 = new MockEntity(); entity2.Initialize(algorithm); MockEntity entity3 = new MockEntity(); entity3.Initialize(algorithm); MockEntity entity4 = new MockEntity(); entity4.Initialize(algorithm); slices.Add(new WheelSlice(entity1, 0)); slices.Add(new WheelSlice(entity2, 0)); slices.Add(new WheelSlice(entity3, 0)); slices.Add(new WheelSlice(entity4, 0)); TestRandomUtil randomUtil = new TestRandomUtil(); RandomNumberService.Instance = randomUtil; randomUtil.RandomValue = 2; GeneticEntity sampledEntity = RouletteWheelSampler.GetEntity(slices); Assert.Equal(4, randomUtil.MaxValuePassed); Assert.Same(entity3, sampledEntity); }
private static List <GeneticEntity> CreateMockNodes(List <Trait> traits) { var alice = new GeneticEntity("Alice", traits); var bob = new GeneticEntity("Bob", traits); var charlie = new GeneticEntity("Charlie", traits); var dave = new GeneticEntity("Dave", traits); var ethan = new GeneticEntity("Ethan", traits); var felix = new GeneticEntity("Felix", traits); alice.AddTrait(new Trait("Size 2", 0.125f)); var nodes = new List <GeneticEntity> { alice, bob, charlie, dave, ethan, felix }; return(nodes); }
protected override bool GenerateMutation(GeneticEntity entity) { bool isMutated = false; // In addition to the base mutation implementation, each bit has a // probability (equal to the mutation rate) of being removed. BinaryStringEntity binaryEntity = (BinaryStringEntity)entity; for (int i = binaryEntity.Length - 1; i >= 0; i--) { if (RandomNumberService.Instance.GetDouble() <= this.MutationRate) { binaryEntity.RemoveAt(i); isMutated = true; } } if (base.GenerateMutation(entity)) { isMutated = true; } return(isMutated); }
public override int CompareTo(GeneticEntity other) { throw new NotImplementedException(); }
public override int CompareTo(GeneticEntity other) { return(this.CompareFactor.CompareTo(((TestEntity)other).CompareFactor)); }
public override Task <double> EvaluateFitnessAsync(GeneticEntity entity) { return(Task.FromResult <double>(0)); }