#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 HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Encodings.BinaryVectorEncoding;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
namespace HeuristicLab.Algorithms.ScatterSearch.Knapsack {
///
/// N child crossover for binary vectors.
///
[Item("NChildCrossover", "N child crossover for binary vectors.")]
[StorableClass]
public sealed class NChildCrossover : NBinaryVectorCrossover {
public IValueLookupParameter NParameter {
get { return (IValueLookupParameter)Parameters["N"]; }
}
[StorableConstructor]
private NChildCrossover(bool deserializing) : base(deserializing) { }
private NChildCrossover(NChildCrossover original, Cloner cloner) : base(original, cloner) { }
public NChildCrossover()
: base() {
Parameters.Add(new ValueLookupParameter("N", "Number of children.", new IntValue(2)));
}
public override IDeepCloneable Clone(Cloner cloner) {
return new NChildCrossover(this, cloner);
}
public static ItemArray Apply(IRandom random, BinaryVector parent1, BinaryVector parent2, IntValue n) {
if (parent1.Length != parent2.Length)
throw new ArgumentException("NPointCrossover: The parents are of different length.");
if (n.Value > Math.Pow(2, parent1.Length) - 2)
throw new ArgumentException("NPointCrossover: There cannot be more breakpoints than the size of the parents.");
if (n.Value < 1)
throw new ArgumentException("NPointCrossover: N cannot be < 1.");
var solutions = new BinaryVector[n.Value];
for (int i = 0; i < n.Value; i++) {
var solution = new BinaryVector(parent1.Length);
for (int j = 0; j < solution.Length; j++) {
solution[j] = random.Next(2) % 2 == 0 ? parent1[j] : parent2[j];
}
solutions[i] = solution;
}
return new ItemArray(solutions);
}
protected override ItemArray Cross(IRandom random, ItemArray parents) {
if (parents.Length != 2) throw new ArgumentException("ERROR in NChildCrossover: The number of parents is not equal to 2");
if (NParameter.ActualValue == null) throw new InvalidOperationException("NChildCrossover: Parameter " + NParameter.ActualName + " could not be found.");
return Apply(random, parents[0], parents[1], NParameter.Value);
}
}
}