Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1682: Set range values of DepthConstrainedCrossover to read only.

File size: 8.2 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
40    #region Parameter properties
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)).AsReadOnly());
60      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.Standard)).AsReadOnly());
61      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.LowLevel)).AsReadOnly());
62    }
63    public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicDataAnalysisExpressionDepthConstrainedCrossover<T>(this, cloner); }
64
65    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
66      return Cross(random, parent0, parent1, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value, DepthRange.Value);
67    }
68
69
70    /// <summary>
71    /// Takes two parent individuals P0 and P1.
72    /// Randomly choose nodes that fall within the specified depth range in both parents.
73    /// </summary>
74    /// <param name="random">Pseudo-random number generator.</param>
75    /// <param name="parent0">First parent.</param>
76    /// <param name="parent1">Second parent.</param>
77    /// <param name="maxDepth">Maximum allowed length depth.</param>
78    /// <param name="maxLength">Maximum allowed tree length.</param>
79    /// <param name="mode">Controls the crossover behavior:
80    /// - HighLevel (upper 25% of the tree),
81    /// - Standard (mid 50%)
82    /// - LowLevel (low 25%)</param>
83    /// <returns></returns>
84    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, int maxDepth, int maxLength, string mode) {
85      int depth = parent0.Root.GetDepth() - 1; // subtract 1 because the tree levels are counted from 0
86      var depthRange = new IntRange();
87      const int depthOffset = 2; // skip the first 2 levels (root + startNode)
88      switch ((int)Enum.Parse(typeof(Ranges), mode)) {
89        case (int)Ranges.HighLevel:
90          depthRange.Start = depthOffset; // skip the first 2 levels (root + startNode)
91          depthRange.End = depthRange.Start + (int)Math.Round(depth * 0.25);
92          break;
93        case (int)Ranges.Standard:
94          depthRange.Start = depthOffset + (int)Math.Round(depth * 0.25);
95          depthRange.End = depthRange.Start + (int)Math.Round(depth * 0.5);
96          break;
97        case (int)Ranges.LowLevel:
98          depthRange.Start = depthOffset + (int)Math.Round(depth * 0.75);
99          depthRange.End = Math.Max(depthRange.Start, depth);
100          break;
101      }
102
103      // make sure that the depth range does not exceeded the actual depth of parent0
104      if (depthRange.Start > depth)
105        depthRange.Start = depth;
106      if (depthRange.End < depthRange.Start)
107        depthRange.End = depthRange.Start;
108
109      var crossoverPoints0 = (from node in GetNodesAtDepth(parent0, depthRange) select new CutPoint(node.Parent, node)).ToList();
110
111      if (crossoverPoints0.Count == 0)
112        throw new Exception("No crossover points available in the first parent");
113
114      var crossoverPoint0 = crossoverPoints0.SelectRandom(random);
115
116      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
117      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
118
119      var allowedBranches = (from s in GetNodesAtDepth(parent1, depthRange)
120                             where
121                               crossoverPoint0.IsMatchingPointType(s) &&
122                               s.GetDepth() + level <= maxDepth &&
123                               s.GetLength() + length <= maxLength
124                             select s).ToList();
125      if (allowedBranches.Count == 0) return parent0;
126      var selectedBranch = allowedBranches.SelectRandom(random);
127      swap(crossoverPoint0, selectedBranch);
128      return parent0;
129    }
130
131    private static IEnumerable<ISymbolicExpressionTreeNode> GetNodesAtDepth(ISymbolicExpressionTree tree, IntRange depthRange) {
132      var treeDepth = tree.Root.GetDepth();
133      return from node in tree.Root.IterateNodesPostfix()
134             let depth = treeDepth - node.GetDepth()
135             where depthRange.Start <= depth
136             where depth <= depthRange.End
137             select node;
138
139      //var list = new List<Tuple<ISymbolicExpressionTreeNode, int>> { new Tuple<ISymbolicExpressionTreeNode, int>(root, 0) };
140      //int offset = 0;
141      //int level = 0;
142      //while (level < range.End) {
143      //  ++level;
144      //  int count = list.Count;
145      //  for (int i = offset; i != count; ++i) {
146      //    if (list[i].Item1.Subtrees.Any())
147      //      list.AddRange(from s in list[i].Item1.Subtrees select new Tuple<ISymbolicExpressionTreeNode, int>(s, level));
148      //  }
149      //  offset = count;
150      //}
151      //// taking advantage of the fact that the list is already sorted by level
152      //for (int i = list.Count - 1; i >= 0; --i) {
153      //  if (list[i].Item2 >= range.Start)
154      //    yield return list[i].Item1;
155      //  else break;
156      //}
157    }
158
159    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
160      // perform the actual swap
161      if (crossoverPoint.Child != null) {
162        // manipulate the tree of parent0 in place
163        // replace the branch in tree0 with the selected branch from tree1
164        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
165        if (selectedBranch != null) {
166          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
167        }
168      } else {
169        // child is null (additional child should be added under the parent)
170        if (selectedBranch != null) {
171          crossoverPoint.Parent.AddSubtree(selectedBranch);
172        }
173      }
174    }
175  }
176}
Note: See TracBrowser for help on using the repository browser.