Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs @ 17491

Last change on this file since 17491 was 17491, checked in by gkronber, 4 years ago

#3067: fix reproducability by calling the PRNG only when probability is < 1

File size: 11.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Parameters;
29using HEAL.Attic;
30using HeuristicLab.Random;
31
32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
33  /// <summary>
34  /// Takes two parent individuals P0 and P1 each. Selects a random node N0 of P0 and a random node N1 of P1.
35  /// And replaces the branch with root0 N0 in P0 with N1 from P1 if the tree-size limits are not violated.
36  /// When recombination with N0 and N1 would create a tree that is too large or invalid the operator randomly selects new N0 and N1
37  /// until a valid configuration is found.
38  /// </summary> 
39  [Item("SubtreeSwappingCrossover", "An operator which performs subtree swapping crossover.")]
40  [StorableType("2A2552C0-11C8-4F60-90B2-5FDDD3AB2444")]
41  public class SubtreeCrossover : SymbolicExpressionTreeCrossover, ISymbolicExpressionTreeSizeConstraintOperator {
42    private const string InternalCrossoverPointProbabilityParameterName = "InternalCrossoverPointProbability";
43    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
44    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
45    private const string CrossoverProbabilityParameterName = "CrossoverProbability";
46
47    #region Parameter Properties
48    public IValueLookupParameter<PercentValue> InternalCrossoverPointProbabilityParameter {
49      get { return (IValueLookupParameter<PercentValue>)Parameters[InternalCrossoverPointProbabilityParameterName]; }
50    }
51    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
52      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
53    }
54    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
55      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
56    }
57    public IFixedValueParameter<DoubleValue> CrossoverProbabilityParameter {
58      get { return (IFixedValueParameter<DoubleValue>)Parameters[CrossoverProbabilityParameterName]; }
59    }
60    #endregion
61    #region Properties
62    public PercentValue InternalCrossoverPointProbability {
63      get { return InternalCrossoverPointProbabilityParameter.ActualValue; }
64    }
65    public IntValue MaximumSymbolicExpressionTreeLength {
66      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
67    }
68    public IntValue MaximumSymbolicExpressionTreeDepth {
69      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
70    }
71    public double CrossoverProbability {
72      get { return CrossoverProbabilityParameter.Value.Value; }
73      set { CrossoverProbabilityParameter.Value.Value = value; }
74    }
75    #endregion
76    [StorableConstructor]
77    protected SubtreeCrossover(StorableConstructorFlag _) : base(_) { }
78    protected SubtreeCrossover(SubtreeCrossover original, Cloner cloner) : base(original, cloner) { }
79    public SubtreeCrossover()
80      : base() {
81      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
82      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
83      Parameters.Add(new ValueLookupParameter<PercentValue>(InternalCrossoverPointProbabilityParameterName, "The probability to select an internal crossover point (instead of a leaf node).", new PercentValue(0.9)));
84      Parameters.Add(new FixedValueParameter<DoubleValue>(CrossoverProbabilityParameterName, "", new DoubleValue(1)));
85    }
86
87    [StorableHook(HookType.AfterDeserialization)]
88    private void AfterDeserialization() {
89      if (!Parameters.ContainsKey(CrossoverProbabilityParameterName)) {
90        Parameters.Add(new FixedValueParameter<DoubleValue>(CrossoverProbabilityParameterName, "", new DoubleValue(1)));
91      }
92    }
93
94    public override IDeepCloneable Clone(Cloner cloner) {
95      return new SubtreeCrossover(this, cloner);
96    }
97
98    public override ISymbolicExpressionTree Crossover(IRandom random,
99      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
100      return Cross(random, parent0, parent1, CrossoverProbability, InternalCrossoverPointProbability.Value,
101        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
102    }
103
104    public static ISymbolicExpressionTree Cross(IRandom random,
105      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
106      double probability,
107      double internalCrossoverPointProbability, int maxTreeLength, int maxTreeDepth) {
108      if ((probability < 1) && (random.NextDouble() >= probability)) return random.NextDouble() < 0.5 ? parent0 : parent1;
109      // select a random crossover point in the first parent
110      CutPoint crossoverPoint0;
111      SelectCrossoverPoint(random, parent0, internalCrossoverPointProbability, maxTreeLength, maxTreeDepth, out crossoverPoint0);
112
113      int childLength = crossoverPoint0.Child != null ? crossoverPoint0.Child.GetLength() : 0;
114      // calculate the max length and depth that the inserted branch can have
115      int maxInsertedBranchLength = Math.Max(0, maxTreeLength - (parent0.Length - childLength));
116      int maxInsertedBranchDepth = Math.Max(0, maxTreeDepth - parent0.Root.GetBranchLevel(crossoverPoint0.Parent));
117
118      List<ISymbolicExpressionTreeNode> allowedBranches = new List<ISymbolicExpressionTreeNode>();
119      parent1.Root.ForEachNodePostfix((n) => {
120        if (n.GetLength() <= maxInsertedBranchLength &&
121            n.GetDepth() <= maxInsertedBranchDepth && crossoverPoint0.IsMatchingPointType(n))
122          allowedBranches.Add(n);
123      });
124      // empty branch
125      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
126
127      if (allowedBranches.Count == 0) {
128        return parent0;
129      } else {
130        var selectedBranch = SelectRandomBranch(random, allowedBranches, internalCrossoverPointProbability);
131        if (selectedBranch != null)
132          selectedBranch = (ISymbolicExpressionTreeNode)selectedBranch.Clone();
133
134        if (crossoverPoint0.Child != null) {
135          // manipulate the tree of parent0 in place
136          // replace the branch in tree0 with the selected branch from tree1
137          crossoverPoint0.Parent.RemoveSubtree(crossoverPoint0.ChildIndex);
138          if (selectedBranch != null) {
139            crossoverPoint0.Parent.InsertSubtree(crossoverPoint0.ChildIndex, selectedBranch);
140          }
141        } else {
142          // child is null (additional child should be added under the parent)
143          if (selectedBranch != null) {
144            crossoverPoint0.Parent.AddSubtree(selectedBranch);
145          }
146        }
147        return parent0;
148      }
149    }
150
151    private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out CutPoint crossoverPoint) {
152      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
153      List<CutPoint> internalCrossoverPoints = new List<CutPoint>();
154      List<CutPoint> leafCrossoverPoints = new List<CutPoint>();
155      parent0.Root.ForEachNodePostfix((n) => {
156        if (n.SubtreeCount > 0 && n != parent0.Root) {
157          //avoid linq to reduce memory pressure
158          for (int i = 0; i < n.SubtreeCount; i++) {
159            var child = n.GetSubtree(i);
160            if (child.GetLength() <= maxBranchLength &&
161                child.GetDepth() <= maxBranchDepth) {
162              if (child.SubtreeCount > 0)
163                internalCrossoverPoints.Add(new CutPoint(n, child));
164              else
165                leafCrossoverPoints.Add(new CutPoint(n, child));
166            }
167          }
168
169          // add one additional extension point if the number of sub trees for the symbol is not full
170          if (n.SubtreeCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
171            // empty extension point
172            internalCrossoverPoints.Add(new CutPoint(n, n.SubtreeCount));
173          }
174        }
175      }
176    );
177
178      if (random.NextDouble() < internalNodeProbability) {
179        // select from internal node if possible
180        if (internalCrossoverPoints.Count > 0) {
181          // select internal crossover point or leaf
182          crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
183        } else {
184          // otherwise select external node
185          crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
186        }
187      } else if (leafCrossoverPoints.Count > 0) {
188        // select from leaf crossover point if possible
189        crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
190      } else {
191        // otherwise select internal crossover point
192        crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
193      }
194    }
195
196    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, IEnumerable<ISymbolicExpressionTreeNode> branches, double internalNodeProbability) {
197      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
198      List<ISymbolicExpressionTreeNode> allowedInternalBranches;
199      List<ISymbolicExpressionTreeNode> allowedLeafBranches;
200      if (random.NextDouble() < internalNodeProbability) {
201        // select internal node if possible
202        allowedInternalBranches = (from branch in branches
203                                   where branch != null && branch.SubtreeCount > 0
204                                   select branch).ToList();
205        if (allowedInternalBranches.Count > 0) {
206          return allowedInternalBranches.SampleRandom(random);
207
208        } else {
209          // no internal nodes allowed => select leaf nodes
210          allowedLeafBranches = (from branch in branches
211                                 where branch == null || branch.SubtreeCount == 0
212                                 select branch).ToList();
213          return allowedLeafBranches.SampleRandom(random);
214        }
215      } else {
216        // select leaf node if possible
217        allowedLeafBranches = (from branch in branches
218                               where branch == null || branch.SubtreeCount == 0
219                               select branch).ToList();
220        if (allowedLeafBranches.Count > 0) {
221          return allowedLeafBranches.SampleRandom(random);
222        } else {
223          allowedInternalBranches = (from branch in branches
224                                     where branch != null && branch.SubtreeCount > 0
225                                     select branch).ToList();
226          return allowedInternalBranches.SampleRandom(random);
227
228        }
229      }
230    }
231  }
232}
Note: See TracBrowser for help on using the repository browser.