Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15018 was 15018, checked in by gkronber, 7 years ago

#2520 introduced StorableConstructorFlag type for StorableConstructors

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