using System.Collections.Generic; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Encodings.BinaryVectorEncoding; using HeuristicLab.Parameters; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; namespace HeuristicLab.Problems.NK { [Item("NK BitFlip Move Evaluator", "Evaluates a single bit flip on an NK landscape.")] [StorableClass] public class NKBitFlipMoveEvaluator : NKMoveEvaluator, IOneBitflipMoveOperator { public ILookupParameter OneBitflipMoveParameter { get { return (ILookupParameter)Parameters["OneBitflipMove"]; } } public LookupParameter MovedBinaryVectorParameter { get { return (LookupParameter)Parameters["MovedBinaryVector"]; } } [StorableConstructor] protected NKBitFlipMoveEvaluator(bool deserializing) : base(deserializing) { } protected NKBitFlipMoveEvaluator(NKBitFlipMoveEvaluator original, Cloner cloner) : base(original, cloner) { } public NKBitFlipMoveEvaluator() : base() { Parameters.Add(new LookupParameter("OneBitflipMove", "The move to evaluate.")); Parameters.Add(new LookupParameter("MovedBinaryVector", "The resulting binary vector after the move.")); } public override IDeepCloneable Clone(Cloner cloner) { return new NKBitFlipMoveEvaluator(this, cloner); } public override IOperation Apply() { BinaryVector binaryVector = BinaryVectorParameter.ActualValue; OneBitflipMove move = OneBitflipMoveParameter.ActualValue; BoolMatrix interactions = GeneInteractionsParameter.ActualValue; DoubleArray weights = WeightsParameter.ActualValue; int seed = InteractionSeedParameter.ActualValue.Value; double moveQuality = QualityParameter.ActualValue.Value; List affectedFitnessComponents = new List(); for (int c = 0; c < interactions.Columns; c++) if (interactions[move.Index, c]) affectedFitnessComponents.Add(c); BinaryVector moved = new BinaryVector(binaryVector); MovedBinaryVectorParameter.ActualValue = moved; moved[move.Index] = !moved[move.Index]; if (affectedFitnessComponents.Count * 2 > interactions.Columns) { double[] f_i; moveQuality = NKLandscapeNew.Evaluate(moved, interactions, weights, seed, out f_i); } else { long x = NKLandscapeNew.Encode(binaryVector); long y = NKLandscapeNew.Encode(moved); long[] g = NKLandscapeNew.Encode(interactions); double[] w = NKLandscapeNew.Normalize(weights); foreach (var c in affectedFitnessComponents) { moveQuality -= w[c % w.Length] * NKLandscapeNew.F_i(x, c, g[c], seed); moveQuality += w[c % w.Length] * NKLandscapeNew.F_i(y, c, g[c], seed); } } if (MoveQualityParameter.ActualValue == null) MoveQualityParameter.ActualValue = new DoubleValue(moveQuality); else MoveQualityParameter.ActualValue.Value = moveQuality; return base.Apply(); } } }