source: branches/GrammaticalEvolution/HeuristicLab.Problems.GrammaticalEvolution/Mappers/DepthFirstMapper.cs @ 10276

Last change on this file since 10276 was 10276, checked in by sawinkle, 9 years ago

#2109:
Refactoring:

  • Removed recursive version of mapping in /Mappers/DepthFirstMapper.cs, because only the iterative one is used.
  • Removed unused using statements and unused commented code.
File size: 5.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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 HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Encodings.IntegerVectorEncoding;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29using HeuristicLab.Random;
30
31namespace HeuristicLab.Problems.GrammaticalEvolution {
32  /// <summary>
33  /// DepthFirstMapper
34  /// </summary>
35  [Item("DepthFirstMapper", "Resolves the non-terminal symbols of the resulting phenotypic syntax tree in a depth-first manner.")]
36  [StorableClass]
37  public class DepthFirstMapper : GenotypeToPhenotypeMapper {
38
39    [StorableConstructor]
40    protected DepthFirstMapper(bool deserializing) : base(deserializing) { }
41    protected DepthFirstMapper(DepthFirstMapper original, Cloner cloner) : base(original, cloner) { }
42    public DepthFirstMapper() : base() { }
43
44    public override IDeepCloneable Clone(Cloner cloner) {
45      return new DepthFirstMapper(this, cloner);
46    }
47
48
49    /// <summary>
50    /// Maps a genotype (an integer vector) to a phenotype (a symbolic expression tree).
51    /// Depth-first approach.
52    /// </summary>
53    /// <param name="grammar">grammar definition</param>
54    /// <param name="genotype">integer vector, which should be mapped to a tree</param>
55    /// <returns>phenotype (a symbolic expression tree)</returns>
56    public override SymbolicExpressionTree Map(ISymbolicExpressionGrammar grammar,
57                                               IntegerVector genotype) {
58
59      SymbolicExpressionTree tree = new SymbolicExpressionTree();
60      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
61      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(new MersenneTwister());
62      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
63      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(new MersenneTwister());
64      rootNode.AddSubtree(startNode);
65      tree.Root = rootNode;
66
67      MapDepthFirstIteratively(startNode, genotype, grammar,
68                               genotype.Length, new MersenneTwister());
69      return tree;
70    }
71
72
73    /// <summary>
74    /// Genotype-to-Phenotype mapper (iterative depth-first approach, by using a stack -> LIFO).
75    /// </summary>
76    /// <param name="startNode">first node of the tree with arity 1</param>
77    /// <param name="genotype">integer vector, which should be mapped to a tree</param>
78    /// <param name="grammar">grammar to determine the allowed child symbols for each node</param>
79    /// <param name="maxSubtreeCount">maximum allowed subtrees (= number of used genomes)</param>
80    /// <param name="random">random number generator</param>
81    private void MapDepthFirstIteratively(ISymbolicExpressionTreeNode startNode,
82                                          IntegerVector genotype,
83                                          ISymbolicExpressionGrammar grammar,
84                                          int maxSubtreeCount, IRandom random) {
85
86      Stack<Tuple<ISymbolicExpressionTreeNode, int>> stack
87        = new Stack<Tuple<ISymbolicExpressionTreeNode, int>>(); // tuples of <node, arity>
88
89      int genotypeIndex = 0;
90      int currSubtreeCount = 1;
91
92      stack.Push(new Tuple<ISymbolicExpressionTreeNode, int>(startNode, 1));
93
94      while ((currSubtreeCount < maxSubtreeCount) && (stack.Count > 0)) {
95
96        // get next node from stack and re-push it, if this node still has unhandled subtrees ...
97        Tuple<ISymbolicExpressionTreeNode, int> current = stack.Pop();
98        if (current.Item2 > 1) {
99          stack.Push(new Tuple<ISymbolicExpressionTreeNode, int>(current.Item1, current.Item2 - 1));
100        }
101
102        var newNode = GetNewChildNode(current.Item1, genotype, grammar, genotypeIndex, random);
103        int arity = SampleArity(random, newNode, maxSubtreeCount - currSubtreeCount);
104
105        if (arity < 0) {
106          current.Item1.AddSubtree(GetRandomTerminalNode(current.Item1, grammar, random));
107        } else {
108          current.Item1.AddSubtree(newNode);
109          genotypeIndex++;
110          currSubtreeCount += arity;
111          if (arity > 0) {
112            // new node has subtrees so push it onto the stack
113            stack.Push(new Tuple<ISymbolicExpressionTreeNode, int>(newNode, arity));
114          }
115        }
116      }
117
118      // maximum allowed subtree count was already reached, but there are still
119      // incomplete subtrees (non-terminal symbols) in the tree
120      // -> fill them with terminal symbols
121      while (stack.Count > 0) {
122        Tuple<ISymbolicExpressionTreeNode, int> current = stack.Pop();
123        if (current.Item2 > 1) {
124          stack.Push(new Tuple<ISymbolicExpressionTreeNode, int>(current.Item1, current.Item2 - 1));
125        }
126        current.Item1.AddSubtree(GetRandomTerminalNode(current.Item1, grammar, random));
127      }
128    }
129  }
130}
Note: See TracBrowser for help on using the repository browser.