Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2457_ExpertSystem/HeuristicLab.OptimizationExpertSystem.Common/3.3/KnowledgeCenter.cs @ 15762

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

#2457: small changes

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