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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Drawing;
|
---|
25 | using System.IO;
|
---|
26 | using System.Linq;
|
---|
27 | using System.Threading;
|
---|
28 | using System.Threading.Tasks;
|
---|
29 | using HeuristicLab.Algorithms.DataAnalysis;
|
---|
30 | using HeuristicLab.Analysis;
|
---|
31 | using HeuristicLab.Analysis.SelfOrganizingMaps;
|
---|
32 | using HeuristicLab.Collections;
|
---|
33 | using HeuristicLab.Common;
|
---|
34 | using HeuristicLab.Common.Resources;
|
---|
35 | using HeuristicLab.Core;
|
---|
36 | using HeuristicLab.Data;
|
---|
37 | using HeuristicLab.MainForm;
|
---|
38 | using HeuristicLab.Optimization;
|
---|
39 | using HeuristicLab.Persistence.Default.Xml;
|
---|
40 | using HeuristicLab.Problems.DataAnalysis;
|
---|
41 | using HeuristicLab.Random;
|
---|
42 | using Algorithm = HeuristicLab.Clients.OKB.Administration.Algorithm;
|
---|
43 | using Problem = HeuristicLab.Clients.OKB.Administration.Problem;
|
---|
44 | using RunCreationClient = HeuristicLab.Clients.OKB.RunCreation.RunCreationClient;
|
---|
45 | using SingleObjectiveOKBProblem = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBProblem;
|
---|
46 | using SingleObjectiveOKBSolution = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBSolution;
|
---|
47 |
|
---|
48 | namespace 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", "QualityPerClock", "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) || double.IsNaN(((DoubleValue)bkParam).Value)) {
|
---|
520 | var list = kvp.Value.SelectMany(x => x.Value)
|
---|
521 | .Where(x => x.Results.ContainsKey("QualityPerClock"))
|
---|
522 | .Select(x => (IndexedDataTable<double>)x.Results["QualityPerClock"])
|
---|
523 | .Where(x => x.Rows.Count > 0 && x.Rows.First().Values.Count > 0)
|
---|
524 | .Select(x => x.Rows.First().Values.Last().Item2);
|
---|
525 | if (!list.Any()) continue;
|
---|
526 | bkParam = new DoubleValue(maximization ? list.Max() : list.Min());
|
---|
527 | prob.Parameters["BestKnownQuality"] = bkParam;
|
---|
528 | }
|
---|
529 | }
|
---|
530 |
|
---|
531 | // add algorithm instance ranks as features to the problem instances for a range of targets
|
---|
532 | foreach (var target in new[] {0, 0.01, 0.05, 0.1, 0.2, 0.5}) {
|
---|
533 | var cls = GetPerformanceClasses(target, 5);
|
---|
534 | foreach (var kvp in cls) {
|
---|
535 | var prob = kvp.Key;
|
---|
536 | foreach (var kvp2 in kvp.Value) {
|
---|
537 | var resultName = "Rank." + algorithmId2AlgorithmInstanceMapping.GetByFirst(kvp2.Key) + "@" + (target * 100) + "%";
|
---|
538 | prob.Results[resultName] = new IntValue(kvp2.Value);
|
---|
539 | }
|
---|
540 | }
|
---|
541 | }
|
---|
542 | } finally { progress.Finish(); ProblemInstances.UpdateOfRunsInProgress = false; }
|
---|
543 | UpdateInstanceProjection(ProblemInstances.ResultNames.Where(x => x.StartsWith("Characteristic.")).ToArray());
|
---|
544 | }
|
---|
545 |
|
---|
546 | private void DownloadAlgorithmInstance(IProgress progress, Algorithm algInst, int[] p, int total) {
|
---|
547 | IAlgorithm alg = null;
|
---|
548 | var data = Clients.OKB.Administration.AdministrationClient.GetAlgorithmData(algInst.Id);
|
---|
549 | if (data != null) {
|
---|
550 | using (var stream = new MemoryStream(data)) {
|
---|
551 | try {
|
---|
552 | alg = (IAlgorithm)XmlParser.Deserialize<IContent>(stream);
|
---|
553 | } catch { }
|
---|
554 | stream.Close();
|
---|
555 | }
|
---|
556 | if (alg != null) {
|
---|
557 | lock (progress) {
|
---|
558 | algorithmInstances.Add(alg);
|
---|
559 | algorithmId2AlgorithmInstanceMapping.Add(algInst.Id, alg);
|
---|
560 | progress.Status = string.Format("Downloaded algorithm {0} (okb-id: {1})...", algInst.Name, algInst.Id);
|
---|
561 | p[0]++;
|
---|
562 | progress.ProgressValue = p[0] / (double)total;
|
---|
563 | }
|
---|
564 | }
|
---|
565 | }
|
---|
566 | }
|
---|
567 |
|
---|
568 | private void DownloadProblemInstance(IProgress progress, Problem pInst, int[] p, int totalProblems, HashSet<string> characteristics) {
|
---|
569 | var charas = new List<string>();
|
---|
570 | IRun probRun = null;
|
---|
571 | var data = Clients.OKB.Administration.AdministrationClient.GetProblemData(pInst.Id);
|
---|
572 | if (data != null) {
|
---|
573 | using (var stream = new MemoryStream(data)) {
|
---|
574 | try {
|
---|
575 | var prob = (IProblem)XmlParser.Deserialize<IContent>(stream);
|
---|
576 | probRun = new Run() {Name = prob.Name};
|
---|
577 | prob.CollectParameterValues(probRun.Parameters);
|
---|
578 | probRun.Parameters["Problem Name"] = new StringValue(prob.Name);
|
---|
579 | probRun.Parameters["Problem Type"] = new StringValue(prob.GetType().Name);
|
---|
580 | foreach (var v in RunCreationClient.Instance.GetCharacteristicValues(pInst.Id)) {
|
---|
581 | probRun.Results.Add("Characteristic." + v.Name, RunCreationClient.Instance.ConvertToItem(v));
|
---|
582 | charas.Add("Characteristic." + v.Name);
|
---|
583 | }
|
---|
584 | } catch { }
|
---|
585 | stream.Close();
|
---|
586 | }
|
---|
587 | if (probRun != null) {
|
---|
588 | lock (progress) {
|
---|
589 | problemId2ProblemInstanceMapping.Add(pInst.Id, probRun);
|
---|
590 | ProblemInstances.Add(probRun);
|
---|
591 | progress.Status = string.Format("Downloaded problem {0} (okb-id: {1})....", pInst.Name, pInst.Id);
|
---|
592 | p[0]++;
|
---|
593 | progress.ProgressValue = p[0] / (double)totalProblems;
|
---|
594 | foreach (var c in charas) characteristics.Add(c);
|
---|
595 | }
|
---|
596 | }
|
---|
597 | }
|
---|
598 | }
|
---|
599 |
|
---|
600 | private List<long> LoadRunsFromCache(IEnumerable<long> runIds, List<IRun> runList, IProgress progress) {
|
---|
601 | var hashSet = new HashSet<long>(runIds);
|
---|
602 | var total = hashSet.Count;
|
---|
603 | try {
|
---|
604 | var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HeuristicLab.OKB", "cache", "runs");
|
---|
605 | Parallel.ForEach(Directory.EnumerateDirectories(path).Select((d, i) => new { Index = i, Directory = d }).GroupBy(x => x.Index / 100), new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount },
|
---|
606 | (folderGroup) => {
|
---|
607 | var localRunList = new List<Tuple<long, long, IRun>>();
|
---|
608 | foreach (var runPath in folderGroup.Select(x => x.Directory)) {
|
---|
609 | long runId;
|
---|
610 | var runFolder = new DirectoryInfo(runPath).Name;
|
---|
611 | if (!long.TryParse(runFolder, out runId) || !hashSet.Contains(runId)) continue;
|
---|
612 | var runFilePath = Directory.EnumerateFiles(runPath).Single();
|
---|
613 | var runFileName = Path.GetFileNameWithoutExtension(runFilePath);
|
---|
614 | long algId;
|
---|
615 | if (!long.TryParse(runFileName, out algId)) continue;
|
---|
616 | IRun run = null;
|
---|
617 | try {
|
---|
618 | using (var file = File.OpenRead(runFilePath))
|
---|
619 | run = XmlParser.Deserialize<IRun>(file);
|
---|
620 | } catch {
|
---|
621 | File.Delete(runFilePath);
|
---|
622 | Directory.Delete(runPath);
|
---|
623 | }
|
---|
624 | if (run != null) localRunList.Add(Tuple.Create(algId, runId, run));
|
---|
625 | }
|
---|
626 | lock (runList) {
|
---|
627 | foreach (var r in localRunList) {
|
---|
628 | hashSet.Remove(r.Item2);
|
---|
629 | algorithmId2RunMapping.Add(r.Item1, r.Item3);
|
---|
630 | runList.Add(r.Item3);
|
---|
631 | }
|
---|
632 | progress.Status = string.Format("Retrieved {0} of {1} from cache", runList.Count, total);
|
---|
633 | progress.ProgressValue = (double)runList.Count / total;
|
---|
634 | }
|
---|
635 | });
|
---|
636 | } catch { }
|
---|
637 | return hashSet.ToList();
|
---|
638 | }
|
---|
639 |
|
---|
640 | private void SaveToCache(IEnumerable<Tuple<long, long, IRun>> runs) {
|
---|
641 | try {
|
---|
642 | var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HeuristicLab.OKB", "cache", "runs");
|
---|
643 | if (!Directory.Exists(path)) Directory.CreateDirectory(path);
|
---|
644 | foreach (var r in runs) {
|
---|
645 | var runPath = Path.Combine(path, r.Item2.ToString());
|
---|
646 | if (!Directory.Exists(runPath)) Directory.CreateDirectory(runPath);
|
---|
647 | using (var file = File.Open(Path.Combine(runPath, r.Item1.ToString()), FileMode.Create, FileAccess.ReadWrite)) {
|
---|
648 | XmlGenerator.Serialize(r.Item3, file);
|
---|
649 | }
|
---|
650 | }
|
---|
651 | } catch { }
|
---|
652 | }
|
---|
653 |
|
---|
654 | public static double[][] GetFeatures(IRun[] problemInstances, string[] characteristics, double[] medianValues = null) {
|
---|
655 | var instances = new double[problemInstances.Length][];
|
---|
656 | for (var p = 0; p < problemInstances.Length; p++) {
|
---|
657 | instances[p] = new double[characteristics.Length];
|
---|
658 | for (var f = 0; f < characteristics.Length; f++) {
|
---|
659 | IItem item;
|
---|
660 | if (problemInstances[p].Results.TryGetValue(characteristics[f], out item)) {
|
---|
661 | double val = 0;
|
---|
662 | var dItem = item as DoubleValue;
|
---|
663 | if (dItem != null) {
|
---|
664 | val = dItem.Value;
|
---|
665 | } else {
|
---|
666 | var iItem = item as IntValue;
|
---|
667 | if (iItem != null) val = iItem.Value;
|
---|
668 | else val = double.NaN;
|
---|
669 | }
|
---|
670 | if (double.IsNaN(val) && medianValues != null)
|
---|
671 | instances[p][f] = medianValues[f];
|
---|
672 | else instances[p][f] = val;
|
---|
673 | } else instances[p][f] = medianValues != null ? medianValues[f] : double.NaN;
|
---|
674 | }
|
---|
675 | }
|
---|
676 | return instances;
|
---|
677 | }
|
---|
678 |
|
---|
679 | public static double[][] GetFeaturesStandardized(IRun[] problemInstances, string[] characteristics, out double[] means, out double[] sdevs, double[] medianValues = null) {
|
---|
680 | var instances = new double[problemInstances.Length][];
|
---|
681 | var columns = new List<double>[characteristics.Length];
|
---|
682 | for (var p = 0; p < problemInstances.Length; p++) {
|
---|
683 | instances[p] = new double[characteristics.Length];
|
---|
684 | for (var f = 0; f < characteristics.Length; f++) {
|
---|
685 | if (columns[f] == null) {
|
---|
686 | columns[f] = new List<double>(problemInstances.Length);
|
---|
687 | }
|
---|
688 | IItem item;
|
---|
689 | if (problemInstances[p].Results.TryGetValue(characteristics[f], out item)) {
|
---|
690 | double val = 0;
|
---|
691 | var dItem = item as DoubleValue;
|
---|
692 | if (dItem != null) {
|
---|
693 | val = dItem.Value;
|
---|
694 | } else {
|
---|
695 | var iItem = item as IntValue;
|
---|
696 | if (iItem != null) val = iItem.Value;
|
---|
697 | else val = double.NaN;
|
---|
698 | }
|
---|
699 | if (double.IsNaN(val) && medianValues != null)
|
---|
700 | instances[p][f] = medianValues[f];
|
---|
701 | else instances[p][f] = val;
|
---|
702 | columns[f].Add(instances[p][f]);
|
---|
703 | } else instances[p][f] = medianValues != null ? medianValues[f] : double.NaN;
|
---|
704 | }
|
---|
705 | }
|
---|
706 |
|
---|
707 | means = new double[characteristics.Length];
|
---|
708 | sdevs = new double[characteristics.Length];
|
---|
709 | for (var f = 0; f < characteristics.Length; f++) {
|
---|
710 | var mean = columns[f].Average();
|
---|
711 | var dev = columns[f].StandardDeviation();
|
---|
712 | means[f] = mean;
|
---|
713 | sdevs[f] = dev;
|
---|
714 | for (var p = 0; p < problemInstances.Length; p++) {
|
---|
715 | if (dev.IsAlmost(0)) instances[p][f] = 0;
|
---|
716 | else instances[p][f] = (instances[p][f] - mean) / dev;
|
---|
717 | }
|
---|
718 | }
|
---|
719 |
|
---|
720 | return instances;
|
---|
721 | }
|
---|
722 |
|
---|
723 | public static double[] GetMedianValues(IRun[] problemInstances, string[] characteristics) {
|
---|
724 | var values = new List<double>[characteristics.Length];
|
---|
725 | foreach (var problemInstance in problemInstances) {
|
---|
726 | for (var f = 0; f < characteristics.Length; f++) {
|
---|
727 | if (values[f] == null) values[f] = new List<double>(problemInstances.Length);
|
---|
728 | IItem item;
|
---|
729 | if (problemInstance.Results.TryGetValue(characteristics[f], out item)) {
|
---|
730 | var dItem = item as DoubleValue;
|
---|
731 | if (dItem != null) values[f].Add(dItem.Value);
|
---|
732 | else {
|
---|
733 | var iItem = item as IntValue;
|
---|
734 | if (iItem != null) values[f].Add(iItem.Value);
|
---|
735 | }
|
---|
736 | }
|
---|
737 | }
|
---|
738 | }
|
---|
739 | return values.Select(x => x.Count == 0 ? 0.0 : x.Median()).ToArray();
|
---|
740 | }
|
---|
741 |
|
---|
742 | public Dictionary<IRun, double[]> GetProblemCharacteristics(string[] characteristics) {
|
---|
743 | var map = ProblemInstances.Select((v, i) => new { Index = i, ProblemInstance = v }).ToDictionary(x => x.Index, x => x.ProblemInstance);
|
---|
744 | var instances = GetFeatures(ProblemInstances.ToArray(), characteristics);
|
---|
745 | var median = GetMedianValues(ProblemInstances.ToArray(), characteristics);
|
---|
746 |
|
---|
747 | var allValues = instances.Select(x => x.Select((f, i) => new { Idx = i, Val = double.IsNaN(f) ? median[i] : f }).ToList())
|
---|
748 | .SelectMany(x => x)
|
---|
749 | .GroupBy(x => x.Idx, x => x.Val)
|
---|
750 | .OrderBy(x => x.Key).ToList();
|
---|
751 | var avg = allValues.Select(x => x.Average()).ToList();
|
---|
752 | var stdev = allValues.Select(x => x.StandardDeviation()).ToList();
|
---|
753 |
|
---|
754 | // normalize characteristic values by transforming them to their z-score
|
---|
755 | foreach (var features in instances) {
|
---|
756 | for (var i = 0; i < features.Length; i++) {
|
---|
757 | if (double.IsNaN(features[i])) features[i] = median[i];
|
---|
758 | if (stdev[i] > 0) features[i] = (features[i] - avg[i]) / stdev[i];
|
---|
759 | }
|
---|
760 | }
|
---|
761 | return instances.Select((v, i) => new { ProblemInstance = map[i], Features = v }).ToDictionary(x => x.ProblemInstance, x => x.Features);
|
---|
762 | }
|
---|
763 |
|
---|
764 | public Dictionary<IAlgorithm, double> GetAlgorithmPerformance(IRun problemInstance) {
|
---|
765 | if (!problemInstance.Parameters.ContainsKey("BestKnownQuality")) return new Dictionary<IAlgorithm, double>();
|
---|
766 | var target = GetTarget(((DoubleValue)problemInstance.Parameters["BestKnownQuality"]).Value, MinimumTarget.Value, Maximization);
|
---|
767 | return knowledgeBase.Where(x => ((StringValue)x.Parameters["Problem Name"]).Value == ((StringValue)problemInstance.Parameters["Problem Name"]).Value)
|
---|
768 | .GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
|
---|
769 | .ToDictionary(x => x.Key, x => ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerClock", target, Maximization).ExpectedRuntime);
|
---|
770 | }
|
---|
771 |
|
---|
772 | public Dictionary<IAlgorithm, double> GetAlgorithmPerformanceLog10(IRun problemInstance) {
|
---|
773 | if (!problemInstance.Parameters.ContainsKey("BestKnownQuality")) return new Dictionary<IAlgorithm, double>();
|
---|
774 | var target = GetTarget(((DoubleValue)problemInstance.Parameters["BestKnownQuality"]).Value, MinimumTarget.Value, Maximization);
|
---|
775 | return knowledgeBase.Where(x => ((StringValue)x.Parameters["Problem Name"]).Value == ((StringValue)problemInstance.Parameters["Problem Name"]).Value)
|
---|
776 | .GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
|
---|
777 | .ToDictionary(x => x.Key, x => Math.Log10(ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerClock", target, Maximization).ExpectedRuntime));
|
---|
778 | }
|
---|
779 |
|
---|
780 | public Dictionary<IAlgorithm, List<IRun>> GetAlgorithmRuns(IRun problemInstance) {
|
---|
781 | return knowledgeBase.Where(x => ((StringValue)x.Parameters["Problem Name"]).Value == ((StringValue)problemInstance.Parameters["Problem Name"]).Value)
|
---|
782 | .GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
|
---|
783 | .ToDictionary(x => x.Key, x => x.ToList());
|
---|
784 | }
|
---|
785 |
|
---|
786 | public Dictionary<IAlgorithm, List<IRun>> GetKnowledgeBaseByAlgorithm() {
|
---|
787 | return KnowledgeBase.GroupBy(x => algorithmId2AlgorithmInstanceMapping.GetByFirst(algorithmId2RunMapping.GetBySecond(x).Single()))
|
---|
788 | .ToDictionary(x => x.Key, x => x.ToList());
|
---|
789 | }
|
---|
790 |
|
---|
791 | public IEnumerable<IRegressionProblem> GetRegressionProblemPerAlgorithmInstance(double target, string[] characteristics) {
|
---|
792 | if (Problem == null) yield break;
|
---|
793 | var features = GetProblemCharacteristics(characteristics);
|
---|
794 | // TODO: knowledgebase only stores problem name as a string
|
---|
795 | // this doesn't work if there are two equally named problem instances
|
---|
796 | var problemMap = ProblemInstances.Select(x => new { Key = ((StringValue)x.Parameters["Problem Name"]).Value, Value = x })
|
---|
797 | .ToDictionary(x => x.Key, x => x.Value);
|
---|
798 | foreach (var relevantRuns in knowledgeBase.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())) {
|
---|
799 | var problemRuns = relevantRuns.GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value).ToList();
|
---|
800 | var ds = new ModifiableDataset();
|
---|
801 | ds.AddVariable("Problem Name", new List<string>());
|
---|
802 | foreach (var pc in characteristics)
|
---|
803 | ds.AddVariable(pc, new List<double>());
|
---|
804 | ds.AddVariable("ERT", new List<double>());
|
---|
805 | foreach (var pr in problemRuns) {
|
---|
806 | var prob = problemMap[pr.Key];
|
---|
807 | var f = features[prob];
|
---|
808 | var max = ((BoolValue)prob.Parameters["Maximization"]).Value;
|
---|
809 | var bkq = ((DoubleValue)prob.Parameters["BestKnownQuality"]).Value;
|
---|
810 | var ert = ExpectedRuntimeHelper.CalculateErt(pr.ToList(), "QualityPerClock", GetTarget(bkq, target, max), max).ExpectedRuntime;
|
---|
811 | if (double.IsInfinity(ert)) ert = int.MaxValue;
|
---|
812 | ds.AddRow(new object[] { pr.Key }.Concat(f.Cast<object>()).Concat(new object[] { ert }));
|
---|
813 | }
|
---|
814 | var datAnalysisData = new RegressionProblemData(ds, characteristics, "ERT");
|
---|
815 | var result = new RegressionProblem() {
|
---|
816 | Name = algorithmId2AlgorithmInstanceMapping.GetByFirst(relevantRuns.Key).Name
|
---|
817 | };
|
---|
818 | result.ProblemDataParameter.Value = datAnalysisData;
|
---|
819 | yield return result;
|
---|
820 | }
|
---|
821 | }
|
---|
822 |
|
---|
823 | public IEnumerable<IClassificationProblem> GetClassificationProblemPerAlgorithmInstance(double target, string[] characteristics) {
|
---|
824 | if (Problem == null) yield break;
|
---|
825 |
|
---|
826 | var classes = GetPerformanceClasses(target, 5);
|
---|
827 | var features = GetProblemCharacteristics(characteristics);
|
---|
828 |
|
---|
829 | foreach (var alg in AlgorithmInstances) {
|
---|
830 | var ds = new ModifiableDataset();
|
---|
831 | ds.AddVariable("Problem Name", new List<string>());
|
---|
832 | foreach (var pc in characteristics)
|
---|
833 | ds.AddVariable(pc, new List<double>());
|
---|
834 | ds.AddVariable("Class", new List<double>());
|
---|
835 |
|
---|
836 | foreach (var c in classes) {
|
---|
837 | int cls;
|
---|
838 | if (c.Value.TryGetValue(algorithmId2AlgorithmInstanceMapping.GetBySecond(alg), out cls)) {
|
---|
839 | ds.AddRow(new object[] { ((StringValue)c.Key.Parameters["Problem Name"]).Value }
|
---|
840 | .Concat(features[c.Key].Cast<object>()).Concat(new object[] { cls }));
|
---|
841 | }
|
---|
842 | }
|
---|
843 | var datAnalysisData = new ClassificationProblemData(ds, characteristics, "Class");
|
---|
844 | var result = new ClassificationProblem() {
|
---|
845 | Name = alg.Name
|
---|
846 | };
|
---|
847 | result.ProblemDataParameter.Value = datAnalysisData;
|
---|
848 | yield return result;
|
---|
849 | }
|
---|
850 | }
|
---|
851 |
|
---|
852 | public Dictionary<IRun, double> GetProblemDistances(string[] characteristics) {
|
---|
853 | var result = new Dictionary<IRun, double>();
|
---|
854 | var currentInstance = problemId2ProblemInstanceMapping.GetByFirst(Problem.ProblemId);
|
---|
855 | var features = GetProblemCharacteristics(characteristics);
|
---|
856 | var cF = features[currentInstance];
|
---|
857 | foreach (var b in ProblemInstances) {
|
---|
858 | if (b == currentInstance) continue;
|
---|
859 | var sum = features[b].Select((t, f) => (cF[f] - t) * (cF[f] - t)).Sum();
|
---|
860 | result[b] = Math.Sqrt(sum);
|
---|
861 | }
|
---|
862 | return result;
|
---|
863 | }
|
---|
864 |
|
---|
865 | public Dictionary<IRun, Dictionary<long, int>> GetPerformanceClasses(double target, int nClasses) {
|
---|
866 | var result = new Dictionary<IRun, Dictionary<long, int>>();
|
---|
867 | var problemMap = ProblemInstances.Select(x => new { Key = ((StringValue)x.Parameters["Problem Name"]).Value, Value = x })
|
---|
868 | .ToDictionary(x => x.Key, x => x.Value);
|
---|
869 | foreach (var pr in KnowledgeBase.GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value).ToList()) {
|
---|
870 | var bkq = ((DoubleValue)problemMap[pr.Key].Parameters["BestKnownQuality"]).Value;
|
---|
871 | var max = ((BoolValue)problemMap[pr.Key].Parameters["Maximization"]).Value;
|
---|
872 |
|
---|
873 | result[problemMap[pr.Key]] = new Dictionary<long, int>();
|
---|
874 |
|
---|
875 | var values = pr.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())
|
---|
876 | .ToDictionary(x => x.Key, x => Math.Log10(ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerClock", GetTarget(bkq, target, max), max).ExpectedRuntime));
|
---|
877 | var ranks = ClusteringHelper<long>.Cluster(nClasses, values, x => double.IsInfinity(x.Value))
|
---|
878 | .GetByCluster().ToList();
|
---|
879 | foreach (var c in ranks) {
|
---|
880 | foreach (var a in c.Value)
|
---|
881 | result[problemMap[pr.Key]][a.Key] = c.Key;
|
---|
882 | }
|
---|
883 | }
|
---|
884 | return result;
|
---|
885 | }
|
---|
886 |
|
---|
887 | public double GetTarget(double bestKnownQuality, double target, bool maximization) {
|
---|
888 | return bestKnownQuality * (maximization ? (1 - target) : (1 + target));
|
---|
889 | }
|
---|
890 |
|
---|
891 | public event EventHandler<EventArgs<IProgress>> DownloadStarted;
|
---|
892 | private void OnDownloadStarted(IProgress progress) {
|
---|
893 | var handler = DownloadStarted;
|
---|
894 | if (handler != null) handler(this, new EventArgs<IProgress>(progress));
|
---|
895 | }
|
---|
896 |
|
---|
897 | public event EventHandler<EventArgs<IAlgorithm>> AlgorithmInstanceStarted;
|
---|
898 | private void OnAlgorithmInstanceStarted(IAlgorithm instance) {
|
---|
899 | var handler = AlgorithmInstanceStarted;
|
---|
900 | if (handler != null) handler(this, new EventArgs<IAlgorithm>(instance));
|
---|
901 | }
|
---|
902 |
|
---|
903 | public event EventHandler RecommendationModelChanged;
|
---|
904 | private void OnRecommenderModelChanged() {
|
---|
905 | var handler = RecommendationModelChanged;
|
---|
906 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
907 | }
|
---|
908 |
|
---|
909 | public IEnumerable<KeyValuePair<IAlgorithm, double>> GetAlgorithmInstanceRanking() {
|
---|
910 | return RecommendationModel.GetRanking(ProblemInstances.Single(IsCurrentInstance));
|
---|
911 | }
|
---|
912 | }
|
---|
913 | }
|
---|