Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
01/18/15 18:24:58 (9 years ago)
Author:
gkronber
Message:

#2283 fixed compile errors and refactoring

Location:
branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization
Files:
2 added
3 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/ExhaustiveBreadthFirstSearch.cs

    r11732 r11793  
    4242
    4343        char nt = phrase.FirstNonTerminal;
    44         int ntIdx;
    4544
    4645        var alts = grammar.GetAlternatives(nt);
  • branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/RandomSearch.cs

    r11732 r11793  
    11using System;
    2 using System;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    62using HeuristicLab.Problems.GrammaticalOptimization;
    73
  • branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialSearch.cs

    r11792 r11793  
    2424  // 3) Collect reward and update policy (feedback: state of visited rewards from step 2)
    2525  public class SequentialSearch {
     26    // only for storing states so that it is not necessary to allocate new state strings whenever we select a follow state using the policy
     27    private class TreeNode {
     28      public int randomTries;
     29      public string phrase;
     30      public Sequence alternative;
     31      public TreeNode[] children;
     32
     33      public TreeNode(string phrase, Sequence alternative) {
     34        this.alternative = alternative;
     35        this.phrase = phrase;
     36      }
     37    }
     38
    2639
    2740    public event Action<string, double> FoundNewBestSolution;
     
    3447    private readonly IGrammarPolicy behaviourPolicy;
    3548    private readonly IGrammarPolicy greedyPolicy;
     49    private TreeNode rootNode;
     50
     51    private int tries;
    3652    private int maxSearchDepth;
    3753
    3854    private double bestQuality;
    3955    private string bestPhrase;
    40     private int tries;
    41     private readonly List<ReadonlySequence> stateChain;
     56    private readonly List<string> stateChain;
    4257
    4358    public SequentialSearch(IProblem problem, int maxLen, Random random, int randomTries, IGrammarPolicy behaviourPolicy) {
     
    4762      this.randomTries = randomTries;
    4863      this.behaviourPolicy = behaviourPolicy;
    49       this.greedyPolicy = new GreedyPolicy(problem, false);
    50       this.stateChain = new List<ReadonlySequence>();
    51       this.cache = new Dictionary<ReadonlySequence, ReadonlySequence[]>();
     64      this.greedyPolicy = new GenericGrammarPolicy(problem, new EpsGreedyPolicy(0.0), false);
     65      this.stateChain = new List<string>();
    5266    }
    5367
    5468    public void Run(int maxIterations) {
    5569      bestQuality = double.MinValue;
    56       //InitPolicies(problem.Grammar);
    5770      Reset();
    5871
     
    7992
    8093
    81     private ReadonlySequence SampleSentence(IGrammar grammar) {
    82       ReadonlySequence phrase;
     94    private Sequence SampleSentence(IGrammar grammar) {
     95      Sequence phrase;
    8396      do {
    8497        stateChain.Clear();
    85         phrase = new ReadonlySequence(grammar.SentenceSymbol);
     98        phrase = new Sequence(rootNode.phrase);
    8699        //var startPhrase = new Sequence("a*b+c*d+e*f+E");
    87100      } while (!Done() && !TryCompleteSentence(grammar, ref phrase));
     
    89102    }
    90103
    91     private bool TryCompleteSentence(IGrammar g, ref ReadonlySequence phrase) {
     104    private bool TryCompleteSentence(IGrammar g, ref Sequence phrase) {
    92105      if (phrase.Length > maxLen) throw new ArgumentException();
    93106      if (g.MinPhraseLength(phrase) > maxLen) throw new ArgumentException();
    94107      var curDepth = 0;
    95 
    96       stateChain.Add(phrase);
     108      var n = rootNode;
     109      stateChain.Add(n.phrase);
     110
    97111      while (!phrase.IsTerminal) {
    98112
    99         var newPhrases = GenerateFollowStates(g, phrase);
    100        
    101         throw new NotImplementedException(); // TODO: reintroduce random-trie checking once the tree of all states has been reintroduced
     113
    102114        //if (n.randomTries < randomTries) {
    103115        //  n.randomTries++;
    104         //  treeDepth = Math.Max(treeDepth, curDepth);
    105         //  lastNode = n;
    106         //  return g.CompleteSentenceRandomly(random, phrase, maxLen);
     116        //  curDepth = Math.Max(curDepth, curDepth);
     117        //  g.CompleteSentenceRandomly(random, phrase, maxLen);
     118        //  return true;
    107119        //} else {
    108 
    109 
    110           // => select using bandit policy
    111           // failure means we simply restart
    112           if (!behaviourPolicy.TrySelect(random, phrase, newPhrases, out phrase)) {
    113             return false;
    114           }
    115         // }
    116         stateChain.Add(phrase);
     120        // => select using bandit policy
     121        // failure means we simply restart
     122        GenerateFollowStates(n); // creates child nodes for node n
     123
     124        int selectedChildIdx;
     125        if (!behaviourPolicy.TrySelect(random, n.phrase, n.children.Select(ch => ch.phrase), out selectedChildIdx)) {
     126          return false;
     127        }
     128        phrase.ReplaceAt(phrase.FirstNonTerminalIndex, 1, n.children[selectedChildIdx].alternative);
     129
     130        // prepare for next iteration
     131        n = n.children[selectedChildIdx];
     132        stateChain.Add(n.phrase);
    117133        curDepth++;
     134        //}
    118135      } // while
    119136
     
    123140
    124141
    125     private readonly Dictionary<ReadonlySequence, ReadonlySequence[]> cache;
    126     private IEnumerable<ReadonlySequence> GenerateFollowStates(IGrammar g, ReadonlySequence phrase) {
    127       throw new NotImplementedException();
    128       // TODO: Replace caching by a tree of all states. tree is only used for easily retrieving the follow-states of a state
    129       ReadonlySequence[] follow;
    130       //if (!cache.TryGetValue(phrase, out follow)) {
     142    private IEnumerable<string> GenerateFollowStates(TreeNode n) {
     143      // create children on the first visit
     144      if (n.children == null) {
     145        var g = problem.Grammar;
     146        // tree is only used for easily retrieving the follow-states of a state
     147        var phrase = new Sequence(n.phrase);
    131148        char nt = phrase.FirstNonTerminal;
    132149
     
    137154        var alts = g.GetAlternatives(nt).Where(alt => g.MinPhraseLength(alt) <= maxLenOfReplacement);
    138155
    139         follow = new ReadonlySequence[alts.Count()];
     156        var children = new TreeNode[alts.Count()];
    140157        int idx = 0;
    141158        foreach (var alt in alts) {
    142159          var newPhrase = new Sequence(phrase); // clone
    143160          newPhrase.ReplaceAt(newPhrase.FirstNonTerminalIndex, 1, alt);
    144           follow[idx++] = new ReadonlySequence(newPhrase);
    145         }
    146       //  cache[phrase] = follow;
    147       //}
    148       return follow;
     161          children[idx++] = new TreeNode(newPhrase.ToString(), alt);
     162        }
     163        n.children = children;
     164      }
     165      return n.children.Select(ch => ch.phrase);
    149166    }
    150167
     
    161178      bestQuality = 0.0;
    162179      tries = 0;
    163       cache.Clear();
     180      rootNode = new TreeNode(problem.Grammar.SentenceSymbol.ToString(), new ReadonlySequence("$"));
    164181    }
    165182
    166183    public bool Done() {
    167       var g = problem.Grammar;
    168       var startState = new ReadonlySequence(g.SentenceSymbol);
    169       var follow = GenerateFollowStates(g, startState);
    170       ReadonlySequence selectedState;
    171       return !behaviourPolicy.TrySelect(random, startState, follow, out selectedState);
     184      int selectedStateIdx;
     185      return !behaviourPolicy.TrySelect(random, rootNode.phrase, GenerateFollowStates(rootNode), out selectedStateIdx);
    172186    }
    173187
     
    176190      Console.WriteLine("depth: {0,5} tries: {1,5} best phrase {2,50} bestQ {3:F3}", maxSearchDepth, tries, bestPhrase, bestQuality);
    177191
    178       // use greedy strategy to generate the currently prefered sentence
    179       var phrase = new ReadonlySequence(problem.Grammar.SentenceSymbol);
     192      // use behaviour strategy to generate the currently prefered sentence
    180193      var policy = behaviourPolicy;
    181       while (!phrase.IsTerminal) {
     194
     195      var n = rootNode;
     196
     197      while (n != null) {
     198        var phrase = n.phrase;
    182199        Console.ForegroundColor = ConsoleColor.White;
    183200        Console.WriteLine("{0,-30}", phrase);
    184         var newPhrases = GenerateFollowStates(problem.Grammar, phrase);
    185         if (!newPhrases.Any()) break;
    186         var values = newPhrases.Select(p => policy.GetValue(p));
     201        var children = n.children;
     202        if (children == null || !children.Any()) break;
     203        var values = children.Select(ch => policy.GetValue(ch.phrase));
    187204        var maxValue = values.Max();
    188205        if (maxValue == 0) maxValue = 1.0;
    189206
    190207        // write phrases
    191         foreach (var p in newPhrases) {
    192           SetColorForValue(policy.GetValue(p) / maxValue);
    193           Console.Write(" {0,-4}", p.Subsequence(Math.Max(0, p.Length - 3), Math.Min(3, p.Length)));
     208        foreach (var ch in children) {
     209          SetColorForValue(policy.GetValue(ch.phrase) / maxValue);
     210          Console.Write(" {0,-4}", ch.phrase.Substring(Math.Max(0, ch.phrase.Length - 3), Math.Min(3, ch.phrase.Length)));
    194211        }
    195212        Console.WriteLine();
    196213
    197214        // write values
    198         foreach (var p in newPhrases) {
    199           SetColorForValue(policy.GetValue(p) / maxValue);
    200           Console.Write(" {0:F2}", policy.GetValue(p) * 10.0);
     215        foreach (var ch in children) {
     216          SetColorForValue(policy.GetValue(ch.phrase) / maxValue);
     217          Console.Write(" {0:F2}", policy.GetValue(ch.phrase) * 10.0);
    201218        }
    202219        Console.WriteLine();
    203220
    204221        // write tries
    205         foreach (var p in newPhrases) {
    206           SetColorForValue(policy.GetValue(p) / maxValue);
    207           Console.Write(" {0,4}", policy.GetTries(p));
     222        foreach (var ch in children) {
     223          SetColorForValue(policy.GetValue(ch.phrase) / maxValue);
     224          Console.Write(" {0,4}", policy.GetTries(ch.phrase));
    208225        }
    209226        Console.WriteLine();
    210         if (!policy.TrySelect(random, phrase, newPhrases, out phrase)) {
     227        int selectedChildIdx;
     228        if (!policy.TrySelect(random, phrase, children.Select(ch => ch.phrase), out selectedChildIdx)) {
    211229          break;
    212230        }
     231        n = n.children[selectedChildIdx];
    213232      }
    214233
Note: See TracChangeset for help on using the changeset viewer.