1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using HeuristicLab.Problems.GrammaticalOptimization;
|
---|
6 |
|
---|
7 | namespace 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);
|
---|
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 | var nt = phrase.First(grammar.IsNonTerminal);
|
---|
42 | var ntIdx = phrase.IndexOf(nt); // TODO perf
|
---|
43 | var alts = grammar.GetAlternatives(nt);
|
---|
44 | foreach (var alt in alts) {
|
---|
45 | var newPhrase = phrase.Remove(ntIdx, 1).Insert(ntIdx, alt);
|
---|
46 | if (newPhrase.All(grammar.IsTerminal) && newPhrase.Length <= maxLen) {
|
---|
47 | yield return newPhrase;
|
---|
48 | } else if (grammar.MinPhraseLength(newPhrase) <= maxLen) {
|
---|
49 | stack.Push(newPhrase);
|
---|
50 | }
|
---|
51 | }
|
---|
52 | }
|
---|
53 | }
|
---|
54 |
|
---|
55 |
|
---|
56 | private void RaiseSolutionEvaluated(string sentence, double quality) {
|
---|
57 | var handler = SolutionEvaluated;
|
---|
58 | if (handler != null) handler(sentence, quality);
|
---|
59 | }
|
---|
60 | private void RaiseFoundNewBestSolution(string sentence, double quality) {
|
---|
61 | var handler = FoundNewBestSolution;
|
---|
62 | if (handler != null) handler(sentence, quality);
|
---|
63 | }
|
---|
64 | }
|
---|
65 | }
|
---|