Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7150 was 6803, checked in by mkommend, 13 years ago

#1479: Merged grammar editor branch into trunk.

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