source: branches/ScopedAlgorithms/HeuristicLab.Selection/3.3/TournamentSelector.cs @ 14429

Last change on this file since 14429 was 14429, checked in by abeham, 4 years ago

#2701, #2708: Made a new branch from ProblemRefactoring and removed ScopedBasicAlgorithm branch (which becomes MemPR branch)

File size: 6.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Optimization.Selection;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Selection {
34  /// <summary>
35  /// A tournament selection operator which considers a single double quality value for selection.
36  /// </summary>
37  [Item("TournamentSelector", "A tournament selection operator which considers a single double quality value for selection.")]
38  [StorableClass]
39  public sealed class TournamentSelector : StochasticSingleObjectiveSelector, ISingleObjectiveSelector {
40    public ValueLookupParameter<IntValue> GroupSizeParameter {
41      get { return (ValueLookupParameter<IntValue>)Parameters["GroupSize"]; }
42    }
43
44    [StorableConstructor]
45    private TournamentSelector(bool deserializing) : base(deserializing) { }
46    private TournamentSelector(TournamentSelector original, Cloner cloner) : base(original, cloner) { }
47    public override IDeepCloneable Clone(Cloner cloner) {
48      return new TournamentSelector(this, cloner);
49    }
50
51    public TournamentSelector()
52      : base() {
53      Parameters.Add(new ValueLookupParameter<IntValue>("GroupSize", "The size of the tournament group.", new IntValue(2)));
54    }
55
56    protected override IScope[] Select(List<IScope> scopes) {
57      int count = NumberOfSelectedSubScopesParameter.ActualValue.Value;
58      bool copy = CopySelectedParameter.Value.Value;
59      IRandom random = RandomParameter.ActualValue;
60      bool maximization = MaximizationParameter.ActualValue.Value;
61      List<double> qualities = QualityParameter.ActualValue.Where(x => IsValidQuality(x.Value)).Select(x => x.Value).ToList();
62      int groupSize = GroupSizeParameter.ActualValue.Value;
63      IScope[] selected = new IScope[count];
64
65      //check if list with indexes is as long as the original scope list
66      //otherwise invalid quality values were filtered
67      if (qualities.Count != scopes.Count) {
68        throw new ArgumentException("The scopes contain invalid quality values (either infinity or double.NaN) on which the selector cannot operate.");
69      }
70
71      for (int i = 0; i < count; i++) {
72        int best = random.Next(scopes.Count);
73        int index;
74        for (int j = 1; j < groupSize; j++) {
75          index = random.Next(scopes.Count);
76          if (((maximization) && (qualities[index] > qualities[best])) ||
77              ((!maximization) && (qualities[index] < qualities[best]))) {
78            best = index;
79          }
80        }
81
82        if (copy)
83          selected[i] = (IScope)scopes[best].Clone();
84        else {
85          selected[i] = scopes[best];
86          scopes.RemoveAt(best);
87          qualities.RemoveAt(best);
88        }
89      }
90      return selected;
91    }
92  }
93
94  [Item("Tournament Selector", "", ExcludeGenericTypeInfo = true)]
95  [StorableClass]
96  public sealed class TournamentSelector<TContext, TProblem, TEncoding, TSolution> : ParameterizedNamedItem, ISelector<TContext>
97      where TContext : ISingleObjectivePopulationContext<TSolution>, IMatingpoolContext<TSolution>, IStochasticContext,
98                       IProblemContext<TProblem, TEncoding, TSolution>
99      where TProblem : class, ISingleObjectiveProblem<TEncoding, TSolution>, ISingleObjectiveProblemDefinition<TEncoding, TSolution>
100      where TEncoding : class, IEncoding<TSolution>
101      where TSolution : class, ISolution {
102
103    [Storable]
104    private IValueParameter<IntValue> groupSizeParameter;
105    public int GroupSize {
106      get { return groupSizeParameter.Value.Value; }
107      set {
108        if (value < 1) throw new ArgumentException("Cannot use a group size less than 1 in tournament selection.");
109        groupSizeParameter.Value.Value = value;
110      }
111    }
112   
113    [StorableConstructor]
114    private TournamentSelector(bool deserializing) : base(deserializing) { }
115    private TournamentSelector(TournamentSelector<TContext, TProblem, TEncoding, TSolution> original, Cloner cloner)
116      : base(original, cloner) {
117      groupSizeParameter = cloner.Clone(groupSizeParameter);
118    }
119    public TournamentSelector() {
120      Parameters.Add(groupSizeParameter = new ValueParameter<IntValue>("GroupSize", "The group size that competes in the tournament.", new IntValue(2)));
121    }
122
123    public override IDeepCloneable Clone(Cloner cloner) {
124      return new TournamentSelector<TContext, TProblem, TEncoding, TSolution>(this, cloner);
125    }
126
127    public void Select(TContext context, int n, bool withRepetition) {
128      context.MatingPool = Select(context.Random, context.Problem.IsBetter, context.Population, GroupSize, n, withRepetition);
129    }
130
131    public static IEnumerable<ISingleObjectiveSolutionScope<TSolution>> Select(IRandom random, Func<double, double, bool> isBetterFunc, IEnumerable<ISingleObjectiveSolutionScope<TSolution>> population, int groupSize, int n, bool withRepetition) {
132      var pop = population.Where(x => !double.IsNaN(x.Fitness)).ToList();
133
134      var i = n;
135      while (i > 0 && pop.Count > 0) {
136        var best = random.Next(pop.Count);
137        for (var j = 1; j < groupSize; j++) {
138          var index = random.Next(pop.Count);
139          if (isBetterFunc(pop[index].Fitness, pop[best].Fitness)) {
140            best = index;
141          }
142        }
143
144        yield return pop[best];
145        i--;
146        if (!withRepetition) {
147          pop.RemoveAt(i);
148        }
149      }
150    }
151  }
152}
Note: See TracBrowser for help on using the repository browser.