#region License Information
/* HeuristicLab
* Copyright (C) 2002-2016 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 HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Encodings.PermutationEncoding;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.Problems.QuadraticAssignment;
using HeuristicLab.Random;
using System;
using System.Collections.Generic;
using System.Linq;
namespace HeuristicLab.Problems.CharacteristicAnalysis.QAP {
[Item("Directed Walk (QAP-specific)", "")]
[StorableClass]
public class QAPDirectedWalk : CharacteristicCalculator {
public IFixedValueParameter PathsParameter {
get { return (IFixedValueParameter)Parameters["Paths"]; }
}
public IFixedValueParameter BestImprovementParameter {
get { return (IFixedValueParameter)Parameters["BestImprovement"]; }
}
public IValueParameter SeedParameter {
get { return (IValueParameter)Parameters["Seed"]; }
}
public int Paths {
get { return PathsParameter.Value.Value; }
set { PathsParameter.Value.Value = value; }
}
public bool BestImprovement {
get { return BestImprovementParameter.Value.Value; }
set { BestImprovementParameter.Value.Value = value; }
}
public int? Seed {
get { return SeedParameter.Value != null ? SeedParameter.Value.Value : (int?)null; }
set { SeedParameter.Value = value.HasValue ? new IntValue(value.Value) : null; }
}
[StorableConstructor]
private QAPDirectedWalk(bool deserializing) : base(deserializing) { }
private QAPDirectedWalk(QAPDirectedWalk original, Cloner cloner) : base(original, cloner) { }
public QAPDirectedWalk() {
characteristics.AddRange(new[] { "Swap2.Sharpness", "Swap2.Bumpiness", "Swap2.Flatness", "Swap2.Steadiness" }
.Select(x => new StringValue(x)).ToList());
Parameters.Add(new FixedValueParameter("Paths", "The number of paths to explore (a path is a set of solutions that connect two randomly chosen solutions).", new IntValue(50)));
Parameters.Add(new FixedValueParameter("BestImprovement", "Whether the best of all alternatives should be chosen for each step in the path or just the first improving (least degrading) move should be made.", new BoolValue(true)));
Parameters.Add(new OptionalValueParameter("Seed", "The seed for the random number generator."));
}
public override IDeepCloneable Clone(Cloner cloner) {
return new QAPDirectedWalk(this, cloner);
}
public override bool CanCalculate() {
return Problem is QuadraticAssignmentProblem;
}
public override IEnumerable Calculate() {
var pathCount = Paths;
var random = Seed.HasValue ? new MersenneTwister((uint)Seed.Value) : new MersenneTwister();
var bestImprovement = BestImprovement;
var qap = (QuadraticAssignmentProblem)Problem;
var N = qap.Weights.Rows;
var start = new Permutation(PermutationTypes.Absolute, N, random);
var end = start;
List ips = new List(), ups = new List(), sd2 = new List();
var pathsD1 = new List>>();
for (var i = 0; i < pathCount; i++) {
var trajD1 = new List>();
pathsD1.Add(trajD1);
if ((i + 1) % N == 0) {
start = new Permutation(PermutationTypes.Absolute, N, random);
end = start;
}
end = (Permutation)end.Clone();
Rot1(end);
var hist = new Tuple[5];
var walkDist = 0.0;
var prevVal = double.NaN;
var sumD2 = 0.0;
var inflectionPoints = 0;
var undulationPoints = 0;
var countPoints = 0;
var counter = 0;
var path = bestImprovement ? BestImprovementWalk(qap, start, QAPEvaluator.Apply(start, qap.Weights, qap.Distances), end)
: FirstImprovementWalk(qap, start, QAPEvaluator.Apply(start, qap.Weights, qap.Distances), end, random);
foreach (var next in path) {
if (hist[0] != null) {
var dist = Dist(next.Item1, hist[0].Item1);
walkDist += dist;
}
// from the past 5 values we can calculate the 2nd derivative
// first derivative in point 2 as differential between points 1 and 3
// first derivative in point 4 as differential between points 3 and 5
// second derivative in point 3 as differential between the first derivatives in points 2 and 4
hist[4] = hist[3];
hist[3] = hist[2];
hist[2] = hist[1];
hist[1] = hist[0];
hist[0] = next;
counter++;
if (counter < 3) continue;
var grad1 = (hist[0].Item2 - hist[2].Item2) / Dist(hist[0].Item1, hist[2].Item1);
if (!double.IsNaN(grad1) && !double.IsInfinity(grad1))
trajD1.Add(Tuple.Create(walkDist, grad1));
if (counter < 5) continue;
countPoints++;
var grad2 = (hist[2].Item2 - hist[4].Item2) / Dist(hist[2].Item1, hist[4].Item1);
var dgrad = (grad1 - grad2) / Dist(hist[1].Item1, hist[3].Item1);
if (double.IsNaN(dgrad) || double.IsInfinity(dgrad)) continue;
if (!double.IsNaN(prevVal)) {
if (prevVal < 0 && dgrad > 0 || prevVal > 0 && dgrad < 0)
inflectionPoints++;
else if (prevVal.IsAlmost(0) && dgrad.IsAlmost(0)
|| prevVal.IsAlmost(0) && !dgrad.IsAlmost(0)
|| !prevVal.IsAlmost(0) && dgrad.IsAlmost(0))
undulationPoints++;
}
sumD2 += Math.Abs(grad1 - grad2);
prevVal = dgrad;
}
start = end;
ips.Add(inflectionPoints / (double)countPoints);
ups.Add(undulationPoints / (double)countPoints);
sd2.Add(sumD2 / walkDist);
} // end paths
var avgZero = pathsD1.Select(path => path.SkipWhile(v => v.Item2 < 0).First().Item1 / path.Last().Item1).Median();
foreach (var chara in characteristics.CheckedItems.Select(x => x.Value.Value)) {
if (chara == "Swap2.Sharpness") yield return new Result("Swap2.Sharpness", new DoubleValue(sd2.Average()));
if (chara == "Swap2.Bumpiness") yield return new Result("Swap2.Bumpiness", new DoubleValue(ips.Average()));
if (chara == "Swap2.Flatness") yield return new Result("Swap2.Flatness", new DoubleValue(ups.Average()));
if (chara == "Swap2.Steadiness") yield return new Result("Swap2.Steadiness", new DoubleValue(avgZero));
}
}
public IEnumerable> BestImprovementWalk(QuadraticAssignmentProblem qap, Permutation start, double fitness, Permutation end) {
var N = qap.Weights.Rows;
var sol = start;
var invSol = GetInverse(sol);
// we require at most N-1 steps to move from one permutation to another
for (var step = 0; step < N - 1; step++) {
var bestFitness = double.MaxValue;
var bestIndex = -1;
sol = (Permutation)sol.Clone();
for (var index = 0; index < N; index++) {
if (sol[index] == end[index]) continue;
var fit = QAPSwap2MoveEvaluator.Apply(sol, new Swap2Move(index, invSol[end[index]]), qap.Weights, qap.Distances);
if (fit < bestFitness) { // QAP is minimization
bestFitness = fit;
bestIndex = index;
}
}
if (bestIndex >= 0) {
var prev = sol[bestIndex];
Swap2Manipulator.Apply(sol, bestIndex, invSol[end[bestIndex]]);
fitness += bestFitness;
yield return Tuple.Create(sol, fitness);
invSol[prev] = invSol[end[bestIndex]];
invSol[sol[bestIndex]] = bestIndex;
} else break;
}
}
public IEnumerable> FirstImprovementWalk(QuadraticAssignmentProblem qap, Permutation start, double fitness, Permutation end, IRandom random) {
var N = qap.Weights.Rows;
var sol = start;
var invSol = GetInverse(sol);
// randomize the order in which improvements are tried
var order = Enumerable.Range(0, N).Shuffle(random).ToArray();
// we require at most N-1 steps to move from one permutation to another
for (var step = 0; step < N - 1; step++) {
var bestFitness = double.MaxValue;
var bestIndex = -1;
sol = (Permutation)sol.Clone();
for (var i = 0; i < N; i++) {
var index = order[i];
if (sol[index] == end[index]) continue;
var fit = QAPSwap2MoveEvaluator.Apply(sol, new Swap2Move(index, invSol[end[index]]), qap.Weights, qap.Distances);
if (fit < bestFitness) { // QAP is minimization
bestFitness = fit;
bestIndex = index;
if (bestFitness < 0) break;
}
}
if (bestIndex >= 0) {
var prev = sol[bestIndex];
Swap2Manipulator.Apply(sol, bestIndex, invSol[end[bestIndex]]);
fitness += bestFitness;
yield return Tuple.Create(sol, fitness);
invSol[prev] = invSol[end[bestIndex]];
invSol[sol[bestIndex]] = bestIndex;
} else break;
}
}
private static double Dist(Permutation a, Permutation b) {
return a.Where((t, i) => t != b[i]).Count();
}
private static int[] GetInverse(Permutation p) {
var inv = new int[p.Length];
for (var i = 0; i < p.Length; i++) inv[p[i]] = i;
return inv;
}
private static void Rot1(Permutation p) {
var first = p[0];
for (var i = 0; i < p.Length - 1; i++) p[i] = p[i + 1];
p[p.Length - 1] = first;
}
}
}