Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Crossovers/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionDepthConstrainedCrossover.cs @ 7481

Last change on this file since 7481 was 7481, checked in by mkommend, 12 years ago

#1682: Corrected gp-crossover code.

  • Changed ISymbolicExpressionTreeCrossover
  • Corrected SubtreeCrossover
  • Updated MultiSymbolicDataAnalysisCrossover
File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33
34  [Item("DepthConstrainedCrossover", "An operator which performs subtree swapping within a specific depth range.")]
35  public sealed class SymbolicDataAnalysisExpressionDepthConstrainedCrossover<T> :
36    SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
37    private enum Ranges { HighLevel, Standard, LowLevel };
38    private const string DepthRangeParameterName = "DepthRange";
39    #region Parameter properties
40
41    public ConstrainedValueParameter<StringValue> DepthRangeParameter {
42      get { return (ConstrainedValueParameter<StringValue>)Parameters[DepthRangeParameterName]; }
43    }
44    #endregion
45
46    #region Properties
47    public StringValue DepthRange {
48      get { return (StringValue)DepthRangeParameter.ActualValue; }
49    }
50    #endregion
51
52    [StorableConstructor]
53    private SymbolicDataAnalysisExpressionDepthConstrainedCrossover(bool deserializing) : base(deserializing) { }
54    private SymbolicDataAnalysisExpressionDepthConstrainedCrossover(SymbolicDataAnalysisExpressionCrossover<T> original, Cloner cloner)
55      : base(original, cloner) { }
56    public SymbolicDataAnalysisExpressionDepthConstrainedCrossover()
57      : base() {
58      Parameters.Add(new ConstrainedValueParameter<StringValue>(DepthRangeParameterName, "Depth range specifier"));
59      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.HighLevel)));
60      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.Standard)));
61      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.LowLevel)));
62      Name = "DepthConstrainedCrossover";
63    }
64    public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicDataAnalysisExpressionDepthConstrainedCrossover<T>(this, cloner); }
65
66    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
67      return Cross(random, parent0, parent1, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value, DepthRange.Value);
68    }
69
70
71    /// <summary>
72    /// Takes two parent individuals P0 and P1.
73    /// Randomly choose nodes that fall within the specified depth range in both parents.
74    /// </summary>
75    /// <param name="random">Pseudo-random number generator.</param>
76    /// <param name="parent0">First parent.</param>
77    /// <param name="parent1">Second parent.</param>
78    /// <param name="maxDepth">Maximum allowed length depth.</param>
79    /// <param name="maxLength">Maximum allowed tree length.</param>
80    /// <param name="mode">Controls the crossover behavior:
81    /// - HighLevel (upper 25% of the tree),
82    /// - Standard (mid 50%)
83    /// - LowLevel (low 25%)</param>
84    /// <returns></returns>
85    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, int maxDepth, int maxLength, string mode) {
86      int depth = parent0.Root.GetDepth() - 1; // subtract 1 because the tree levels are counted from 0
87      var depthRange = new IntRange();
88      const int depthOffset = 2; // skip the first 2 levels (root + startNode)
89      switch ((int)Enum.Parse(typeof(Ranges), mode)) {
90        case (int)Ranges.HighLevel:
91          depthRange.Start = depthOffset; // skip the first 2 levels (root + startNode)
92          depthRange.End = depthRange.Start + (int)Math.Round(depth * 0.25);
93          break;
94        case (int)Ranges.Standard:
95          depthRange.Start = depthOffset + (int)Math.Round(depth * 0.25);
96          depthRange.End = depthRange.Start + (int)Math.Round(depth * 0.5);
97          break;
98        case (int)Ranges.LowLevel:
99          depthRange.Start = depthOffset + (int)Math.Round(depth * 0.75);
100          depthRange.End = Math.Max(depthRange.Start, depth);
101          break;
102      }
103
104      // make sure that the depth range does not exceeded the actual depth of parent0
105      if (depthRange.Start > depth)
106        depthRange.Start = depth;
107      if (depthRange.End < depthRange.Start)
108        depthRange.End = depthRange.Start;
109
110      var crossoverPoints0 = (from node in GetNodesAtDepth(parent0.Root, depthRange) select new CutPoint(node.Parent, node)).ToList();
111
112      if (crossoverPoints0.Count == 0)
113        throw new Exception("No crossover points available in the first parent");
114
115      var crossoverPoint0 = crossoverPoints0.SelectRandom(random);
116
117      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
118      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
119
120      var allowedBranches = (from s in GetNodesAtDepth(parent1.Root, depthRange)
121                             where
122                               crossoverPoint0.IsMatchingPointType(s) &&
123                               s.GetDepth() + level <= maxDepth &&
124                               s.GetLength() + length <= maxLength
125                             select s).ToList();
126      if (allowedBranches.Count == 0) return parent0;
127      var selectedBranch = allowedBranches.SelectRandom(random);
128      swap(crossoverPoint0, selectedBranch);
129      return parent0;
130    }
131
132    private static IEnumerable<ISymbolicExpressionTreeNode> GetNodesAtDepth(ISymbolicExpressionTreeNode root, IntRange range) {
133      var list = new List<Tuple<ISymbolicExpressionTreeNode, int>> { new Tuple<ISymbolicExpressionTreeNode, int>(root, 0) };
134      int offset = 0;
135      int level = 0;
136      while (level < range.End) {
137        ++level;
138        int count = list.Count;
139        for (int i = offset; i != count; ++i) {
140          if (list[i].Item1.Subtrees.Any())
141            list.AddRange(from s in list[i].Item1.Subtrees select new Tuple<ISymbolicExpressionTreeNode, int>(s, level));
142        }
143        offset = count;
144      }
145      // taking advantage of the fact that the list is already sorted by level
146      for (int i = list.Count - 1; i >= 0; --i) {
147        if (list[i].Item2 >= range.Start)
148          yield return list[i].Item1;
149        else break;
150      }
151    }
152
153    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
154      // perform the actual swap
155      if (crossoverPoint.Child != null) {
156        // manipulate the tree of parent0 in place
157        // replace the branch in tree0 with the selected branch from tree1
158        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
159        if (selectedBranch != null) {
160          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
161        }
162      } else {
163        // child is null (additional child should be added under the parent)
164        if (selectedBranch != null) {
165          crossoverPoint.Parent.AddSubtree(selectedBranch);
166        }
167      }
168    }
169  }
170}
Note: See TracBrowser for help on using the repository browser.