Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/ExhaustiveDepthFirstSearch.cs @ 11728

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

#2283: worked on grammatical optimization problem solvers (simple MCTS done)

File size: 2.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Problems.GrammaticalOptimization;
6
7namespace HeuristicLab.Algorithms.GrammaticalOptimization {
8  public class ExhaustiveDepthFirstSearch {
9    public event Action<string, double> FoundNewBestSolution;
10    public event Action<string, double> SolutionEvaluated;
11
12    private readonly int maxLen;
13    private readonly Stack<string> stack = new Stack<string>();
14
15    public ExhaustiveDepthFirstSearch(int maxLen) {
16      this.maxLen = maxLen;
17    }
18
19    public void Run(IProblem problem, int maxIterations) {
20      double bestQuality = double.MinValue;
21      stack.Push(problem.Grammar.SentenceSymbol.ToString());
22      var sentences = GenerateLanguage(problem.Grammar);
23      var sentenceEnumerator = sentences.GetEnumerator();
24      for (int i = 0; sentenceEnumerator.MoveNext() && i < maxIterations; i++) {
25        var sentence = sentenceEnumerator.Current;
26        var quality = problem.Evaluate(sentence) / problem.GetBestKnownQuality(maxLen);
27        RaiseSolutionEvaluated(sentence, quality);
28
29        if (quality > bestQuality) {
30          bestQuality = quality;
31          RaiseFoundNewBestSolution(sentence, quality);
32        }
33      }
34    }
35
36    // create sentences lazily
37    private IEnumerable<string> GenerateLanguage(IGrammar grammar) {
38      while (stack.Any()) {
39        var phrase = stack.Pop();
40
41        char nt;
42        int ntIdx;
43        Grammar.FindFirstNonTerminal(grammar, phrase, out nt, out ntIdx);
44        var alts = grammar.GetAlternatives(nt);
45        foreach (var alt in alts) {
46          var newPhrase = phrase.Remove(ntIdx, 1).Insert(ntIdx, alt);
47          if (newPhrase.All(grammar.IsTerminal) && newPhrase.Length <= maxLen) {
48            yield return newPhrase;
49          } else if (grammar.MinPhraseLength(newPhrase) <= maxLen) {
50            stack.Push(newPhrase);
51          }
52        }
53      }
54    }
55
56
57    private void RaiseSolutionEvaluated(string sentence, double quality) {
58      var handler = SolutionEvaluated;
59      if (handler != null) handler(sentence, quality);
60    }
61    private void RaiseFoundNewBestSolution(string sentence, double quality) {
62      var handler = FoundNewBestSolution;
63      if (handler != null) handler(sentence, quality);
64    }
65  }
66}
Note: See TracBrowser for help on using the repository browser.