Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2745 added LatinHyperCubeDesign as possible InitialSamplingPlan

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