Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GBT/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs @ 12495

Last change on this file since 12495 was 12495, checked in by gkronber, 9 years ago

#2261: merged trunk changes to branch
r12494
#2403: added a null check in the MatlabParameterVectorEvaluator to prevent exceptions when clearstate is called


r12493
#2369: added support for squared errors and relative errors to error-characteristic-curve view


r12492
#2392: implemented PearsonsRCalculator to fix incorrect correlation values in the correlation matrix.


r12491
#2402 don't set task state to waiting when it fails


r12490
#2401 added missing Mono.Cecil plugin dependency


r12488
#2400 - Interfaces for Capaciated-, PickupAndDelivery- and TimeWindowed-ProblemInstances now specify an additional penalty parameter to set the current penalty factor for the constraint relaxation. - The setter of the penalty-property in ...


r12485
#2374 made RegressionSolution and ClassificationSolution non-abstract


r12482
#2320: Fixed warnings in unit test solutions introduced in r12420 by marking methods as obsolete.


r12481
#2320: Fixed AfterDeserialization of GEArtifialAntEvaluator.


r12480
#2320: Fixed error in symbolicexpressiontree crossover regarding the wiring of lookup parameters if persisted file is loaded.


r12479
#2397 moved GeoIP project into ExtLibs


r12478
#2329 fixed bug in simple code editor


r12476
#2331 removed outdated plugins


r12475
#2368 fixed compile warnings


r12474
#2399 worked on Mono project prepare script


r12473
#2329 added a simple code editor for Linux


r12472
#2399 - fixed MathJax.js file name - worked on Mono project prepare script


r12471
#2399 worked on Mono project prepare script


r12470
#2399 fixed pre-build events in project files


r12465
#2399 worked on mono project prepare script


r12464
#2399 added patch to project


r12463
#2399 fixed EPPlus so that it compiles on Linux


r12461
#2398: Skip root and start symbols when calculating impacts and replacement values in the pruning operators.


r12458
#2354 show label when no data is displayed and don't show the legend


r12457
#2353 removed duplicated call to Any() in Hive Status page


r12456
#2368 fixed modifier


r12455
#2368 added support in persistence for typecaches in streams


r12445
#2394: Changed Web.config compilation from debug to release to force script bundling. Changed history loading type from lazy to eager loading to increase performance. Fixed "getCoreStatus" typo in statusCtrl.js


r12443
#2394: Fixed UserTaskQuery and GetStatusHistory in the WebApp.Status plugin


r12442
#2394 added nuget folders to svn ignore list


r12435
#2394: Improved PluginManager and updated hive status monitor.


r12434
#2396 added symbolic expression tree formatter for C#


r12433
#2395: Minor change in DoubleValue.GetValue.


r12432
#2395 Use simple round-trip format for doubles because G17 prints some strange numbers (20.22 to 20.219999999999999999). Some accuracy can still be lost on 64bit machines, but should be very rare and minimal. double.MaxValue can still be pa...


r12431
#2395 Fixed parsing issues by using the G17 format.


r12430
#2394 added missing package config


r12429
#2394 added missing package config


r12428
#2394 added web app and status page to trunk


r12424
#2320: Adapted plugin file and updated project file of SymbolicExpressionTreeEncoding.


r12422
#2320: Merged the encoding class and all accompanying changes in the trunk.


r12401
#2387 Fixed a bug where the automatic selection of the first element behaved differently for the NewItemDialog.


r12400
#2387 Forgot to commit a file.


r12399
#2387 - Added context-menu for expanding and collapsing tree-nodes. - Improve response time when expanding/collapsing all nodes for TypeSelector and NewItemDialog.


r12398
#2387 - Added clearSearch-button in TypeSelector. - Adapted behavior of TypeSelector and NewItemDialog that a selected node stays selected as long as it matches the search criteria.


r12397
#2387 - Adapted behavior of the matching in the TypeSelector that it behave the same as the NewItemDialog. The search string is tokenized by space and matches if all tokens are contained, (eg. "Sym Reg" matches "SymbolicRegression...")...


r12393
#2025 - Removed Expand/CollapseAll buttons. - Removed cycling of items.


r12392
#2386: Updated GetHashCode method in the EnumerableBoolEqualityComparer.


File size: 10.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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;
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  [StorableClass]
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
46    #region Parameter Properties
47    public IValueLookupParameter<PercentValue> InternalCrossoverPointProbabilityParameter {
48      get { return (IValueLookupParameter<PercentValue>)Parameters[InternalCrossoverPointProbabilityParameterName]; }
49    }
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
68    [StorableConstructor]
69    protected SubtreeCrossover(bool deserializing) : base(deserializing) { }
70    protected SubtreeCrossover(SubtreeCrossover original, Cloner cloner) : base(original, cloner) { }
71    public SubtreeCrossover()
72      : base() {
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)));
76    }
77
78    public override IDeepCloneable Clone(Cloner cloner) {
79      return new SubtreeCrossover(this, cloner);
80    }
81
82    public override ISymbolicExpressionTree Crossover(IRandom random,
83      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
84      return Cross(random, parent0, parent1, InternalCrossoverPointProbability.Value,
85        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
86    }
87
88    public static ISymbolicExpressionTree Cross(IRandom random,
89      ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
90      double internalCrossoverPointProbability, int maxTreeLength, int maxTreeDepth) {
91      // select a random crossover point in the first parent
92      CutPoint crossoverPoint0;
93      SelectCrossoverPoint(random, parent0, internalCrossoverPointProbability, maxTreeLength, maxTreeDepth, out crossoverPoint0);
94
95      int childLength = crossoverPoint0.Child != null ? crossoverPoint0.Child.GetLength() : 0;
96      // calculate the max length and depth that the inserted branch can have
97      int maxInsertedBranchLength = maxTreeLength - (parent0.Length - childLength);
98      int maxInsertedBranchDepth = maxTreeDepth - parent0.Root.GetBranchLevel(crossoverPoint0.Parent);
99
100      List<ISymbolicExpressionTreeNode> allowedBranches = new List<ISymbolicExpressionTreeNode>();
101      parent1.Root.ForEachNodePostfix((n) => {
102        if (n.GetLength() <= maxInsertedBranchLength &&
103            n.GetDepth() <= maxInsertedBranchDepth && crossoverPoint0.IsMatchingPointType(n))
104          allowedBranches.Add(n);
105      });
106      // empty branch
107      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
108
109      if (allowedBranches.Count == 0) {
110        return parent0;
111      } else {
112        var selectedBranch = SelectRandomBranch(random, allowedBranches, internalCrossoverPointProbability);
113
114        if (crossoverPoint0.Child != null) {
115          // manipulate the tree of parent0 in place
116          // replace the branch in tree0 with the selected branch from tree1
117          crossoverPoint0.Parent.RemoveSubtree(crossoverPoint0.ChildIndex);
118          if (selectedBranch != null) {
119            crossoverPoint0.Parent.InsertSubtree(crossoverPoint0.ChildIndex, selectedBranch);
120          }
121        } else {
122          // child is null (additional child should be added under the parent)
123          if (selectedBranch != null) {
124            crossoverPoint0.Parent.AddSubtree(selectedBranch);
125          }
126        }
127        return parent0;
128      }
129    }
130
131    private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out CutPoint crossoverPoint) {
132      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
133      List<CutPoint> internalCrossoverPoints = new List<CutPoint>();
134      List<CutPoint> leafCrossoverPoints = new List<CutPoint>();
135      parent0.Root.ForEachNodePostfix((n) => {
136        if (n.SubtreeCount > 0 && n != parent0.Root) {
137          foreach (var child in n.Subtrees) {
138            if (child.GetLength() <= maxBranchLength &&
139                child.GetDepth() <= maxBranchDepth) {
140              if (child.SubtreeCount > 0)
141                internalCrossoverPoints.Add(new CutPoint(n, child));
142              else
143                leafCrossoverPoints.Add(new CutPoint(n, child));
144            }
145          }
146
147          // add one additional extension point if the number of sub trees for the symbol is not full
148          if (n.SubtreeCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
149            // empty extension point
150            internalCrossoverPoints.Add(new CutPoint(n, n.SubtreeCount));
151          }
152        }
153      }
154    );
155
156      if (random.NextDouble() < internalNodeProbability) {
157        // select from internal node if possible
158        if (internalCrossoverPoints.Count > 0) {
159          // select internal crossover point or leaf
160          crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
161        } else {
162          // otherwise select external node
163          crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
164        }
165      } else if (leafCrossoverPoints.Count > 0) {
166        // select from leaf crossover point if possible
167        crossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
168      } else {
169        // otherwise select internal crossover point
170        crossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
171      }
172    }
173
174    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, IEnumerable<ISymbolicExpressionTreeNode> branches, double internalNodeProbability) {
175      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
176      List<ISymbolicExpressionTreeNode> allowedInternalBranches;
177      List<ISymbolicExpressionTreeNode> allowedLeafBranches;
178      if (random.NextDouble() < internalNodeProbability) {
179        // select internal node if possible
180        allowedInternalBranches = (from branch in branches
181                                   where branch != null && branch.SubtreeCount > 0
182                                   select branch).ToList();
183        if (allowedInternalBranches.Count > 0) {
184          return allowedInternalBranches.SampleRandom(random);
185
186        } else {
187          // no internal nodes allowed => select leaf nodes
188          allowedLeafBranches = (from branch in branches
189                                 where branch == null || branch.SubtreeCount == 0
190                                 select branch).ToList();
191          return allowedLeafBranches.SampleRandom(random);
192        }
193      } else {
194        // select leaf node if possible
195        allowedLeafBranches = (from branch in branches
196                               where branch == null || branch.SubtreeCount == 0
197                               select branch).ToList();
198        if (allowedLeafBranches.Count > 0) {
199          return allowedLeafBranches.SampleRandom(random);
200        } else {
201          allowedInternalBranches = (from branch in branches
202                                     where branch != null && branch.SubtreeCount > 0
203                                     select branch).ToList();
204          return allowedInternalBranches.SampleRandom(random);
205
206        }
207      }
208    }
209  }
210}
Note: See TracBrowser for help on using the repository browser.