Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.OptimizationExpertSystem.Common/3.3/KnowledgeCenter.cs @ 13878

Last change on this file since 13878 was 13878, checked in by abeham, 8 years ago

#2457: added standardization of features for recommendation and using log10 of the expected runtime for clustering

File size: 43.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 HeuristicLab.Analysis;
23using HeuristicLab.Analysis.SelfOrganizingMaps;
24using HeuristicLab.Collections;
25using HeuristicLab.Common;
26using HeuristicLab.Common.Resources;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.MainForm;
30using HeuristicLab.Optimization;
31using HeuristicLab.Persistence.Default.Xml;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Random;
34using System;
35using System.Collections.Generic;
36using System.Drawing;
37using System.IO;
38using System.Linq;
39using System.Threading;
40using System.Threading.Tasks;
41using Algorithm = HeuristicLab.Clients.OKB.Administration.Algorithm;
42using Problem = HeuristicLab.Clients.OKB.Administration.Problem;
43using RunCreationClient = HeuristicLab.Clients.OKB.RunCreation.RunCreationClient;
44using SingleObjectiveOKBProblem = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBProblem;
45using SingleObjectiveOKBSolution = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBSolution;
46
47namespace HeuristicLab.OptimizationExpertSystem.Common {
48  [Item("Knowledge Center", "Currently in experimental phase, an expert system that makes algorithm suggestions based on fitness landscape analysis features and an optimization knowledge base.")]
49  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 119)]
50  public sealed class KnowledgeCenter : IContent {
51    private bool SuppressEvents { get; set; }
52
53    public string Filename { get; set; }
54
55    public static Image StaticItemImage {
56      get { return VSImageLibrary.Library; }
57    }
58
59    private readonly IntValue maximumEvaluations;
60    public IntValue MaximumEvaluations {
61      get { return maximumEvaluations; }
62    }
63
64    private readonly DoubleValue minimumTarget;
65    public DoubleValue MinimumTarget {
66      get { return minimumTarget; }
67    }
68   
69    private readonly RunCollection instanceRuns;
70    public RunCollection InstanceRuns {
71      get { return instanceRuns; }
72    }
73
74    private readonly RunCollection seededRuns;
75    public RunCollection SeededRuns {
76      get { return seededRuns; }
77    }
78
79    private readonly RunCollection knowledgeBase;
80    public RunCollection KnowledgeBase {
81      get { return knowledgeBase; }
82    }
83
84    private readonly SingleObjectiveOKBProblem problem;
85    public SingleObjectiveOKBProblem Problem {
86      get { return problem; }
87    }
88
89    private readonly ItemList<IAlgorithm> algorithmInstances;
90    private readonly ReadOnlyItemList<IAlgorithm> readonlyAlgorithmInstances;
91    public ReadOnlyItemList<IAlgorithm> AlgorithmInstances {
92      get { return readonlyAlgorithmInstances; }
93    }
94
95    private readonly RunCollection problemInstances;
96    public RunCollection ProblemInstances {
97      get { return problemInstances; }
98    }
99
100    private IRecommendationModel recommendationModel;
101    public IRecommendationModel RecommendationModel {
102      get { return recommendationModel; }
103      set {
104        if (recommendationModel == value) return;
105        recommendationModel = value;
106        OnRecommenderModelChanged();
107      }
108    }
109
110    private readonly CheckedItemList<IScope> solutionSeedingPool;
111    public CheckedItemList<IScope> SolutionSeedingPool {
112      get { return solutionSeedingPool; }
113    }
114
115    private readonly EnumValue<SeedingStrategyTypes> seedingStrategy;
116    public EnumValue<SeedingStrategyTypes> SeedingStrategy {
117      get { return seedingStrategy; }
118    }
119   
120    private BidirectionalLookup<long, IRun> algorithmId2RunMapping;
121    private BidirectionalDictionary<long, IAlgorithm> algorithmId2AlgorithmInstanceMapping;
122    private BidirectionalDictionary<long, IRun> problemId2ProblemInstanceMapping;
123   
124    public bool Maximization {
125      get { return Problem != null && Problem.ProblemId >= 0 && ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; }
126    }
127
128    public KnowledgeCenter() {
129      maximumEvaluations = new IntValue(10000);
130      minimumTarget = new DoubleValue(0.05);
131      instanceRuns = new RunCollection();
132      seededRuns = new RunCollection();
133      knowledgeBase = new RunCollection();
134      algorithmInstances = new ItemList<IAlgorithm>();
135      readonlyAlgorithmInstances = algorithmInstances.AsReadOnly();
136      problemInstances = new RunCollection();
137      recommendationModel = FixedRankModel.GetEmpty();
138      problem = new SingleObjectiveOKBProblem();
139      algorithmId2RunMapping = new BidirectionalLookup<long, IRun>();
140      algorithmId2AlgorithmInstanceMapping = new BidirectionalDictionary<long, IAlgorithm>();
141      problemId2ProblemInstanceMapping = new BidirectionalDictionary<long, IRun>();
142      solutionSeedingPool = new CheckedItemList<IScope>();
143      seedingStrategy = new EnumValue<SeedingStrategyTypes>(SeedingStrategyTypes.NoSeeding);
144      RegisterEventHandlers();
145    }
146
147    private void ProblemOnProblemChanged(object sender, EventArgs eventArgs) {
148      // TODO: Potentially, knowledge base has to be re-downloaded
149    }
150
151    private void RegisterEventHandlers() {
152      maximumEvaluations.ValueChanged += MaximumEvaluationsOnValueChanged;
153      minimumTarget.ValueChanged += MinimumTargetOnValueChanged;
154      problem.ProblemChanged += ProblemOnProblemChanged;
155      problem.Solutions.ItemsAdded += ProblemSolutionsChanged;
156      problem.Solutions.ItemsReplaced += ProblemSolutionsChanged;
157      problem.Solutions.ItemsRemoved += ProblemSolutionsChanged;
158      problem.Solutions.CollectionReset += ProblemSolutionsChanged;
159      instanceRuns.CollectionReset += InformationChanged;
160      instanceRuns.ItemsAdded += InformationChanged;
161      instanceRuns.ItemsRemoved += InformationChanged;
162      instanceRuns.Reset += InformationChanged;
163      instanceRuns.UpdateOfRunsInProgressChanged += InformationChanged;
164      knowledgeBase.CollectionReset += InformationChanged;
165      knowledgeBase.ItemsAdded += InformationChanged;
166      knowledgeBase.ItemsRemoved += InformationChanged;
167    }
168
169    private void MaximumEvaluationsOnValueChanged(object sender, EventArgs eventArgs) {
170
171    }
172
173    private void MinimumTargetOnValueChanged(object sender, EventArgs e) {
174
175    }
176
177    private void ProblemSolutionsChanged(object sender, EventArgs e) {
178      foreach (var sol in Problem.Solutions.Select(x => x.Solution).OfType<IScope>()) {
179        if (!SolutionSeedingPool.Contains(sol))
180          SolutionSeedingPool.Add(sol, false);
181      }
182    }
183
184    private void InformationChanged(object sender, EventArgs e) {
185      var runCollection = sender as RunCollection;
186      if (runCollection != null && runCollection.UpdateOfRunsInProgress) return;
187    }
188   
189    public bool IsCurrentInstance(IRun run) {
190      if (!problemId2ProblemInstanceMapping.ContainsSecond(run)) return false;
191      return problemId2ProblemInstanceMapping.GetBySecond(run) == Problem.ProblemId;
192    }
193
194    public void UpdateInstanceProjection(string[] characteristics) {
195      if (characteristics.Length == 0) return;
196
197      var instances = GetProblemCharacteristics(characteristics);
198
199      var key2Idx = new BidirectionalDictionary<IRun, int>();
200      foreach (var kvp in instances.Select((k, i) => new { Index = i, Key = k.Key }))
201        key2Idx.Add(kvp.Key, kvp.Index);
202
203      #region MDS
204      Func<double[], double[], double> euclid = (a, b) => Math.Sqrt(a.Zip(b, (x, y) => (x - y)).Sum(x => x * x));
205      var num = instances.Count;
206      var matrix = new DoubleMatrix(num, num);
207      for (var i = 0; i < num - 1; i++) {
208        for (var j = i + 1; j < num; j++) {
209          matrix[i, j] = matrix[j, i] = euclid(instances[key2Idx.GetBySecond(i)], instances[key2Idx.GetBySecond(j)]);
210        }
211      }
212
213      var coords = MultidimensionalScaling.KruskalShepard(matrix);
214      #endregion
215      #region PCA
216      double[,] v = null;
217      var ds = new double[instances.Count, characteristics.Length];
218      if (characteristics.Length > 1) {
219        foreach (var instance in instances) {
220          var arr = instance.Value;
221          for (var feature = 0; feature < arr.Length; feature++)
222            ds[key2Idx.GetByFirst(instance.Key), feature] = arr[feature];
223        }
224
225        int info;
226        double[] s2;
227        alglib.pcabuildbasis(ds, ds.GetLength(0), ds.GetLength(1), out info, out s2, out v);
228      }
229      #endregion
230      #region SOM
231      var features = new DoubleMatrix(characteristics.Length, instances.Count);
232      foreach (var instance in instances) {
233        var arr = instance.Value;
234        for (var feature = 0; feature < arr.Length; feature++)
235          features[feature, key2Idx.GetByFirst(instance.Key)] = arr[feature];
236      }
237      var somCoords = SOM.Map(features, new MersenneTwister(42), somSize: 10, learningRadius: 20, iterations: 200, jittering: true);
238      #endregion
239
240      ProblemInstances.UpdateOfRunsInProgress = true;
241      try {
242        foreach (var instance in ProblemInstances) {
243          IItem item;
244          if (v != null) {
245            double x = 0, y = 0;
246            for (var feature = 0; feature < ds.GetLength(1); feature++) {
247              x += ds[key2Idx.GetByFirst(instance), feature] * v[feature, 0];
248              y += ds[key2Idx.GetByFirst(instance), feature] * v[feature, 1];
249            }
250
251            if (instance.Results.TryGetValue("Projection.PCA.X", out item)) {
252              ((DoubleValue)item).Value = x;
253            } else instance.Results.Add("Projection.PCA.X", new DoubleValue(x));
254            if (instance.Results.TryGetValue("Projection.PCA.Y", out item)) {
255              ((DoubleValue)item).Value = y;
256            } else instance.Results.Add("Projection.PCA.Y", new DoubleValue(y));
257          } else {
258            instance.Results.Remove("Projection.PCA.X");
259            instance.Results.Remove("Projection.PCA.Y");
260          }
261
262          if (instance.Results.TryGetValue("Projection.MDS.X", out item)) {
263            ((DoubleValue)item).Value = coords[key2Idx.GetByFirst(instance), 0];
264          } else instance.Results.Add("Projection.MDS.X", new DoubleValue(coords[key2Idx.GetByFirst(instance), 0]));
265          if (instance.Results.TryGetValue("Projection.MDS.Y", out item)) {
266            ((DoubleValue)item).Value = coords[key2Idx.GetByFirst(instance), 1];
267          } else instance.Results.Add("Projection.MDS.Y", new DoubleValue(coords[key2Idx.GetByFirst(instance), 1]));
268
269          if (instance.Results.TryGetValue("Projection.SOM.X", out item)) {
270            ((DoubleValue)item).Value = somCoords[key2Idx.GetByFirst(instance), 0];
271          } else instance.Results.Add("Projection.SOM.X", new DoubleValue(somCoords[key2Idx.GetByFirst(instance), 0]));
272          if (instance.Results.TryGetValue("Projection.SOM.Y", out item)) {
273            ((DoubleValue)item).Value = somCoords[key2Idx.GetByFirst(instance), 1];
274          } else instance.Results.Add("Projection.SOM.Y", new DoubleValue(somCoords[key2Idx.GetByFirst(instance), 1]));
275        }
276      } finally { ProblemInstances.UpdateOfRunsInProgress = false; }
277    }
278
279    private static readonly HashSet<string> InterestingValueNames = new HashSet<string>() {
280      "QualityPerEvaluations", "Problem Name", "Problem Type", "Algorithm Name", "Algorithm Type", "Maximization", "BestKnownQuality"
281    };
282
283    public Task<ResultCollection> StartAlgorithmAsync(int index) {
284      return StartAlgorithmAsync(index, CancellationToken.None);
285    }
286
287    public Task<ResultCollection> StartAlgorithmAsync(int index, CancellationToken cancellation) {
288      var selectedInstance = algorithmInstances[index];
289      var algorithmClone = (IAlgorithm)selectedInstance.Clone();
290      var problemClone = Problem.CloneProblem() as ISingleObjectiveHeuristicOptimizationProblem;
291      if (problemClone == null) throw new InvalidOperationException("Problem is not of type " + typeof(ISingleObjectiveHeuristicOptimizationProblem).FullName);
292      // TODO: It is assumed the problem instance by default is configured using no preexisting solution creator
293      var seedingStrategyLocal = SeedingStrategy.Value;
294      if (seedingStrategyLocal != SeedingStrategyTypes.NoSeeding) {
295        if (!SolutionSeedingPool.CheckedItems.Any()) throw new InvalidOperationException("There are no solutions selected for seeding.");
296        // TODO: It would be necessary to specify the solution creator somewhere (property and GUI)
297        var seedingCreator = problemClone.Operators.OfType<IPreexistingSolutionCreator>().FirstOrDefault();
298        if (seedingCreator == null) throw new InvalidOperationException("The problem does not contain a solution creator that allows seeding.");
299        seedingCreator.PreexistingSolutionsParameter.Value.Replace(SolutionSeedingPool.CheckedItems.Select(x => x.Value));
300        seedingCreator.SampleFromPreexistingParameter.Value.Value = seedingStrategyLocal == SeedingStrategyTypes.SeedBySampling;
301        // TODO: WHY!? WHY??!?
302        ((dynamic)problemClone.SolutionCreatorParameter).Value = (dynamic)seedingCreator;
303      }
304      algorithmClone.Problem = problemClone;
305      algorithmClone.Prepare(true);
306      IParameter stopParam;
307      var monitorStop = true;
308      if (algorithmClone.Parameters.TryGetValue("MaximumEvaluations", out stopParam)) {
309        var maxEvalParam = stopParam as IValueParameter<Data.IntValue>;
310        if (maxEvalParam != null) {
311          maxEvalParam.Value.Value = MaximumEvaluations.Value;
312          monitorStop = false;
313        }
314      }
315
316      // TODO: The following can be simplified when we have async implementation patterns for our algorithms:
317      // TODO: The closures can be removed and replaced with private member methods
318      var waitHandle = new AutoResetEvent(false);
319
320      #region EventHandler closures
321      EventHandler exeStateChanged = (sender, e) => {
322        if (algorithmClone.ExecutionState == ExecutionState.Stopped) {
323          lock (Problem.Solutions) {
324            foreach (var solution in algorithmClone.Results.Where(x => x.Name.ToLower().Contains("solution")).Select(x => x.Value).OfType<IScope>()) {
325              Problem.Solutions.Add(new SingleObjectiveOKBSolution(Problem.ProblemId) {
326                Quality = solution.Variables.ContainsKey(Problem.Problem.Evaluator.QualityParameter.ActualName) ? ((DoubleValue)solution.Variables[Problem.Problem.Evaluator.QualityParameter.ActualName].Value).Value : double.NaN,
327                Solution = (IItem)solution.Clone()
328              });
329            }
330          }
331          if (seedingStrategyLocal == SeedingStrategyTypes.NoSeeding) {
332            lock (InstanceRuns) {
333              InstanceRuns.Add(algorithmClone.Runs.Last());
334            }
335          } else {
336            lock (SeededRuns) {
337              SeededRuns.Add(algorithmClone.Runs.Last());
338            }
339          }
340          waitHandle.Set();
341        }
342      };
343
344      EventHandler<EventArgs<Exception>> exceptionOccurred = (sender, e) => {
345        waitHandle.Set();
346      };
347
348      EventHandler timeChanged = (sender, e) => {
349        IResult evalSolResult;
350        if (!algorithmClone.Results.TryGetValue("EvaluatedSolutions", out evalSolResult) || !(evalSolResult.Value is Data.IntValue)) return;
351        var evalSols = ((Data.IntValue)evalSolResult.Value).Value;
352        if (evalSols >= MaximumEvaluations.Value && algorithmClone.ExecutionState == ExecutionState.Started)
353          algorithmClone.Stop();
354      };
355      #endregion
356
357      algorithmClone.ExecutionStateChanged += exeStateChanged;
358      algorithmClone.ExceptionOccurred += exceptionOccurred;
359      if (monitorStop) algorithmClone.ExecutionTimeChanged += timeChanged;
360
361      return Task.Factory.StartNew(() => {
362        algorithmClone.Start();
363        OnAlgorithmInstanceStarted(algorithmClone);
364        var cancelRequested = false;
365        while (!waitHandle.WaitOne(200)) {
366          if (cancellation.IsCancellationRequested) {
367            cancelRequested = true;
368            break;
369          }
370        }
371        if (cancelRequested) {
372          try { algorithmClone.Stop(); } catch { } // ignore race condition if it is stopped in the meantime
373          waitHandle.WaitOne();
374        }
375        waitHandle.Dispose();
376        return algorithmClone.Results;
377      }, TaskCreationOptions.LongRunning);
378    }
379
380    public ResultCollection StartAlgorithm(int index, CancellationToken cancellation) {
381      var task = StartAlgorithmAsync(index, cancellation);
382      task.Wait(cancellation);
383      return task.Result;
384    }
385
386    public Task UpdateKnowledgeBaseAsync(IProgress progress = null) {
387      if (progress == null) progress = new Progress(string.Empty);
388      progress.Start("Updating Knowledge Base from OKB");
389      OnDownloadStarted(progress);
390      return Task.Factory.StartNew(() => { DoUpdateKnowledgeBase(progress); }, TaskCreationOptions.LongRunning);
391    }
392
393    public void UpdateKnowledgeBase(IProgress progress = null) {
394      UpdateKnowledgeBaseAsync(progress).Wait();
395    }
396
397    private void DoUpdateKnowledgeBase(IProgress progress) {
398      var queryClient = Clients.OKB.Query.QueryClient.Instance;
399      var adminClient = Clients.OKB.Administration.AdministrationClient.Instance;
400      try {
401        progress.Status = "Connecting to OKB...";
402        progress.ProgressValue = 0;
403        // FIXME: How to tell if refresh is necessary?
404        var refreshTasks = new[] {
405          Task.Factory.StartNew(() => queryClient.Refresh()),
406          Task.Factory.StartNew(() => adminClient.Refresh())
407        };
408        Task.WaitAll(refreshTasks);
409
410        var probInstance = adminClient.Problems.SingleOrDefault(x => x.Id == Problem.ProblemId);
411        if (probInstance == null) throw new InvalidOperationException("The chosen problem instance cannot be found in the OKB.");
412        var probClassId = probInstance.ProblemClassId;
413
414        var problemClassFilter = (Clients.OKB.Query.StringComparisonAvailableValuesFilter)queryClient.Filters.Single(x => x.Label == "Problem Class Name");
415        problemClassFilter.Value = adminClient.ProblemClasses.Single(x => x.Id == probClassId).Name;
416
417        problemId2ProblemInstanceMapping.Clear();
418        progress.Status = "Downloading algorithm and problem instances...";
419        progress.ProgressValue = 0;
420
421        int[] p = { 0 };
422        ProblemInstances.UpdateOfRunsInProgress = true;
423        ProblemInstances.Clear();
424        algorithmId2AlgorithmInstanceMapping.Clear();
425        algorithmId2RunMapping.Clear();
426        algorithmInstances.Clear();
427
428        var characteristics = new HashSet<string>();
429        var totalProblems = adminClient.Problems.Count(x => x.ProblemClassId == probClassId);
430        var totalAlgorithms = adminClient.Algorithms.Count;
431        var problems = adminClient.Problems.Where(x => x.ProblemClassId == probClassId);
432        var algorithms = adminClient.Algorithms;
433        var combined = problems.Cast<object>().Concat(algorithms.Cast<object>()).Shuffle(new MersenneTwister());
434        Parallel.ForEach(combined, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, (inst) => {
435          var pInst = inst as Clients.OKB.Administration.Problem;
436          if (pInst != null) DownloadProblemInstance(progress, pInst, p, totalProblems + totalAlgorithms, characteristics);
437          else {
438            var aInst = inst as Clients.OKB.Administration.Algorithm;
439            DownloadAlgorithmInstance(progress, aInst, p, totalProblems + totalAlgorithms);
440          }
441        });
442
443        var interestingValues = queryClient.ValueNames.Where(x => InterestingValueNames.Contains(x.Name)).ToList();
444
445        progress.Status = "Downloading runs...";
446        progress.ProgressValue = 0;
447        p[0] = 0;
448        var count = queryClient.GetNumberOfRuns(problemClassFilter);
449        if (count == 0) return;
450       
451        var runList = new List<IRun>();
452        var runIds = LoadRunsFromCache(queryClient.GetRunIds(problemClassFilter), runList, progress);
453        var batches = runIds.Select((v, i) => new { Idx = i, Val = v }).GroupBy(x => x.Idx / 500, x => x.Val);
454        Parallel.ForEach(batches.Select(x => x.ToList()), new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4) },
455          (batch) => {
456          var okbRuns = queryClient.GetRunsWithValues(batch, true, interestingValues);
457          var hlRuns = okbRuns.AsParallel().Select(x => new { AlgorithmId = x.Algorithm.Id, RunId = x.Id, Run = queryClient.ConvertToOptimizationRun(x) }).ToList();
458          lock (runList) {
459            var toCache = new List<Tuple<long, long, IRun>>();
460            foreach (var r in hlRuns) {
461              algorithmId2RunMapping.Add(r.AlgorithmId, r.Run);
462              runList.Add(r.Run);
463              toCache.Add(Tuple.Create(r.AlgorithmId, r.RunId, r.Run));
464            }
465            SaveToCache(toCache);
466            progress.Status = string.Format("Downloaded runs {0} to {1} of {2}...", p[0], p[0] + batch.Count, count);
467            p[0] += batch.Count;
468            progress.ProgressValue = p[0] / (double)count;
469          }
470        });
471        progress.Status = "Finishing...";
472
473        // remove algorithm instances that do not appear in any downloaded run
474        for (var algIdx = 0; algIdx < algorithmInstances.Count; algIdx++) {
475          var id = algorithmId2AlgorithmInstanceMapping.GetBySecond(algorithmInstances[algIdx]);
476          if (!algorithmId2RunMapping.ContainsFirst(id)) {
477            algorithmId2AlgorithmInstanceMapping.RemoveByFirst(id);
478            algorithmInstances.RemoveAt(algIdx);
479            algIdx--;
480          }
481        }
482       
483        try {
484          KnowledgeBase.UpdateOfRunsInProgress = true;
485          KnowledgeBase.Clear();
486          KnowledgeBase.AddRange(runList);
487        } finally { KnowledgeBase.UpdateOfRunsInProgress = false; }
488
489        var algInstRunDict = runList.Where(x => x.Parameters.ContainsKey("Problem Name") && x.Parameters["Problem Name"] is StringValue)
490                                          .GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value)
491                                          .ToDictionary(x => x.Key, x => x.GroupBy(y => ((StringValue)y.Parameters["Algorithm Name"]).Value)
492                                                                                  .ToDictionary(y => y.Key, y => y.ToList()));
493
494        // set best-known quality to best-found in case it is not known
495        foreach (var kvp in algInstRunDict) {
496          var prob = ProblemInstances.SingleOrDefault(x => ((StringValue)x.Parameters["Problem Name"]).Value == kvp.Key);
497          if (prob == null) continue;
498          var maximization = ((BoolValue)prob.Parameters["Maximization"]).Value;
499
500          IItem bkParam;
501          if (!prob.Parameters.TryGetValue("BestKnownQuality", out bkParam) || !(bkParam is DoubleValue)) {
502            var list = kvp.Value.SelectMany(x => x.Value)
503              .Where(x => x.Results.ContainsKey("QualityPerEvaluations"))
504              .Select(x => ((IndexedDataTable<double>)x.Results["QualityPerEvaluations"]).Rows.First().Values.Last().Item2);
505            if (!list.Any()) continue;
506            bkParam = new DoubleValue(maximization ? list.Max() : list.Min());
507            prob.Parameters["BestKnownQuality"] = bkParam;
508          }
509        }
510
511        // add algorithm instance ranks as features to the problem instances for a range of targets
512        foreach (var target in new[] {0, 0.01, 0.05, 0.1, 0.2, 0.5}) {
513          var cls = GetPerformanceClasses(target, 5);
514          foreach (var kvp in cls) {
515            var prob = kvp.Key;
516            foreach (var kvp2 in kvp.Value) {
517              var resultName = "Rank." + algorithmId2AlgorithmInstanceMapping.GetByFirst(kvp2.Key) + "@" + (target * 100) + "%";
518              prob.Results[resultName] = new IntValue(kvp2.Value);
519            }
520          }
521        }
522      } finally { progress.Finish(); ProblemInstances.UpdateOfRunsInProgress = false; }
523      UpdateInstanceProjection(ProblemInstances.ResultNames.Where(x => x.StartsWith("Characteristic.")).ToArray());
524    }
525
526    private void DownloadAlgorithmInstance(IProgress progress, Algorithm algInst, int[] p, int total) {
527      IAlgorithm alg = null;
528      var data = Clients.OKB.Administration.AdministrationClient.GetAlgorithmData(algInst.Id);
529      if (data != null) {
530        using (var stream = new MemoryStream(data)) {
531          try {
532            alg = (IAlgorithm)XmlParser.Deserialize<IContent>(stream);
533          } catch { }
534          stream.Close();
535        }
536        if (alg != null) {
537          lock (progress) {
538            algorithmInstances.Add(alg);
539            algorithmId2AlgorithmInstanceMapping.Add(algInst.Id, alg);
540            progress.Status = string.Format("Downloaded algorithm {0} (okb-id: {1})...", algInst.Name, algInst.Id);
541            p[0]++;
542            progress.ProgressValue = p[0] / (double)total;
543          }
544        }
545      }
546    }
547
548    private void DownloadProblemInstance(IProgress progress, Problem pInst, int[] p, int totalProblems, HashSet<string> characteristics) {
549      var charas = new List<string>();
550      IRun probRun = null;
551      var data = Clients.OKB.Administration.AdministrationClient.GetProblemData(pInst.Id);
552      if (data != null) {
553        using (var stream = new MemoryStream(data)) {
554          try {
555            var prob = (IProblem)XmlParser.Deserialize<IContent>(stream);
556            probRun = new Run() {Name = prob.Name};
557            prob.CollectParameterValues(probRun.Parameters);
558            probRun.Parameters["Problem Name"] = new StringValue(prob.Name);
559            probRun.Parameters["Problem Type"] = new StringValue(prob.GetType().Name);
560            foreach (var v in RunCreationClient.Instance.GetCharacteristicValues(pInst.Id)) {
561              probRun.Results.Add("Characteristic." + v.Name, RunCreationClient.Instance.ConvertToItem(v));
562              charas.Add("Characteristic." + v.Name);
563            }
564          } catch { }
565          stream.Close();
566        }
567        if (probRun != null) {
568          lock (progress) {
569            problemId2ProblemInstanceMapping.Add(pInst.Id, probRun);
570            ProblemInstances.Add(probRun);
571            progress.Status = string.Format("Downloaded problem {0} (okb-id: {1})....", pInst.Name, pInst.Id);
572            p[0]++;
573            progress.ProgressValue = p[0] / (double)totalProblems;
574            foreach (var c in charas) characteristics.Add(c);
575          }
576        }
577      }
578    }
579
580    private List<long> LoadRunsFromCache(IEnumerable<long> runIds, List<IRun> runList, IProgress progress) {
581      var hashSet = new HashSet<long>(runIds);
582      var total = hashSet.Count;
583      try {
584        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HeuristicLab.OKB", "cache", "runs");
585        Parallel.ForEach(Directory.EnumerateDirectories(path).Select((d, i) => new { Index = i, Directory = d }).GroupBy(x => x.Index / 100), new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount },
586          (folderGroup) => {
587          var localRunList = new List<Tuple<long, long, IRun>>();
588          foreach (var runPath in folderGroup.Select(x => x.Directory)) {
589            long runId;
590            var runFolder = new DirectoryInfo(runPath).Name;
591            if (!long.TryParse(runFolder, out runId) || !hashSet.Contains(runId)) continue;
592            var runFilePath = Directory.EnumerateFiles(runPath).Single();
593            var runFileName = Path.GetFileNameWithoutExtension(runFilePath);
594            long algId;
595            if (!long.TryParse(runFileName, out algId)) continue;
596            IRun run = null;
597            try {
598              using (var file = File.OpenRead(runFilePath))
599                run = XmlParser.Deserialize<IRun>(file);
600            } catch {
601              File.Delete(runFilePath);
602              Directory.Delete(runPath);
603            }
604            if (run != null) localRunList.Add(Tuple.Create(algId, runId, run));
605          }
606          lock (runList) {
607            foreach (var r in localRunList) {
608              hashSet.Remove(r.Item2);
609              algorithmId2RunMapping.Add(r.Item1, r.Item3);
610              runList.Add(r.Item3);
611            }
612            progress.Status = string.Format("Retrieved {0} of {1} from cache", runList.Count, total);
613            progress.ProgressValue = (double)runList.Count / total;
614          }
615        });
616      } catch { }
617      return hashSet.ToList();
618    }
619
620    private void SaveToCache(IEnumerable<Tuple<long, long, IRun>> runs) {
621      try {
622        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HeuristicLab.OKB", "cache", "runs");
623        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
624        foreach (var r in runs) {
625          var runPath = Path.Combine(path, r.Item2.ToString());
626          if (!Directory.Exists(runPath)) Directory.CreateDirectory(runPath);
627          using (var file = File.Open(Path.Combine(runPath, r.Item1.ToString()), FileMode.Create, FileAccess.ReadWrite)) {
628            XmlGenerator.Serialize(r.Item3, file);
629          }
630        }
631      } catch { }
632    }
633
634    public static double[][] GetFeatures(IRun[] problemInstances, string[] characteristics, double[] medianValues = null) {
635      var instances = new double[problemInstances.Length][];
636      for (var p = 0; p < problemInstances.Length; p++) {
637        instances[p] = new double[characteristics.Length];
638        for (var f = 0; f < characteristics.Length; f++) {
639          IItem item;
640          if (problemInstances[p].Results.TryGetValue(characteristics[f], out item)) {
641            double val = 0;
642            var dItem = item as DoubleValue;
643            if (dItem != null) {
644              val = dItem.Value;
645            } else {
646              var iItem = item as IntValue;
647              if (iItem != null) val = iItem.Value;
648              else val = double.NaN;
649            }
650            if (double.IsNaN(val) && medianValues != null)
651              instances[p][f] = medianValues[f];
652            else instances[p][f] = val;
653          } else instances[p][f] = medianValues != null ? medianValues[f] : double.NaN;
654        }
655      }
656      return instances;
657    }
658
659    public static double[][] GetFeaturesStandardized(IRun[] problemInstances, string[] characteristics, out double[] means, out double[] sdevs, double[] medianValues = null) {
660      var instances = new double[problemInstances.Length][];
661      var columns = new List<double>[characteristics.Length];
662      for (var p = 0; p < problemInstances.Length; p++) {
663        instances[p] = new double[characteristics.Length];
664        for (var f = 0; f < characteristics.Length; f++) {
665          if (columns[f] == null) {
666            columns[f] = new List<double>(problemInstances.Length);
667          }
668          IItem item;
669          if (problemInstances[p].Results.TryGetValue(characteristics[f], out item)) {
670            double val = 0;
671            var dItem = item as DoubleValue;
672            if (dItem != null) {
673              val = dItem.Value;
674            } else {
675              var iItem = item as IntValue;
676              if (iItem != null) val = iItem.Value;
677              else val = double.NaN;
678            }
679            if (double.IsNaN(val) && medianValues != null)
680              instances[p][f] = medianValues[f];
681            else instances[p][f] = val;
682            columns[f].Add(instances[p][f]);
683          } else instances[p][f] = medianValues != null ? medianValues[f] : double.NaN;
684        }
685      }
686
687      means = new double[characteristics.Length];
688      sdevs = new double[characteristics.Length];
689      for (var f = 0; f < characteristics.Length; f++) {
690        var mean = columns[f].Average();
691        var dev = columns[f].StandardDeviation();
692        means[f] = mean;
693        sdevs[f] = dev;
694        for (var p = 0; p < problemInstances.Length; p++) {
695          if (dev.IsAlmost(0)) instances[p][f] = 0;
696          else instances[p][f] = (instances[p][f] - mean) / dev;
697        }
698      }
699
700      return instances;
701    }
702
703    public static double[] GetMedianValues(IRun[] problemInstances, string[] characteristics) {
704      var values = new List<double>[characteristics.Length];
705      foreach (var problemInstance in problemInstances) {
706        for (var f = 0; f < characteristics.Length; f++) {
707          if (values[f] == null) values[f] = new List<double>(problemInstances.Length);
708          IItem item;
709          if (problemInstance.Results.TryGetValue(characteristics[f], out item)) {
710            var dItem = item as DoubleValue;
711            if (dItem != null) values[f].Add(dItem.Value);
712            else {
713              var iItem = item as IntValue;
714              if (iItem != null) values[f].Add(iItem.Value);
715            }
716          }
717        }
718      }
719      return values.Select(x => x.Count == 0 ? 0.0 : x.Median()).ToArray();
720    }
721
722    public Dictionary<IRun, double[]> GetProblemCharacteristics(string[] characteristics) {
723      var map = ProblemInstances.Select((v, i) => new { Index = i, ProblemInstance = v }).ToDictionary(x => x.Index, x => x.ProblemInstance);
724      var instances = GetFeatures(ProblemInstances.ToArray(), characteristics);
725      var median = GetMedianValues(ProblemInstances.ToArray(), characteristics);
726
727      var allValues = instances.Select(x => x.Select((f, i) => new { Idx = i, Val = double.IsNaN(f) ? median[i] : f }).ToList())
728        .SelectMany(x => x)
729        .GroupBy(x => x.Idx, x => x.Val)
730        .OrderBy(x => x.Key).ToList();
731      var avg = allValues.Select(x => x.Average()).ToList();
732      var stdev = allValues.Select(x => x.StandardDeviation()).ToList();
733
734      // normalize characteristic values by transforming them to their z-score
735      foreach (var features in instances) {
736        for (var i = 0; i < features.Length; i++) {
737          if (double.IsNaN(features[i])) features[i] = median[i];
738          if (stdev[i] > 0) features[i] = (features[i] - avg[i]) / stdev[i];
739        }
740      }
741      return instances.Select((v, i) => new { ProblemInstance = map[i], Features = v }).ToDictionary(x => x.ProblemInstance, x => x.Features);
742    }
743
744    public Dictionary<IAlgorithm, double> GetAlgorithmPerformance(IRun problemInstance) {
745      if (!problemInstance.Parameters.ContainsKey("BestKnownQuality")) return new Dictionary<IAlgorithm, double>();
746      var target = GetTarget(((DoubleValue)problemInstance.Parameters["BestKnownQuality"]).Value, MinimumTarget.Value, Maximization);
747      return knowledgeBase.Where(x => ((StringValue)x.Parameters["Problem Name"]).Value == ((StringValue)problemInstance.Parameters["Problem Name"]).Value)
748                          .GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
749                          .ToDictionary(x => x.Key, x => ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerEvaluations", target, Maximization).ExpectedRuntime);
750    }
751
752    public Dictionary<IAlgorithm, double> GetAlgorithmPerformanceLog10(IRun problemInstance) {
753      if (!problemInstance.Parameters.ContainsKey("BestKnownQuality")) return new Dictionary<IAlgorithm, double>();
754      var target = GetTarget(((DoubleValue)problemInstance.Parameters["BestKnownQuality"]).Value, MinimumTarget.Value, Maximization);
755      return knowledgeBase.Where(x => ((StringValue)x.Parameters["Problem Name"]).Value == ((StringValue)problemInstance.Parameters["Problem Name"]).Value)
756                          .GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
757                          .ToDictionary(x => x.Key, x => Math.Log10(ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerEvaluations", target, Maximization).ExpectedRuntime));
758    }
759
760    public Dictionary<IAlgorithm, List<IRun>> GetAlgorithmRuns(IRun problemInstance) {
761      return knowledgeBase.Where(x => ((StringValue)x.Parameters["Problem Name"]).Value == ((StringValue)problemInstance.Parameters["Problem Name"]).Value)
762                          .GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
763                          .ToDictionary(x => x.Key, x => x.ToList());
764    }
765
766    public Dictionary<IAlgorithm, List<IRun>> GetKnowledgeBaseByAlgorithm() {
767      return KnowledgeBase.GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
768                          .ToDictionary(x => x.Key, x => x.ToList());
769    }
770
771    public IEnumerable<IRegressionProblem> GetRegressionProblemPerAlgorithmInstance(double target, string[] characteristics) {
772      if (Problem == null) yield break;
773      var features = GetProblemCharacteristics(characteristics);
774      // TODO: knowledgebase only stores problem name as a string
775      // this doesn't work if there are two equally named problem instances
776      var problemMap = ProblemInstances.Select(x => new { Key = ((StringValue)x.Parameters["Problem Name"]).Value, Value = x })
777                                       .ToDictionary(x => x.Key, x => x.Value);
778      foreach (var relevantRuns in knowledgeBase.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())) {
779        var problemRuns = relevantRuns.GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value).ToList();
780        var ds = new ModifiableDataset();
781        ds.AddVariable("Problem Name", new List<string>());
782        foreach (var pc in characteristics)
783          ds.AddVariable(pc, new List<double>());
784        ds.AddVariable("ERT", new List<double>());
785        foreach (var pr in problemRuns) {
786          var prob = problemMap[pr.Key];
787          var f = features[prob];
788          var max = ((BoolValue)prob.Parameters["Maximization"]).Value;
789          var bkq = ((DoubleValue)prob.Parameters["BestKnownQuality"]).Value;
790          var ert = ExpectedRuntimeHelper.CalculateErt(pr.ToList(), "QualityPerEvaluations", GetTarget(bkq, target, max), max).ExpectedRuntime;
791          if (double.IsInfinity(ert)) ert = int.MaxValue;
792          ds.AddRow(new object[] { pr.Key }.Concat(f.Cast<object>()).Concat(new object[] { ert }));
793        }
794        var datAnalysisData = new RegressionProblemData(ds, characteristics, "ERT");
795        var result = new RegressionProblem() {
796          Name = algorithmId2AlgorithmInstanceMapping.GetByFirst(relevantRuns.Key).Name
797        };
798        result.ProblemDataParameter.Value = datAnalysisData;
799        yield return result;
800      }
801    }
802
803    public IEnumerable<IClassificationProblem> GetClassificationProblemPerAlgorithmInstance(double target, string[] characteristics) {
804      if (Problem == null) yield break;
805
806      var classes = GetPerformanceClasses(target, 5);
807      var features = GetProblemCharacteristics(characteristics);
808
809      foreach (var alg in AlgorithmInstances) {
810        var ds = new ModifiableDataset();
811        ds.AddVariable("Problem Name", new List<string>());
812        foreach (var pc in characteristics)
813          ds.AddVariable(pc, new List<double>());
814        ds.AddVariable("Class", new List<double>());
815
816        foreach (var c in classes) {
817          int cls;
818          if (c.Value.TryGetValue(algorithmId2AlgorithmInstanceMapping.GetBySecond(alg), out cls)) {
819            ds.AddRow(new object[] { ((StringValue)c.Key.Parameters["Problem Name"]).Value }
820              .Concat(features[c.Key].Cast<object>()).Concat(new object[] { cls }));
821          }
822        }
823        var datAnalysisData = new ClassificationProblemData(ds, characteristics, "Class");
824        var result = new ClassificationProblem() {
825          Name = alg.Name
826        };
827        result.ProblemDataParameter.Value = datAnalysisData;
828        yield return result;
829      }
830    }
831
832    public Dictionary<IRun, double> GetProblemDistances(string[] characteristics) {
833      var result = new Dictionary<IRun, double>();
834      var currentInstance = problemId2ProblemInstanceMapping.GetByFirst(Problem.ProblemId);
835      var features = GetProblemCharacteristics(characteristics);
836      var cF = features[currentInstance];
837      foreach (var b in ProblemInstances) {
838        if (b == currentInstance) continue;
839        var sum = features[b].Select((t, f) => (cF[f] - t) * (cF[f] - t)).Sum();
840        result[b] = Math.Sqrt(sum);
841      }
842      return result;
843    }
844
845    public Dictionary<IRun, Dictionary<long, int>> GetPerformanceClasses(double target, int nClasses) {
846      var result = new Dictionary<IRun, Dictionary<long, int>>();
847      var problemMap = ProblemInstances.Select(x => new { Key = ((StringValue)x.Parameters["Problem Name"]).Value, Value = x })
848                                       .ToDictionary(x => x.Key, x => x.Value);
849      foreach (var pr in KnowledgeBase.GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value).ToList()) {
850        var bkq = ((DoubleValue)problemMap[pr.Key].Parameters["BestKnownQuality"]).Value;
851        var max = ((BoolValue)problemMap[pr.Key].Parameters["Maximization"]).Value;
852
853        result[problemMap[pr.Key]] = new Dictionary<long, int>();
854
855        var values = pr.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())
856                       .ToDictionary(x => x.Key, x => Math.Log10(ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerEvaluations", GetTarget(bkq, target, max), max).ExpectedRuntime));
857        var ranks = ClusteringHelper<long>.Cluster(nClasses, values, x => double.IsInfinity(x.Value))
858          .GetByCluster().ToList();
859        foreach (var c in ranks) {
860          foreach (var a in c.Value)
861            result[problemMap[pr.Key]][a.Key] = c.Key;
862        }
863      }
864      return result;
865    }
866
867    public double GetTarget(double bestKnownQuality, double target, bool maximization) {
868      return bestKnownQuality * (maximization ? (1 - target) : (1 + target));
869    }
870
871    public event EventHandler<EventArgs<IProgress>> DownloadStarted;
872    private void OnDownloadStarted(IProgress progress) {
873      var handler = DownloadStarted;
874      if (handler != null) handler(this, new EventArgs<IProgress>(progress));
875    }
876
877    public event EventHandler<EventArgs<IAlgorithm>> AlgorithmInstanceStarted;
878    private void OnAlgorithmInstanceStarted(IAlgorithm instance) {
879      var handler = AlgorithmInstanceStarted;
880      if (handler != null) handler(this, new EventArgs<IAlgorithm>(instance));
881    }
882
883    public event EventHandler RecommendationModelChanged;
884    private void OnRecommenderModelChanged() {
885      var handler = RecommendationModelChanged;
886      if (handler != null) handler(this, EventArgs.Empty);
887    }
888
889    public IEnumerable<KeyValuePair<IAlgorithm, double>> GetAlgorithmInstanceRanking() {
890      return RecommendationModel.GetRanking(ProblemInstances.Single(IsCurrentInstance));
891    }
892  }
893}
Note: See TracBrowser for help on using the repository browser.