From 508157785ba0797bfc781e1b9b2a9b428bcee514 Mon Sep 17 00:00:00 2001 From: elpht Date: Thu, 21 Mar 2024 10:25:15 +0100 Subject: [PATCH] #119 - Initialize Stopwatch on constructor to allow resuming algorithms using a population that is not in the first generation (#120) Co-authored-by: elpht --- .../GeneticAlgorithmTest.cs | 36 +++++++++++++++++++ src/GeneticSharp.Domain/GeneticAlgorithm.cs | 4 +-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/GeneticSharp.Domain.UnitTests/GeneticAlgorithmTest.cs b/src/GeneticSharp.Domain.UnitTests/GeneticAlgorithmTest.cs index 0d5cbb94..8510393d 100644 --- a/src/GeneticSharp.Domain.UnitTests/GeneticAlgorithmTest.cs +++ b/src/GeneticSharp.Domain.UnitTests/GeneticAlgorithmTest.cs @@ -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); + } } } diff --git a/src/GeneticSharp.Domain/GeneticAlgorithm.cs b/src/GeneticSharp.Domain/GeneticAlgorithm.cs index ab00a849..9c3ac3ed 100644 --- a/src/GeneticSharp.Domain/GeneticAlgorithm.cs +++ b/src/GeneticSharp.Domain/GeneticAlgorithm.cs @@ -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 @@ -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;