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