Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs @ 18092

Last change on this file since 18092 was 17246, checked in by gkronber, 5 years ago

#2925: merged r17037:17242 from trunk to branch

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 IValueParameter<PercentValue> CrossoverProbabilityParameter {
58      get { return (IValueParameter<PercentValue>)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 PercentValue CrossoverProbability {
72      get { return CrossoverProbabilityParameter.Value; }
73    }
74    #endregion
75    [StorableConstructor]
76    protected SubtreeCrossover(StorableConstructorFlag _) : base(_) { }
77    protected SubtreeCrossover(SubtreeCrossover original, Cloner cloner) : base(original, cloner) { }
78    public SubtreeCrossover()
79      : base() {
80      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
81      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
82      Parameters.Add(new ValueLookupParameter<PercentValue>(InternalCrossoverPointProbabilityParameterName, "The probability to select an internal crossover point (instead of a leaf node).", new PercentValue(0.9)));
83      Parameters.Add(new ValueParameter<PercentValue>(CrossoverProbabilityParameterName, "The probability to apply crossover (default 100%).", new PercentValue(1)));
84    }
85
86    public override IDeepCloneable Clone(Cloner cloner) {
87      return new SubtreeCrossover(this, cloner);
88    }
89
90    [StorableHook(HookType.AfterDeserialization)]
91    private void AfterDeserialization() {
92      if (!Parameters.ContainsKey(CrossoverProbabilityParameterName)) {
93        Parameters.Add(new ValueParameter<PercentValue>(CrossoverProbabilityParameterName, "The probability to apply crossover (default 100%).", new PercentValue(1)));
94      }
95    }
96
97    public override ISymbolicExpressionTree Crossover(IRandom random,
98      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
99      return Cross(random, parent0, parent1, InternalCrossoverPointProbability.Value,
100        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value, CrossoverProbability.Value);
101    }
102
103    public static ISymbolicExpressionTree Cross(IRandom random,
104      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
105      double internalCrossoverPointProbability, int maxTreeLength, int maxTreeDepth, double crossoverProbability = 1.0) {
106      if (random.NextDouble() >= crossoverProbability) {
107        return parent0;
108      }
109
110      // select a random crossover point in the first parent
111      CutPoint crossoverPoint0;
112      SelectCrossoverPoint(random, parent0, internalCrossoverPointProbability, maxTreeLength, maxTreeDepth, out crossoverPoint0);
113
114      int childLength = crossoverPoint0.Child != null ? crossoverPoint0.Child.GetLength() : 0;
115      // calculate the max length and depth that the inserted branch can have
116      int maxInsertedBranchLength = Math.Max(0, maxTreeLength - (parent0.Length - childLength));
117      int maxInsertedBranchDepth = Math.Max(0, maxTreeDepth - parent0.Root.GetBranchLevel(crossoverPoint0.Parent));
118
119      List<ISymbolicExpressionTreeNode> allowedBranches = new List<ISymbolicExpressionTreeNode>();
120      parent1.Root.ForEachNodePostfix((n) => {
121        if (n.GetLength() <= maxInsertedBranchLength &&
122            n.GetDepth() <= maxInsertedBranchDepth && crossoverPoint0.IsMatchingPointType(n))
123          allowedBranches.Add(n);
124      });
125      // empty branch
126      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
127
128      if (allowedBranches.Count == 0) {
129        return parent0;
130      } else {
131        var selectedBranch = SelectRandomBranch(random, allowedBranches, internalCrossoverPointProbability);
132        if (selectedBranch != null)
133          selectedBranch = (ISymbolicExpressionTreeNode)selectedBranch.Clone();
134
135        if (crossoverPoint0.Child != null) {
136          // manipulate the tree of parent0 in place
137          // replace the branch in tree0 with the selected branch from tree1
138          crossoverPoint0.Parent.RemoveSubtree(crossoverPoint0.ChildIndex);
139          if (selectedBranch != null) {
140            crossoverPoint0.Parent.InsertSubtree(crossoverPoint0.ChildIndex, selectedBranch);
141          }
142        } else {
143          // child is null (additional child should be added under the parent)
144          if (selectedBranch != null) {
145            crossoverPoint0.Parent.AddSubtree(selectedBranch);
146          }
147        }
148        return parent0;
149      }
150    }
151
152    private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out CutPoint crossoverPoint) {
153      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
154      List<CutPoint> internalCrossoverPoints = new List<CutPoint>();
155      List<CutPoint> leafCrossoverPoints = new List<CutPoint>();
156      parent0.Root.ForEachNodePostfix((n) => {
157        if (n.SubtreeCount > 0 && n != parent0.Root) {
158          //avoid linq to reduce memory pressure
159          for (int i = 0; i < n.SubtreeCount; i++) {
160            var child = n.GetSubtree(i);
161            if (child.GetLength() <= maxBranchLength &&
162                child.GetDepth() <= maxBranchDepth) {
163              if (child.SubtreeCount > 0)
164                internalCrossoverPoints.Add(new CutPoint(n, child));
165              else
166                leafCrossoverPoints.Add(new CutPoint(n, child));
167            }
168          }
169
170          // add one additional extension point if the number of sub trees for the symbol is not full
171          if (n.SubtreeCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
172            // empty extension point
173            internalCrossoverPoints.Add(new CutPoint(n, n.SubtreeCount));
174          }
175        }
176      }
177    );
178
179      if (random.NextDouble() < internalNodeProbability) {
180        // select from internal node if possible
181        if (internalCrossoverPoints.Count > 0) {
182          // select internal crossover point or leaf
183          crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
184        } else {
185          // otherwise select external node
186          crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
187        }
188      } else if (leafCrossoverPoints.Count > 0) {
189        // select from leaf crossover point if possible
190        crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
191      } else {
192        // otherwise select internal crossover point
193        crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
194      }
195    }
196
197    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, IEnumerable<ISymbolicExpressionTreeNode> branches, double internalNodeProbability) {
198      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
199      List<ISymbolicExpressionTreeNode> allowedInternalBranches;
200      List<ISymbolicExpressionTreeNode> allowedLeafBranches;
201      if (random.NextDouble() < internalNodeProbability) {
202        // select internal node if possible
203        allowedInternalBranches = (from branch in branches
204                                   where branch != null && branch.SubtreeCount > 0
205                                   select branch).ToList();
206        if (allowedInternalBranches.Count > 0) {
207          return allowedInternalBranches.SampleRandom(random);
208
209        } else {
210          // no internal nodes allowed => select leaf nodes
211          allowedLeafBranches = (from branch in branches
212                                 where branch == null || branch.SubtreeCount == 0
213                                 select branch).ToList();
214          return allowedLeafBranches.SampleRandom(random);
215        }
216      } else {
217        // select leaf node if possible
218        allowedLeafBranches = (from branch in branches
219                               where branch == null || branch.SubtreeCount == 0
220                               select branch).ToList();
221        if (allowedLeafBranches.Count > 0) {
222          return allowedLeafBranches.SampleRandom(random);
223        } else {
224          allowedInternalBranches = (from branch in branches
225                                     where branch != null && branch.SubtreeCount > 0
226                                     select branch).ToList();
227          return allowedInternalBranches.SampleRandom(random);
228
229        }
230      }
231    }
232  }
233}
Note: See TracBrowser for help on using the repository browser.