#region License Information
/* HeuristicLab
* Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
namespace HeuristicLab.Encodings.DecisionList.Crossover {
[Item("SinglePointCrossover", "Description missing")]
[StorableClass]
public class SinglePointCrossover : DecisionListCrossover {
#region Parameter Properties
#endregion
[StorableConstructor]
protected SinglePointCrossover(bool deserializing) : base(deserializing) { }
protected SinglePointCrossover(SinglePointCrossover original, Cloner cloner)
: base(original, cloner) {
}
public SinglePointCrossover()
: base() {
}
public override IDeepCloneable Clone(Cloner cloner) {
return new SinglePointCrossover(this, cloner);
}
public static DecisionList Apply(IRandom random, DecisionList parent1, DecisionList parent2) {
if (parent1 == null && parent1 != parent2) { throw new ArgumentException("Either both parents have a default action or none does."); }
if (parent1.DefaultAction != null && !parent1.DefaultAction.Match(parent2.DefaultAction)) { throw new ArgumentException("Default action of parents have to match!"); }
int rulesP1 = random.Next(0, parent1.Rules.Count());
int rulesP2 = random.Next(0, parent2.Rules.Count());
var rules = new List(rulesP1 + rulesP2);
for (int i = 0; i < rulesP1; i++) {
rules.Add((Rule)parent1.Rules[i].Clone());
}
rules.Add(parent1.Rules[rulesP1].Crossover(parent2.Rules[rulesP2], random));
for (int i = rulesP2 + 1; i < parent2.Rules.Count(); i++) {
rules.Add((Rule)parent2.Rules[i].Clone());
}
if (parent1.DefaultAction == null) {
return new DecisionList(rules);
}
return new DecisionList(rules, parent1.DefaultAction);
}
protected override DecisionList Cross(IRandom random, ItemArray parents) {
if (parents.Length != 2) throw new ArgumentException("ERROR in SinglePointCrossover: The number of parents is not equal to 2");
return Apply(random, parents[0], parents[1]);
}
}
}