Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs @ 14908

Last change on this file since 14908 was 14798, checked in by mkommend, 8 years ago

#2647: Merged r14221, r14223, r14224 into stable.

File size: 10.9 KB
RevLine 
[645]1#region License Information
2/* HeuristicLab
[14186]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[645]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
[4068]22using System;
[645]23using System.Collections.Generic;
[4068]24using System.Linq;
[4722]25using HeuristicLab.Common;
[645]26using HeuristicLab.Core;
[3237]27using HeuristicLab.Data;
28using HeuristicLab.Parameters;
[4068]29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[12706]30using HeuristicLab.Random;
[645]31
[5499]32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[3237]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> 
[7506]39  [Item("SubtreeSwappingCrossover", "An operator which performs subtree swapping crossover.")]
[3237]40  [StorableClass]
[7506]41  public class SubtreeCrossover : SymbolicExpressionTreeCrossover, ISymbolicExpressionTreeSizeConstraintOperator {
[5499]42    private const string InternalCrossoverPointProbabilityParameterName = "InternalCrossoverPointProbability";
43    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
44    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
[7506]45
[5499]46    #region Parameter Properties
[3237]47    public IValueLookupParameter<PercentValue> InternalCrossoverPointProbabilityParameter {
[5499]48      get { return (IValueLookupParameter<PercentValue>)Parameters[InternalCrossoverPointProbabilityParameterName]; }
[645]49    }
[5499]50    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
51      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
52    }
53    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
54      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
55    }
56    #endregion
57    #region Properties
58    public PercentValue InternalCrossoverPointProbability {
59      get { return InternalCrossoverPointProbabilityParameter.ActualValue; }
60    }
61    public IntValue MaximumSymbolicExpressionTreeLength {
62      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
63    }
64    public IntValue MaximumSymbolicExpressionTreeDepth {
65      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
66    }
67    #endregion
[4722]68    [StorableConstructor]
[7506]69    protected SubtreeCrossover(bool deserializing) : base(deserializing) { }
70    protected SubtreeCrossover(SubtreeCrossover original, Cloner cloner) : base(original, cloner) { }
[3237]71    public SubtreeCrossover()
72      : base() {
[5499]73      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
74      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
75      Parameters.Add(new ValueLookupParameter<PercentValue>(InternalCrossoverPointProbabilityParameterName, "The probability to select an internal crossover point (instead of a leaf node).", new PercentValue(0.9)));
[3237]76    }
77
[4722]78    public override IDeepCloneable Clone(Cloner cloner) {
79      return new SubtreeCrossover(this, cloner);
80    }
81
[7506]82    public override ISymbolicExpressionTree Crossover(IRandom random,
[5510]83      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
[5499]84      return Cross(random, parent0, parent1, InternalCrossoverPointProbability.Value,
85        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
[3237]86    }
87
[5510]88    public static ISymbolicExpressionTree Cross(IRandom random,
89      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
[5549]90      double internalCrossoverPointProbability, int maxTreeLength, int maxTreeDepth) {
[3294]91      // select a random crossover point in the first parent
[5916]92      CutPoint crossoverPoint0;
93      SelectCrossoverPoint(random, parent0, internalCrossoverPointProbability, maxTreeLength, maxTreeDepth, out crossoverPoint0);
[645]94
[5916]95      int childLength = crossoverPoint0.Child != null ? crossoverPoint0.Child.GetLength() : 0;
[5549]96      // calculate the max length and depth that the inserted branch can have
[14199]97      int maxInsertedBranchLength = Math.Max(0, maxTreeLength - (parent0.Length - childLength));
98      int maxInsertedBranchDepth = Math.Max(0, maxTreeDepth - parent0.Root.GetBranchLevel(crossoverPoint0.Parent));
[645]99
[5510]100      List<ISymbolicExpressionTreeNode> allowedBranches = new List<ISymbolicExpressionTreeNode>();
[3997]101      parent1.Root.ForEachNodePostfix((n) => {
[5549]102        if (n.GetLength() <= maxInsertedBranchLength &&
[7506]103            n.GetDepth() <= maxInsertedBranchDepth && crossoverPoint0.IsMatchingPointType(n))
[3997]104          allowedBranches.Add(n);
105      });
[5916]106      // empty branch
[7506]107      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
[645]108
[3997]109      if (allowedBranches.Count == 0) {
[3297]110        return parent0;
111      } else {
[3294]112        var selectedBranch = SelectRandomBranch(random, allowedBranches, internalCrossoverPointProbability);
[14798]113        if (selectedBranch != null)
114          selectedBranch = (ISymbolicExpressionTreeNode)selectedBranch.Clone();
[645]115
[5916]116        if (crossoverPoint0.Child != null) {
117          // manipulate the tree of parent0 in place
118          // replace the branch in tree0 with the selected branch from tree1
119          crossoverPoint0.Parent.RemoveSubtree(crossoverPoint0.ChildIndex);
120          if (selectedBranch != null) {
121            crossoverPoint0.Parent.InsertSubtree(crossoverPoint0.ChildIndex, selectedBranch);
122          }
123        } else {
124          // child is null (additional child should be added under the parent)
125          if (selectedBranch != null) {
126            crossoverPoint0.Parent.AddSubtree(selectedBranch);
127          }
128        }
[3294]129        return parent0;
[645]130      }
131    }
132
[5916]133    private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out CutPoint crossoverPoint) {
[3997]134      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
[5686]135      List<CutPoint> internalCrossoverPoints = new List<CutPoint>();
136      List<CutPoint> leafCrossoverPoints = new List<CutPoint>();
[3997]137      parent0.Root.ForEachNodePostfix((n) => {
[7506]138        if (n.SubtreeCount > 0 && n != parent0.Root) {
[12702]139          //avoid linq to reduce memory pressure
140          for (int i = 0; i < n.SubtreeCount; i++) {
141            var child = n.GetSubtree(i);
[5549]142            if (child.GetLength() <= maxBranchLength &&
143                child.GetDepth() <= maxBranchDepth) {
[7506]144              if (child.SubtreeCount > 0)
[5686]145                internalCrossoverPoints.Add(new CutPoint(n, child));
[5367]146              else
[5686]147                leafCrossoverPoints.Add(new CutPoint(n, child));
[5367]148            }
[3997]149          }
[7506]150
[5916]151          // add one additional extension point if the number of sub trees for the symbol is not full
[6803]152          if (n.SubtreeCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
[5916]153            // empty extension point
[6803]154            internalCrossoverPoints.Add(new CutPoint(n, n.SubtreeCount));
[5916]155          }
[3997]156        }
[7506]157      }
158    );
[5367]159
[3997]160      if (random.NextDouble() < internalNodeProbability) {
161        // select from internal node if possible
162        if (internalCrossoverPoints.Count > 0) {
163          // select internal crossover point or leaf
[5916]164          crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
[3997]165        } else {
166          // otherwise select external node
[5916]167          crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
[3997]168        }
169      } else if (leafCrossoverPoints.Count > 0) {
170        // select from leaf crossover point if possible
[5916]171        crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
[3997]172      } else {
173        // otherwise select internal crossover point
[5916]174        crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
[645]175      }
176    }
[3237]177
[5510]178    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, IEnumerable<ISymbolicExpressionTreeNode> branches, double internalNodeProbability) {
[3237]179      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
[5510]180      List<ISymbolicExpressionTreeNode> allowedInternalBranches;
181      List<ISymbolicExpressionTreeNode> allowedLeafBranches;
[3997]182      if (random.NextDouble() < internalNodeProbability) {
183        // select internal node if possible
184        allowedInternalBranches = (from branch in branches
[7506]185                                   where branch != null && branch.SubtreeCount > 0
[3997]186                                   select branch).ToList();
187        if (allowedInternalBranches.Count > 0) {
[12706]188          return allowedInternalBranches.SampleRandom(random);
189
[3997]190        } else {
191          // no internal nodes allowed => select leaf nodes
192          allowedLeafBranches = (from branch in branches
[7506]193                                 where branch == null || branch.SubtreeCount == 0
[3989]194                                 select branch).ToList();
[12706]195          return allowedLeafBranches.SampleRandom(random);
[3997]196        }
[3237]197      } else {
[3997]198        // select leaf node if possible
199        allowedLeafBranches = (from branch in branches
[7506]200                               where branch == null || branch.SubtreeCount == 0
[3997]201                               select branch).ToList();
202        if (allowedLeafBranches.Count > 0) {
[12706]203          return allowedLeafBranches.SampleRandom(random);
[3997]204        } else {
205          allowedInternalBranches = (from branch in branches
[7506]206                                     where branch != null && branch.SubtreeCount > 0
[3997]207                                     select branch).ToList();
[12706]208          return allowedInternalBranches.SampleRandom(random);
209
[3997]210        }
[3237]211      }
212    }
[645]213  }
214}
Note: See TracBrowser for help on using the repository browser.