source: branches/2839_HiveProjectManagement/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionDepthConstrainedCrossover.cs @ 16057

Last change on this file since 16057 was 16057, checked in by jkarder, 4 years ago

#2839:

File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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;
31using HeuristicLab.Random;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
34  [Item("DepthConstrainedCrossover", "An operator which performs subtree swapping within a specific depth range. The range parameter controls the crossover behavior:\n" +
35                                     "- HighLevel (upper 25% of the tree)\n" +
36                                     "- Standard (mid 50% of the tree)\n" +
37                                     "- LowLevel (lower 25% of the tree)")]
38  [StorableClass]
39  public sealed class SymbolicDataAnalysisExpressionDepthConstrainedCrossover<T> :
40    SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
41    private enum Ranges { HighLevel, Standard, LowLevel };
42    private const string DepthRangeParameterName = "DepthRange";
43
44    #region Parameter properties
45    public IConstrainedValueParameter<StringValue> DepthRangeParameter {
46      get { return (IConstrainedValueParameter<StringValue>)Parameters[DepthRangeParameterName]; }
47    }
48    #endregion
49
50    #region Properties
51    public StringValue DepthRange {
52      get { return (StringValue)DepthRangeParameter.ActualValue; }
53    }
54    #endregion
55
56    [StorableConstructor]
57    private SymbolicDataAnalysisExpressionDepthConstrainedCrossover(bool deserializing) : base(deserializing) { }
58    private SymbolicDataAnalysisExpressionDepthConstrainedCrossover(SymbolicDataAnalysisExpressionCrossover<T> original, Cloner cloner)
59      : base(original, cloner) { }
60    public SymbolicDataAnalysisExpressionDepthConstrainedCrossover()
61      : base() {
62      Parameters.Add(new ConstrainedValueParameter<StringValue>(DepthRangeParameterName, "Depth range specifier"));
63      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.HighLevel)).AsReadOnly());
64      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.Standard)).AsReadOnly());
65      DepthRangeParameter.ValidValues.Add(new StringValue(Enum.GetName(typeof(Ranges), Ranges.LowLevel)).AsReadOnly());
66      name = "DepthConstrainedCrossover";
67    }
68    public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicDataAnalysisExpressionDepthConstrainedCrossover<T>(this, cloner); }
69
70    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
71      return Cross(random, parent0, parent1, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value, DepthRange.Value);
72    }
73
74
75    /// <summary>
76    /// Takes two parent individuals P0 and P1.
77    /// Randomly choose nodes that fall within the specified depth range in both parents.
78    /// </summary>
79    /// <param name="random">Pseudo-random number generator.</param>
80    /// <param name="parent0">First parent.</param>
81    /// <param name="parent1">Second parent.</param>
82    /// <param name="maxDepth">Maximum allowed length depth.</param>
83    /// <param name="maxLength">Maximum allowed tree length.</param>
84    /// <param name="mode">Controls the crossover behavior:
85    /// - HighLevel (upper 25% of the tree),
86    /// - Standard (mid 50%)
87    /// - LowLevel (low 25%)</param>
88    /// <returns></returns>
89    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, int maxDepth, int maxLength, string mode) {
90      int depth = parent0.Root.GetDepth() - 1; // substract 1 because the tree levels are counted from 0
91      var depthRange = new IntRange();
92      const int depthOffset = 2; // skip the first 2 levels (root + startNode)
93      switch ((Ranges)Enum.Parse(typeof(Ranges), mode)) {
94        case Ranges.HighLevel:
95          depthRange.Start = depthOffset; // skip the first 2 levels (root + startNode)
96          depthRange.End = depthRange.Start + (int)Math.Round(depth * 0.25);
97          break;
98        case Ranges.Standard:
99          depthRange.Start = depthOffset + (int)Math.Round(depth * 0.25);
100          depthRange.End = depthRange.Start + (int)Math.Round(depth * 0.5);
101          break;
102        case Ranges.LowLevel:
103          depthRange.Start = depthOffset + (int)Math.Round(depth * 0.75);
104          depthRange.End = Math.Max(depthRange.Start, depth);
105          break;
106      }
107
108      // make sure that the depth range does not exceeded the actual depth of parent0
109      if (depthRange.Start > depth)
110        depthRange.Start = depth;
111      if (depthRange.End < depthRange.Start)
112        depthRange.End = depthRange.Start;
113
114      var crossoverPoints0 = (from node in GetNodesAtDepth(parent0, depthRange) select new CutPoint(node.Parent, node)).ToList();
115
116      if (crossoverPoints0.Count == 0)
117        throw new Exception("No crossover points available in the first parent");
118
119      var crossoverPoint0 = crossoverPoints0.SampleRandom(random);
120      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
121      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
122
123      var allowedBranches = (from s in GetNodesAtDepth(parent1, depthRange)
124                             where s.GetDepth() + level <= maxDepth
125                             where s.GetLength() + length <= maxLength
126                             where crossoverPoint0.IsMatchingPointType(s)
127                             select s).ToList();
128      if (allowedBranches.Count == 0) return parent0;
129
130      var selectedBranch = allowedBranches.SampleRandom(random);
131      Swap(crossoverPoint0, selectedBranch);
132      return parent0;
133    }
134
135    private static IEnumerable<ISymbolicExpressionTreeNode> GetNodesAtDepth(ISymbolicExpressionTree tree, IntRange depthRange) {
136      var treeDepth = tree.Root.GetDepth();
137      return from node in tree.Root.IterateNodesPostfix()
138             let depth = treeDepth - node.GetDepth()
139             where depthRange.Start <= depth
140             where depth <= depthRange.End
141             select node;
142    }
143  }
144}
Note: See TracBrowser for help on using the repository browser.