Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeNode.cs @ 18211

Last change on this file since 18211 was 18211, checked in by gkronber, 2 years ago

#3145: refactored infix formatter to improve output (less parenthesis) and added unit tests to test that the infix formatter works correclty.

File size: 7.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
27
28namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
29  [StorableType("E3549A82-D4C5-4AEC-A44C-D3205A618A21")]
30  public class SymbolicExpressionTreeNode : DeepCloneable, ISymbolicExpressionTreeNode {
31    [Storable]
32    private IList<ISymbolicExpressionTreeNode> subtrees;
33    [Storable]
34    private ISymbol symbol;
35
36    // cached values to prevent unnecessary tree iterations
37    private ushort length;
38    private ushort depth;
39
40    public ISymbol Symbol {
41      get { return symbol; }
42      protected set { symbol = value; }
43    }
44
45    [Storable]
46    private ISymbolicExpressionTreeNode parent;
47    public ISymbolicExpressionTreeNode Parent {
48      get { return parent; }
49      set { parent = value; }
50    }
51
52    [StorableConstructor]
53    protected SymbolicExpressionTreeNode(StorableConstructorFlag _) { }
54    protected SymbolicExpressionTreeNode(SymbolicExpressionTreeNode original, Cloner cloner)
55      : base(original, cloner) {
56      symbol = original.symbol; // symbols are reused
57      length = original.length;
58      depth = original.depth;
59      if (original.subtrees != null) {
60        subtrees = new List<ISymbolicExpressionTreeNode>(original.subtrees.Count);
61        foreach (var subtree in original.subtrees) {
62          var clonedSubtree = cloner.Clone(subtree);
63          subtrees.Add(clonedSubtree);
64          clonedSubtree.Parent = this;
65        }
66      }
67    }
68    public override IDeepCloneable Clone(Cloner cloner) {
69      return new SymbolicExpressionTreeNode(this, cloner);
70    }
71
72    internal SymbolicExpressionTreeNode()
73      : base() {
74      // don't allocate subtrees list here!
75      // because we don't want to allocate it in terminal nodes
76    }
77
78    public SymbolicExpressionTreeNode(ISymbol symbol)
79      : base() {
80      subtrees = new List<ISymbolicExpressionTreeNode>(3);
81      this.symbol = symbol;
82    }
83
84
85    [StorableHook(HookType.AfterDeserialization)]
86    private void AfterDeserialization() {
87      if (subtrees != null) {
88        foreach (var subtree in subtrees)
89          if (subtree.Parent == null)
90            subtree.Parent = this;
91      }
92    }
93
94    public virtual bool HasLocalParameters {
95      get { return false; }
96    }
97
98    public virtual IEnumerable<ISymbolicExpressionTreeNode> Subtrees {
99      get { return subtrees; }
100    }
101
102    public virtual ISymbolicExpressionTreeGrammar Grammar {
103      get { return parent.Grammar; }
104    }
105
106    public int GetLength() {
107      if (length > 0) return length;
108      else {
109        ushort l = 1;
110        if (subtrees != null) {
111          for (int i = 0; i < subtrees.Count; i++) {
112            checked { l += (ushort)subtrees[i].GetLength(); }
113          }
114        }
115        length = l;
116        return length;
117      }
118    }
119
120    public int GetDepth() {
121      if (depth > 0) return depth;
122      else {
123        ushort d = 0;
124        if (subtrees != null) {
125          for (int i = 0; i < subtrees.Count; i++) d = Math.Max(d, (ushort)subtrees[i].GetDepth());
126        }
127        d++;
128        depth = d;
129        return depth;
130      }
131    }
132
133    public int GetBranchLevel(ISymbolicExpressionTreeNode child) {
134      return GetBranchLevel(this, child);
135    }
136
137    private static int GetBranchLevel(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode point) {
138      if (root == point)
139        return 0;
140      foreach (var subtree in root.Subtrees) {
141        int branchLevel = GetBranchLevel(subtree, point);
142        if (branchLevel < int.MaxValue)
143          return 1 + branchLevel;
144      }
145      return int.MaxValue;
146    }
147
148    public virtual void ResetLocalParameters(IRandom random) { }
149    public virtual void ShakeLocalParameters(IRandom random, double shakingFactor) { }
150
151    public int SubtreeCount {
152      get {
153        if (subtrees == null) return 0;
154        return subtrees.Count;
155      }
156    }
157
158    public virtual ISymbolicExpressionTreeNode GetSubtree(int index) {
159      return subtrees[index];
160    }
161    public virtual int IndexOfSubtree(ISymbolicExpressionTreeNode tree) {
162      return subtrees.IndexOf(tree);
163    }
164    public virtual void AddSubtree(ISymbolicExpressionTreeNode tree) {
165      subtrees.Add(tree);
166      tree.Parent = this;
167      ResetCachedValues();
168    }
169    public virtual void InsertSubtree(int index, ISymbolicExpressionTreeNode tree) {
170      subtrees.Insert(index, tree);
171      tree.Parent = this;
172      ResetCachedValues();
173    }
174    public virtual void RemoveSubtree(int index) {
175      subtrees[index].Parent = null;
176      subtrees.RemoveAt(index);
177      ResetCachedValues();
178    }
179    public virtual void ReplaceSubtree(int index, ISymbolicExpressionTreeNode repl) {
180      subtrees[index].Parent = null;
181      subtrees[index] = repl;
182      repl.Parent = this;
183      ResetCachedValues();
184    }
185    public virtual void ReplaceSubtree(ISymbolicExpressionTreeNode old, ISymbolicExpressionTreeNode repl) {
186      var index = IndexOfSubtree(old);
187      subtrees[index].Parent = null;
188      subtrees[index] = repl;
189      repl.Parent = this;
190      ResetCachedValues();
191    }
192
193    public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth() {
194      var list = new List<ISymbolicExpressionTreeNode>(GetLength()) { this };
195      int i = 0;
196      while (i != list.Count) {
197        for (int j = 0; j != list[i].SubtreeCount; ++j)
198          list.Add(list[i].GetSubtree(j));
199        ++i;
200      }
201      return list;
202    }
203
204    public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPrefix() {
205      List<ISymbolicExpressionTreeNode> list = new List<ISymbolicExpressionTreeNode>();
206      ForEachNodePrefix((n) => list.Add(n));
207      return list;
208    }
209
210    public void ForEachNodePrefix(Action<ISymbolicExpressionTreeNode> a) {
211      a(this);
212      if (subtrees != null) {
213        //avoid linq to reduce memory pressure
214        for (int i = 0; i < subtrees.Count; i++) {
215          subtrees[i].ForEachNodePrefix(a);
216        }
217      }
218    }
219
220    public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPostfix() {
221      List<ISymbolicExpressionTreeNode> list = new List<ISymbolicExpressionTreeNode>();
222      ForEachNodePostfix((n) => list.Add(n));
223      return list;
224    }
225
226    public void ForEachNodePostfix(Action<ISymbolicExpressionTreeNode> a) {
227      if (subtrees != null) {
228        //avoid linq to reduce memory pressure
229        for (int i = 0; i < subtrees.Count; i++) {
230          subtrees[i].ForEachNodePostfix(a);
231        }
232      }
233      a(this);
234    }
235
236    public override string ToString() {
237      if (Symbol != null) return Symbol.Name;
238      return "SymbolicExpressionTreeNode";
239    }
240
241    private void ResetCachedValues() {
242      length = 0; depth = 0;
243      SymbolicExpressionTreeNode parentNode = parent as SymbolicExpressionTreeNode;
244      if (parentNode != null) parentNode.ResetCachedValues();
245    }
246  }
247}
Note: See TracBrowser for help on using the repository browser.