forked from giacomelli/GeneticSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FitnessStagnationTermination.cs
72 lines (64 loc) · 2.46 KB
/
FitnessStagnationTermination.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System.ComponentModel;
namespace GeneticSharp
{
/// <summary>
/// Fitness Stagnation Termination.
/// <remarks>
/// The genetic algorithm will be terminate when the best chromosome's fitness has no change in the last generations specified.
/// </remarks>
/// </summary>
[DisplayName("Fitness Stagnation")]
public class FitnessStagnationTermination : TerminationBase
{
#region Fields
private double m_lastFitness;
private int m_stagnantGenerationsCount;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="FitnessStagnationTermination"/> class.
/// </summary>
/// <remarks>
/// The ExpectedStagnantGenerationsNumber default value is 100.
/// </remarks>
public FitnessStagnationTermination() : this(100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FitnessStagnationTermination"/> class.
/// </summary>
/// <param name="expectedStagnantGenerationsNumber">The expected stagnant generations number to reach the termination.</param>
public FitnessStagnationTermination(int expectedStagnantGenerationsNumber)
{
ExpectedStagnantGenerationsNumber = expectedStagnantGenerationsNumber;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the expected stagnant generations number to reach the termination.
/// </summary>
public int ExpectedStagnantGenerationsNumber { get; set; }
#endregion
#region Methods
/// <summary>
/// Determines whether the specified geneticAlgorithm reached the termination condition.
/// </summary>
/// <returns>True if termination has been reached, otherwise false.</returns>
/// <param name="geneticAlgorithm">The genetic algorithm.</param>
protected override bool PerformHasReached(IGeneticAlgorithm geneticAlgorithm)
{
var bestFitness = geneticAlgorithm.BestChromosome.Fitness.Value;
if (m_lastFitness == bestFitness)
{
m_stagnantGenerationsCount++;
}
else
{
m_stagnantGenerationsCount = 1;
}
m_lastFitness = bestFitness;
return m_stagnantGenerationsCount >= ExpectedStagnantGenerationsNumber;
}
#endregion
}
}