Skip to content

Commit

Permalink
#119 - Initialize Stopwatch on constructor to allow resuming algorith…
Browse files Browse the repository at this point in the history
…ms using a population that is not in the first generation (#120)

Co-authored-by: elpht <[email protected]>
  • Loading branch information
elpht and elpht authored Mar 21, 2024
1 parent dd2aaec commit 5081577
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
36 changes: 36 additions & 0 deletions src/GeneticSharp.Domain.UnitTests/GeneticAlgorithmTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -858,6 +858,42 @@ public void Resume_TerminationReachedAndTerminationExtend_Resumed()
Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
Assert.IsFalse(target.IsRunning);
}

[Test]
public void Resume_PopulationFromAnotherGeneticAlgorithm_Resumed()
{
// Arrange
var selection = new EliteSelection();
var crossover = new OnePointCrossover(2);
var mutation = new UniformMutation();
var chromosome = new ChromosomeStub();
var population = new Population(100, 199, chromosome)
{
GenerationStrategy = new TrackingGenerationStrategy()
};
var fitnessStub = new FitnessStub { SupportsParallel = false };

// initialize a GA and run it for 100 generations
var initialGeneticAlgorithm = new GeneticAlgorithm(population, fitnessStub, selection, crossover, mutation)
{
Termination = new GenerationNumberTermination(100)
};
initialGeneticAlgorithm.Start();

// initialize a new GA with the same population to run it for 100 generations more
var target = new GeneticAlgorithm(population, fitnessStub, selection, crossover, mutation)
{
Termination = new GenerationNumberTermination(200)
};

// Act
target.Resume();

// Assert
Assert.AreEqual(200, target.Population.Generations.Count);
Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
Assert.IsFalse(target.IsRunning);
}

}
}
Expand Down
4 changes: 2 additions & 2 deletions src/GeneticSharp.Domain/GeneticAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public sealed class GeneticAlgorithm : IGeneticAlgorithm
private bool m_stopRequested;
private readonly object m_lock = new object();
private GeneticAlgorithmState m_state;
private Stopwatch m_stopwatch;
private readonly Stopwatch m_stopwatch = new Stopwatch();
#endregion

#region Constructors
Expand Down Expand Up @@ -258,7 +258,7 @@ public void Start()
lock (m_lock)
{
State = GeneticAlgorithmState.Started;
m_stopwatch = Stopwatch.StartNew();
m_stopwatch.Restart();
Population.CreateInitialGeneration();
m_stopwatch.Stop();
TimeEvolving = m_stopwatch.Elapsed;
Expand Down

0 comments on commit 5081577

Please sign in to comment.