Changeset 11730 for branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/AlternativesSampler.cs
- Timestamp:
- 01/02/15 16:08:21 (9 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/AlternativesSampler.cs
r11727 r11730 27 27 InitPolicies(problem.Grammar); 28 28 for (int i = 0; i < maxIterations; i++) { 29 var sentence = SampleSentence(problem.Grammar) ;30 var quality = problem.Evaluate(sentence) / problem.GetBestKnownQuality(maxLen); 29 var sentence = SampleSentence(problem.Grammar).ToString(); 30 var quality = problem.Evaluate(sentence) / problem.GetBestKnownQuality(maxLen); 31 31 DistributeReward(quality); 32 32 … … 52 52 } 53 53 54 private stringSampleSentence(IGrammar grammar) {54 private Sequence SampleSentence(IGrammar grammar) { 55 55 updateChain.Clear(); 56 return CompleteSentence(grammar, grammar.SentenceSymbol.ToString());56 return CompleteSentence(grammar, new Sequence(grammar.SentenceSymbol)); 57 57 } 58 58 59 public string CompleteSentence(IGrammar g, stringphrase) {59 public Sequence CompleteSentence(IGrammar g, Sequence phrase) { 60 60 if (phrase.Length > maxLen) throw new ArgumentException(); 61 61 if (g.MinPhraseLength(phrase) > maxLen) throw new ArgumentException(); 62 bool done = phrase. All(g.IsTerminal); // terminal phrase means we are done62 bool done = phrase.IsTerminal; // terminal phrase means we are done 63 63 while (!done) { 64 int ntIdx; char nt; 65 Grammar.FindFirstNonTerminal(g, phrase, out nt, out ntIdx); 64 char nt = phrase.FirstNonTerminal; 66 65 67 66 int maxLenOfReplacement = maxLen - (phrase.Length - 1); // replacing aAb with maxLen 4 means we can only use alternatives with a minPhraseLen <= 2 … … 69 68 70 69 var alts = g.GetAlternatives(nt); 71 stringselectedAlt;70 Sequence selectedAlt; 72 71 // if the choice is restricted then one of the allowed alternatives is selected randomly 73 72 if (alts.Any(alt => g.MinPhraseLength(alt) > maxLenOfReplacement)) { … … 84 83 85 84 // replace nt with alt 86 phrase = phrase.Remove(ntIdx, 1); 87 phrase = phrase.Insert(ntIdx, selectedAlt); 85 phrase.ReplaceAt(phrase.FirstNonTerminalIndex, 1, selectedAlt); 88 86 89 done = phrase. All(g.IsTerminal); // terminal phrase means we are done87 done = phrase.IsTerminal; // terminal phrase means we are done 90 88 } 91 89 return phrase;
Note: See TracChangeset
for help on using the changeset viewer.