Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/MctsSampler.cs @ 11744

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

#2283 worked on TD, and models for MCTS

File size: 6.5 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using HeuristicLab.Algorithms.Bandits;
7using HeuristicLab.Problems.GrammaticalOptimization;
8
9namespace HeuristicLab.Algorithms.GrammaticalOptimization {
10  public class MctsSampler {
11    private class TreeNode {
12      public string ident;
13      public int randomTries;
14      public IBanditPolicyActionInfo actionInfo;
15      public TreeNode[] children;
16      public bool done = false;
17
18      public TreeNode(string id) {
19        this.ident = id;
20      }
21
22      public override string ToString() {
23        return string.Format("Node({0} tries: {1}, done: {2}, policy: {3})", ident, actionInfo.Tries, done, actionInfo);
24      }
25    }
26
27
28    public event Action<string, double> FoundNewBestSolution;
29    public event Action<string, double> SolutionEvaluated;
30
31    private readonly int maxLen;
32    private readonly IProblem problem;
33    private readonly Random random;
34    private readonly int randomTries;
35    private readonly IBanditPolicy policy;
36
37    private List<TreeNode> updateChain;
38    private TreeNode rootNode;
39
40    public int treeDepth;
41    public int treeSize;
42    private double bestQuality;
43
44    // public MctsSampler(IProblem problem, int maxLen, Random random) :
45    //   this(problem, maxLen, random, 10, (rand, numActions) => new EpsGreedyPolicy(rand, numActions, 0.1)) {
46    //
47    // }
48
49    public MctsSampler(IProblem problem, int maxLen, Random random, int randomTries, IBanditPolicy policy) {
50      this.maxLen = maxLen;
51      this.problem = problem;
52      this.random = random;
53      this.randomTries = randomTries;
54      this.policy = policy;
55    }
56
57    public void Run(int maxIterations) {
58      bestQuality = double.MinValue;
59      InitPolicies(problem.Grammar);
60      for (int i = 0; !rootNode.done && i < maxIterations; i++) {
61        var sentence = SampleSentence(problem.Grammar).ToString();
62        var quality = problem.Evaluate(sentence) / problem.BestKnownQuality(maxLen);
63        Debug.Assert(quality >= 0 && quality <= 1.0);
64        DistributeReward(quality);
65
66        RaiseSolutionEvaluated(sentence, quality);
67
68        if (quality > bestQuality) {
69          bestQuality = quality;
70          RaiseFoundNewBestSolution(sentence, quality);
71        }
72      }
73
74      // clean up
75      InitPolicies(problem.Grammar); GC.Collect();
76    }
77
78    public void PrintStats() {
79      var n = rootNode;
80      Console.WriteLine("depth: {0,5} size: {1,10} root tries {2,10}, rootQ {3:F3}, bestQ {4:F3}", treeDepth, treeSize, n.actionInfo.Tries, n.actionInfo.Value, bestQuality);
81      while (n.children != null) {
82        Console.WriteLine();
83        Console.WriteLine("{0,5}->{1,-50}", n.ident, string.Join(" ", n.children.Select(ch => string.Format("{0,4}", ch.ident))));
84        Console.WriteLine("{0,5}  {1,-50}", string.Empty, string.Join(" ", n.children.Select(ch => string.Format("{0,4:F2}", ch.actionInfo.Value * 10))));
85        Console.WriteLine("{0,5}  {1,-50}", string.Empty, string.Join(" ", n.children.Select(ch => string.Format("{0,4}", ch.done ? "X" : ch.actionInfo.Tries.ToString()))));
86        //n.policy.PrintStats();
87        n = n.children.Where(ch => !ch.done).OrderByDescending(c => c.actionInfo.Value).First();
88      }
89    }
90
91    private void InitPolicies(IGrammar grammar) {
92      this.updateChain = new List<TreeNode>();
93
94      rootNode = new TreeNode(grammar.SentenceSymbol.ToString());
95      rootNode.actionInfo = policy.CreateActionInfo();
96      treeDepth = 0;
97      treeSize = 0;
98    }
99
100    private Sequence SampleSentence(IGrammar grammar) {
101      updateChain.Clear();
102      var startPhrase = new Sequence(grammar.SentenceSymbol);
103      return CompleteSentence(grammar, startPhrase);
104    }
105
106    private Sequence CompleteSentence(IGrammar g, Sequence phrase) {
107      if (phrase.Length > maxLen) throw new ArgumentException();
108      if (g.MinPhraseLength(phrase) > maxLen) throw new ArgumentException();
109      TreeNode n = rootNode;
110      var curDepth = 0;
111      while (!phrase.IsTerminal) {
112        updateChain.Add(n);
113
114        if (n.randomTries < randomTries) {
115          n.randomTries++;
116          treeDepth = Math.Max(treeDepth, curDepth);
117          return g.CompleteSentenceRandomly(random, phrase, maxLen);
118        } else {
119          char nt = phrase.FirstNonTerminal;
120
121          int maxLenOfReplacement = maxLen - (phrase.Length - 1); // replacing aAb with maxLen 4 means we can only use alternatives with a minPhraseLen <= 2
122          Debug.Assert(maxLenOfReplacement > 0);
123
124          var alts = g.GetAlternatives(nt).Where(alt => g.MinPhraseLength(alt) <= maxLenOfReplacement);
125
126          if (n.randomTries == randomTries && n.children == null) {
127            n.children = alts.Select(alt => new TreeNode(alt.ToString())).ToArray(); // create a new node for each alternative
128            foreach (var ch in n.children) ch.actionInfo = policy.CreateActionInfo();
129            treeSize += n.children.Length;
130          }
131          // => select using bandit policy
132          int selectedAltIdx = policy.SelectAction(random, n.children.Select(c => c.actionInfo));
133          Sequence selectedAlt = alts.ElementAt(selectedAltIdx);
134
135          // replace nt with alt
136          phrase.ReplaceAt(phrase.FirstNonTerminalIndex, 1, selectedAlt);
137
138          curDepth++;
139
140          // prepare for next iteration
141          n = n.children[selectedAltIdx];
142        }
143      } // while
144
145      updateChain.Add(n);
146
147
148      // the last node is a leaf node (sentence is done), so we never need to visit this node again
149      n.done = true;
150
151      treeDepth = Math.Max(treeDepth, curDepth);
152      return phrase;
153    }
154
155    private void DistributeReward(double reward) {
156      // iterate in reverse order (bottom up)
157      updateChain.Reverse();
158
159      foreach (var e in updateChain) {
160        var node = e;
161        if (node.done) node.actionInfo.Disable();
162        if (node.children != null && node.children.All(c => c.done)) {
163          node.done = true;
164          node.actionInfo.Disable();
165        }
166        if (!node.done) {
167          node.actionInfo.UpdateReward(reward);
168        }
169      }
170    }
171
172    private void RaiseSolutionEvaluated(string sentence, double quality) {
173      var handler = SolutionEvaluated;
174      if (handler != null) handler(sentence, quality);
175    }
176    private void RaiseFoundNewBestSolution(string sentence, double quality) {
177      var handler = FoundNewBestSolution;
178      if (handler != null) handler(sentence, quality);
179    }
180  }
181}
Note: See TracBrowser for help on using the repository browser.