Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2283: refactoring and bug fixes

File size: 6.6 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 int policyTries;
15      public IPolicyActionInfo actionInfo;
16      public TreeNode[] children;
17      public bool done = false;
18
19      public TreeNode(string id) {
20        this.ident = id;
21      }
22
23      public override string ToString() {
24        return string.Format("Node({0} tries: {1}, done: {2}, policy: {3})", ident, randomTries + policyTries, done, actionInfo);
25      }
26    }
27
28
29    public event Action<string, double> FoundNewBestSolution;
30    public event Action<string, double> SolutionEvaluated;
31
32    private readonly int maxLen;
33    private readonly IProblem problem;
34    private readonly Random random;
35    private readonly int randomTries;
36    private readonly IPolicy policy;
37
38    private List<TreeNode> updateChain;
39    private TreeNode rootNode;
40
41    public int treeDepth;
42    public int treeSize;
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, IPolicy 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      double 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}", treeDepth, treeSize, rootNode.policyTries + rootNode.randomTries);
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}", ch.randomTries + ch.policyTries))));
85        //n.policy.PrintStats();
86        n = n.children.OrderByDescending(c => c.policyTries).First();
87      }
88      Console.ReadLine();
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      bool done = phrase.IsTerminal;
111      var curDepth = 0;
112      while (!done) {
113        updateChain.Add(n);
114
115        if (n.randomTries < randomTries) {
116          n.randomTries++;
117          treeDepth = Math.Max(treeDepth, curDepth);
118          return g.CompleteSentenceRandomly(random, phrase, maxLen);
119        } else {
120          char nt = phrase.FirstNonTerminal;
121
122          int maxLenOfReplacement = maxLen - (phrase.Length - 1); // replacing aAb with maxLen 4 means we can only use alternatives with a minPhraseLen <= 2
123          Debug.Assert(maxLenOfReplacement > 0);
124
125          var alts = g.GetAlternatives(nt).Where(alt => g.MinPhraseLength(alt) <= maxLenOfReplacement);
126
127          if (n.randomTries == randomTries && n.children == null) {
128            n.children = alts.Select(alt => new TreeNode(alt.ToString())).ToArray(); // create a new node for each alternative
129            //n.children = alts.Select(alt => new TreeNode(string.Empty)).ToArray(); // create a new node for each alternative
130            foreach (var ch in n.children) ch.actionInfo = policy.CreateActionInfo();
131            treeSize += n.children.Length;
132          }
133          n.policyTries++;
134          // => select using bandit policy
135          int selectedAltIdx = policy.SelectAction(random, n.children.Select(c => c.actionInfo));
136          Sequence selectedAlt = alts.ElementAt(selectedAltIdx);
137
138          // replace nt with alt
139          phrase.ReplaceAt(phrase.FirstNonTerminalIndex, 1, selectedAlt);
140
141          curDepth++;
142
143          done = phrase.IsTerminal;
144
145          // prepare for next iteration
146          n = n.children[selectedAltIdx];
147        }
148      } // while
149
150      updateChain.Add(n);
151
152
153      // the last node is a leaf node (sentence is done), so we never need to visit this node again
154      n.done = true;
155      n.actionInfo.Disable();
156
157      treeDepth = Math.Max(treeDepth, curDepth);
158      return phrase;
159    }
160
161    private void DistributeReward(double reward) {
162      // iterate in reverse order (bottom up)
163      updateChain.Reverse();
164
165      foreach (var e in updateChain) {
166        var node = e;
167        if (node.children != null && node.children.All(c => c.done)) {
168          node.done = true;
169          node.actionInfo.Disable();
170        }
171        if (!node.done) {
172          node.actionInfo.UpdateReward(reward);
173          //policy.UpdateReward(action, reward / updateChain.Count);
174        }
175      }
176    }
177
178    private void RaiseSolutionEvaluated(string sentence, double quality) {
179      var handler = SolutionEvaluated;
180      if (handler != null) handler(sentence, quality);
181    }
182    private void RaiseFoundNewBestSolution(string sentence, double quality) {
183      var handler = FoundNewBestSolution;
184      if (handler != null) handler(sentence, quality);
185    }
186  }
187}
Note: See TracBrowser for help on using the repository browser.