#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.Data; using HeuristicLab.Encodings.BinaryVectorEncoding; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; namespace HeuristicLab.Algorithms.ScatterSearch.Knapsack { /// /// An operator that relinks paths between knapsack solutions. /// [Item("KnapsackPathRelinker", "An operator that relinks paths between knapsack solutions.")] [StorableClass] public sealed class KnapsackPathRelinker : PathRelinker { [StorableConstructor] private KnapsackPathRelinker(bool deserializing) : base(deserializing) { } private KnapsackPathRelinker(KnapsackPathRelinker original, Cloner cloner) : base(original, cloner) { } public KnapsackPathRelinker() : base() { ParentsParameter.ActualName = "KnapsackSolution"; } public override IDeepCloneable Clone(Cloner cloner) { return new KnapsackPathRelinker(this, cloner); } public static ItemArray Apply(IItem initiator, IItem guide, PercentValue n) { var v1 = initiator.Clone() as BinaryVector; var v2 = guide as BinaryVector; if (v1.Length != v2.Length) throw new ArgumentException("KnapsackPathRelinker: The solutions are of different length."); if (n.Value == 0.0) throw new ArgumentException("KnapsackPathRelinker: RelinkingAccuracy is 0."); var solutions = new List(); for (int i = 0; i < v1.Length; i++) { if (v1[i] != v2[i]) { v1[i] = v2[i]; solutions.Add((BinaryVector)v1.Clone()); } } var stepSize = 1 / n.Value; var selection = new List(); for (int i = 0; i < solutions.Count; i = (int)Math.Round(i + stepSize)) { selection.Add(solutions.ElementAt(i)); } return new ItemArray(selection); } protected override ItemArray Relink(ItemArray parents, PercentValue n) { if (parents.Length != 2) throw new ArgumentException("KnapsackPathRelinker: The number of parents is not equal to 2."); return Apply(parents[0], parents[1], n); } } }