[12842] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[13667] | 3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[12842] | 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 |
|
---|
[12860] | 22 | using HeuristicLab.Analysis;
|
---|
[13750] | 23 | using HeuristicLab.Analysis.SelfOrganizingMaps;
|
---|
[13551] | 24 | using HeuristicLab.Collections;
|
---|
[13485] | 25 | using HeuristicLab.Common;
|
---|
| 26 | using HeuristicLab.Common.Resources;
|
---|
[12842] | 27 | using HeuristicLab.Core;
|
---|
[13485] | 28 | using HeuristicLab.Data;
|
---|
| 29 | using HeuristicLab.MainForm;
|
---|
[12842] | 30 | using HeuristicLab.Optimization;
|
---|
[13485] | 31 | using HeuristicLab.Persistence.Default.Xml;
|
---|
[13774] | 32 | using HeuristicLab.Problems.DataAnalysis;
|
---|
[13750] | 33 | using HeuristicLab.Random;
|
---|
[13649] | 34 | using System;
|
---|
| 35 | using System.Collections.Generic;
|
---|
| 36 | using System.Drawing;
|
---|
| 37 | using System.IO;
|
---|
| 38 | using System.Linq;
|
---|
| 39 | using System.Threading;
|
---|
| 40 | using System.Threading.Tasks;
|
---|
[14667] | 41 | using HeuristicLab.Algorithms.DataAnalysis;
|
---|
[13809] | 42 | using Algorithm = HeuristicLab.Clients.OKB.Administration.Algorithm;
|
---|
| 43 | using Problem = HeuristicLab.Clients.OKB.Administration.Problem;
|
---|
[13551] | 44 | using RunCreationClient = HeuristicLab.Clients.OKB.RunCreation.RunCreationClient;
|
---|
| 45 | using SingleObjectiveOKBProblem = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBProblem;
|
---|
[13713] | 46 | using SingleObjectiveOKBSolution = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBSolution;
|
---|
[12842] | 47 |
|
---|
[13663] | 48 | namespace HeuristicLab.OptimizationExpertSystem.Common {
|
---|
[13722] | 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.")]
|
---|
[12860] | 50 | [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 119)]
|
---|
[13722] | 51 | public sealed class KnowledgeCenter : IContent {
|
---|
[13752] | 52 | private bool SuppressEvents { get; set; }
|
---|
[12842] | 53 |
|
---|
| 54 | public string Filename { get; set; }
|
---|
| 55 |
|
---|
[13774] | 56 | public static Image StaticItemImage {
|
---|
[12842] | 57 | get { return VSImageLibrary.Library; }
|
---|
| 58 | }
|
---|
| 59 |
|
---|
[13751] | 60 | private readonly IntValue maximumEvaluations;
|
---|
[13722] | 61 | public IntValue MaximumEvaluations {
|
---|
[12847] | 62 | get { return maximumEvaluations; }
|
---|
| 63 | }
|
---|
| 64 |
|
---|
[13757] | 65 | private readonly DoubleValue minimumTarget;
|
---|
| 66 | public DoubleValue MinimumTarget {
|
---|
| 67 | get { return minimumTarget; }
|
---|
| 68 | }
|
---|
| 69 |
|
---|
[13751] | 70 | private readonly RunCollection instanceRuns;
|
---|
[13722] | 71 | public RunCollection InstanceRuns {
|
---|
| 72 | get { return instanceRuns; }
|
---|
[12842] | 73 | }
|
---|
| 74 |
|
---|
[13751] | 75 | private readonly RunCollection seededRuns;
|
---|
[13722] | 76 | public RunCollection SeededRuns {
|
---|
| 77 | get { return seededRuns; }
|
---|
| 78 | }
|
---|
| 79 |
|
---|
[13751] | 80 | private readonly RunCollection knowledgeBase;
|
---|
[13551] | 81 | public RunCollection KnowledgeBase {
|
---|
| 82 | get { return knowledgeBase; }
|
---|
[12842] | 83 | }
|
---|
| 84 |
|
---|
[13751] | 85 | private readonly SingleObjectiveOKBProblem problem;
|
---|
[13551] | 86 | public SingleObjectiveOKBProblem Problem {
|
---|
[12842] | 87 | get { return problem; }
|
---|
| 88 | }
|
---|
| 89 |
|
---|
[13774] | 90 | private readonly ItemList<IAlgorithm> algorithmInstances;
|
---|
| 91 | private readonly ReadOnlyItemList<IAlgorithm> readonlyAlgorithmInstances;
|
---|
| 92 | public ReadOnlyItemList<IAlgorithm> AlgorithmInstances {
|
---|
| 93 | get { return readonlyAlgorithmInstances; }
|
---|
[12847] | 94 | }
|
---|
| 95 |
|
---|
[13751] | 96 | private readonly RunCollection problemInstances;
|
---|
[12957] | 97 | public RunCollection ProblemInstances {
|
---|
| 98 | get { return problemInstances; }
|
---|
| 99 | }
|
---|
| 100 |
|
---|
[13787] | 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 | }
|
---|
[13757] | 109 | }
|
---|
[13751] | 110 |
|
---|
| 111 | private readonly CheckedItemList<IScope> solutionSeedingPool;
|
---|
[13713] | 112 | public CheckedItemList<IScope> SolutionSeedingPool {
|
---|
| 113 | get { return solutionSeedingPool; }
|
---|
[13663] | 114 | }
|
---|
[13713] | 115 |
|
---|
[13751] | 116 | private readonly EnumValue<SeedingStrategyTypes> seedingStrategy;
|
---|
[13713] | 117 | public EnumValue<SeedingStrategyTypes> SeedingStrategy {
|
---|
| 118 | get { return seedingStrategy; }
|
---|
| 119 | }
|
---|
[13663] | 120 |
|
---|
[13551] | 121 | private BidirectionalLookup<long, IRun> algorithmId2RunMapping;
|
---|
| 122 | private BidirectionalDictionary<long, IAlgorithm> algorithmId2AlgorithmInstanceMapping;
|
---|
[13751] | 123 | private BidirectionalDictionary<long, IRun> problemId2ProblemInstanceMapping;
|
---|
| 124 |
|
---|
[13774] | 125 | public bool Maximization {
|
---|
[13722] | 126 | get { return Problem != null && Problem.ProblemId >= 0 && ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; }
|
---|
[12842] | 127 | }
|
---|
| 128 |
|
---|
[13722] | 129 | public KnowledgeCenter() {
|
---|
[13748] | 130 | maximumEvaluations = new IntValue(10000);
|
---|
[13759] | 131 | minimumTarget = new DoubleValue(0.05);
|
---|
[13722] | 132 | instanceRuns = new RunCollection();
|
---|
[13748] | 133 | seededRuns = new RunCollection();
|
---|
[13551] | 134 | knowledgeBase = new RunCollection();
|
---|
[13774] | 135 | algorithmInstances = new ItemList<IAlgorithm>();
|
---|
| 136 | readonlyAlgorithmInstances = algorithmInstances.AsReadOnly();
|
---|
[12957] | 137 | problemInstances = new RunCollection();
|
---|
[13787] | 138 | recommendationModel = FixedRankModel.GetEmpty();
|
---|
[13551] | 139 | problem = new SingleObjectiveOKBProblem();
|
---|
| 140 | algorithmId2RunMapping = new BidirectionalLookup<long, IRun>();
|
---|
| 141 | algorithmId2AlgorithmInstanceMapping = new BidirectionalDictionary<long, IAlgorithm>();
|
---|
[13751] | 142 | problemId2ProblemInstanceMapping = new BidirectionalDictionary<long, IRun>();
|
---|
[13713] | 143 | solutionSeedingPool = new CheckedItemList<IScope>();
|
---|
| 144 | seedingStrategy = new EnumValue<SeedingStrategyTypes>(SeedingStrategyTypes.NoSeeding);
|
---|
[12860] | 145 | RegisterEventHandlers();
|
---|
[12842] | 146 | }
|
---|
| 147 |
|
---|
[13551] | 148 | private void ProblemOnProblemChanged(object sender, EventArgs eventArgs) {
|
---|
[13748] | 149 | // TODO: Potentially, knowledge base has to be re-downloaded
|
---|
[13551] | 150 | }
|
---|
| 151 |
|
---|
[12860] | 152 | private void RegisterEventHandlers() {
|
---|
[13722] | 153 | maximumEvaluations.ValueChanged += MaximumEvaluationsOnValueChanged;
|
---|
[13757] | 154 | minimumTarget.ValueChanged += MinimumTargetOnValueChanged;
|
---|
[13551] | 155 | problem.ProblemChanged += ProblemOnProblemChanged;
|
---|
[13713] | 156 | problem.Solutions.ItemsAdded += ProblemSolutionsChanged;
|
---|
| 157 | problem.Solutions.ItemsReplaced += ProblemSolutionsChanged;
|
---|
| 158 | problem.Solutions.ItemsRemoved += ProblemSolutionsChanged;
|
---|
| 159 | problem.Solutions.CollectionReset += ProblemSolutionsChanged;
|
---|
[13722] | 160 | instanceRuns.CollectionReset += InformationChanged;
|
---|
| 161 | instanceRuns.ItemsAdded += InformationChanged;
|
---|
| 162 | instanceRuns.ItemsRemoved += InformationChanged;
|
---|
| 163 | instanceRuns.Reset += InformationChanged;
|
---|
| 164 | instanceRuns.UpdateOfRunsInProgressChanged += InformationChanged;
|
---|
[13551] | 165 | knowledgeBase.CollectionReset += InformationChanged;
|
---|
| 166 | knowledgeBase.ItemsAdded += InformationChanged;
|
---|
| 167 | knowledgeBase.ItemsRemoved += InformationChanged;
|
---|
[12842] | 168 | }
|
---|
| 169 |
|
---|
[13722] | 170 | private void MaximumEvaluationsOnValueChanged(object sender, EventArgs eventArgs) {
|
---|
[13787] | 171 |
|
---|
[13722] | 172 | }
|
---|
| 173 |
|
---|
[13757] | 174 | private void MinimumTargetOnValueChanged(object sender, EventArgs e) {
|
---|
[13787] | 175 |
|
---|
[13757] | 176 | }
|
---|
| 177 |
|
---|
[13713] | 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 |
|
---|
[12860] | 185 | private void InformationChanged(object sender, EventArgs e) {
|
---|
| 186 | var runCollection = sender as RunCollection;
|
---|
| 187 | if (runCollection != null && runCollection.UpdateOfRunsInProgress) return;
|
---|
[12842] | 188 | }
|
---|
[13774] | 189 |
|
---|
[13751] | 190 | public bool IsCurrentInstance(IRun run) {
|
---|
| 191 | if (!problemId2ProblemInstanceMapping.ContainsSecond(run)) return false;
|
---|
| 192 | return problemId2ProblemInstanceMapping.GetBySecond(run) == Problem.ProblemId;
|
---|
| 193 | }
|
---|
[13561] | 194 |
|
---|
[13787] | 195 | public void UpdateInstanceProjection(string[] characteristics) {
|
---|
| 196 | if (characteristics.Length == 0) return;
|
---|
[13751] | 197 |
|
---|
[13787] | 198 | var instances = GetProblemCharacteristics(characteristics);
|
---|
[13718] | 199 |
|
---|
[13751] | 200 | var key2Idx = new BidirectionalDictionary<IRun, int>();
|
---|
[13561] | 201 | foreach (var kvp in instances.Select((k, i) => new { Index = i, Key = k.Key }))
|
---|
| 202 | key2Idx.Add(kvp.Key, kvp.Index);
|
---|
| 203 |
|
---|
[14776] | 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));
|
---|
[13561] | 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
|
---|
[13791] | 218 | double[,] v = null;
|
---|
[13787] | 219 | var ds = new double[instances.Count, characteristics.Length];
|
---|
[13791] | 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);
|
---|
[13561] | 230 | }
|
---|
| 231 | #endregion
|
---|
[13750] | 232 | #region SOM
|
---|
[13787] | 233 | var features = new DoubleMatrix(characteristics.Length, instances.Count);
|
---|
[13750] | 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 | }
|
---|
[13791] | 239 | var somCoords = SOM.Map(features, new MersenneTwister(42), somSize: 10, learningRadius: 20, iterations: 200, jittering: true);
|
---|
[13750] | 240 | #endregion
|
---|
[14667] | 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 | }
|
---|
[14776] | 246 | var tsne = new TSNE<DoubleArray>(new EuclidianDistance(), new FastRandom(42), stopLyingIter: 0, momSwitchIter: 0, momentum: 0, finalMomentum: 0, eta: 10);
|
---|
| 247 | var tsneCoords = tsne.Run(tsneFeatures, 2, Math.Min((instances.Count - 1) / 4, 50), 0);
|
---|
| 248 | //var tsneCoords = TSNE<DoubleArray>.Run(tsneFeatures, 2, Math.Min((instances.Count - 1) / 4, 50), 0, euclidDArray, new FastRandom(42));
|
---|
[14667] | 249 | #endregion
|
---|
[12957] | 250 |
|
---|
| 251 | ProblemInstances.UpdateOfRunsInProgress = true;
|
---|
| 252 | try {
|
---|
| 253 | foreach (var instance in ProblemInstances) {
|
---|
[13791] | 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");
|
---|
[12957] | 271 | }
|
---|
[13561] | 272 |
|
---|
| 273 | if (instance.Results.TryGetValue("Projection.MDS.X", out item)) {
|
---|
[13751] | 274 | ((DoubleValue)item).Value = coords[key2Idx.GetByFirst(instance), 0];
|
---|
| 275 | } else instance.Results.Add("Projection.MDS.X", new DoubleValue(coords[key2Idx.GetByFirst(instance), 0]));
|
---|
[13561] | 276 | if (instance.Results.TryGetValue("Projection.MDS.Y", out item)) {
|
---|
[13751] | 277 | ((DoubleValue)item).Value = coords[key2Idx.GetByFirst(instance), 1];
|
---|
| 278 | } else instance.Results.Add("Projection.MDS.Y", new DoubleValue(coords[key2Idx.GetByFirst(instance), 1]));
|
---|
[13750] | 279 |
|
---|
| 280 | if (instance.Results.TryGetValue("Projection.SOM.X", out item)) {
|
---|
[13751] | 281 | ((DoubleValue)item).Value = somCoords[key2Idx.GetByFirst(instance), 0];
|
---|
| 282 | } else instance.Results.Add("Projection.SOM.X", new DoubleValue(somCoords[key2Idx.GetByFirst(instance), 0]));
|
---|
[13750] | 283 | if (instance.Results.TryGetValue("Projection.SOM.Y", out item)) {
|
---|
[13751] | 284 | ((DoubleValue)item).Value = somCoords[key2Idx.GetByFirst(instance), 1];
|
---|
| 285 | } else instance.Results.Add("Projection.SOM.Y", new DoubleValue(somCoords[key2Idx.GetByFirst(instance), 1]));
|
---|
[14667] | 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]));
|
---|
[12957] | 293 | }
|
---|
| 294 | } finally { ProblemInstances.UpdateOfRunsInProgress = false; }
|
---|
| 295 | }
|
---|
| 296 |
|
---|
[13485] | 297 | private static readonly HashSet<string> InterestingValueNames = new HashSet<string>() {
|
---|
[13551] | 298 | "QualityPerEvaluations", "Problem Name", "Problem Type", "Algorithm Name", "Algorithm Type", "Maximization", "BestKnownQuality"
|
---|
[13485] | 299 | };
|
---|
| 300 |
|
---|
[13722] | 301 | public Task<ResultCollection> StartAlgorithmAsync(int index) {
|
---|
| 302 | return StartAlgorithmAsync(index, CancellationToken.None);
|
---|
| 303 | }
|
---|
| 304 |
|
---|
| 305 | public Task<ResultCollection> StartAlgorithmAsync(int index, CancellationToken cancellation) {
|
---|
[13774] | 306 | var selectedInstance = algorithmInstances[index];
|
---|
[13713] | 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
|
---|
[13722] | 311 | var seedingStrategyLocal = SeedingStrategy.Value;
|
---|
| 312 | if (seedingStrategyLocal != SeedingStrategyTypes.NoSeeding) {
|
---|
[13713] | 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));
|
---|
[13722] | 318 | seedingCreator.SampleFromPreexistingParameter.Value.Value = seedingStrategyLocal == SeedingStrategyTypes.SeedBySampling;
|
---|
[13713] | 319 | // TODO: WHY!? WHY??!?
|
---|
| 320 | ((dynamic)problemClone.SolutionCreatorParameter).Value = (dynamic)seedingCreator;
|
---|
| 321 | }
|
---|
| 322 | algorithmClone.Problem = problemClone;
|
---|
| 323 | algorithmClone.Prepare(true);
|
---|
[13649] | 324 | IParameter stopParam;
|
---|
| 325 | var monitorStop = true;
|
---|
[13713] | 326 | if (algorithmClone.Parameters.TryGetValue("MaximumEvaluations", out stopParam)) {
|
---|
[13649] | 327 | var maxEvalParam = stopParam as IValueParameter<Data.IntValue>;
|
---|
| 328 | if (maxEvalParam != null) {
|
---|
[13722] | 329 | maxEvalParam.Value.Value = MaximumEvaluations.Value;
|
---|
[13649] | 330 | monitorStop = false;
|
---|
| 331 | }
|
---|
| 332 | }
|
---|
| 333 |
|
---|
[13713] | 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);
|
---|
[13649] | 337 |
|
---|
[13713] | 338 | #region EventHandler closures
|
---|
| 339 | EventHandler exeStateChanged = (sender, e) => {
|
---|
[13722] | 340 | if (algorithmClone.ExecutionState == ExecutionState.Stopped) {
|
---|
[13748] | 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 | }
|
---|
[13713] | 348 | }
|
---|
[13722] | 349 | if (seedingStrategyLocal == SeedingStrategyTypes.NoSeeding) {
|
---|
[13748] | 350 | lock (InstanceRuns) {
|
---|
| 351 | InstanceRuns.Add(algorithmClone.Runs.Last());
|
---|
| 352 | }
|
---|
| 353 | } else {
|
---|
| 354 | lock (SeededRuns) {
|
---|
| 355 | SeededRuns.Add(algorithmClone.Runs.Last());
|
---|
| 356 | }
|
---|
| 357 | }
|
---|
[13713] | 358 | waitHandle.Set();
|
---|
[13649] | 359 | }
|
---|
[13713] | 360 | };
|
---|
[13649] | 361 |
|
---|
[13713] | 362 | EventHandler<EventArgs<Exception>> exceptionOccurred = (sender, e) => {
|
---|
| 363 | waitHandle.Set();
|
---|
| 364 | };
|
---|
[13649] | 365 |
|
---|
[13713] | 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;
|
---|
[13722] | 370 | if (evalSols >= MaximumEvaluations.Value && algorithmClone.ExecutionState == ExecutionState.Started)
|
---|
[13713] | 371 | algorithmClone.Stop();
|
---|
| 372 | };
|
---|
| 373 | #endregion
|
---|
[13649] | 374 |
|
---|
[13713] | 375 | algorithmClone.ExecutionStateChanged += exeStateChanged;
|
---|
| 376 | algorithmClone.ExceptionOccurred += exceptionOccurred;
|
---|
| 377 | if (monitorStop) algorithmClone.ExecutionTimeChanged += timeChanged;
|
---|
[13649] | 378 |
|
---|
[13713] | 379 | return Task.Factory.StartNew(() => {
|
---|
| 380 | algorithmClone.Start();
|
---|
[13722] | 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 | }
|
---|
[13713] | 393 | waitHandle.Dispose();
|
---|
[13722] | 394 | return algorithmClone.Results;
|
---|
| 395 | }, TaskCreationOptions.LongRunning);
|
---|
[13649] | 396 | }
|
---|
| 397 |
|
---|
[13722] | 398 | public ResultCollection StartAlgorithm(int index, CancellationToken cancellation) {
|
---|
| 399 | var task = StartAlgorithmAsync(index, cancellation);
|
---|
| 400 | task.Wait(cancellation);
|
---|
| 401 | return task.Result;
|
---|
[13649] | 402 | }
|
---|
| 403 |
|
---|
[13718] | 404 | public Task UpdateKnowledgeBaseAsync(IProgress progress = null) {
|
---|
| 405 | if (progress == null) progress = new Progress(string.Empty);
|
---|
[13485] | 406 | progress.Start("Updating Knowledge Base from OKB");
|
---|
[13718] | 407 | OnDownloadStarted(progress);
|
---|
| 408 | return Task.Factory.StartNew(() => { DoUpdateKnowledgeBase(progress); }, TaskCreationOptions.LongRunning);
|
---|
[13485] | 409 | }
|
---|
| 410 |
|
---|
[13718] | 411 | public void UpdateKnowledgeBase(IProgress progress = null) {
|
---|
| 412 | UpdateKnowledgeBaseAsync(progress).Wait();
|
---|
[13485] | 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 {
|
---|
[13752] | 419 | progress.Status = "Connecting to OKB...";
|
---|
[13551] | 420 | progress.ProgressValue = 0;
|
---|
| 421 | // FIXME: How to tell if refresh is necessary?
|
---|
[13759] | 422 | var refreshTasks = new[] {
|
---|
| 423 | Task.Factory.StartNew(() => queryClient.Refresh()),
|
---|
| 424 | Task.Factory.StartNew(() => adminClient.Refresh())
|
---|
| 425 | };
|
---|
| 426 | Task.WaitAll(refreshTasks);
|
---|
[13551] | 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 |
|
---|
[13757] | 435 | problemId2ProblemInstanceMapping.Clear();
|
---|
[13809] | 436 | progress.Status = "Downloading algorithm and problem instances...";
|
---|
[13551] | 437 | progress.ProgressValue = 0;
|
---|
[13809] | 438 |
|
---|
[13752] | 439 | int[] p = { 0 };
|
---|
[13551] | 440 | ProblemInstances.UpdateOfRunsInProgress = true;
|
---|
| 441 | ProblemInstances.Clear();
|
---|
| 442 | algorithmId2AlgorithmInstanceMapping.Clear();
|
---|
[13804] | 443 | algorithmId2RunMapping.Clear();
|
---|
| 444 | algorithmInstances.Clear();
|
---|
[13809] | 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);
|
---|
[13551] | 458 | }
|
---|
[13752] | 459 | });
|
---|
[13551] | 460 |
|
---|
[13485] | 461 | var interestingValues = queryClient.ValueNames.Where(x => InterestingValueNames.Contains(x.Name)).ToList();
|
---|
| 462 |
|
---|
[13752] | 463 | progress.Status = "Downloading runs...";
|
---|
[13551] | 464 | progress.ProgressValue = 0;
|
---|
[13752] | 465 | p[0] = 0;
|
---|
[13551] | 466 | var count = queryClient.GetNumberOfRuns(problemClassFilter);
|
---|
[13485] | 467 | if (count == 0) return;
|
---|
[13649] | 468 |
|
---|
[13752] | 469 | var runList = new List<IRun>();
|
---|
[13809] | 470 | var runIds = LoadRunsFromCache(queryClient.GetRunIds(problemClassFilter), runList, progress);
|
---|
[13752] | 471 | var batches = runIds.Select((v, i) => new { Idx = i, Val = v }).GroupBy(x => x.Idx / 500, x => x.Val);
|
---|
[13809] | 472 | Parallel.ForEach(batches.Select(x => x.ToList()), new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4) },
|
---|
| 473 | (batch) => {
|
---|
[13752] | 474 | var okbRuns = queryClient.GetRunsWithValues(batch, true, interestingValues);
|
---|
[13809] | 475 | var hlRuns = okbRuns.AsParallel().Select(x => new { AlgorithmId = x.Algorithm.Id, RunId = x.Id, Run = queryClient.ConvertToOptimizationRun(x) }).ToList();
|
---|
[13752] | 476 | lock (runList) {
|
---|
[13809] | 477 | var toCache = new List<Tuple<long, long, IRun>>();
|
---|
[13752] | 478 | foreach (var r in hlRuns) {
|
---|
| 479 | algorithmId2RunMapping.Add(r.AlgorithmId, r.Run);
|
---|
| 480 | runList.Add(r.Run);
|
---|
[13809] | 481 | toCache.Add(Tuple.Create(r.AlgorithmId, r.RunId, r.Run));
|
---|
[13485] | 482 | }
|
---|
[13809] | 483 | SaveToCache(toCache);
|
---|
[13752] | 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 | });
|
---|
[13804] | 489 | progress.Status = "Finishing...";
|
---|
[13551] | 490 |
|
---|
[13804] | 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 | }
|
---|
[13787] | 500 |
|
---|
| 501 | try {
|
---|
| 502 | KnowledgeBase.UpdateOfRunsInProgress = true;
|
---|
| 503 | KnowledgeBase.Clear();
|
---|
| 504 | KnowledgeBase.AddRange(runList);
|
---|
| 505 | } finally { KnowledgeBase.UpdateOfRunsInProgress = false; }
|
---|
| 506 |
|
---|
[13551] | 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 |
|
---|
[13787] | 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;
|
---|
[13551] | 517 |
|
---|
[13649] | 518 | IItem bkParam;
|
---|
[13787] | 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;
|
---|
[13649] | 524 | bkParam = new DoubleValue(maximization ? list.Max() : list.Min());
|
---|
[13787] | 525 | prob.Parameters["BestKnownQuality"] = bkParam;
|
---|
| 526 | }
|
---|
| 527 | }
|
---|
[13551] | 528 |
|
---|
[13787] | 529 | // add algorithm instance ranks as features to the problem instances for a range of targets
|
---|
[13797] | 530 | foreach (var target in new[] {0, 0.01, 0.05, 0.1, 0.2, 0.5}) {
|
---|
[13787] | 531 | var cls = GetPerformanceClasses(target, 5);
|
---|
| 532 | foreach (var kvp in cls) {
|
---|
| 533 | var prob = kvp.Key;
|
---|
| 534 | foreach (var kvp2 in kvp.Value) {
|
---|
[13797] | 535 | var resultName = "Rank." + algorithmId2AlgorithmInstanceMapping.GetByFirst(kvp2.Key) + "@" + (target * 100) + "%";
|
---|
[13787] | 536 | prob.Results[resultName] = new IntValue(kvp2.Value);
|
---|
[13485] | 537 | }
|
---|
| 538 | }
|
---|
| 539 | }
|
---|
[13551] | 540 | } finally { progress.Finish(); ProblemInstances.UpdateOfRunsInProgress = false; }
|
---|
[13787] | 541 | UpdateInstanceProjection(ProblemInstances.ResultNames.Where(x => x.StartsWith("Characteristic.")).ToArray());
|
---|
[13485] | 542 | }
|
---|
| 543 |
|
---|
[13809] | 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 |
|
---|
[13791] | 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 |
|
---|
[13878] | 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 |
|
---|
[13791] | 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 |
|
---|
[13774] | 762 | public Dictionary<IAlgorithm, double> GetAlgorithmPerformance(IRun problemInstance) {
|
---|
| 763 | if (!problemInstance.Parameters.ContainsKey("BestKnownQuality")) return new Dictionary<IAlgorithm, double>();
|
---|
[13797] | 764 | var target = GetTarget(((DoubleValue)problemInstance.Parameters["BestKnownQuality"]).Value, MinimumTarget.Value, Maximization);
|
---|
[13774] | 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 |
|
---|
[13878] | 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 |
|
---|
[13791] | 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 |
|
---|
[13774] | 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 |
|
---|
[13787] | 789 | public IEnumerable<IRegressionProblem> GetRegressionProblemPerAlgorithmInstance(double target, string[] characteristics) {
|
---|
[13774] | 790 | if (Problem == null) yield break;
|
---|
[13787] | 791 | var features = GetProblemCharacteristics(characteristics);
|
---|
[13774] | 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);
|
---|
[13649] | 796 | foreach (var relevantRuns in knowledgeBase.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())) {
|
---|
[13774] | 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>());
|
---|
[13787] | 800 | foreach (var pc in characteristics)
|
---|
| 801 | ds.AddVariable(pc, new List<double>());
|
---|
[13774] | 802 | ds.AddVariable("ERT", new List<double>());
|
---|
| 803 | foreach (var pr in problemRuns) {
|
---|
| 804 | var prob = problemMap[pr.Key];
|
---|
[13787] | 805 | var f = features[prob];
|
---|
| 806 | var max = ((BoolValue)prob.Parameters["Maximization"]).Value;
|
---|
[13774] | 807 | var bkq = ((DoubleValue)prob.Parameters["BestKnownQuality"]).Value;
|
---|
[13797] | 808 | var ert = ExpectedRuntimeHelper.CalculateErt(pr.ToList(), "QualityPerEvaluations", GetTarget(bkq, target, max), max).ExpectedRuntime;
|
---|
[13803] | 809 | if (double.IsInfinity(ert)) ert = int.MaxValue;
|
---|
[13787] | 810 | ds.AddRow(new object[] { pr.Key }.Concat(f.Cast<object>()).Concat(new object[] { ert }));
|
---|
[12860] | 811 | }
|
---|
[13787] | 812 | var datAnalysisData = new RegressionProblemData(ds, characteristics, "ERT");
|
---|
[13774] | 813 | var result = new RegressionProblem() {
|
---|
| 814 | Name = algorithmId2AlgorithmInstanceMapping.GetByFirst(relevantRuns.Key).Name
|
---|
| 815 | };
|
---|
| 816 | result.ProblemDataParameter.Value = datAnalysisData;
|
---|
| 817 | yield return result;
|
---|
[12860] | 818 | }
|
---|
[13774] | 819 | }
|
---|
[12842] | 820 |
|
---|
[13787] | 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 | }
|
---|
[12842] | 848 | }
|
---|
| 849 |
|
---|
[13787] | 850 | public Dictionary<IRun, double> GetProblemDistances(string[] characteristics) {
|
---|
| 851 | var result = new Dictionary<IRun, double>();
|
---|
[13759] | 852 | var currentInstance = problemId2ProblemInstanceMapping.GetByFirst(Problem.ProblemId);
|
---|
[13787] | 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);
|
---|
[13757] | 859 | }
|
---|
[13759] | 860 | return result;
|
---|
[13757] | 861 | }
|
---|
| 862 |
|
---|
[13787] | 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 |
|
---|
[13794] | 873 | var values = pr.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())
|
---|
[13878] | 874 | .ToDictionary(x => x.Key, x => Math.Log10(ExpectedRuntimeHelper.CalculateErt(x.ToList(), "QualityPerEvaluations", GetTarget(bkq, target, max), max).ExpectedRuntime));
|
---|
[13803] | 875 | var ranks = ClusteringHelper<long>.Cluster(nClasses, values, x => double.IsInfinity(x.Value))
|
---|
[13794] | 876 | .GetByCluster().ToList();
|
---|
| 877 | foreach (var c in ranks) {
|
---|
| 878 | foreach (var a in c.Value)
|
---|
[13797] | 879 | result[problemMap[pr.Key]][a.Key] = c.Key;
|
---|
[13787] | 880 | }
|
---|
[13759] | 881 | }
|
---|
[13787] | 882 | return result;
|
---|
[13757] | 883 | }
|
---|
| 884 |
|
---|
[13797] | 885 | public double GetTarget(double bestKnownQuality, double target, bool maximization) {
|
---|
| 886 | return bestKnownQuality * (maximization ? (1 - target) : (1 + target));
|
---|
[13787] | 887 | }
|
---|
| 888 |
|
---|
[13718] | 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 | }
|
---|
[13722] | 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 | }
|
---|
[13757] | 900 |
|
---|
[13787] | 901 | public event EventHandler RecommendationModelChanged;
|
---|
| 902 | private void OnRecommenderModelChanged() {
|
---|
| 903 | var handler = RecommendationModelChanged;
|
---|
| 904 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
| 905 | }
|
---|
| 906 |
|
---|
[13794] | 907 | public IEnumerable<KeyValuePair<IAlgorithm, double>> GetAlgorithmInstanceRanking() {
|
---|
[13791] | 908 | return RecommendationModel.GetRanking(ProblemInstances.Single(IsCurrentInstance));
|
---|
[13787] | 909 | }
|
---|
[12842] | 910 | }
|
---|
| 911 | }
|
---|