Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Algorithms.IteratedSentenceConstruction/HeuristicLab.Algorithms.IteratedSymbolicExpressionConstruction/3.3/SearchTree.cs @ 12922

Last change on this file since 12922 was 12922, checked in by gkronber, 9 years ago

#2471

  • added a simple implementation of Koza-style symbolic regression
  • added ucb tuned and estimation of variance to tabular quality functions
File size: 2.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics.Contracts;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7
8namespace HeuristicLab.Algorithms.IteratedSymbolicExpressionConstruction {
9  internal class SearchTree {
10    private class Node {
11      internal Node parent;
12      internal Node[] children;
13      // children == null -> never visited
14      // children[i] != null -> visited at least once, still allowed
15      // children[i] = null -> fully explored
16    }
17
18    private Node root;
19
20    // for iteration
21    private Node currentNode;
22
23    public SearchTree() {
24      root = new Node();
25      currentNode = root;
26    }
27
28    public void ResetPosition() {
29      currentNode = root;
30    }
31
32    public bool IsLeafNode() {
33      return currentNode.children == null;
34    }
35
36    public void ExpandCurrentNode<T>(IEnumerable<T> actions) {
37      Contract.Assert(actions.Any());
38      Contract.Assert(currentNode.children == null);
39      currentNode.children = actions.Select(_ => new Node() { parent = currentNode }).ToArray();
40    }
41
42    public void Follow(int action) {
43      Contract.Assert(currentNode.children != null);
44      Contract.Assert(currentNode.children[action] != null);
45      currentNode = currentNode.children[action];
46    }
47
48    public IEnumerable<int> PossibleActions {
49      get {
50        return Enumerable.Range(0, currentNode.children.Length)
51                         .Where(i => currentNode.children[i] != null);
52      }
53    }
54
55    public void RemoveBranch(int action) {
56      Contract.Assert(currentNode.children != null);
57      Contract.Assert(currentNode.children[action] != null);
58      currentNode.children[action] = null;
59
60      RemoveRecursively(currentNode);
61    }
62
63    private void RemoveRecursively(Node node) {
64      // when the last child has been removed we must remove the current node from it's parent
65      while (node.parent != null && node.children.All(ch => ch == null)) {
66        node.parent.children[Array.IndexOf(node.parent.children, node)] = null;
67        node = node.parent;
68      }
69    }
70  }
71}
Note: See TracBrowser for help on using the repository browser.