Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1682: Overhauled the crossover operators, fixed bug in the DeterministicBestCrossover.

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