Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gp-crossover/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionDepthConstrainedCrossover.cs @ 7303

Last change on this file since 7303 was 7303, checked in by bburlacu, 12 years ago

#1682: Override of the CanChangeName property, added friendly names for the crossover operators.

File size: 7.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Persistence.Default.CompositeSerializers.Storable;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Data;
30using HeuristicLab.Parameters;
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    protected override ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
67      return Cross(random, parent0, parent1, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value, DepthRange.Value);
68    }
69
70    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
71      return Cross(random, parent0, parent1);
72    }
73
74    /// <summary>
75    /// Takes two parent individuals P0 and P1.
76    /// Randomly choose nodes that fall within the specified depth range in both parents.
77    /// </summary>
78    /// <param name="random">Pseudo-random number generator.</param>
79    /// <param name="parent0">First parent.</param>
80    /// <param name="parent1">Second parent.</param>
81    /// <param name="maxDepth">Maximum allowed length depth.</param>
82    /// <param name="maxLength">Maximum allowed tree length.</param>
83    /// <param name="mode">Controls the crossover behavior:
84    /// - HighLevel (upper 25% of the tree),
85    /// - Standard (mid 50%)
86    /// - LowLevel (low 25%)</param>
87    /// <returns></returns>
88    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, int maxDepth, int maxLength, string mode) {
89      int depth = parent0.Root.GetDepth();
90      var depthRange = new DoubleRange();
91      const int depthOffset = 2; // skip the first 2 levels (root + startNode)
92      switch ((int)Enum.Parse(typeof(Ranges), mode)) {
93        case (int)Ranges.HighLevel:
94          depthRange.Start = depthOffset; // skip the first 2 levels (root + startNode)
95          depthRange.End = depthRange.Start + Math.Round(depth * 0.25);
96          break;
97        case (int)Ranges.Standard:
98          depthRange.Start = depthOffset + Math.Round(depth * 0.25);
99          depthRange.End = depthRange.Start + Math.Round(depth * 0.5);
100          break;
101        case (int)Ranges.Lowlevel:
102          depthRange.Start = depthOffset + Math.Round(depth * 0.75);
103          depthRange.End = Math.Max(depthRange.Start, depth);
104          break;
105      }
106
107      var crossoverPoints0 = new List<CutPoint>();
108      parent0.Root.ForEachNodePostfix((n) => {
109        if (n.Subtrees.Any() && n != parent0.Root)
110          crossoverPoints0.AddRange(from s in n.Subtrees
111                                    where parent0.Root.GetBranchLevel(s) >= depthRange.Start && parent0.Root.GetBranchLevel(s) <= depthRange.End
112                                    select new CutPoint(n, s));
113      });
114
115      if (crossoverPoints0.Count == 0)
116        throw new Exception("No crossover points available in the first parent");
117
118      CutPoint crossoverPoint0 = crossoverPoints0.SelectRandom(random);
119      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
120      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
121
122      var allowedBranches = new List<ISymbolicExpressionTreeNode>();
123      parent1.Root.ForEachNodePostfix((n) => {
124        if (n.Subtrees.Any() && n != parent1.Root) {
125          allowedBranches.AddRange(from s in n.Subtrees
126                                   let branchLevel = parent1.Root.GetBranchLevel(s)
127                                   where branchLevel >= depthRange.Start && branchLevel <= depthRange.End && s.GetDepth() + level <= maxDepth && s.GetLength() + length <= maxLength
128                                   select s);
129        }
130      });
131
132      if (allowedBranches.Count == 0)
133        return parent0;
134
135      var selectedBranch = allowedBranches.SelectRandom(random);
136
137      swap(crossoverPoint0, selectedBranch);
138
139      return parent0;
140    }
141
142    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
143      // perform the actual swap
144      if (crossoverPoint.Child != null) {
145        // manipulate the tree of parent0 in place
146        // replace the branch in tree0 with the selected branch from tree1
147        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
148        if (selectedBranch != null) {
149          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
150        }
151      } else {
152        // child is null (additional child should be added under the parent)
153        if (selectedBranch != null) {
154          crossoverPoint.Parent.AddSubtree(selectedBranch);
155        }
156      }
157    }
158  }
159}
Note: See TracBrowser for help on using the repository browser.