Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2745 added several new InfillCriteria and moved Parameters from the InfillProblem to the Criteria themselves; added Sanitiy checks for GaussianProcessRegression

File size: 6.3 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    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
53    public static ResultCollection SyncRunSubAlgorithm(IAlgorithm alg, int random) {
54
55      if (alg.Parameters.ContainsKey("SetSeedRandomly") && alg.Parameters.ContainsKey("Seed")) {
56        var setSeed = alg.Parameters["SetSeedRandomly"].ActualValue as BoolValue;
57        var seed = alg.Parameters["Seed"].ActualValue as IntValue;
58        if (seed == null || setSeed == null) throw new ArgumentException("wrong SeedParametertypes");
59        setSeed.Value = false;
60        seed.Value = random;
61
62      }
63
64
65      EventWaitHandle trigger = new AutoResetEvent(false);
66      Exception ex = null;
67      EventHandler<EventArgs<Exception>> exhandler = (sender, e) => ex = e.Value;
68      EventHandler stoppedHandler = (sender, e) => trigger.Set();
69      alg.ExceptionOccurred += exhandler;
70      alg.Stopped += stoppedHandler;
71      alg.Prepare();
72      alg.Start();
73      trigger.WaitOne();
74      alg.ExceptionOccurred -= exhandler;
75      alg.Stopped -= stoppedHandler;
76      if (ex != null) throw ex;
77      return alg.Results;
78    }
79    public static RealVector[] GetUniformRandomDesign(int points, int dim, DoubleMatrix bounds, IRandom random) {
80      var res = new RealVector[points];
81      for (var i = 0; i < points; i++) {
82        var r = new RealVector(dim);
83        res[i] = r;
84        for (var j = 0; j < dim; j++) {
85          var b = j % bounds.Rows;
86          r[j] = UniformRandom(bounds[b, 0], bounds[b, 1], random);
87        }
88      }
89      return res;
90    }
91    public static double UniformRandom(double min, double max, IRandom rand) {
92      return rand.NextDouble() * (max - min) + min;
93    }
94
95    public static double GetEstimation(this IRegressionModel model, RealVector r) {
96      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
97      return model.GetEstimatedValues(dataset, new[] { 0 }).First();
98    }
99    public static double GetVariance(this IConfidenceRegressionModel model, RealVector r) {
100      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
101      return model.GetEstimatedVariances(dataset, new[] { 0 }).First();
102    }
103
104
105    public static double GetDoubleValue(this IDataset dataset, int i, int j) {
106      return dataset.GetDoubleValue("input" + j, i);
107    }
108    public static Dataset GetDataSet(IReadOnlyList<Tuple<RealVector, double>> samples, bool removeDuplicates) {
109      if (removeDuplicates)
110        samples = RemoveDuplicates(samples); //TODO duplicates require heteroskedasticity in Models
111
112
113      var dimensions = samples[0].Item1.Length + 1;
114      var data = new double[samples.Count, dimensions];
115      var names = new string[dimensions - 1];
116      for (var i = 0; i < names.Length; i++) names[i] = "input" + i;
117
118      for (var j = 0; j < samples.Count; j++) {
119        for (var i = 0; i < names.Length; i++) data[j, i] = samples[j].Item1[i];
120        data[j, dimensions - 1] = samples[j].Item2;
121
122      }
123
124
125      return new Dataset(names.Concat(new[] { "output" }).ToArray(), data);
126    }
127
128    private static IReadOnlyList<Tuple<RealVector, double>> RemoveDuplicates(IReadOnlyList<Tuple<RealVector, double>> samples) {
129      var res = new List<Tuple<RealVector, double, int>>();
130
131      foreach (var sample in samples) {
132        if (res.Count == 0) {
133          res.Add(new Tuple<RealVector, double, int>(sample.Item1, sample.Item2, 1));
134          continue;
135        }
136
137        var index = res.ArgMin(x => Euclidian(sample.Item1, x.Item1));
138        var d = Euclidian(res[index].Item1, sample.Item1);
139        if (d > 0.0001)
140          res.Add(new Tuple<RealVector, double, int>(sample.Item1, sample.Item2, 1));
141        else {
142          var t = res[index];
143          res.RemoveAt(index);
144          res.Add(new Tuple<RealVector, double, int>(t.Item1, t.Item2 + sample.Item2, t.Item3 + 1));
145        }
146      }
147      return res.Select(x => new Tuple<RealVector, double>(x.Item1, x.Item2 / x.Item3)).ToArray();
148    }
149
150    private static double Euclidian(IEnumerable<double> a, IEnumerable<double> b) {
151      return Math.Sqrt(a.Zip(b, (d, d1) => d - d1).Sum(d => d * d));
152    }
153
154    public static DoubleMatrix GetBoundingBox(IEnumerable<RealVector> vectors) {
155      DoubleMatrix res = null;
156      foreach (var vector in vectors)
157        if (res == null) {
158          res = new DoubleMatrix(vector.Length, 2);
159          for (var i = 0; i < vector.Length; i++)
160            res[i, 0] = res[i, 1] = vector[i];
161        } else
162          for (var i = 0; i < vector.Length; i++) {
163            res[i, 0] = Math.Min(vector[i], res[i, 0]);
164            res[i, 1] = Math.Max(vector[i], res[i, 1]);
165          }
166      return res;
167    }
168
169
170  }
171}
Note: See TracBrowser for help on using the repository browser.