Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.RealVectorEncoding/3.3/Creators/NormalDistributedRealVectorCreator.cs @ 10186

Last change on this file since 10186 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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 HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Optimization;
27using HeuristicLab.Parameters;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29using HeuristicLab.Random;
30
31namespace HeuristicLab.Encodings.RealVectorEncoding {
32  /// <summary>
33  /// An operator which creates a new random real vector with each element normally distributed in a specified range.
34  /// </summary>
35  [Item("NormalDistributedRealVectorCreator", "An operator which creates a new random real vector with each element normally distributed in a specified range.")]
36  [StorableClass]
37  public class NormalDistributedRealVectorCreator : RealVectorCreator, IStrategyParameterCreator {
38
39    public IValueLookupParameter<RealVector> MeanParameter {
40      get { return (IValueLookupParameter<RealVector>)Parameters["Mean"]; }
41    }
42
43    public IValueLookupParameter<DoubleArray> SigmaParameter {
44      get { return (IValueLookupParameter<DoubleArray>)Parameters["Sigma"]; }
45    }
46
47    public IValueParameter<IntValue> MaximumTriesParameter {
48      get { return (IValueParameter<IntValue>)Parameters["MaximumTries"]; }
49    }
50
51    [StorableConstructor]
52    protected NormalDistributedRealVectorCreator(bool deserializing) : base(deserializing) { }
53    protected NormalDistributedRealVectorCreator(NormalDistributedRealVectorCreator original, Cloner cloner) : base(original, cloner) { }
54    public NormalDistributedRealVectorCreator()
55      : base() {
56      Parameters.Add(new ValueLookupParameter<RealVector>("Mean", "The mean vector around which the points will be sampled."));
57      Parameters.Add(new ValueLookupParameter<DoubleArray>("Sigma", "The standard deviations for all or for each dimension."));
58      Parameters.Add(new ValueParameter<IntValue>("MaximumTries", "The maximum number of tries to sample within the specified bounds.", new IntValue(1000)));
59    }
60
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new NormalDistributedRealVectorCreator(this, cloner);
63    }
64
65    [StorableHook(HookType.AfterDeserialization)]
66    private void AfterDeserialization() {
67      if (!Parameters.ContainsKey("MaximumTries"))
68        Parameters.Add(new ValueParameter<IntValue>("MaximumTries", "The maximum number of tries to sample within the specified bounds.", new IntValue(1000)));
69    }
70
71    /// <summary>
72    /// Generates a new random real vector normally distributed around the given mean with the given <paramref name="length"/> and in the interval [min,max).
73    /// </summary>
74    /// <exception cref="ArgumentException">
75    /// Thrown when <paramref name="random"/> is null.<br />
76    /// Thrown when <paramref name="mean"/> is null or of length 0.<br />
77    /// Thrown when <paramref name="sigma"/> is null or of length 0.<br />
78    /// </exception>
79    /// <remarks>
80    /// If no bounds are given the bounds will be set to (double.MinValue;double.MaxValue).
81    ///
82    /// If dimensions of the mean do not lie within the given bounds they're set to either to the min or max of the bounds depending on whether the given dimension
83    /// for the mean is smaller or larger than the bounds. If min and max for a certain dimension are almost the same the resulting value will be set to min.
84    ///
85    /// However, please consider that such static bounds are not really meaningful to optimize.
86    ///
87    /// The sigma vector can contain 0 values in which case the dimension will be exactly the same as the given mean.
88    /// </remarks>
89    /// <param name="random">The random number generator.</param>
90    /// <param name="mean">The mean vector around which the resulting vector is sampled.</param>
91    /// <param name="sigma">The vector of standard deviations, must have at least one row.</param>
92    /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
93    /// <param name="maximumTries">The maximum number of tries to sample a value inside the bounds for each dimension. If a valid value cannot be obtained, the mean will be used.</param>
94    /// <returns>The newly created real vector.</returns>
95    public static RealVector Apply(IRandom random, RealVector mean, DoubleArray sigma, DoubleMatrix bounds, int maximumTries = 1000) {
96      if (random == null) throw new ArgumentNullException("Random is not defined", "random");
97      if (mean == null || mean.Length == 0) throw new ArgumentNullException("Mean is not defined", "mean");
98      if (sigma == null || sigma.Length == 0) throw new ArgumentNullException("Sigma is not defined.", "sigma");
99      if (bounds == null || bounds.Rows == 0) bounds = new DoubleMatrix(new[,] { { double.MinValue, double.MaxValue } });
100      var nd = new NormalDistributedRandom(random, 0, 1);
101      var result = (RealVector)mean.Clone();
102      for (int i = 0; i < result.Length; i++) {
103        var min = bounds[i % bounds.Rows, 0];
104        var max = bounds[i % bounds.Rows, 1];
105        if (min.IsAlmost(max) || mean[i] < min) result[i] = min;
106        else if (mean[i] > max) result[i] = max;
107        else {
108          int count = 0;
109          bool inRange;
110          do {
111            result[i] = mean[i] + sigma[i % sigma.Length] * nd.NextDouble();
112            inRange = result[i] >= bounds[i % bounds.Rows, 0] && result[i] < bounds[i % bounds.Rows, 1];
113            count++;
114          } while (count < maximumTries && !inRange);
115          if (count == maximumTries && !inRange)
116            result[i] = mean[i];
117        }
118      }
119      return result;
120    }
121
122    /// <summary>
123    /// Forwards the call to <see cref="Apply(IRandom, RealVector, DoubleArray, DoubleMatrix)"/>.
124    /// </summary>
125    /// <param name="random">The pseudo random number generator to use.</param>
126    /// <param name="length">The length of the real vector.</param>
127    /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
128    /// <returns>The newly created real vector.</returns>
129    protected override RealVector Create(IRandom random, IntValue length, DoubleMatrix bounds) {
130      return Apply(random, MeanParameter.ActualValue, SigmaParameter.ActualValue, bounds, MaximumTriesParameter.Value.Value);
131    }
132  }
133}
Note: See TracBrowser for help on using the repository browser.