Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/GeneticSharp.Domain/Chromosomes/IChromosome.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;

namespace GeneticSharp
namespace GeneticSharp
{
/// <summary>
/// Defines an interface for a chromosome.
Expand Down
47 changes: 47 additions & 0 deletions src/GeneticSharp.Domain/Mutations/DeletionMutation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeneticSharp.Domain.Mutations
{
/// <summary>
/// Replaces a gene with the supplied replacement gene, which should do nothing. Useful for search criteria allowing for a wider search space.
/// </summary>
public class DeletionMutation :MutationBase
{
private Gene _replacementGene;

public DeletionMutation(Gene replacementGene) :base()
{
_replacementGene = replacementGene;
}

protected override void PerformMutate(IChromosome chromosome, float probability)
{
ValidateLength(chromosome);

if (RandomizationProvider.Current.GetDouble() <= probability)
{
int deletionIndex = RandomizationProvider.Current.GetInt(0, chromosome.Length-1);

chromosome.ReplaceGene(deletionIndex, _replacementGene);


}
}

/// <summary>
/// Validate length of the chromosome.
/// </summary>
/// <param name="chromosome">The chromosome.</param>
protected virtual void ValidateLength(IChromosome chromosome)
{
if (chromosome.Length < 3)
{
throw new MutationException(this, "A chromosome should have, at least, 3 genes. {0} has only {1} gene.".With(chromosome.GetType().Name, chromosome.Length));
}
}
}
}
35 changes: 35 additions & 0 deletions src/GeneticSharp.Domain/Mutations/RandomMutation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeneticSharp.Domain.Mutations
{
/// <summary>
/// Performs a random mutation of one supplied.
/// </summary>
public class RandomMutation : IMutation
{
private readonly bool _isOrdered;
private readonly IMutation[] _mutations;
private RandomMutation() { }

public RandomMutation(bool isOrdered, params IMutation[] mutations)
{
_isOrdered = isOrdered;
_mutations = mutations;

if (_mutations.Length == 0) { throw new ArgumentException("Requires at least one mutation type."); }
}
public bool IsOrdered => _isOrdered;

public void Mutate(IChromosome chromosome, float probability)
{
int i = Random.Shared.Next(0, _mutations.Length);
_mutations[i].Mutate(chromosome, probability);


}
}
}