Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Problems.GrammaticalOptimization/Problems/RoyalPairProblem.cs @ 12815

Last change on this file since 12815 was 12815, checked in by aballeit, 9 years ago

#2283 added SelectionIndicator for MCTS and problems SantaFeAnt, SymbolicRegression10, RoyalSymbol; updated SantaFeAnt grammar

File size: 2.3 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 pair of symbols occurs in a sentence
11  public class RoyalPairProblem : 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    private readonly IGrammar grammar;
23    public string Name { get { return "RoyalPair"; } }
24   
25    public RoyalPairProblem() {
26      this.grammar = new Grammar(grammarString);
27      this.TreeBasedGPGrammar = new Grammar(hlGrammarString);
28      // TODO: allow configuration of the number of symbols
29    }
30
31    public double BestKnownQuality(int maxLen) {
32      return maxLen - 1;
33    }
34
35    public IGrammar Grammar {
36      get { return grammar; }
37    }
38
39    private Regex regex = new Regex("(?=ab)|(?=ba)"); // count the number of "ab" and "ba" pairs
40    public double Evaluate(string sentence) {
41      // sentence must contain only terminal symbols, we are not checking if the sentence is syntactically valid here because it would be too slow!
42      Debug.Assert(sentence.Any(c => grammar.IsTerminal(c)));
43      return regex.Matches(sentence).Count;
44    }
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    public IGrammar TreeBasedGPGrammar { get; private set; }
54    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
55      var sb = new StringBuilder();
56      foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
57        if (s.Symbol.Name == "S") continue;
58        sb.Append(s.Symbol.Name);
59      }
60      return sb.ToString();
61    }
62
63
64    public void GenerateProblemSolutions(int maxLen)
65    {
66        throw new NotImplementedException();
67    }
68
69    public bool IsParentOfProblemSolution(string sentence, int maxLen)
70    {
71        throw new NotImplementedException();
72    }
73  }
74}
Note: See TracBrowser for help on using the repository browser.