forked from giacomelli/GeneticSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniformCrossover.cs
80 lines (74 loc) · 3.1 KB
/
UniformCrossover.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
73
74
75
76
77
78
79
80
using System.Collections.Generic;
using System.ComponentModel;
using GeneticSharp.Domain.Chromosomes;
using GeneticSharp.Domain.Randomizations;
namespace GeneticSharp.Domain.Crossovers
{
/// <summary>
/// The Uniform Crossover uses a fixed mixing ratio between two parents.
/// Unlike one-point and two-point crossover, the Uniform Crossover enables the parent chromosomes to contribute the gene level rather than the segment level.
/// <remarks>
/// If the mix probability is 0.5, the offspring has approximately half of the genes from first parent and the other half from second parent, although cross over points can be randomly chosen.
/// </remarks>
/// <see href="http://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)#Uniform_Crossover_and_Half_Uniform_Crossover">Wikipedia</see>
/// </summary>
[DisplayName("Uniform")]
public class UniformCrossover : CrossoverBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="GeneticSharp.Domain.Crossovers.UniformCrossover"/> class.
/// </summary>
/// <param name="mixProbability">The mix probability. he default mix probability is 0.5.</param>
public UniformCrossover(float mixProbability)
: base(2, 2)
{
MixProbability = mixProbability;
}
/// <summary>
/// Initializes a new instance of the <see cref="GeneticSharp.Domain.Crossovers.UniformCrossover"/> class.
/// <remarks>
/// The default mix probability is 0.5.
/// </remarks>
/// </summary>
public UniformCrossover() : this(0.5f)
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the mix probability.
/// </summary>
/// <value>The mix probability.</value>
public float MixProbability { get; set; }
#endregion
#region Methods
/// <summary>
/// Performs the cross with specified parents generating the children.
/// </summary>
/// <param name="parents">The parents chromosomes.</param>
/// <returns>The offspring (children) of the parents.</returns>
protected override IList<IChromosome> PerformCross(IList<IChromosome> parents)
{
var firstParent = parents[0];
var secondParent = parents[1];
var firstChild = firstParent.CreateNew();
var secondChild = secondParent.CreateNew();
for (int i = 0; i < firstParent.Length; i++)
{
if (RandomizationProvider.Current.GetDouble() < MixProbability)
{
firstChild.ReplaceGene(i, firstParent.GetGene(i));
secondChild.ReplaceGene(i, secondParent.GetGene(i));
}
else
{
firstChild.ReplaceGene(i, secondParent.GetGene(i));
secondChild.ReplaceGene(i, firstParent.GetGene(i));
}
}
return new List<IChromosome> { firstChild, secondChild };
}
#endregion
}
}