Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

File size: 11.9 KB
RevLine 
[645]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) 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;
[16565]29using HEAL.Attic;
[12422]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.")]
[16565]40  [StorableType("2A2552C0-11C8-4F60-90B2-5FDDD3AB2444")]
[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";
[17490]45    private const string CrossoverProbabilityParameterName = "CrossoverProbability";
[7506]46
[5499]47    #region Parameter Properties
[3237]48    public IValueLookupParameter<PercentValue> InternalCrossoverPointProbabilityParameter {
[5499]49      get { return (IValueLookupParameter<PercentValue>)Parameters[InternalCrossoverPointProbabilityParameterName]; }
[645]50    }
[5499]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    }
[17490]57    public IFixedValueParameter<DoubleValue> CrossoverProbabilityParameter {
58      get { return (IFixedValueParameter<DoubleValue>)Parameters[CrossoverProbabilityParameterName]; }
59    }
[5499]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    }
[17490]71    public double CrossoverProbability {
72      get { return CrossoverProbabilityParameter.Value.Value; }
73      set { CrossoverProbabilityParameter.Value.Value = value; }
74    }
[5499]75    #endregion
[4722]76    [StorableConstructor]
[16565]77    protected SubtreeCrossover(StorableConstructorFlag _) : base(_) { }
[7506]78    protected SubtreeCrossover(SubtreeCrossover original, Cloner cloner) : base(original, cloner) { }
[3237]79    public SubtreeCrossover()
80      : base() {
[5499]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)));
[17490]84      Parameters.Add(new FixedValueParameter<DoubleValue>(CrossoverProbabilityParameterName, "", new DoubleValue(1)));
[3237]85    }
86
[17490]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
[4722]94    public override IDeepCloneable Clone(Cloner cloner) {
95      return new SubtreeCrossover(this, cloner);
96    }
97
[7506]98    public override ISymbolicExpressionTree Crossover(IRandom random,
[5510]99      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
[17490]100      return Cross(random, parent0, parent1, CrossoverProbability, InternalCrossoverPointProbability.Value,
[5499]101        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
[3237]102    }
103
[5510]104    public static ISymbolicExpressionTree Cross(IRandom random,
105      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
[17490]106      double probability,
[5549]107      double internalCrossoverPointProbability, int maxTreeLength, int maxTreeDepth) {
[17491]108      if ((probability < 1) && (random.NextDouble() >= probability)) return random.NextDouble() < 0.5 ? parent0 : parent1;
[3294]109      // select a random crossover point in the first parent
[5916]110      CutPoint crossoverPoint0;
111      SelectCrossoverPoint(random, parent0, internalCrossoverPointProbability, maxTreeLength, maxTreeDepth, out crossoverPoint0);
[645]112
[5916]113      int childLength = crossoverPoint0.Child != null ? crossoverPoint0.Child.GetLength() : 0;
[5549]114      // calculate the max length and depth that the inserted branch can have
[14198]115      int maxInsertedBranchLength = Math.Max(0, maxTreeLength - (parent0.Length - childLength));
116      int maxInsertedBranchDepth = Math.Max(0, maxTreeDepth - parent0.Root.GetBranchLevel(crossoverPoint0.Parent));
[645]117
[5510]118      List<ISymbolicExpressionTreeNode> allowedBranches = new List<ISymbolicExpressionTreeNode>();
[3997]119      parent1.Root.ForEachNodePostfix((n) => {
[5549]120        if (n.GetLength() <= maxInsertedBranchLength &&
[7506]121            n.GetDepth() <= maxInsertedBranchDepth && crossoverPoint0.IsMatchingPointType(n))
[3997]122          allowedBranches.Add(n);
123      });
[5916]124      // empty branch
[7506]125      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
[645]126
[3997]127      if (allowedBranches.Count == 0) {
[3297]128        return parent0;
129      } else {
[3294]130        var selectedBranch = SelectRandomBranch(random, allowedBranches, internalCrossoverPointProbability);
[14221]131        if (selectedBranch != null)
132          selectedBranch = (ISymbolicExpressionTreeNode)selectedBranch.Clone();
[645]133
[5916]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        }
[3294]147        return parent0;
[645]148      }
149    }
150
[5916]151    private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out CutPoint crossoverPoint) {
[3997]152      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
[5686]153      List<CutPoint> internalCrossoverPoints = new List<CutPoint>();
154      List<CutPoint> leafCrossoverPoints = new List<CutPoint>();
[3997]155      parent0.Root.ForEachNodePostfix((n) => {
[7506]156        if (n.SubtreeCount > 0 && n != parent0.Root) {
[12509]157          //avoid linq to reduce memory pressure
158          for (int i = 0; i < n.SubtreeCount; i++) {
159            var child = n.GetSubtree(i);
[5549]160            if (child.GetLength() <= maxBranchLength &&
161                child.GetDepth() <= maxBranchDepth) {
[7506]162              if (child.SubtreeCount > 0)
[5686]163                internalCrossoverPoints.Add(new CutPoint(n, child));
[5367]164              else
[5686]165                leafCrossoverPoints.Add(new CutPoint(n, child));
[5367]166            }
[3997]167          }
[7506]168
[5916]169          // add one additional extension point if the number of sub trees for the symbol is not full
[6803]170          if (n.SubtreeCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
[5916]171            // empty extension point
[6803]172            internalCrossoverPoints.Add(new CutPoint(n, n.SubtreeCount));
[5916]173          }
[3997]174        }
[7506]175      }
176    );
[5367]177
[3997]178      if (random.NextDouble() < internalNodeProbability) {
179        // select from internal node if possible
180        if (internalCrossoverPoints.Count > 0) {
181          // select internal crossover point or leaf
[5916]182          crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
[3997]183        } else {
184          // otherwise select external node
[5916]185          crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
[3997]186        }
187      } else if (leafCrossoverPoints.Count > 0) {
188        // select from leaf crossover point if possible
[5916]189        crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
[3997]190      } else {
191        // otherwise select internal crossover point
[5916]192        crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
[645]193      }
194    }
[3237]195
[5510]196    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, IEnumerable<ISymbolicExpressionTreeNode> branches, double internalNodeProbability) {
[3237]197      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
[5510]198      List<ISymbolicExpressionTreeNode> allowedInternalBranches;
199      List<ISymbolicExpressionTreeNode> allowedLeafBranches;
[3997]200      if (random.NextDouble() < internalNodeProbability) {
201        // select internal node if possible
202        allowedInternalBranches = (from branch in branches
[7506]203                                   where branch != null && branch.SubtreeCount > 0
[3997]204                                   select branch).ToList();
205        if (allowedInternalBranches.Count > 0) {
[12422]206          return allowedInternalBranches.SampleRandom(random);
207
[3997]208        } else {
209          // no internal nodes allowed => select leaf nodes
210          allowedLeafBranches = (from branch in branches
[7506]211                                 where branch == null || branch.SubtreeCount == 0
[3989]212                                 select branch).ToList();
[12422]213          return allowedLeafBranches.SampleRandom(random);
[3997]214        }
[3237]215      } else {
[3997]216        // select leaf node if possible
217        allowedLeafBranches = (from branch in branches
[7506]218                               where branch == null || branch.SubtreeCount == 0
[3997]219                               select branch).ToList();
220        if (allowedLeafBranches.Count > 0) {
[12422]221          return allowedLeafBranches.SampleRandom(random);
[3997]222        } else {
223          allowedInternalBranches = (from branch in branches
[7506]224                                     where branch != null && branch.SubtreeCount > 0
[3997]225                                     select branch).ToList();
[12422]226          return allowedInternalBranches.SampleRandom(random);
227
[3997]228        }
[3237]229      }
230    }
[645]231  }
232}
Note: See TracBrowser for help on using the repository browser.