forked from giacomelli/GeneticSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultOperatorsStrategy.cs
58 lines (53 loc) · 2.38 KB
/
DefaultOperatorsStrategy.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
using System.Collections.Generic;
using System.Linq;
using GeneticSharp.Domain.Chromosomes;
using GeneticSharp.Domain.Crossovers;
using GeneticSharp.Domain.Mutations;
using GeneticSharp.Domain.Populations;
using GeneticSharp.Domain.Randomizations;
namespace GeneticSharp.Domain
{
/// <summary>
/// Defines an operators strategy which use a linear execution
/// </summary>
public class DefaultOperatorsStrategy : IOperatorsStrategy
{
/// <summary>
/// Crosses the specified parents.
/// </summary>
/// <param name="crossover">The crossover class.</param>
/// <param name="crossoverProbability">The crossover probability.</param>
/// <param name="parents">The parents.</param>
/// <returns>The result chromosomes.</returns>
public IList<IChromosome> Cross(IPopulation population, ICrossover crossover, float crossoverProbability, IList<IChromosome> parents)
{
var minSize = population.MinSize;
var offspring = new List<IChromosome>(minSize);
for (int i = 0; i < minSize; i += crossover.ParentsNumber)
{
var selectedParents = parents.Skip(i).Take(crossover.ParentsNumber).ToList();
// If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
// Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
// have some rest chromosomes.
if (selectedParents.Count == crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= crossoverProbability)
{
offspring.AddRange(crossover.Cross(selectedParents));
}
}
return offspring;
}
/// <summary>
/// Mutate the specified chromosomes.
/// </summary>
/// <param name="mutation">The mutation class.</param>
/// <param name="mutationProbability">The mutation probability.</param>
/// <param name="chromosomes">The chromosomes.</param>
public void Mutate(IMutation mutation, float mutationProbability, IList<IChromosome> chromosomes)
{
for (int i = 0; i < chromosomes.Count; i++)
{
mutation.Mutate(chromosomes[i], mutationProbability);
}
}
}
}