Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2457_ExpertSystem/WalkExporter/RandomWalk.cs @ 17712

Last change on this file since 17712 was 16955, checked in by abeham, 6 years ago

#2457: worked on thesis

File size: 8.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.IO;
25using System.Linq;
26using HeuristicLab.Analysis.FitnessLandscape;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.PermutationEncoding;
29using HeuristicLab.Problems.Instances;
30using HeuristicLab.Problems.Instances.QAPLIB;
31using HeuristicLab.Random;
32using ProtoBuf;
33
34namespace WalkExporter {
35  class RandomWalk {
36    public static (Knowledgebase training, Knowledgebase test) GetKnowledgeBases(Experiment experiment, int length) {
37      var training = new Knowledgebase() { Problems = new List<ProblemInstanceDescriptor>() };
38      var test = new Knowledgebase() { Problems = new List<ProblemInstanceDescriptor>() };
39      foreach (var trial in experiment.Trials) {
40        foreach (var desc in AnalyzeEachWalk(trial, length)) {
41          if (training.Problems.Count == test.Problems.Count)
42            training.Problems.Add(desc);
43          else test.Problems.Add(desc);
44        }
45      }
46      return (training, test);
47    }
48
49    private static IEnumerable<ProblemInstanceDescriptor> AnalyzeEachWalk(Exploration trial, int length) {
50      var instance = trial.Problem;
51      var dim = trial.Dimension;
52      foreach (var walk in trial.Walks) {
53        var trail = walk.QualityTrail.Take(length).ToArray();
54        var clen = RuggednessCalculator.CalculateCorrelationLength(trail, out double[] acf);
55        var ia = new InformationAnalysis(trail);
56        var desc = new ProblemInstanceDescriptor() {
57          Name = instance,
58          Class = Util.GetGeneratorClass(instance),
59          Dimension = dim,
60          DescriptionEffort = length * 4.0 / dim,
61        };
62        desc.Features = new List<KeyValue>();
63        desc.Features.Add(new KeyValue { Key = "AC1", ContinuousValue = acf[1] });
64        desc.Features.Add(new KeyValue { Key = "CorrelationLength", DiscreteValue = clen });
65        foreach (var f in ia.GetFeatures()) {
66          if (f.Item2 is double d) desc.Features.Add(new KeyValue { Key = f.Item1, ContinuousValue = d });
67          else if (f.Item2 is int i) desc.Features.Add(new KeyValue { Key = f.Item1, DiscreteValue = i });
68        }
69        yield return desc;
70      }
71    }
72
73    public static Experiment PerformExperiment() {
74      var experiment = new Experiment() { Algorithm = "RandomWalk", Trials = new List<Exploration>() };
75      foreach (var dimension in new[] { 20, 30, 40 }) {
76        var provider = new OneSizeInstanceProvider(dimension);
77        foreach (var desc in provider.GetDataDescriptors()) {
78          var qapData = provider.LoadData(desc);
79          var exploration = new Exploration() { Problem = qapData.Name, Dimension = qapData.Dimension, Walks = new List<Walk>() };
80          for (var r = 0; r < 2; r++) {
81            var walk = RandomWalk.Run(new MersenneTwister((uint)(r + 13)), qapData).Take((int)Math.Pow(2, 18)).ToList();
82            exploration.Walks.Add(new Walk() { QualityTrail = walk });
83          }
84          experiment.Trials.Add(exploration);
85        }
86      }
87      return experiment;
88    }
89
90    public static IEnumerable<double> Run(IRandom random, QAPData qap) {
91      var sol = new Permutation(PermutationTypes.Absolute, qap.Dimension, random);
92      var fit = Util.Evaluate(sol, qap);
93      yield return fit;
94      while (true) {
95        var z1 = random.Next(qap.Dimension);
96        var z2 = (z1 + random.Next(1, qap.Dimension)) % qap.Dimension;
97        var move = Util.EvaluateSwap2Diff(sol, z1, z2, qap);
98        fit += move;
99        yield return fit;
100        sol.Swap(z1, z2);
101      }
102    }
103
104    ///////////////////////////////////////////////////////////////////////////////////
105    ///                             CONFINED RANDOM WALK                            ///
106    ///////////////////////////////////////////////////////////////////////////////////
107
108   
109    public static void ConfinedRandomWalkAnalysis(QAPData qapData) {
110      Exploration exploration = null;
111      if (File.Exists($"confinedrandwalk_{qapData.Name}.buf")) {
112        using (var file = File.OpenRead($"confinedrandwalk_{qapData.Name}.buf")) {
113          exploration = Serializer.Deserialize<Exploration>(file);
114        }
115      } else {
116        exploration = PerformCondinedRandomwWalkExploration(qapData, 100);
117        using (var file = File.Create($"confinedrandwalk_{qapData.Name}.buf")) {
118          Serializer.Serialize(file, exploration);
119        }
120      }
121
122      using (var writer = File.CreateText($"confinedrandwalk_{qapData.Name}.csv")) {
123        var headers = new[] { "Run", "Algorithm Name", "Problem Name", "Dimension", "Ld(Iterations)", "Iterations", "Effort",
124          "AC1", "CorrelationLength", "InformationContent", "DensityBasinInformation", "PartialInformationContent",
125          "InformationStability", "Diversity", "Regularity", "TotalEntropy", "SymmetricInformationContent",
126          "SymmetricDensityBasinInformation", "SymmetricTotalEntropy", "PeakInformationContent", "PeakDensityBasinInformation",
127          "PeakTotalEntropy", "PeakSymmetricInformationContent", "PeakSymmetricDensityBasinInformation", "PeakSymmetricTotalEntropy" };
128        var order = headers.Select((v, i) => new { Index = i, Header = v }).ToDictionary(x => x.Header, x => x.Index);
129        writer.WriteLine(string.Format(string.Join(";", Enumerable.Range(0, headers.Length).Select(x => "{" + x + "}")), headers));
130        foreach (var exp in Enumerable.Range(7, 18 - 6)) {
131          var length = (int)Math.Pow(2, exp);
132          var run = 0;
133          foreach (var desc in AnalyzeEachWalk(exploration, length)) {
134            var features = string.Join(";", desc.Features.OrderBy(x => order[x.Key]).Select(x => x.GetNumericValue().ToString()));
135            writer.WriteLine(string.Format("R{0};Confined Random Walk;{5};{6};{1};{2};{3};{4}", run, exp, length, length * 4.0 / qapData.Dimension, features, qapData.Name, qapData.Dimension));
136            run++;
137          }
138        }
139      }
140    }
141
142    private static Exploration PerformCondinedRandomwWalkExploration(QAPData qapData, int repetitions) {
143      var exploration = new Exploration() { Problem = qapData.Name, Dimension = qapData.Dimension, Walks = new List<Walk>() };
144      for (var r = 0; r < repetitions; r++) {
145        var walk = RunConfined(new MersenneTwister((uint)r), qapData, qapData.Dimension / 5).Take((int)Math.Pow(2, 18)).ToList();
146        exploration.Walks.Add(new Walk() { QualityTrail = walk });
147      }
148      return exploration;
149    }
150
151    public static IEnumerable<double> RunConfined(IRandom random, QAPData qap, int distance) {
152      var sol = new Permutation(PermutationTypes.Absolute, qap.Dimension, random);
153      var anchor = (Permutation)sol.Clone();
154      var fit = Util.Evaluate(sol, qap);
155      var dist = 0;
156      yield return fit;
157
158      while (true) {
159        var (j, k, deltaDist) = MoveConfined(random, sol, anchor, dist, distance);
160        dist += deltaDist;
161        var move = Util.EvaluateSwap2Diff(sol, j, k, qap);
162        fit += move;
163        yield return fit;
164        sol.Swap(j, k);
165      }
166    }
167
168    private static (int j, int k, int deltaDist) MoveConfined(IRandom random, Permutation current, Permutation anchor, int dist, int maxDist) {
169      var evalSolPerMove = 4.0 / current.Length;
170      var orderJ = Enumerable.Range(0, current.Length).Shuffle(random);
171      var orderK = Enumerable.Range(0, current.Length).Shuffle(random);
172      foreach (var j in orderJ) {
173        if (dist == maxDist && current[j] == anchor[j]) continue;
174        foreach (var k in orderK) {
175          if (j == k) continue;
176          var distChange = 0;
177          if (current[j] != anchor[j] && current[k] == anchor[j]) distChange--;
178          if (current[k] != anchor[k] && current[j] == anchor[k]) distChange--;
179          if (current[j] == anchor[j]) distChange++;
180          if (current[k] == anchor[k]) distChange++;
181          if (dist + distChange > maxDist) continue;
182
183          return (j, k, distChange);
184        }
185      }
186      return (-1, -1, 0);
187    }
188  }
189}
Note: See TracBrowser for help on using the repository browser.