Skip to content

Commit

Permalink
Merge branch 'bugfix/fix-bugs' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
giacomelli committed Sep 10, 2022
2 parents e78e73c + 3d85583 commit 77fa88a
Show file tree
Hide file tree
Showing 24 changed files with 417 additions and 128 deletions.
3 changes: 3 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ Steps to reproduce the behavior:
**Expected behavior**
A clear and concise description of what you expected to happen.

**Sample code**
Provide a sample code exposing the bug.

**Screenshots**
If applicable, add screenshots to help explain your problem.

Expand Down
3 changes: 3 additions & 0 deletions .github/ISSUE_TEMPLATE/question.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ Did you search for your answer at GeneticSharp's Stack Overflow [tag](https://st

**Ask a question**
If you did not find your answer at wiki and Stack Overflow tag, please, describe your question.

** Sample code **
Provide a sample code of what you have tried so far.
16 changes: 16 additions & 0 deletions src/GeneticSharp.Benchmarks/SelectionsBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,21 @@ public ISelection Tournament()
target.SelectChromosomes(_chromosomesNumber, _generation);
return target;
}

[Benchmark]
public ISelection Rank()
{
var target = new RankSelection();
target.SelectChromosomes(_chromosomesNumber, _generation);
return target;
}

[Benchmark]
public ISelection Truncation()
{
var target = new TruncationSelection();
target.SelectChromosomes(_chromosomesNumber, _generation);
return target;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,22 +125,6 @@ public void ReplaceGenes_NullGenes_Exception()
});
}

[Test]
public void ReplaceGenes_GenesExceedChromosomeLength_Exception()
{
var target = Substitute.For<ChromosomeBase>(3);

Assert.Catch<ArgumentException>(() =>
{
target.ReplaceGenes(0, new Gene[] { new Gene(1), new Gene(2), new Gene(3), new Gene(4) });
}, "The number of genes to be replaced is greater than available space, there is 3 genes between the index 0 and the end of chromosome, but there is 4 genes to be replaced.");

Assert.Catch<ArgumentException>(() =>
{
target.ReplaceGenes(1, new Gene[] { new Gene(1), new Gene(2), new Gene(3) });
}, "The number of genes to be replaced is greater than available space, there is 2 genes between the index 1 and the end of chromosome, but there is 3 genes to be replaced.");
}

[Test]
public void ReplaceGenes_ValidIndex_Replaced()
{
Expand Down
11 changes: 10 additions & 1 deletion src/GeneticSharp.Domain.UnitTests/GeneticAlgorithmTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading.Tasks;
using NUnit.Framework;
using NSubstitute;
using System.Security.Cryptography;

namespace GeneticSharp.Domain.UnitTests
{
Expand Down Expand Up @@ -536,7 +537,15 @@ public void Start_UsingAllConfigurationCombinationsAvailable_AllRun()
target.Termination = new GenerationNumberTermination(25);
target.CrossoverProbability = reinsertion.CanExpand ? 0.75f : 1f;

target.Start();
try
{
target.Start();
}
catch(Exception ex)
{
throw new Exception($"GA start failed using selection:{s}, crossover:{c}, mutation:{m} and reinsertion:{r}. Error: {ex.Message}", ex);
}

Assert.AreEqual(25, target.Population.Generations.Count);
}
}
Expand Down
32 changes: 32 additions & 0 deletions src/GeneticSharp.Domain.UnitTests/Populations/PopulationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,38 @@ public void EndCurrentGeneration_BestChromosomeChanged_ChangeEventRaise()

Assert.IsTrue(eventRaise);
}

/// <summary>
/// https://github.com/giacomelli/GeneticSharp/issues/70
/// </summary>
[Test]
public void EndCurrentGeneration_Issue70_Solved()
{
var target = new Population(100, 100, new ChromosomeStub());

var eventRaise = false;
IChromosome lastChromosome = null;

target.BestChromosomeChanged += (e, a) =>
{
eventRaise = true;

if (lastChromosome != null && lastChromosome.Fitness == target.BestChromosome.Fitness)
Assert.Fail("BestChromosomeChanged should only be raised if fitness is different.");

lastChromosome = target.BestChromosome;
};

target.CreateInitialGeneration();
target.CurrentGeneration.Chromosomes.Each(c => c.Fitness = 0);
target.CurrentGeneration.Chromosomes[1].Fitness = 1;
target.EndCurrentGeneration();

target.CurrentGeneration.Chromosomes[0].Fitness = 1;
target.EndCurrentGeneration();

Assert.IsTrue(eventRaise);
}
}
}

59 changes: 51 additions & 8 deletions src/GeneticSharp.Domain.UnitTests/Selections/EliteSelectionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
using System.Collections.Generic;
using NUnit.Framework;
using NSubstitute;
using System.Linq;

namespace GeneticSharp.Domain.UnitTests.Selections
{
[TestFixture()]
[Category("Selections")]
public class EliteSelectionTest
{
[Test()]
[Test]
public void SelectChromosomes_InvalidNumber_Exception()
{
var target = new EliteSelection();
Expand All @@ -30,7 +31,7 @@ public void SelectChromosomes_InvalidNumber_Exception()
}, "The number of selected chromosomes should be at least 2.");
}

[Test()]
[Test]
public void SelectChromosomes_NullGeneration_Exception()
{
var target = new EliteSelection();
Expand All @@ -43,7 +44,7 @@ public void SelectChromosomes_NullGeneration_Exception()
Assert.AreEqual("generation", actual.ParamName);
}

[Test()]
[Test]
public void SelectChromosomes_Generation_ChromosomesSelected()
{
var target = new EliteSelection();
Expand All @@ -59,22 +60,64 @@ public void SelectChromosomes_Generation_ChromosomesSelected()
var c4 = Substitute.ForPartsOf<ChromosomeBase>(2);
c4.Fitness = 0.7;

var generation = new Generation(1, new List<IChromosome>() {
var generation1 = new Generation(1, new List<IChromosome>() {
c1, c2, c3
});

var generation2 = new Generation(1, new List<IChromosome>() {
c1, c2, c3, c4
});


var actual = target.SelectChromosomes(2, generation);
var actual = target.SelectChromosomes(2, generation1);
Assert.AreEqual(2, actual.Count);
Assert.AreEqual(0.7, actual[0].Fitness);
Assert.AreEqual(0.5, actual[1].Fitness);
Assert.AreEqual(0.5, actual[0].Fitness);
Assert.AreEqual(0.1, actual[1].Fitness);

actual = target.SelectChromosomes(3, generation);
actual = target.SelectChromosomes(3, generation2);
Assert.AreEqual(3, actual.Count);
Assert.AreEqual(0.7, actual[0].Fitness);
Assert.AreEqual(0.5, actual[1].Fitness);
Assert.AreEqual(0.1, actual[2].Fitness);
}

/// <summary>
/// https://github.com/giacomelli/GeneticSharp/issues/72
/// </summary>
[Test]
public void SelectChromosomes_Issue72_Solved()
{
var target = new EliteSelection();
var chromosomes = new IChromosome[10];

for (int i = 0; i < chromosomes.Length; i++)
{
var c = Substitute.ForPartsOf<ChromosomeBase>(2);
c.Fitness = i;
chromosomes[i] = c;
}

var generation3 = new Generation(3, chromosomes.Take(4).ToList());
var generation2 = new Generation(2, chromosomes.Skip(4).Take(3).ToList());
var generation1 = new Generation(1, chromosomes.Skip(7).Take(3).ToList());


var actual = target.SelectChromosomes(2, generation1);
Assert.AreEqual(2, actual.Count);
Assert.AreEqual(9, actual[0].Fitness);
Assert.AreEqual(8, actual[1].Fitness);

actual = target.SelectChromosomes(3, generation2);
Assert.AreEqual(3, actual.Count);
Assert.AreEqual(9, actual[0].Fitness);
Assert.AreEqual(6, actual[1].Fitness);
Assert.AreEqual(5, actual[2].Fitness);

actual = target.SelectChromosomes(2, generation3);
Assert.AreEqual(2, actual.Count);
Assert.AreEqual(9, actual[0].Fitness);
Assert.AreEqual(3, actual[1].Fitness);
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using NUnit.Framework;
using NSubstitute;
using GeneticSharp.Extensions;
using NSubstitute.Routing.Handlers;

namespace GeneticSharp.Domain.UnitTests.Selections
{
Expand All @@ -17,7 +18,7 @@ public void Cleanup()
RandomizationProvider.Current = new BasicRandomization();
}

[Test()]
[Test]
public void SelectChromosomes_InvalidNumber_Exception()
{
var target = new RankSelection();
Expand All @@ -38,7 +39,7 @@ public void SelectChromosomes_InvalidNumber_Exception()
}, "The number of selected chromosomes should be at least 2.");
}

[Test()]
[Test]
public void SelectChromosomes_NullGeneration_Exception()
{
var target = new RankSelection();
Expand All @@ -51,7 +52,7 @@ public void SelectChromosomes_NullGeneration_Exception()
Assert.AreEqual("generation", actual.ParamName);
}

[Test()]
[Test]
public void SelectChromosomes_Generation_ChromosomesSelected()
{
var target = new RankSelection();
Expand Down Expand Up @@ -157,7 +158,7 @@ public void SelectChromosomes_NullFitness_Exception()
Assert.AreEqual("RankSelection: There are chromosomes with null fitness.", actual.Message);
}

[Test()]
[Test]
public void SelectChromosomes_Generation_ChromosomesZeroFitness()
{
var target = new RankSelection();
Expand All @@ -179,6 +180,6 @@ public void SelectChromosomes_Generation_ChromosomesZeroFitness()

var actual = target.SelectChromosomes(2, generation);
Assert.AreEqual(2, actual.Count);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NSubstitute;
using GeneticSharp.Extensions;

namespace GeneticSharp.Domain.UnitTests.Selections
{
[TestFixture()]
[Category("Selections")]
public class SelectionIssuesTest
{
[SetUp]
public void Cleanup()
{
RandomizationProvider.Current = new BasicRandomization();
}

/// <summary>
/// https://github.com/giacomelli/GeneticSharp/issues/92
/// </summary>
[Test]
[TestCase("Rank")]
[TestCase("Roulette Wheel")]
[TestCase("Tournament")]
public void SelectChromosomes_Issue92_Solved(string selectionName)
{
var target = SelectionService.CreateSelectionByName(selectionName);
var c1 = new SelectionStubChromosome();
c1.Fitness = 1;

var c2 = new SelectionStubChromosome();
var c3 = new SelectionStubChromosome();
var c4 = new SelectionStubChromosome();

var generation = new Generation(1, new List<IChromosome>() {
c1, c2, c3, c4
});

var actual = target.SelectChromosomes(10, generation);
Assert.AreEqual(10, actual.Count);

var previousChromosomes = actual.Select(c => c.GetGenes().ToArray()).ToArray();
var mutation = new UniformMutation(true);


for (int i = 0; i < actual.Count; i++)
{
if (actual[i].Fitness == 1)
{
mutation.Mutate(actual[i], 1);

Assert.AreEqual(1, actual.Count(c => c.GetGene(0).Value != null), "Mutation has changed more than one chromosome at the time");
break;
}
}

for (int i = 0; i < actual.Count; i++)
{
for (int j = 0; j < actual.Count; j++)
{
if (i == j)
continue;

if (object.ReferenceEquals(actual[i], actual[j]))
Assert.Fail($"Chromosomes on index {i} and {j} are the same.");
}
}
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,27 @@ public void GetSelectionTypes_NoArgs_AllAvailableSelections()
{
var actual = SelectionService.GetSelectionTypes();

Assert.AreEqual(5, actual.Count);
Assert.AreEqual(6, actual.Count);
Assert.AreEqual(typeof(EliteSelection), actual[0]);
Assert.AreEqual(typeof(RankSelection), actual[1]);
Assert.AreEqual(typeof(RouletteWheelSelection), actual[2]);
Assert.AreEqual(typeof(StochasticUniversalSamplingSelection), actual[3]);
Assert.AreEqual(typeof(TournamentSelection), actual[4]);

Assert.AreEqual(typeof(TruncationSelection), actual[5]);
}

[Test()]
public void GetSelectionNames_NoArgs_AllAvailableSelectionsNames()
{
var actual = SelectionService.GetSelectionNames();

Assert.AreEqual(5, actual.Count);
Assert.AreEqual(6, actual.Count);
Assert.AreEqual("Elite", actual[0]);
Assert.AreEqual("Rank", actual[1]);
Assert.AreEqual("Roulette Wheel", actual[2]);
Assert.AreEqual("Stochastic Universal Sampling", actual[3]);
Assert.AreEqual("Tournament", actual[4]);
Assert.AreEqual("Truncation", actual[5]);
}

[Test()]
Expand All @@ -48,7 +49,7 @@ public void CreateSelectionByName_ValidNameButInvalidConstructorArgs_Exception()
{
Assert.Catch<ArgumentException>(() =>
{
SelectionService.CreateSelectionByName("Elite", 1);
SelectionService.CreateSelectionByName("Elite", 1, 2);
}, "A ISelection's implementation with name 'Elite' was found, but seems the constructor args were invalid.");
}

Expand Down
Loading

0 comments on commit 77fa88a

Please sign in to comment.