Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14667 was 14667, checked in by abeham, 7 years ago

#2457: added TSNE visualization of problem instance map

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