Free cookie consent management tool by TermsFeed Policy Generator

source: branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/EgoUtilities.cs @ 15341

Last change on this file since 15341 was 15338, checked in by bwerth, 8 years ago

#2745 fixed bug concerning new Start and StartAsync methods; passed CancellationToken to sub algorithms

File size: 5.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.RealVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Problems.DataAnalysis;
31
32namespace HeuristicLab.Algorithms.EGO {
33  internal static class EgoUtilities {
34    //Extention methods for convenience
35    public static int ArgMax<T>(this IEnumerable<T> values, Func<T, double> func) {
36      var max = double.MinValue;
37      var maxIdx = 0;
38      var idx = 0;
39      foreach (var v in values) {
40        var d = func.Invoke(v);
41        if (d > max) {
42          max = d;
43          maxIdx = idx;
44        }
45        idx++;
46      }
47      return maxIdx;
48    }
49    public static int ArgMin<T>(this IEnumerable<T> values, Func<T, double> func) {
50      return ArgMax(values, x => -func.Invoke(x));
51    }
52    public static double GetEstimation(this IRegressionModel model, RealVector r) {
53      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
54      return model.GetEstimatedValues(dataset, new[] { 0 }).First();
55    }
56    public static double GetVariance(this IConfidenceRegressionModel model, RealVector r) {
57      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
58      return model.GetEstimatedVariances(dataset, new[] { 0 }).First();
59    }
60    public static double GetDoubleValue(this IDataset dataset, int i, int j) {
61      return dataset.GetDoubleValue("input" + j, i);
62    }
63
64    //Sub-ALgorithms
65    public static ResultCollection SyncRunSubAlgorithm(IAlgorithm alg, int random, CancellationToken cancellation) {
66      if (alg.Parameters.ContainsKey("SetSeedRandomly") && alg.Parameters.ContainsKey("Seed")) {
67        var setSeed = alg.Parameters["SetSeedRandomly"].ActualValue as BoolValue;
68        var seed = alg.Parameters["Seed"].ActualValue as IntValue;
69        if (seed == null || setSeed == null) throw new ArgumentException("wrong SeedParametertypes");
70        setSeed.Value = false;
71        seed.Value = random;
72      }
73      if (alg.ExecutionState != ExecutionState.Paused) alg.Prepare();
74      alg.Start(cancellation);
75      return alg.Results;
76    }
77
78    //RegressionModel extensions
79    private const double DuplicateResolution = 0.0001;
80    public static Dataset GetDataSet(IReadOnlyList<Tuple<RealVector, double>> samples, bool removeDuplicates) {
81      if (removeDuplicates) samples = RemoveDuplicates(samples); //TODO duplicate removal leads to incorrect uncertainty values in models
82      var dimensions = samples[0].Item1.Length + 1;
83      var data = new double[samples.Count, dimensions];
84      var names = new string[dimensions - 1];
85      for (var i = 0; i < names.Length; i++) names[i] = "input" + i;
86      for (var j = 0; j < samples.Count; j++) {
87        for (var i = 0; i < names.Length; i++) data[j, i] = samples[j].Item1[i];
88        data[j, dimensions - 1] = samples[j].Item2;
89      }
90      return new Dataset(names.Concat(new[] { "output" }).ToArray(), data);
91    }
92    private static IReadOnlyList<Tuple<RealVector, double>> RemoveDuplicates(IReadOnlyList<Tuple<RealVector, double>> samples) {
93      var res = new List<Tuple<RealVector, double, int>>();
94      foreach (var sample in samples) {
95        if (res.Count == 0) {
96          res.Add(new Tuple<RealVector, double, int>(sample.Item1, sample.Item2, 1));
97          continue;
98        }
99        var index = res.ArgMin(x => Euclidian(sample.Item1, x.Item1));
100        var d = Euclidian(res[index].Item1, sample.Item1);
101        if (d > DuplicateResolution)
102          res.Add(new Tuple<RealVector, double, int>(sample.Item1, sample.Item2, 1));
103        else {
104          var t = res[index];
105          res.RemoveAt(index);
106          res.Add(new Tuple<RealVector, double, int>(t.Item1, t.Item2 + sample.Item2, t.Item3 + 1));
107        }
108      }
109      return res.Select(x => new Tuple<RealVector, double>(x.Item1, x.Item2 / x.Item3)).ToArray();
110    }
111    private static double Euclidian(IEnumerable<double> a, IEnumerable<double> b) {
112      return Math.Sqrt(a.Zip(b, (d, d1) => d - d1).Sum(d => d * d));
113    }
114  }
115}
Note: See TracBrowser for help on using the repository browser.