Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10280 was 10280, checked in by sawinkle, 10 years ago

#2109: Fetched random number generator in Evaluator implementations from scope, so that the same results are produced using the same seed.

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