Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15268 was 15064, checked in by bwerth, 7 years ago

#2745 implemented EGO as EngineAlgorithm + some simplifications in the IInfillCriterion interface

File size: 5.6 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.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.RealVectorEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Problems.DataAnalysis;
32
33namespace HeuristicLab.Algorithms.EGO {
34  internal static class EgoUtilities {
35    //Extention methods for convenience
36    public static int ArgMax<T>(this IEnumerable<T> values, Func<T, double> func) {
37      var max = double.MinValue;
38      var maxIdx = 0;
39      var idx = 0;
40      foreach (var v in values) {
41        var d = func.Invoke(v);
42        if (d > max) {
43          max = d;
44          maxIdx = idx;
45        }
46        idx++;
47      }
48      return maxIdx;
49    }
50    public static int ArgMin<T>(this IEnumerable<T> values, Func<T, double> func) {
51      return ArgMax(values, x => -func.Invoke(x));
52    }
53    public static double GetEstimation(this IRegressionModel model, RealVector r) {
54      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
55      return model.GetEstimatedValues(dataset, new[] { 0 }).First();
56    }
57    public static double GetVariance(this IConfidenceRegressionModel model, RealVector r) {
58      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
59      return model.GetEstimatedVariances(dataset, new[] { 0 }).First();
60    }
61    public static double GetDoubleValue(this IDataset dataset, int i, int j) {
62      return dataset.GetDoubleValue("input" + j, i);
63    }
64
65    //Sub-ALgorithms
66    public static ResultCollection SyncRunSubAlgorithm(IAlgorithm alg, int random) {
67
68      if (alg.Parameters.ContainsKey("SetSeedRandomly") && alg.Parameters.ContainsKey("Seed")) {
69        var setSeed = alg.Parameters["SetSeedRandomly"].ActualValue as BoolValue;
70        var seed = alg.Parameters["Seed"].ActualValue as IntValue;
71        if (seed == null || setSeed == null) throw new ArgumentException("wrong SeedParametertypes");
72        setSeed.Value = false;
73        seed.Value = random;
74
75      }
76
77
78      EventWaitHandle trigger = new AutoResetEvent(false);
79      Exception ex = null;
80      EventHandler<EventArgs<Exception>> exhandler = (sender, e) => { ex = e.Value; trigger.Set(); };
81      EventHandler stoppedHandler = (sender, e) => trigger.Set();
82
83      alg.ExceptionOccurred -= exhandler; //avoid double attaching in case of pause
84      alg.ExceptionOccurred += exhandler;
85      alg.Stopped -= stoppedHandler;
86      alg.Stopped += stoppedHandler;
87      alg.Paused -= stoppedHandler;
88      alg.Paused += stoppedHandler;
89
90      if (alg.ExecutionState != ExecutionState.Paused) alg.Prepare();
91      alg.Start();
92      trigger.WaitOne();
93      alg.ExceptionOccurred -= exhandler;
94      alg.Stopped -= stoppedHandler;
95      if (ex != null) throw ex;
96      return alg.Results;
97    }
98
99    //RegressionModel extensions
100    public const double DuplicateResolution = 0.0001;
101    public static Dataset GetDataSet(IReadOnlyList<Tuple<RealVector, double>> samples, bool removeDuplicates) {
102      if (removeDuplicates) samples = RemoveDuplicates(samples); //TODO duplicate removal leads to incorrect uncertainty values in models
103      var dimensions = samples[0].Item1.Length + 1;
104      var data = new double[samples.Count, dimensions];
105      var names = new string[dimensions - 1];
106      for (var i = 0; i < names.Length; i++) names[i] = "input" + i;
107      for (var j = 0; j < samples.Count; j++) {
108        for (var i = 0; i < names.Length; i++) data[j, i] = samples[j].Item1[i];
109        data[j, dimensions - 1] = samples[j].Item2;
110      }
111      return new Dataset(names.Concat(new[] { "output" }).ToArray(), data);
112    }
113    private static IReadOnlyList<Tuple<RealVector, double>> RemoveDuplicates(IReadOnlyList<Tuple<RealVector, double>> samples) {
114      var res = new List<Tuple<RealVector, double, int>>();
115      foreach (var sample in samples) {
116        if (res.Count == 0) {
117          res.Add(new Tuple<RealVector, double, int>(sample.Item1, sample.Item2, 1));
118          continue;
119        }
120        var index = res.ArgMin(x => Euclidian(sample.Item1, x.Item1));
121        var d = Euclidian(res[index].Item1, sample.Item1);
122        if (d > DuplicateResolution)
123          res.Add(new Tuple<RealVector, double, int>(sample.Item1, sample.Item2, 1));
124        else {
125          var t = res[index];
126          res.RemoveAt(index);
127          res.Add(new Tuple<RealVector, double, int>(t.Item1, t.Item2 + sample.Item2, t.Item3 + 1));
128        }
129      }
130      return res.Select(x => new Tuple<RealVector, double>(x.Item1, x.Item2 / x.Item3)).ToArray();
131    }
132    private static double Euclidian(IEnumerable<double> a, IEnumerable<double> b) {
133      return Math.Sqrt(a.Zip(b, (d, d1) => d - d1).Sum(d => d * d));
134    }
135  }
136}
Note: See TracBrowser for help on using the repository browser.