1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Diagnostics;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Text;
|
---|
6 | using HeuristicLab.Algorithms.Bandits;
|
---|
7 | using HeuristicLab.Problems.GrammaticalOptimization;
|
---|
8 |
|
---|
9 | namespace 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 |
|
---|
43 | // public MctsSampler(IProblem problem, int maxLen, Random random) :
|
---|
44 | // this(problem, maxLen, random, 10, (rand, numActions) => new EpsGreedyPolicy(rand, numActions, 0.1)) {
|
---|
45 | //
|
---|
46 | // }
|
---|
47 |
|
---|
48 | public MctsSampler(IProblem problem, int maxLen, Random random, int randomTries, IBanditPolicy policy) {
|
---|
49 | this.maxLen = maxLen;
|
---|
50 | this.problem = problem;
|
---|
51 | this.random = random;
|
---|
52 | this.randomTries = randomTries;
|
---|
53 | this.policy = policy;
|
---|
54 | }
|
---|
55 |
|
---|
56 | public void Run(int maxIterations) {
|
---|
57 | double bestQuality = double.MinValue;
|
---|
58 | InitPolicies(problem.Grammar);
|
---|
59 | for (int i = 0; !rootNode.done && i < maxIterations; i++) {
|
---|
60 | var sentence = SampleSentence(problem.Grammar).ToString();
|
---|
61 | var quality = problem.Evaluate(sentence) / problem.BestKnownQuality(maxLen);
|
---|
62 | Debug.Assert(quality >= 0 && quality <= 1.0);
|
---|
63 | DistributeReward(quality);
|
---|
64 |
|
---|
65 | RaiseSolutionEvaluated(sentence, quality);
|
---|
66 |
|
---|
67 | if (quality > bestQuality) {
|
---|
68 | bestQuality = quality;
|
---|
69 | RaiseFoundNewBestSolution(sentence, quality);
|
---|
70 | }
|
---|
71 | }
|
---|
72 |
|
---|
73 | // clean up
|
---|
74 | InitPolicies(problem.Grammar); GC.Collect();
|
---|
75 | }
|
---|
76 |
|
---|
77 | public void PrintStats() {
|
---|
78 | var n = rootNode;
|
---|
79 | Console.WriteLine("depth: {0,5} size: {1,10} root tries {2,10}", treeDepth, treeSize, n.actionInfo.Tries);
|
---|
80 | while (n.children != null) {
|
---|
81 | Console.WriteLine();
|
---|
82 | Console.WriteLine("{0,5}->{1,-50}", n.ident, string.Join(" ", n.children.Select(ch => string.Format("{0,4}", ch.ident))));
|
---|
83 | Console.WriteLine("{0,5} {1,-50}", string.Empty, string.Join(" ", n.children.Select(ch => string.Format("{0,4:F2}", ch.actionInfo.Value * 10))));
|
---|
84 | 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()))));
|
---|
85 | //n.policy.PrintStats();
|
---|
86 | n = n.children.Where(ch => !ch.done).OrderByDescending(c => c.actionInfo.Value).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 | 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 | }
|
---|