[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;
|
---|
[13750] | 32 | using HeuristicLab.Random;
|
---|
[13649] | 33 | using System;
|
---|
| 34 | using System.Collections.Generic;
|
---|
| 35 | using System.Drawing;
|
---|
| 36 | using System.IO;
|
---|
| 37 | using System.Linq;
|
---|
| 38 | using System.Threading;
|
---|
| 39 | using System.Threading.Tasks;
|
---|
[13551] | 40 | using RunCreationClient = HeuristicLab.Clients.OKB.RunCreation.RunCreationClient;
|
---|
| 41 | using SingleObjectiveOKBProblem = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBProblem;
|
---|
[13713] | 42 | using SingleObjectiveOKBSolution = HeuristicLab.Clients.OKB.RunCreation.SingleObjectiveOKBSolution;
|
---|
[12842] | 43 |
|
---|
[13663] | 44 | namespace HeuristicLab.OptimizationExpertSystem.Common {
|
---|
[13722] | 45 | [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] | 46 | [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 119)]
|
---|
[13722] | 47 | public sealed class KnowledgeCenter : IContent {
|
---|
[13752] | 48 | private bool SuppressEvents { get; set; }
|
---|
[12842] | 49 |
|
---|
| 50 | public string Filename { get; set; }
|
---|
| 51 |
|
---|
| 52 | public static new Image StaticItemImage {
|
---|
| 53 | get { return VSImageLibrary.Library; }
|
---|
| 54 | }
|
---|
| 55 |
|
---|
[13751] | 56 | private readonly IntValue maximumEvaluations;
|
---|
[13722] | 57 | public IntValue MaximumEvaluations {
|
---|
[12847] | 58 | get { return maximumEvaluations; }
|
---|
| 59 | }
|
---|
| 60 |
|
---|
[13757] | 61 | private readonly DoubleValue minimumTarget;
|
---|
| 62 | public DoubleValue MinimumTarget {
|
---|
| 63 | get { return minimumTarget; }
|
---|
| 64 | }
|
---|
| 65 |
|
---|
[13751] | 66 | private readonly RunCollection instanceRuns;
|
---|
[13722] | 67 | public RunCollection InstanceRuns {
|
---|
| 68 | get { return instanceRuns; }
|
---|
[12842] | 69 | }
|
---|
| 70 |
|
---|
[13751] | 71 | private readonly RunCollection seededRuns;
|
---|
[13722] | 72 | public RunCollection SeededRuns {
|
---|
| 73 | get { return seededRuns; }
|
---|
| 74 | }
|
---|
| 75 |
|
---|
[13751] | 76 | private readonly RunCollection knowledgeBase;
|
---|
[13551] | 77 | public RunCollection KnowledgeBase {
|
---|
| 78 | get { return knowledgeBase; }
|
---|
[12842] | 79 | }
|
---|
| 80 |
|
---|
[13751] | 81 | private readonly SingleObjectiveOKBProblem problem;
|
---|
[13551] | 82 | public SingleObjectiveOKBProblem Problem {
|
---|
[12842] | 83 | get { return problem; }
|
---|
| 84 | }
|
---|
| 85 |
|
---|
[13751] | 86 | private readonly ItemList<IAlgorithm> suggestedInstances;
|
---|
| 87 | private readonly ReadOnlyItemList<IAlgorithm> readOnlySuggestedInstances;
|
---|
[12847] | 88 | public ReadOnlyItemList<IAlgorithm> SuggestedInstances {
|
---|
| 89 | get { return readOnlySuggestedInstances; }
|
---|
| 90 | }
|
---|
| 91 |
|
---|
[13751] | 92 | private readonly RunCollection problemInstances;
|
---|
[12957] | 93 | public RunCollection ProblemInstances {
|
---|
| 94 | get { return problemInstances; }
|
---|
| 95 | }
|
---|
| 96 |
|
---|
[13751] | 97 | private readonly CheckedItemList<StringValue> problemCharacteristics;
|
---|
[13752] | 98 | private readonly ReadOnlyCheckedItemList<StringValue> readonlyProblemCharacteristics;
|
---|
| 99 | public ReadOnlyCheckedItemList<StringValue> ProblemCharacteristics {
|
---|
| 100 | get { return readonlyProblemCharacteristics; }
|
---|
[13757] | 101 | }
|
---|
[13751] | 102 |
|
---|
[13757] | 103 | private readonly EnumValue<ProblemInstanceProximityType> problemInstanceProximity;
|
---|
| 104 | public EnumValue<ProblemInstanceProximityType> ProblemInstanceProximity {
|
---|
| 105 | get { return problemInstanceProximity; }
|
---|
| 106 | }
|
---|
| 107 |
|
---|
| 108 | private readonly DoubleValue problemInstanceNeighborhoodFactor;
|
---|
| 109 | public DoubleValue ProblemInstanceNeighborhoodFactor {
|
---|
| 110 | get { return problemInstanceNeighborhoodFactor; }
|
---|
| 111 | }
|
---|
| 112 |
|
---|
[13751] | 113 | private readonly CheckedItemList<IScope> solutionSeedingPool;
|
---|
[13713] | 114 | public CheckedItemList<IScope> SolutionSeedingPool {
|
---|
| 115 | get { return solutionSeedingPool; }
|
---|
[13663] | 116 | }
|
---|
[13713] | 117 |
|
---|
[13751] | 118 | private readonly EnumValue<SeedingStrategyTypes> seedingStrategy;
|
---|
[13713] | 119 | public EnumValue<SeedingStrategyTypes> SeedingStrategy {
|
---|
| 120 | get { return seedingStrategy; }
|
---|
| 121 | }
|
---|
[13663] | 122 |
|
---|
[13551] | 123 | private BidirectionalLookup<long, IRun> algorithmId2RunMapping;
|
---|
| 124 | private BidirectionalDictionary<long, IAlgorithm> algorithmId2AlgorithmInstanceMapping;
|
---|
[13751] | 125 | private BidirectionalDictionary<long, IRun> problemId2ProblemInstanceMapping;
|
---|
| 126 |
|
---|
[12860] | 127 | private bool Maximization {
|
---|
[13722] | 128 | get { return Problem != null && Problem.ProblemId >= 0 && ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; }
|
---|
[12842] | 129 | }
|
---|
| 130 |
|
---|
[13722] | 131 | public KnowledgeCenter() {
|
---|
[13748] | 132 | maximumEvaluations = new IntValue(10000);
|
---|
[13759] | 133 | minimumTarget = new DoubleValue(0.05);
|
---|
[13722] | 134 | instanceRuns = new RunCollection();
|
---|
[13748] | 135 | seededRuns = new RunCollection();
|
---|
[13551] | 136 | knowledgeBase = new RunCollection();
|
---|
[12847] | 137 | suggestedInstances = new ItemList<IAlgorithm>();
|
---|
| 138 | readOnlySuggestedInstances = suggestedInstances.AsReadOnly();
|
---|
[12957] | 139 | problemInstances = new RunCollection();
|
---|
[13751] | 140 | problemCharacteristics = new CheckedItemList<StringValue>();
|
---|
[13757] | 141 | problemInstanceProximity = new EnumValue<ProblemInstanceProximityType>(ProblemInstanceProximityType.FeatureSpace);
|
---|
[13759] | 142 | problemInstanceNeighborhoodFactor = new DoubleValue(5);
|
---|
[13752] | 143 | readonlyProblemCharacteristics = problemCharacteristics.AsReadOnly();
|
---|
[13551] | 144 | problem = new SingleObjectiveOKBProblem();
|
---|
| 145 | algorithmId2RunMapping = new BidirectionalLookup<long, IRun>();
|
---|
| 146 | algorithmId2AlgorithmInstanceMapping = new BidirectionalDictionary<long, IAlgorithm>();
|
---|
[13751] | 147 | problemId2ProblemInstanceMapping = new BidirectionalDictionary<long, IRun>();
|
---|
[13713] | 148 | solutionSeedingPool = new CheckedItemList<IScope>();
|
---|
| 149 | seedingStrategy = new EnumValue<SeedingStrategyTypes>(SeedingStrategyTypes.NoSeeding);
|
---|
[12860] | 150 | RegisterEventHandlers();
|
---|
[12842] | 151 | }
|
---|
| 152 |
|
---|
[13551] | 153 | private void ProblemOnProblemChanged(object sender, EventArgs eventArgs) {
|
---|
[13748] | 154 | // TODO: Potentially, knowledge base has to be re-downloaded
|
---|
[13551] | 155 | }
|
---|
| 156 |
|
---|
[12860] | 157 | private void RegisterEventHandlers() {
|
---|
[13722] | 158 | maximumEvaluations.ValueChanged += MaximumEvaluationsOnValueChanged;
|
---|
[13757] | 159 | minimumTarget.ValueChanged += MinimumTargetOnValueChanged;
|
---|
[13551] | 160 | problem.ProblemChanged += ProblemOnProblemChanged;
|
---|
[13713] | 161 | problem.Solutions.ItemsAdded += ProblemSolutionsChanged;
|
---|
| 162 | problem.Solutions.ItemsReplaced += ProblemSolutionsChanged;
|
---|
| 163 | problem.Solutions.ItemsRemoved += ProblemSolutionsChanged;
|
---|
| 164 | problem.Solutions.CollectionReset += ProblemSolutionsChanged;
|
---|
[13722] | 165 | instanceRuns.CollectionReset += InformationChanged;
|
---|
| 166 | instanceRuns.ItemsAdded += InformationChanged;
|
---|
| 167 | instanceRuns.ItemsRemoved += InformationChanged;
|
---|
| 168 | instanceRuns.Reset += InformationChanged;
|
---|
| 169 | instanceRuns.UpdateOfRunsInProgressChanged += InformationChanged;
|
---|
[13551] | 170 | knowledgeBase.CollectionReset += InformationChanged;
|
---|
| 171 | knowledgeBase.ItemsAdded += InformationChanged;
|
---|
| 172 | knowledgeBase.ItemsRemoved += InformationChanged;
|
---|
[13752] | 173 | problemCharacteristics.ItemsAdded += CharacteristicChanged;
|
---|
| 174 | problemCharacteristics.ItemsReplaced += CharacteristicChanged;
|
---|
| 175 | problemCharacteristics.ItemsRemoved += CharacteristicChanged;
|
---|
| 176 | problemCharacteristics.CollectionReset += CharacteristicChanged;
|
---|
| 177 | problemCharacteristics.CheckedItemsChanged += CharacteristicChanged;
|
---|
[13757] | 178 | problemInstanceProximity.ValueChanged += ProblemInstanceProximityChanged;
|
---|
| 179 | problemInstanceNeighborhoodFactor.ValueChanged += ProblemInstanceProximityChanged;
|
---|
[12842] | 180 | }
|
---|
| 181 |
|
---|
[13722] | 182 | private void MaximumEvaluationsOnValueChanged(object sender, EventArgs eventArgs) {
|
---|
| 183 | UpdateSuggestions();
|
---|
| 184 | }
|
---|
| 185 |
|
---|
[13757] | 186 | private void MinimumTargetOnValueChanged(object sender, EventArgs e) {
|
---|
| 187 | UpdateSuggestions();
|
---|
| 188 | }
|
---|
| 189 |
|
---|
[13713] | 190 | private void ProblemSolutionsChanged(object sender, EventArgs e) {
|
---|
| 191 | foreach (var sol in Problem.Solutions.Select(x => x.Solution).OfType<IScope>()) {
|
---|
| 192 | if (!SolutionSeedingPool.Contains(sol))
|
---|
| 193 | SolutionSeedingPool.Add(sol, false);
|
---|
| 194 | }
|
---|
| 195 | }
|
---|
| 196 |
|
---|
[12860] | 197 | private void InformationChanged(object sender, EventArgs e) {
|
---|
| 198 | var runCollection = sender as RunCollection;
|
---|
| 199 | if (runCollection != null && runCollection.UpdateOfRunsInProgress) return;
|
---|
| 200 | UpdateSuggestions();
|
---|
[12842] | 201 | }
|
---|
| 202 |
|
---|
[13752] | 203 | private void CharacteristicChanged(object sender, EventArgs e) {
|
---|
| 204 | if (SuppressEvents) return;
|
---|
| 205 | UpdateInstanceProjection();
|
---|
| 206 | }
|
---|
| 207 |
|
---|
[13757] | 208 | private void ProblemInstanceProximityChanged(object sender, EventArgs e) {
|
---|
| 209 | UpdateSuggestions();
|
---|
| 210 | }
|
---|
| 211 |
|
---|
[13751] | 212 | public bool IsCurrentInstance(IRun run) {
|
---|
| 213 | if (!problemId2ProblemInstanceMapping.ContainsSecond(run)) return false;
|
---|
| 214 | return problemId2ProblemInstanceMapping.GetBySecond(run) == Problem.ProblemId;
|
---|
| 215 | }
|
---|
[13561] | 216 |
|
---|
[13751] | 217 | public void UpdateInstanceProjection() {
|
---|
| 218 | if (ProblemCharacteristics.Count == 0) return;
|
---|
| 219 |
|
---|
[13757] | 220 | var instances = GetProblemCharacteristics();
|
---|
[13718] | 221 |
|
---|
[13751] | 222 | var key2Idx = new BidirectionalDictionary<IRun, int>();
|
---|
[13561] | 223 | foreach (var kvp in instances.Select((k, i) => new { Index = i, Key = k.Key }))
|
---|
| 224 | key2Idx.Add(kvp.Key, kvp.Index);
|
---|
| 225 |
|
---|
| 226 | #region MDS
|
---|
| 227 | Func<double[], double[], double> euclid = (a, b) => Math.Sqrt(a.Zip(b, (x, y) => (x - y)).Sum(x => x * x));
|
---|
| 228 | var num = instances.Count;
|
---|
| 229 | var matrix = new DoubleMatrix(num, num);
|
---|
| 230 | for (var i = 0; i < num - 1; i++) {
|
---|
| 231 | for (var j = i + 1; j < num; j++) {
|
---|
| 232 | matrix[i, j] = matrix[j, i] = euclid(instances[key2Idx.GetBySecond(i)], instances[key2Idx.GetBySecond(j)]);
|
---|
| 233 | }
|
---|
| 234 | }
|
---|
| 235 |
|
---|
| 236 | var coords = MultidimensionalScaling.KruskalShepard(matrix);
|
---|
| 237 | #endregion
|
---|
| 238 | #region PCA
|
---|
[13751] | 239 | var ds = new double[instances.Count, ProblemCharacteristics.CheckedItems.Count()];
|
---|
[13561] | 240 | foreach (var instance in instances) {
|
---|
| 241 | var arr = instance.Value;
|
---|
| 242 | for (var feature = 0; feature < arr.Length; feature++)
|
---|
| 243 | ds[key2Idx.GetByFirst(instance.Key), feature] = arr[feature];
|
---|
| 244 | }
|
---|
| 245 |
|
---|
[12957] | 246 | int info;
|
---|
| 247 | double[] s2;
|
---|
| 248 | double[,] v;
|
---|
[13561] | 249 | alglib.pcabuildbasis(ds, ds.GetLength(0), ds.GetLength(1), out info, out s2, out v);
|
---|
| 250 | #endregion
|
---|
[13750] | 251 | #region SOM
|
---|
[13751] | 252 | var features = new DoubleMatrix(ProblemCharacteristics.CheckedItems.Count(), instances.Count);
|
---|
[13750] | 253 | foreach (var instance in instances) {
|
---|
| 254 | var arr = instance.Value;
|
---|
| 255 | for (var feature = 0; feature < arr.Length; feature++)
|
---|
| 256 | features[feature, key2Idx.GetByFirst(instance.Key)] = arr[feature];
|
---|
| 257 | }
|
---|
[13751] | 258 | var somCoords = SOM.Map(features, new MersenneTwister(42), somSize: 20, learningRadius: 20, iterations: 200, jittering: true);
|
---|
[13750] | 259 | #endregion
|
---|
[12957] | 260 |
|
---|
| 261 | ProblemInstances.UpdateOfRunsInProgress = true;
|
---|
| 262 | try {
|
---|
| 263 | foreach (var instance in ProblemInstances) {
|
---|
| 264 | double x = 0, y = 0;
|
---|
[13561] | 265 | for (var feature = 0; feature < ds.GetLength(1); feature++) {
|
---|
[13751] | 266 | x += ds[key2Idx.GetByFirst(instance), feature] * v[feature, 0];
|
---|
| 267 | y += ds[key2Idx.GetByFirst(instance), feature] * v[feature, 1];
|
---|
[12957] | 268 | }
|
---|
[13561] | 269 |
|
---|
[12957] | 270 | IItem item;
|
---|
[13561] | 271 | if (instance.Results.TryGetValue("Projection.PCA.X", out item)) {
|
---|
[12957] | 272 | ((DoubleValue)item).Value = x;
|
---|
[13561] | 273 | } else instance.Results.Add("Projection.PCA.X", new DoubleValue(x));
|
---|
| 274 | if (instance.Results.TryGetValue("Projection.PCA.Y", out item)) {
|
---|
[12957] | 275 | ((DoubleValue)item).Value = y;
|
---|
[13561] | 276 | } else instance.Results.Add("Projection.PCA.Y", new DoubleValue(y));
|
---|
[12957] | 277 |
|
---|
[13561] | 278 | if (instance.Results.TryGetValue("Projection.MDS.X", out item)) {
|
---|
[13751] | 279 | ((DoubleValue)item).Value = coords[key2Idx.GetByFirst(instance), 0];
|
---|
| 280 | } else instance.Results.Add("Projection.MDS.X", new DoubleValue(coords[key2Idx.GetByFirst(instance), 0]));
|
---|
[13561] | 281 | if (instance.Results.TryGetValue("Projection.MDS.Y", out item)) {
|
---|
[13751] | 282 | ((DoubleValue)item).Value = coords[key2Idx.GetByFirst(instance), 1];
|
---|
| 283 | } else instance.Results.Add("Projection.MDS.Y", new DoubleValue(coords[key2Idx.GetByFirst(instance), 1]));
|
---|
[13750] | 284 |
|
---|
| 285 | if (instance.Results.TryGetValue("Projection.SOM.X", out item)) {
|
---|
[13751] | 286 | ((DoubleValue)item).Value = somCoords[key2Idx.GetByFirst(instance), 0];
|
---|
| 287 | } else instance.Results.Add("Projection.SOM.X", new DoubleValue(somCoords[key2Idx.GetByFirst(instance), 0]));
|
---|
[13750] | 288 | if (instance.Results.TryGetValue("Projection.SOM.Y", out item)) {
|
---|
[13751] | 289 | ((DoubleValue)item).Value = somCoords[key2Idx.GetByFirst(instance), 1];
|
---|
| 290 | } else instance.Results.Add("Projection.SOM.Y", new DoubleValue(somCoords[key2Idx.GetByFirst(instance), 1]));
|
---|
[12957] | 291 | }
|
---|
| 292 | } finally { ProblemInstances.UpdateOfRunsInProgress = false; }
|
---|
| 293 | }
|
---|
| 294 |
|
---|
[13757] | 295 | private Dictionary<IRun, double[]> GetProblemCharacteristics() {
|
---|
| 296 | var instances = new Dictionary<IRun, double[]>();
|
---|
| 297 | var values = new List<double>[ProblemCharacteristics.CheckedItems.Count()];
|
---|
| 298 | foreach (var run in ProblemInstances) {
|
---|
| 299 | var f = 0;
|
---|
| 300 | instances[run] = new double[ProblemCharacteristics.CheckedItems.Count()];
|
---|
| 301 | foreach (var c in ProblemCharacteristics.CheckedItems.Select(x => x.Value.Value)) {
|
---|
| 302 | if (values[f] == null) values[f] = new List<double>(ProblemInstances.Count);
|
---|
| 303 | IItem item;
|
---|
| 304 | if (run.Results.TryGetValue(c, out item)) {
|
---|
| 305 | var val = (double)((dynamic)item).Value;
|
---|
| 306 | if (!double.IsNaN(val)) values[f].Add(val);
|
---|
| 307 | instances[run][f] = val;
|
---|
| 308 | } else instances[run][f] = double.NaN;
|
---|
| 309 | f++;
|
---|
| 310 | }
|
---|
| 311 | }
|
---|
| 312 | var median = values.Select(x => x.Count == 0 ? 0.0 : x.Median()).ToList();
|
---|
| 313 |
|
---|
| 314 | var allValues = instances.Values.Select(x => x.Select((f, i) => new {Idx = i, Val = double.IsNaN(f) ? median[i] : f}).ToList())
|
---|
| 315 | .SelectMany(x => x)
|
---|
| 316 | .GroupBy(x => x.Idx, x => x.Val)
|
---|
| 317 | .OrderBy(x => x.Key).ToList();
|
---|
| 318 | var avg = allValues.Select(x => x.Average()).ToList();
|
---|
| 319 | var stdev = allValues.Select(x => x.StandardDeviation()).ToList();
|
---|
| 320 |
|
---|
| 321 | // normalize characteristic values by transforming them to their z-score
|
---|
| 322 | foreach (var key in instances.Keys.ToList()) {
|
---|
| 323 | var arr = instances[key];
|
---|
| 324 | for (var i = 0; i < arr.Length; i++) {
|
---|
| 325 | if (double.IsNaN(arr[i])) arr[i] = median[i];
|
---|
| 326 | if (stdev[i] > 0) arr[i] = (arr[i] - avg[i]) / stdev[i];
|
---|
| 327 | }
|
---|
| 328 | }
|
---|
| 329 | return instances;
|
---|
| 330 | }
|
---|
| 331 |
|
---|
[13485] | 332 | private static readonly HashSet<string> InterestingValueNames = new HashSet<string>() {
|
---|
[13551] | 333 | "QualityPerEvaluations", "Problem Name", "Problem Type", "Algorithm Name", "Algorithm Type", "Maximization", "BestKnownQuality"
|
---|
[13485] | 334 | };
|
---|
| 335 |
|
---|
[13722] | 336 | public Task<ResultCollection> StartAlgorithmAsync(int index) {
|
---|
| 337 | return StartAlgorithmAsync(index, CancellationToken.None);
|
---|
| 338 | }
|
---|
| 339 |
|
---|
| 340 | public Task<ResultCollection> StartAlgorithmAsync(int index, CancellationToken cancellation) {
|
---|
[13649] | 341 | var selectedInstance = suggestedInstances[index];
|
---|
[13713] | 342 | var algorithmClone = (IAlgorithm)selectedInstance.Clone();
|
---|
| 343 | var problemClone = Problem.CloneProblem() as ISingleObjectiveHeuristicOptimizationProblem;
|
---|
| 344 | if (problemClone == null) throw new InvalidOperationException("Problem is not of type " + typeof(ISingleObjectiveHeuristicOptimizationProblem).FullName);
|
---|
| 345 | // TODO: It is assumed the problem instance by default is configured using no preexisting solution creator
|
---|
[13722] | 346 | var seedingStrategyLocal = SeedingStrategy.Value;
|
---|
| 347 | if (seedingStrategyLocal != SeedingStrategyTypes.NoSeeding) {
|
---|
[13713] | 348 | if (!SolutionSeedingPool.CheckedItems.Any()) throw new InvalidOperationException("There are no solutions selected for seeding.");
|
---|
| 349 | // TODO: It would be necessary to specify the solution creator somewhere (property and GUI)
|
---|
| 350 | var seedingCreator = problemClone.Operators.OfType<IPreexistingSolutionCreator>().FirstOrDefault();
|
---|
| 351 | if (seedingCreator == null) throw new InvalidOperationException("The problem does not contain a solution creator that allows seeding.");
|
---|
| 352 | seedingCreator.PreexistingSolutionsParameter.Value.Replace(SolutionSeedingPool.CheckedItems.Select(x => x.Value));
|
---|
[13722] | 353 | seedingCreator.SampleFromPreexistingParameter.Value.Value = seedingStrategyLocal == SeedingStrategyTypes.SeedBySampling;
|
---|
[13713] | 354 | // TODO: WHY!? WHY??!?
|
---|
| 355 | ((dynamic)problemClone.SolutionCreatorParameter).Value = (dynamic)seedingCreator;
|
---|
| 356 | }
|
---|
| 357 | algorithmClone.Problem = problemClone;
|
---|
| 358 | algorithmClone.Prepare(true);
|
---|
[13649] | 359 | IParameter stopParam;
|
---|
| 360 | var monitorStop = true;
|
---|
[13713] | 361 | if (algorithmClone.Parameters.TryGetValue("MaximumEvaluations", out stopParam)) {
|
---|
[13649] | 362 | var maxEvalParam = stopParam as IValueParameter<Data.IntValue>;
|
---|
| 363 | if (maxEvalParam != null) {
|
---|
[13722] | 364 | maxEvalParam.Value.Value = MaximumEvaluations.Value;
|
---|
[13649] | 365 | monitorStop = false;
|
---|
| 366 | }
|
---|
| 367 | }
|
---|
| 368 |
|
---|
[13713] | 369 | // TODO: The following can be simplified when we have async implementation patterns for our algorithms:
|
---|
| 370 | // TODO: The closures can be removed and replaced with private member methods
|
---|
| 371 | var waitHandle = new AutoResetEvent(false);
|
---|
[13649] | 372 |
|
---|
[13713] | 373 | #region EventHandler closures
|
---|
| 374 | EventHandler exeStateChanged = (sender, e) => {
|
---|
[13722] | 375 | if (algorithmClone.ExecutionState == ExecutionState.Stopped) {
|
---|
[13748] | 376 | lock (Problem.Solutions) {
|
---|
| 377 | foreach (var solution in algorithmClone.Results.Where(x => x.Name.ToLower().Contains("solution")).Select(x => x.Value).OfType<IScope>()) {
|
---|
| 378 | Problem.Solutions.Add(new SingleObjectiveOKBSolution(Problem.ProblemId) {
|
---|
| 379 | Quality = solution.Variables.ContainsKey(Problem.Problem.Evaluator.QualityParameter.ActualName) ? ((DoubleValue)solution.Variables[Problem.Problem.Evaluator.QualityParameter.ActualName].Value).Value : double.NaN,
|
---|
| 380 | Solution = (IItem)solution.Clone()
|
---|
| 381 | });
|
---|
| 382 | }
|
---|
[13713] | 383 | }
|
---|
[13722] | 384 | if (seedingStrategyLocal == SeedingStrategyTypes.NoSeeding) {
|
---|
[13748] | 385 | lock (InstanceRuns) {
|
---|
| 386 | InstanceRuns.Add(algorithmClone.Runs.Last());
|
---|
| 387 | }
|
---|
| 388 | } else {
|
---|
| 389 | lock (SeededRuns) {
|
---|
| 390 | SeededRuns.Add(algorithmClone.Runs.Last());
|
---|
| 391 | }
|
---|
| 392 | }
|
---|
[13713] | 393 | waitHandle.Set();
|
---|
[13649] | 394 | }
|
---|
[13713] | 395 | };
|
---|
[13649] | 396 |
|
---|
[13713] | 397 | EventHandler<EventArgs<Exception>> exceptionOccurred = (sender, e) => {
|
---|
| 398 | waitHandle.Set();
|
---|
| 399 | };
|
---|
[13649] | 400 |
|
---|
[13713] | 401 | EventHandler timeChanged = (sender, e) => {
|
---|
| 402 | IResult evalSolResult;
|
---|
| 403 | if (!algorithmClone.Results.TryGetValue("EvaluatedSolutions", out evalSolResult) || !(evalSolResult.Value is Data.IntValue)) return;
|
---|
| 404 | var evalSols = ((Data.IntValue)evalSolResult.Value).Value;
|
---|
[13722] | 405 | if (evalSols >= MaximumEvaluations.Value && algorithmClone.ExecutionState == ExecutionState.Started)
|
---|
[13713] | 406 | algorithmClone.Stop();
|
---|
| 407 | };
|
---|
| 408 | #endregion
|
---|
[13649] | 409 |
|
---|
[13713] | 410 | algorithmClone.ExecutionStateChanged += exeStateChanged;
|
---|
| 411 | algorithmClone.ExceptionOccurred += exceptionOccurred;
|
---|
| 412 | if (monitorStop) algorithmClone.ExecutionTimeChanged += timeChanged;
|
---|
[13649] | 413 |
|
---|
[13713] | 414 | return Task.Factory.StartNew(() => {
|
---|
| 415 | algorithmClone.Start();
|
---|
[13722] | 416 | OnAlgorithmInstanceStarted(algorithmClone);
|
---|
| 417 | var cancelRequested = false;
|
---|
| 418 | while (!waitHandle.WaitOne(200)) {
|
---|
| 419 | if (cancellation.IsCancellationRequested) {
|
---|
| 420 | cancelRequested = true;
|
---|
| 421 | break;
|
---|
| 422 | }
|
---|
| 423 | }
|
---|
| 424 | if (cancelRequested) {
|
---|
| 425 | try { algorithmClone.Stop(); } catch { } // ignore race condition if it is stopped in the meantime
|
---|
| 426 | waitHandle.WaitOne();
|
---|
| 427 | }
|
---|
[13713] | 428 | waitHandle.Dispose();
|
---|
[13722] | 429 | return algorithmClone.Results;
|
---|
| 430 | }, TaskCreationOptions.LongRunning);
|
---|
[13649] | 431 | }
|
---|
| 432 |
|
---|
[13722] | 433 | public ResultCollection StartAlgorithm(int index, CancellationToken cancellation) {
|
---|
| 434 | var task = StartAlgorithmAsync(index, cancellation);
|
---|
| 435 | task.Wait(cancellation);
|
---|
| 436 | return task.Result;
|
---|
[13649] | 437 | }
|
---|
| 438 |
|
---|
[13718] | 439 | public Task UpdateKnowledgeBaseAsync(IProgress progress = null) {
|
---|
| 440 | if (progress == null) progress = new Progress(string.Empty);
|
---|
[13485] | 441 | progress.Start("Updating Knowledge Base from OKB");
|
---|
[13718] | 442 | OnDownloadStarted(progress);
|
---|
| 443 | return Task.Factory.StartNew(() => { DoUpdateKnowledgeBase(progress); }, TaskCreationOptions.LongRunning);
|
---|
[13485] | 444 | }
|
---|
| 445 |
|
---|
[13718] | 446 | public void UpdateKnowledgeBase(IProgress progress = null) {
|
---|
| 447 | UpdateKnowledgeBaseAsync(progress).Wait();
|
---|
[13485] | 448 | }
|
---|
| 449 |
|
---|
| 450 | private void DoUpdateKnowledgeBase(IProgress progress) {
|
---|
| 451 | var queryClient = Clients.OKB.Query.QueryClient.Instance;
|
---|
| 452 | var adminClient = Clients.OKB.Administration.AdministrationClient.Instance;
|
---|
| 453 | try {
|
---|
[13752] | 454 | progress.Status = "Connecting to OKB...";
|
---|
[13551] | 455 | progress.ProgressValue = 0;
|
---|
| 456 | // FIXME: How to tell if refresh is necessary?
|
---|
[13759] | 457 | var refreshTasks = new[] {
|
---|
| 458 | Task.Factory.StartNew(() => queryClient.Refresh()),
|
---|
| 459 | Task.Factory.StartNew(() => adminClient.Refresh())
|
---|
| 460 | };
|
---|
| 461 | Task.WaitAll(refreshTasks);
|
---|
[13551] | 462 |
|
---|
| 463 | var probInstance = adminClient.Problems.SingleOrDefault(x => x.Id == Problem.ProblemId);
|
---|
| 464 | if (probInstance == null) throw new InvalidOperationException("The chosen problem instance cannot be found in the OKB.");
|
---|
| 465 | var probClassId = probInstance.ProblemClassId;
|
---|
| 466 |
|
---|
| 467 | var problemClassFilter = (Clients.OKB.Query.StringComparisonAvailableValuesFilter)queryClient.Filters.Single(x => x.Label == "Problem Class Name");
|
---|
| 468 | problemClassFilter.Value = adminClient.ProblemClasses.Single(x => x.Id == probClassId).Name;
|
---|
| 469 |
|
---|
[13757] | 470 | problemId2ProblemInstanceMapping.Clear();
|
---|
[13551] | 471 | progress.Status = "Downloading problem instances...";
|
---|
| 472 | progress.ProgressValue = 0;
|
---|
[13752] | 473 | int[] p = { 0 };
|
---|
[13551] | 474 | ProblemInstances.UpdateOfRunsInProgress = true;
|
---|
| 475 | ProblemInstances.Clear();
|
---|
[13751] | 476 | var characteristics = new HashSet<string>();
|
---|
[13551] | 477 | var totalProblems = adminClient.Problems.Count(x => x.ProblemClassId == probClassId);
|
---|
[13759] | 478 | Parallel.ForEach(adminClient.Problems.Where(x => x.ProblemClassId == probClassId), new ParallelOptions { MaxDegreeOfParallelism = 3 }, (pInst) => {
|
---|
[13752] | 479 | var charas = new List<string>();
|
---|
| 480 | IRun probRun = null;
|
---|
| 481 | var data = Clients.OKB.Administration.AdministrationClient.GetProblemData(pInst.Id);
|
---|
[13551] | 482 | if (data != null) {
|
---|
| 483 | using (var stream = new MemoryStream(data)) {
|
---|
| 484 | try {
|
---|
| 485 | var prob = (IProblem)XmlParser.Deserialize<IContent>(stream);
|
---|
[13752] | 486 | probRun = new Run() { Name = prob.Name };
|
---|
[13551] | 487 | prob.CollectParameterValues(probRun.Parameters);
|
---|
[13649] | 488 | probRun.Parameters["Problem Name"] = new StringValue(prob.Name);
|
---|
| 489 | probRun.Parameters["Problem Type"] = new StringValue(prob.GetType().Name);
|
---|
[13752] | 490 | foreach (var v in RunCreationClient.Instance.GetCharacteristicValues(pInst.Id)) {
|
---|
[13551] | 491 | probRun.Results.Add("Characteristic." + v.Name, RunCreationClient.Instance.ConvertToItem(v));
|
---|
[13752] | 492 | charas.Add("Characteristic." + v.Name);
|
---|
[13551] | 493 | }
|
---|
| 494 | } catch { }
|
---|
| 495 | stream.Close();
|
---|
| 496 | }
|
---|
[13752] | 497 | if (probRun != null) {
|
---|
| 498 | lock (characteristics) {
|
---|
| 499 | problemId2ProblemInstanceMapping.Add(pInst.Id, probRun);
|
---|
| 500 | ProblemInstances.Add(probRun);
|
---|
| 501 | progress.Status = string.Format("Downloaded problem {0} (okb-id: {1})....", pInst.Name, pInst.Id);
|
---|
| 502 | p[0]++;
|
---|
| 503 | progress.ProgressValue = p[0] / (double)totalProblems;
|
---|
| 504 | foreach (var c in charas) characteristics.Add(c);
|
---|
| 505 | }
|
---|
| 506 | }
|
---|
[13551] | 507 | }
|
---|
[13752] | 508 | });
|
---|
[13551] | 509 |
|
---|
| 510 | algorithmId2AlgorithmInstanceMapping.Clear();
|
---|
| 511 | progress.Status = "Downloading algorithm instances...";
|
---|
| 512 | progress.ProgressValue = 0;
|
---|
[13752] | 513 | p[0] = 0;
|
---|
[13759] | 514 | Parallel.ForEach(adminClient.Algorithms, new ParallelOptions { MaxDegreeOfParallelism = 3 }, (algInst) => {
|
---|
[13752] | 515 | IAlgorithm alg = null;
|
---|
[13551] | 516 | var data = Clients.OKB.Administration.AdministrationClient.GetAlgorithmData(algInst.Id);
|
---|
| 517 | if (data != null) {
|
---|
| 518 | using (var stream = new MemoryStream(data)) {
|
---|
| 519 | try {
|
---|
[13752] | 520 | alg = (IAlgorithm)XmlParser.Deserialize<IContent>(stream);
|
---|
[13551] | 521 | } catch { }
|
---|
| 522 | stream.Close();
|
---|
| 523 | }
|
---|
[13752] | 524 | if (alg != null) {
|
---|
| 525 | lock (algorithmId2AlgorithmInstanceMapping) {
|
---|
| 526 | algorithmId2AlgorithmInstanceMapping.Add(algInst.Id, alg);
|
---|
| 527 | progress.Status = string.Format("Downloaded algorithm {0} (okb-id: {1})...", algInst.Name, algInst.Id);
|
---|
| 528 | p[0]++;
|
---|
| 529 | progress.ProgressValue = p[0] / (double)adminClient.Algorithms.Count;
|
---|
| 530 | }
|
---|
| 531 | }
|
---|
[13551] | 532 | }
|
---|
[13752] | 533 | });
|
---|
[13551] | 534 |
|
---|
[13485] | 535 | var interestingValues = queryClient.ValueNames.Where(x => InterestingValueNames.Contains(x.Name)).ToList();
|
---|
| 536 |
|
---|
[13752] | 537 | progress.Status = "Downloading runs...";
|
---|
[13551] | 538 | progress.ProgressValue = 0;
|
---|
[13752] | 539 | p[0] = 0;
|
---|
[13551] | 540 | var count = queryClient.GetNumberOfRuns(problemClassFilter);
|
---|
[13485] | 541 | if (count == 0) return;
|
---|
[13649] | 542 |
|
---|
[13752] | 543 | var runList = new List<IRun>();
|
---|
[13551] | 544 | var runIds = queryClient.GetRunIds(problemClassFilter).ToList();
|
---|
[13752] | 545 | var batches = runIds.Select((v, i) => new { Idx = i, Val = v }).GroupBy(x => x.Idx / 500, x => x.Val);
|
---|
[13759] | 546 | Parallel.ForEach(batches.Select(x => x.ToList()), new ParallelOptions { MaxDegreeOfParallelism = 3 }, (batch) => {
|
---|
[13752] | 547 | var okbRuns = queryClient.GetRunsWithValues(batch, true, interestingValues);
|
---|
| 548 | var hlRuns = okbRuns.AsParallel().Select(x => new { AlgorithmId = x.Algorithm.Id, Run = queryClient.ConvertToOptimizationRun(x) }).ToList();
|
---|
| 549 | lock (runList) {
|
---|
| 550 | foreach (var r in hlRuns) {
|
---|
| 551 | algorithmId2RunMapping.Add(r.AlgorithmId, r.Run);
|
---|
| 552 | runList.Add(r.Run);
|
---|
[13485] | 553 | }
|
---|
[13752] | 554 | progress.Status = string.Format("Downloaded runs {0} to {1} of {2}...", p[0], p[0] + batch.Count, count);
|
---|
| 555 | p[0] += batch.Count;
|
---|
| 556 | progress.ProgressValue = p[0] / (double)count;
|
---|
| 557 | }
|
---|
| 558 | });
|
---|
[13551] | 559 |
|
---|
| 560 | progress.Status = "Finishing...";
|
---|
| 561 | var algInstRunDict = runList.Where(x => x.Parameters.ContainsKey("Problem Name") && x.Parameters["Problem Name"] is StringValue)
|
---|
| 562 | .GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value)
|
---|
| 563 | .ToDictionary(x => x.Key, x => x.GroupBy(y => ((StringValue)y.Parameters["Algorithm Name"]).Value)
|
---|
| 564 | .ToDictionary(y => y.Key, y => y.ToList()));
|
---|
| 565 |
|
---|
| 566 | foreach (var instance in ProblemInstances) {
|
---|
| 567 | IItem probNameParam;
|
---|
| 568 | if (!instance.Parameters.TryGetValue("Problem Name", out probNameParam)) continue;
|
---|
| 569 |
|
---|
| 570 | var probInstanceName = ((StringValue)probNameParam).Value;
|
---|
| 571 | var maximization = ((BoolValue)instance.Parameters["Maximization"]).Value;
|
---|
[13649] | 572 |
|
---|
| 573 | IItem bkParam;
|
---|
| 574 | if (!instance.Parameters.TryGetValue("BestKnownQuality", out bkParam) || !(bkParam is DoubleValue)) {
|
---|
| 575 | Dictionary<string, List<IRun>> algRuns;
|
---|
| 576 | if (!algInstRunDict.TryGetValue(probInstanceName, out algRuns)) continue;
|
---|
| 577 | var list = algRuns.SelectMany(x => x.Value)
|
---|
| 578 | .Where(x => x.Results.ContainsKey("QualityPerEvaluations"))
|
---|
| 579 | .Select(x => ((IndexedDataTable<double>)x.Results["QualityPerEvaluations"]).Rows.First().Values.Last().Item2);
|
---|
| 580 | bkParam = new DoubleValue(maximization ? list.Max() : list.Min());
|
---|
| 581 | instance.Parameters["BestKnownQuality"] = bkParam;
|
---|
| 582 | } else bkParam = instance.Parameters["BestKnownQuality"];
|
---|
[13551] | 583 |
|
---|
[13649] | 584 | var bkQuality = ((DoubleValue)bkParam).Value;
|
---|
| 585 |
|
---|
[13551] | 586 | if (!algInstRunDict.ContainsKey(probInstanceName)) continue;
|
---|
[13757] | 587 | // TODO: Things needs to be configurable here (table name, targets)
|
---|
| 588 | foreach (var target in new[] { 1, 1.01, 1.05, 1.1, 1.2, 1.5 }) {
|
---|
| 589 | var indexMap = new BidirectionalDictionary<string, int>();
|
---|
| 590 | var dict = new Dictionary<string, double>();
|
---|
| 591 | var idx = 0;
|
---|
| 592 | foreach (var kvp in algInstRunDict[probInstanceName]) {
|
---|
[13551] | 593 | var result = ExpectedRuntimeHelper.CalculateErt(kvp.Value, "QualityPerEvaluations", bkQuality * target, maximization);
|
---|
[13757] | 594 | indexMap.Add(kvp.Key, idx);
|
---|
| 595 | dict[kvp.Key] = !double.IsNaN(result.ExpectedRuntime) ? result.ExpectedRuntime : int.MaxValue;
|
---|
| 596 | idx++;
|
---|
[13485] | 597 | }
|
---|
[13757] | 598 | var points = dict.OrderBy(x => indexMap.GetByFirst(x.Key)).Select(x => x.Value > 0 ? Math.Log10(x.Value) : 0).ToArray();
|
---|
| 599 | int[] clusters;
|
---|
| 600 | Ckmeans1dClusters(points, 5, out clusters);
|
---|
| 601 | var ranks = clusters.Select((c, i) => new { Cluster = c, Perf = dict[indexMap.GetBySecond(i)] })
|
---|
| 602 | .GroupBy(x => x.Cluster, x => x.Perf)
|
---|
| 603 | .Select(x => new { Cluster = x.Key, AvgPerf = x.Average() })
|
---|
| 604 | .OrderBy(x => x.AvgPerf)
|
---|
| 605 | .Select((c, i) => new { Cluster = c.Cluster, Rank = i })
|
---|
| 606 | .ToDictionary(x => x.Cluster, x => x.Rank);
|
---|
| 607 | for (var i = 0; i < clusters.Length; i++) {
|
---|
| 608 | var resultName = "Rank." + indexMap.GetBySecond(i) + "@" + ((target - 1) * 100) + "%";
|
---|
| 609 | instance.Results[resultName] = new IntValue(dict[indexMap.GetBySecond(i)] < int.MaxValue ? ranks[clusters[i]] : 6);
|
---|
| 610 | }
|
---|
[13485] | 611 | }
|
---|
| 612 | }
|
---|
[13722] | 613 | try {
|
---|
[13752] | 614 | SuppressEvents = true;
|
---|
| 615 | problemCharacteristics.Replace(characteristics.Select(x => new StringValue(x)));
|
---|
| 616 | foreach (var pc in problemCharacteristics.Where(x => !x.Value.StartsWith("Characteristic.")))
|
---|
| 617 | problemCharacteristics.SetItemCheckedState(pc, false);
|
---|
| 618 | } finally { SuppressEvents = false; }
|
---|
| 619 | try {
|
---|
[13722] | 620 | KnowledgeBase.UpdateOfRunsInProgress = true;
|
---|
| 621 | KnowledgeBase.Clear();
|
---|
| 622 | KnowledgeBase.AddRange(runList);
|
---|
| 623 | } finally { KnowledgeBase.UpdateOfRunsInProgress = false; }
|
---|
[13551] | 624 | } finally { progress.Finish(); ProblemInstances.UpdateOfRunsInProgress = false; }
|
---|
[13720] | 625 | UpdateInstanceProjection();
|
---|
[13757] | 626 | UpdateSuggestions();
|
---|
[13485] | 627 | }
|
---|
| 628 |
|
---|
[12860] | 629 | private void UpdateSuggestions() {
|
---|
| 630 | if (Problem == null) return;
|
---|
[13757] | 631 | var piDistances = GetProblemDistances();
|
---|
[13759] | 632 | var maxDist = piDistances.Max(x => x.Value);
|
---|
[12860] | 633 | var instances = new SortedList<double, IAlgorithm>();
|
---|
[13649] | 634 | foreach (var relevantRuns in knowledgeBase.GroupBy(x => algorithmId2RunMapping.GetBySecond(x).Single())) {
|
---|
| 635 | var algorithm = algorithmId2AlgorithmInstanceMapping.GetByFirst(relevantRuns.Key);
|
---|
[13759] | 636 | Func<double, double> distFunc = (d) => Math.Exp(ProblemInstanceNeighborhoodFactor.Value * (-d / maxDist));
|
---|
| 637 | var pis = relevantRuns.Select(x => ((StringValue)x.Parameters["Problem Name"]).Value).Distinct()
|
---|
| 638 | .Select(x => Tuple.Create(x, ProblemInstances.SingleOrDefault(y => ((StringValue)y.Parameters["Problem Name"]).Value == x)))
|
---|
| 639 | .Where(x => x.Item2 != null)
|
---|
| 640 | .Select(x => Tuple.Create(x.Item1, distFunc(piDistances[x.Item2]), ((DoubleValue)x.Item2.Parameters["BestKnownQuality"]).Value))
|
---|
| 641 | .ToDictionary(x => x.Item1, x => Tuple.Create(x.Item2, x.Item3));
|
---|
| 642 | var sumPis = pis.Sum(x => x.Value.Item1);
|
---|
| 643 | var avgERT = 0.0;
|
---|
[13649] | 644 | foreach (var problemRuns in relevantRuns.GroupBy(x => ((StringValue)x.Parameters["Problem Name"]).Value)) {
|
---|
[13759] | 645 | Tuple<double, double> info;
|
---|
| 646 | if (!pis.TryGetValue(problemRuns.Key, out info)) continue;
|
---|
| 647 | var convGraph = new List<List<Tuple<double, double>>>();
|
---|
[13649] | 648 | foreach (var run in problemRuns) {
|
---|
[13759] | 649 | var current = new List<Tuple<double, double>>();
|
---|
[13649] | 650 | var performanceGraph = ((IndexedDataTable<double>)run.Results["QualityPerEvaluations"]);
|
---|
[13759] | 651 | current.AddRange(performanceGraph.Rows.First().Values.TakeWhile(v => v.Item1 < MaximumEvaluations.Value));
|
---|
| 652 | if (current.Count > 0) {
|
---|
| 653 | current.Add(Tuple.Create((double)MaximumEvaluations.Value, current.Last().Item2));
|
---|
| 654 | convGraph.Add(current);
|
---|
[13649] | 655 | }
|
---|
| 656 | }
|
---|
[13759] | 657 | var ert = ExpectedRuntimeHelper.CalculateErt(convGraph, (Maximization ? (1 - MinimumTarget.Value) : (1 + MinimumTarget.Value)) * info.Item2, Maximization).ExpectedRuntime;
|
---|
| 658 | if (double.IsNaN(ert)) {
|
---|
| 659 | ert = ExpectedRuntimeHelper.CalculateErt(problemRuns.ToList(), "QualityPerEvaluations", (Maximization ? (1 - MinimumTarget.Value) : (1 + MinimumTarget.Value)) * info.Item2, Maximization).ExpectedRuntime;
|
---|
| 660 | if (double.IsNaN(ert)) ert = int.MaxValue;
|
---|
| 661 | }
|
---|
| 662 | avgERT += info.Item1 * ert;
|
---|
[12860] | 663 | }
|
---|
[13759] | 664 | avgERT /= sumPis;
|
---|
| 665 | if (instances.ContainsKey(avgERT)) {
|
---|
| 666 | avgERT += new System.Random().NextDouble();
|
---|
| 667 | }
|
---|
| 668 | instances.Add(avgERT, algorithm);
|
---|
[12860] | 669 | }
|
---|
[12842] | 670 |
|
---|
[13649] | 671 | var instanceLadder = instances.Select(x => (IAlgorithm)x.Value.Clone()).ToList();
|
---|
[13713] | 672 | suggestedInstances.Replace(instanceLadder);
|
---|
[12842] | 673 | }
|
---|
| 674 |
|
---|
[13759] | 675 | private Dictionary<IRun, double> GetProblemDistances() {
|
---|
| 676 | var result = new Dictionary<IRun, double>();
|
---|
| 677 | var currentInstance = problemId2ProblemInstanceMapping.GetByFirst(Problem.ProblemId);
|
---|
[13757] | 678 | switch (ProblemInstanceProximity.Value) {
|
---|
| 679 | case ProblemInstanceProximityType.MDS:
|
---|
| 680 | case ProblemInstanceProximityType.PCA:
|
---|
| 681 | case ProblemInstanceProximityType.SOM:
|
---|
[13759] | 682 | double xa, ya;
|
---|
| 683 | GetProjectionCoordinates(currentInstance, out xa, out ya);
|
---|
| 684 | foreach (var b in ProblemInstances) {
|
---|
| 685 | double xb, yb;
|
---|
| 686 | GetProjectionCoordinates(b, out xb, out yb);
|
---|
| 687 | var d = Math.Sqrt((xa - xb) * (xa - xb) + (ya - yb) * (ya - yb));
|
---|
| 688 | result[b] = d;
|
---|
[13757] | 689 | }
|
---|
| 690 | break;
|
---|
| 691 | case ProblemInstanceProximityType.FeatureSpace:
|
---|
| 692 | var features = GetProblemCharacteristics();
|
---|
[13759] | 693 | var cF = features[currentInstance];
|
---|
| 694 | foreach (var b in ProblemInstances) {
|
---|
| 695 | var sum = features[b].Select((t, f) => (cF[f] - t) * (cF[f] - t)).Sum();
|
---|
| 696 | result[b] = Math.Sqrt(sum);
|
---|
[13757] | 697 | }
|
---|
| 698 | break;
|
---|
| 699 | default: throw new InvalidOperationException(string.Format("Unkonwn proximity type {0}", ProblemInstanceProximity.Value));
|
---|
| 700 | }
|
---|
[13759] | 701 | return result;
|
---|
[13757] | 702 | }
|
---|
| 703 |
|
---|
| 704 | private void GetProjectionCoordinates(IRun problemInstance, out double x, out double y) {
|
---|
| 705 | x = ((DoubleValue)problemInstance.Results["Projection." + ProblemInstanceProximity.Value + ".X"]).Value;
|
---|
| 706 | y = ((DoubleValue)problemInstance.Results["Projection." + ProblemInstanceProximity.Value + ".Y"]).Value;
|
---|
[13759] | 707 | if (ProblemInstanceProximity.Value == ProblemInstanceProximityType.SOM) {
|
---|
| 708 | x = Math.Floor(x);
|
---|
| 709 | y = Math.Floor(y);
|
---|
| 710 | }
|
---|
[13757] | 711 | }
|
---|
| 712 |
|
---|
[13718] | 713 | public event EventHandler<EventArgs<IProgress>> DownloadStarted;
|
---|
| 714 | private void OnDownloadStarted(IProgress progress) {
|
---|
| 715 | var handler = DownloadStarted;
|
---|
| 716 | if (handler != null) handler(this, new EventArgs<IProgress>(progress));
|
---|
| 717 | }
|
---|
[13722] | 718 |
|
---|
| 719 | public event EventHandler<EventArgs<IAlgorithm>> AlgorithmInstanceStarted;
|
---|
| 720 | private void OnAlgorithmInstanceStarted(IAlgorithm instance) {
|
---|
| 721 | var handler = AlgorithmInstanceStarted;
|
---|
| 722 | if (handler != null) handler(this, new EventArgs<IAlgorithm>(instance));
|
---|
| 723 | }
|
---|
[13757] | 724 |
|
---|
| 725 | // implement further classes and methods
|
---|
| 726 | private static SortedList<double, int> Ckmeans1dClusters(double[] estimations, int k, out int[] clusterValues) {
|
---|
| 727 | int nPoints = estimations.Length;
|
---|
| 728 | var distinct = estimations.Distinct().OrderBy(x => x).ToArray();
|
---|
| 729 | var max = distinct.Max();
|
---|
| 730 | if (distinct.Length <= k) {
|
---|
| 731 | var dict = distinct.Select((v, i) => new { Index = i, Value = v }).ToDictionary(x => x.Value, y => y.Index);
|
---|
| 732 | for (int i = distinct.Length; i < k; i++)
|
---|
| 733 | dict.Add(max + i - distinct.Length + 1, i);
|
---|
| 734 |
|
---|
| 735 | clusterValues = new int[nPoints];
|
---|
| 736 | for (int i = 0; i < nPoints; i++)
|
---|
| 737 | if (!dict.ContainsKey(estimations[i])) clusterValues[i] = 0;
|
---|
| 738 | else clusterValues[i] = dict[estimations[i]];
|
---|
| 739 |
|
---|
| 740 | return new SortedList<double, int>(dict);
|
---|
| 741 | }
|
---|
| 742 |
|
---|
| 743 | var n = distinct.Length;
|
---|
| 744 | var D = new double[n, k];
|
---|
| 745 | var B = new int[n, k];
|
---|
| 746 |
|
---|
| 747 | for (int m = 0; m < k; m++) {
|
---|
| 748 | for (int j = m; j <= n - k + m; j++) {
|
---|
| 749 | if (m == 0)
|
---|
| 750 | D[j, m] = SumOfSquaredDistances(distinct, 0, j + 1);
|
---|
| 751 | else {
|
---|
| 752 | var minD = double.MaxValue;
|
---|
| 753 | var minI = 0;
|
---|
| 754 | for (int i = 1; i <= j; i++) {
|
---|
| 755 | var d = D[i - 1, m - 1] + SumOfSquaredDistances(distinct, i, j + 1);
|
---|
| 756 | if (d < minD) {
|
---|
| 757 | minD = d;
|
---|
| 758 | minI = i;
|
---|
| 759 | }
|
---|
| 760 | }
|
---|
| 761 | D[j, m] = minD;
|
---|
| 762 | B[j, m] = minI;
|
---|
| 763 | }
|
---|
| 764 | }
|
---|
| 765 | }
|
---|
| 766 |
|
---|
| 767 | var centers = new SortedList<double, int>();
|
---|
| 768 | var upper = B[n - 1, k - 1];
|
---|
| 769 | var c = Mean(distinct, upper, n);
|
---|
| 770 | centers.Add(c, k - 1);
|
---|
| 771 | for (int i = k - 2; i >= 0; i--) {
|
---|
| 772 | var lower = B[upper - 1, i];
|
---|
| 773 | var c2 = Mean(distinct, lower, upper);
|
---|
| 774 | centers.Add(c2, i);
|
---|
| 775 | upper = lower;
|
---|
| 776 | }
|
---|
| 777 |
|
---|
| 778 | clusterValues = new int[nPoints];
|
---|
| 779 | for (int i = 0; i < estimations.Length; i++) {
|
---|
| 780 | clusterValues[i] = centers.MinItems(x => Math.Abs(estimations[i] - x.Key)).First().Value;
|
---|
| 781 | }
|
---|
| 782 |
|
---|
| 783 | return centers;
|
---|
| 784 | }
|
---|
| 785 |
|
---|
| 786 | private static double SumOfSquaredDistances(double[] x, int start, int end) {
|
---|
| 787 | if (start == end) throw new InvalidOperationException();
|
---|
| 788 | if (start + 1 == end) return 0.0;
|
---|
| 789 | double mean = 0.0;
|
---|
| 790 | for (int i = start; i < end; i++) {
|
---|
| 791 | mean += x[i];
|
---|
| 792 | }
|
---|
| 793 | mean /= (end - start);
|
---|
| 794 | var sum = 0.0;
|
---|
| 795 | for (int i = start; i < end; i++) {
|
---|
| 796 | sum += (x[i] - mean) * (x[i] - mean);
|
---|
| 797 | }
|
---|
| 798 | return sum;
|
---|
| 799 | }
|
---|
| 800 |
|
---|
| 801 | private static double Mean(double[] x, int start, int end) {
|
---|
| 802 | if (start == end) throw new InvalidOperationException();
|
---|
| 803 | double mean = 0.0;
|
---|
| 804 | for (int i = start; i < end; i++) {
|
---|
| 805 | mean += x[i];
|
---|
| 806 | }
|
---|
| 807 | mean /= (end - start);
|
---|
| 808 | return mean;
|
---|
| 809 | }
|
---|
[12842] | 810 | }
|
---|
| 811 | }
|
---|