Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Problems.GrammaticalOptimization/Problems/FindPhrasesProblem.cs @ 11865

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

#2283: implemented royal tree problem and grid test for tree-based gp variants

File size: 7.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using HeuristicLab.Common;
7using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
8
9namespace HeuristicLab.Problems.GrammaticalOptimization {
10  // must find a set of phrases where the ordering of phrases is irrelevant
11  // Parameters
12  // - size of the alphabet
13  // - phrase length
14  // - number of phrases in the sequence
15  // - number of optimal phrases
16  // - reward for optimal phrases
17  // - number of decoy (sub-optimal) phrases
18  // - reward for decoy phrases (must be smaller than reward for optimal phrases)
19  // - phrasesAsSets: a switch to determine wether symbols in a phrase can be shuffled (sets) or if the ordering is relevant (non-sets)
20
21  // this problem should be similar to symbolic regression and should be easier for approaches using a state esimation value and the canoncial state
22  // when phrases are symbol sets instead of sequences then value-estimation routines should be better (TD)
23  public class FindPhrasesProblem : ISymbolicExpressionTreeProblem {
24
25    private readonly IGrammar grammar;
26    private readonly int numPhrases;
27    private readonly int phraseLen;
28    private readonly double correctReward;
29    private readonly double decoyReward;
30    private readonly bool phrasesAsSets;
31    private readonly SortedSet<string> optimalPhrases;
32    private readonly SortedSet<string> decoyPhrases;
33
34    public FindPhrasesProblem(Random rand, int alphabetSize, int numPhrases, int phraseLen, int numOptimalPhrases, int numDecoyPhrases = 1,
35      double correctReward = 1.0, double decoyReward = 0.0, bool phrasesAsSets = false) {
36      if (alphabetSize <= 0 || alphabetSize > 26) throw new ArgumentException();
37      if (numPhrases <= 0) throw new ArgumentException();
38      if (phraseLen < 1) throw new ArgumentException();
39      if (numOptimalPhrases < numPhrases) throw new ArgumentException();
40      if (numDecoyPhrases < 0) throw new ArgumentException();
41      if (correctReward <= decoyReward) throw new ArgumentException();
42
43      this.numPhrases = numPhrases;
44      this.phraseLen = phraseLen;
45      this.correctReward = correctReward;
46      this.decoyReward = decoyReward;
47      this.phrasesAsSets = phrasesAsSets;
48
49      var sentenceSymbol = 'S';
50      var terminalSymbols = Enumerable.Range(0, alphabetSize).Select(off => (char)((byte)'a' + off)).ToArray();
51      var nonTerminalSymbols = new char[] { sentenceSymbol };
52
53      {
54        // create grammar
55        // S -> a..z | aS .. zS
56        var rules = terminalSymbols.Select(t => Tuple.Create(sentenceSymbol, t.ToString()))
57          .Concat(terminalSymbols.Select(t => Tuple.Create(sentenceSymbol, t + sentenceSymbol.ToString())));
58
59        this.grammar = new Grammar(sentenceSymbol, terminalSymbols, nonTerminalSymbols, rules);
60      }
61      {
62        // create grammar for tree-based GP
63        // S -> a..z | SS
64        var rules = terminalSymbols.Select(t => Tuple.Create(sentenceSymbol, t.ToString()))
65          .Concat(new Tuple<char, string>[] { Tuple.Create(sentenceSymbol, sentenceSymbol.ToString() + sentenceSymbol) });
66
67        this.TreeBasedGPGrammar = new Grammar(sentenceSymbol, terminalSymbols, nonTerminalSymbols, rules);
68      }
69
70      // generate optimal phrases
71      optimalPhrases = new SortedSet<string>();
72      while (optimalPhrases.Count < numOptimalPhrases) {
73        string phrase = "";
74        for (int l = 0; l < phraseLen; l++) {
75          phrase += terminalSymbols.SelectRandom(rand);
76        }
77        phrase = CanonicalPhrase(phrase);
78
79        // don't allow dups
80        if (!optimalPhrases.Contains(phrase)) optimalPhrases.Add(phrase);
81      }
82
83      // generate decoy phrases
84      decoyPhrases = new SortedSet<string>();
85      while (decoyPhrases.Count < numDecoyPhrases) {
86        string phrase = "";
87        for (int l = 0; l < phraseLen; l++) {
88          phrase += terminalSymbols.SelectRandom(rand);
89        }
90        phrase = CanonicalPhrase(phrase);
91
92        // don't allow dups
93        if (!optimalPhrases.Contains(phrase) && !decoyPhrases.Contains(phrase)) decoyPhrases.Add(phrase);
94      }
95
96      Debug.Assert(Evaluate(BestKnownSolution) / BestKnownQuality(phraseLen * numPhrases) == 1.0);
97    }
98
99    public double BestKnownQuality(int maxLen) {
100      return Math.Min(maxLen / phraseLen, numPhrases) * correctReward; // integer division
101    }
102
103    public string BestKnownSolution {
104      get { return string.Join("", optimalPhrases.Take(numPhrases)); }
105    }
106
107    public IGrammar Grammar {
108      get { return grammar; }
109    }
110
111    public double Evaluate(string sentence) {
112      // sentence must contain only terminal symbols, we are not checking if the sentence is syntactically valid here because it would be too slow!
113      Debug.Assert(sentence.Any(c => grammar.IsTerminal(c)));
114
115
116      // split the sentence in phrases
117      // phrases must not overlap in the sentence, multiple occurences of a phrase are not counted
118      // the order of phrases is not relevant
119      var numPhrases = sentence.Length / phraseLen;
120      var phrases = new SortedSet<string>();
121      for (int phraseIdx = 0; phraseIdx < numPhrases; phraseIdx++) {
122        var sentenceIdx = phraseIdx * phraseLen;
123        var phrase = sentence.Substring(sentenceIdx, phraseLen);
124        phrase = CanonicalPhrase(phrase);
125        if (!phrases.Contains(phrase)) phrases.Add(phrase);
126      }
127
128      // add reward for each correct phrase that occurs in the sentence
129      // add reward for each decoy phrase that occurs in the sentence
130      var reward = phrases.Intersect(optimalPhrases).Count() * correctReward
131               + phrases.Intersect(decoyPhrases).Count() * decoyReward;
132
133      return reward;
134    }
135
136    // TODO: cache canonical phrases in most-recently used dictionary for increased performance (see symbolicregressionpoly10problem)
137    private string CanonicalPhrase(string phrase) {
138      if (phrasesAsSets) return string.Join("", phrase.OrderBy(ch => (byte)ch));
139      else return phrase;
140    }
141
142    public string CanonicalRepresentation(string phrase) {
143      // as the ordering of phrases does not matter we can reorder the phrases
144      // and remove duplicates
145      var numPhrases = phrase.Length / phraseLen;
146      var phrases = new SortedSet<string>();
147      for (int phraseIdx = 0; phraseIdx < numPhrases; phraseIdx++) {
148        var sentenceIdx = phraseIdx * phraseLen;
149        var subphrase = phrase.Substring(sentenceIdx, phraseLen);
150        subphrase = CanonicalPhrase(subphrase);
151        if (!phrases.Contains(subphrase)) phrases.Add(subphrase);
152      }
153      var remainder = phrase.Substring(numPhrases * phraseLen, phrase.Length - (numPhrases * phraseLen));
154      remainder = CanonicalPhrase(remainder);
155      if (!phrases.Contains(remainder)) phrases.Add(remainder);
156
157      return string.Join("", phrases);
158    }
159
160    public IEnumerable<Feature> GetFeatures(string phrase) {
161      throw new NotImplementedException();
162    }
163
164    public override string ToString() {
165      return string.Format("\"FindPhrasesProblem {0} {1} {2} {3:F2} {4} {5:F2} {6}\"", numPhrases, phraseLen,
166        optimalPhrases.Count, correctReward, decoyPhrases.Count, decoyReward, phrasesAsSets);
167    }
168
169    public IGrammar TreeBasedGPGrammar { get; private set; }
170    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
171      var sb = new StringBuilder();
172      foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
173        if (s.Symbol.Name == "S") continue;
174        sb.Append(s.Symbol.Name);
175      }
176      return sb.ToString();
177    }
178  }
179}
Note: See TracBrowser for help on using the repository browser.