Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone2/sources/HeuristicLab.Selection/3.3/ProportionalSelector.cs @ 5698

Last change on this file since 5698 was 1530, checked in by gkronber, 16 years ago

Moved source files of plugins Hive ... Visualization.Test into version-specific sub-folders. #576

File size: 7.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27
28namespace HeuristicLab.Selection {
29  /// <summary>
30  /// Copies or moves a number of sub scopes from a source scope to a target scope, their probability
31  /// to be selected depending on their quality.
32  /// </summary>
33  public class ProportionalSelector : StochasticSelectorBase {
34    /// <inheritdoc select="summary"/>
35    public override string Description {
36      get { return @"TODO\r\nOperator description still missing ..."; }
37    }
38
39    /// <summary>
40    /// Initializes a new instance of <see cref="ProportionalSelector"/> with three variable infos
41    /// (<c>Maximization</c>, <c>Quality</c> and <c>Windowing</c>, being a local variable and initialized
42    /// with <c>true</c>) and the <c>CopySelected</c> flag set to <c>true</c>.
43    /// </summary>
44    public ProportionalSelector() {
45      AddVariableInfo(new VariableInfo("Maximization", "Maximization problem", typeof(BoolData), VariableKind.In));
46      AddVariableInfo(new VariableInfo("Quality", "Quality value", typeof(DoubleData), VariableKind.In));
47      AddVariableInfo(new VariableInfo("Windowing", "Apply windowing strategy (selection probability is proportional to the quality differences and not to the total quality)", typeof(BoolData), VariableKind.In));
48      GetVariableInfo("Windowing").Local = true;
49      AddVariable(new Variable("Windowing", new BoolData(true)));
50      GetVariable("CopySelected").GetValue<BoolData>().Data = true;
51    }
52
53    /// <summary>
54    /// Copies or movies a number of sub scopes (<paramref name="selected"/>) in the given
55    /// <paramref name="source"/> to the given <paramref name="target"/>, selection takes place with respect
56    /// to the quality of the scope.
57    /// </summary>
58    /// <param name="random">The random number generator.</param>
59    /// <param name="source">The source scope from where to copy/move the sub scopes.</param>
60    /// <param name="selected">The number of sub scopes to copy/move.</param>
61    /// <param name="target">The target scope where to add the sub scopes.</param>
62    /// <param name="copySelected">Boolean flag whether the sub scopes shall be moved or copied.</param>
63    protected override void Select(IRandom random, IScope source, int selected, IScope target, bool copySelected) {
64      bool maximization = GetVariableValue<BoolData>("Maximization", source, true).Data;
65      IVariableInfo qualityInfo = GetVariableInfo("Quality");
66      bool windowing = GetVariableValue<BoolData>("Windowing", source, true).Data;
67
68      double[] qualities;
69      double qualitySum;
70      double selectedQuality;
71      double sum;
72      int j;
73
74      GenerateQualitiesArray(source, maximization, qualityInfo, windowing, out qualities, out qualitySum);
75
76      // perform selection
77      for (int i = 0; i < selected; i++) {
78        selectedQuality = random.NextDouble() * qualitySum;
79        sum = 0;
80        j = 0;
81        while ((j < qualities.Length) && (sum <= selectedQuality)) {
82          sum += qualities[j];
83          j++;
84        }
85        IScope selectedScope = source.SubScopes[j - 1];
86        if (copySelected)
87          target.AddSubScope((IScope)selectedScope.Clone());
88        else {
89          source.RemoveSubScope(selectedScope);
90          target.AddSubScope(selectedScope);
91          GenerateQualitiesArray(source, maximization, qualityInfo, windowing, out qualities, out qualitySum);
92        }
93      }
94    }
95
96    /// <summary>
97    /// Calculates the qualities of the sub scopes of the given <paramref name="source"/>.
98    /// </summary>
99    /// <exception cref="InvalidOperationException">Thrown when the sub scopes are not sorted according
100    /// to their solution qualities or if the quality value is beyond zero and the <c>windowing</c>
101    /// flag is set to <c>false</c>.</exception>
102    /// <param name="source">The scource scope where to calculate the qualities.</param>
103    /// <param name="maximization">Boolean flag whether is a maximization problem.</param>
104    /// <param name="qualityInfo">The quality variable info.</param>
105    /// <param name="windowing">Boolean flag whether the windowing strategy shall be applied.</param>
106    /// <param name="qualities">Output parameter; contains all qualities of the sub scopes.</param>
107    /// <param name="qualitySum">Output parameter; the sum of all qualities.</param>
108    private void GenerateQualitiesArray(IScope source, bool maximization, IVariableInfo qualityInfo, bool windowing, out double[] qualities, out double qualitySum) {
109      int subScopes = source.SubScopes.Count;
110      qualities = new double[subScopes];
111      qualitySum = 0;
112
113      if (subScopes < 1) throw new InvalidOperationException("No source scopes to select available.");
114
115      double best = source.SubScopes[0].GetVariableValue<DoubleData>(qualityInfo.FormalName, false).Data;
116      double worst = source.SubScopes[subScopes - 1].GetVariableValue<DoubleData>(qualityInfo.FormalName, false).Data;
117      double limit = Math.Min(worst * 2, double.MaxValue);
118      double min = Math.Min(best, worst);
119      double max = Math.Max(best, worst);
120      double solutionQuality;
121
122      // preprocess fitness values, apply windowing if desired
123      for (int i = 0; i < qualities.Length; i++) {
124        solutionQuality = source.SubScopes[i].GetVariableValue<DoubleData>(qualityInfo.FormalName, false).Data;
125        if (solutionQuality < min || solutionQuality > max) {
126          // something has obviously gone wrong here
127          string errorMessage = "There is a problem with the ordering of the source sub-scopes in " + Name + ".\r\n" +
128            "The quality of solution number " + i.ToString() + " is ";
129          if (solutionQuality < min) errorMessage += "below";
130          else errorMessage += "greater than";
131          errorMessage += " the calculated qualities range:\r\n";
132          errorMessage += solutionQuality.ToString() + " is outside the interval [ " + min.ToString() + " ; " + max.ToString() + " ].";
133          throw new InvalidOperationException(errorMessage);
134        }
135        if (best != worst) {  // prevent division by zero
136          if (windowing) {
137            if (!maximization) {
138              qualities[i] = 1 - ((solutionQuality - best) / (worst - best));
139            } else {
140              qualities[i] = (solutionQuality - worst) / (best - worst);
141            }
142          } else {
143            if (solutionQuality < 0.0) throw new InvalidOperationException("ERROR in ProportionalSelector: Non-windowing is not working with quality values < 0. Use windowing.");
144            if (!maximization) qualities[i] = limit - solutionQuality;
145            else qualities[i] = solutionQuality;
146          }
147        } else {  // best == worst -> all fitness values are equal
148          qualities[i] = 1;
149        }
150        qualitySum += qualities[i];
151      }
152      if (double.IsInfinity(qualitySum)) qualitySum = double.MaxValue;
153    }
154  }
155}
Note: See TracBrowser for help on using the repository browser.