Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Problems.GrammaticalOptimization/Problems/RoyalSymbolProblem.cs @ 12394

Last change on this file since 12394 was 12099, checked in by gkronber, 10 years ago

#2283: name for all problems (for output), new unit test, and added testsettings file

File size: 2.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using System.Text.RegularExpressions;
7using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
8
9namespace HeuristicLab.Problems.GrammaticalOptimization {
10  // counts the number of times a symbol occurs in a sentence
11  public class RoyalSymbolProblem : ISymbolicExpressionTreeProblem {
12    private const string grammarString = @"
13G(S):
14S -> a | aS | b | bS
15";
16
17    private const string hlGrammarString = @"
18G(S):
19S -> a | b | SS
20";
21
22    // Obj(s \in L(G(S))) = Anzahl "a"-Symbole in s
23
24    private readonly IGrammar grammar;
25    public string Name { get { return "RoyalSymbol"; } }
26    public RoyalSymbolProblem() {
27      this.grammar = new Grammar(grammarString);
28      this.TreeBasedGPGrammar = new Grammar(hlGrammarString);
29      //TODO: allow configuration of the number of symbols
30    }
31
32    public double BestKnownQuality(int maxLen) {
33      return maxLen;
34    }
35
36    public IGrammar Grammar {
37      get { return grammar; }
38    }
39
40    private Regex regex = new Regex("a"); // count the number of "a"s
41    public double Evaluate(string sentence) {
42      // sentence must contain only terminal symbols, we are not checking if the sentence is syntactically valid here because it would be too slow!
43      Debug.Assert(sentence.Any(c => grammar.IsTerminal(c)));
44      return regex.Matches(sentence).Count;
45    }
46    public string CanonicalRepresentation(string phrase) {
47      return phrase;
48    }
49
50    public IEnumerable<Feature> GetFeatures(string phrase) {
51      throw new NotImplementedException();
52    }
53
54    public IGrammar TreeBasedGPGrammar { get; private set; }
55    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
56      var sb = new StringBuilder();
57      foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
58        if (s.Symbol.Name == "S") continue;
59        sb.Append(s.Symbol.Name);
60      }
61      return sb.ToString();
62    }
63  }
64}
Note: See TracBrowser for help on using the repository browser.