Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2886_SymRegGrammarEnumeration/HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration/GrammarEnumeration/GrammarEnumerationAlgorithm.cs @ 15791

Last change on this file since 15791 was 15784, checked in by lkammere, 6 years ago

#2886: Add basic implementation for inverse factors.

File size: 13.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading;
6using HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration.GrammarEnumeration;
7using HeuristicLab.Common;
8using HeuristicLab.Core;
9using HeuristicLab.Data;
10using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
11using HeuristicLab.Optimization;
12using HeuristicLab.Parameters;
13using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
14using HeuristicLab.Problems.DataAnalysis;
15using HeuristicLab.Problems.DataAnalysis.Symbolic;
16using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
17
18namespace HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration {
19  [Item("Grammar Enumeration Symbolic Regression", "Iterates all possible model structures for a fixed grammar.")]
20  [StorableClass]
21  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 250)]
22  public class GrammarEnumerationAlgorithm : FixedDataAnalysisAlgorithm<IRegressionProblem> {
23    #region properties and result names
24    private readonly string BestTrainingQualityName = "Best R² (Training)";
25    private readonly string BestTrainingSolutionName = "Best solution (Training)";
26    private readonly string GeneratedSentencesName = "Generated Sentences";
27    private readonly string DistinctSentencesName = "Distinct Sentences";
28    private readonly string PhraseExpansionsName = "Phrase Expansions";
29    private readonly string AverageTreeLengthName = "Avg. Sentence Length among Distinct";
30    private readonly string GeneratedEqualSentencesName = "Generated equal sentences";
31
32
33    private readonly string SearchDataStructureParameterName = "Search Data Structure";
34    private readonly string MaxTreeSizeParameterName = "Max. Tree Nodes";
35    private readonly string GuiUpdateIntervalParameterName = "GUI Update Interval";
36
37    public override bool SupportsPause { get { return false; } }
38
39    protected IValueParameter<IntValue> MaxTreeSizeParameter {
40      get { return (IValueParameter<IntValue>)Parameters[MaxTreeSizeParameterName]; }
41    }
42    public int MaxTreeSize {
43      get { return MaxTreeSizeParameter.Value.Value; }
44      set { MaxTreeSizeParameter.Value.Value = value; }
45    }
46
47    protected IValueParameter<IntValue> GuiUpdateIntervalParameter {
48      get { return (IValueParameter<IntValue>)Parameters[GuiUpdateIntervalParameterName]; }
49    }
50    public int GuiUpdateInterval {
51      get { return GuiUpdateIntervalParameter.Value.Value; }
52      set { GuiUpdateIntervalParameter.Value.Value = value; }
53    }
54
55    protected IValueParameter<EnumValue<StorageType>> SearchDataStructureParameter {
56      get { return (IValueParameter<EnumValue<StorageType>>)Parameters[SearchDataStructureParameterName]; }
57    }
58    public StorageType SearchDataStructure {
59      get { return SearchDataStructureParameter.Value.Value; }
60      set { SearchDataStructureParameter.Value.Value = value; }
61    }
62
63    public SymbolString BestTrainingSentence;
64
65    #endregion
66
67    public Dictionary<int, SymbolString> DistinctSentences;   // Semantically distinct sentences in a run.
68    public Dictionary<int, List<SymbolString>> AllSentences;  // All sentences ever generated in a run.
69    public Dictionary<int, SymbolString> ArchivedPhrases;     // Nodes in the search tree
70    SearchDataStore OpenPhrases;                              // Stack/Queue/etc. for fetching the next node in the search tree. 
71
72    public int EqualGeneratedSentences; // It is not guaranteed that shorter solutions are found first.
73                                        // When longer solutions are overwritten with shorter ones,
74                                        // this counter is increased.
75    public int Expansions;              // Number, how many times a nonterminal symbol is replaced with a production rule.
76    public Grammar Grammar;
77
78    public StringBuilder dotFileBuilder;
79
80    #region ctors
81    public override IDeepCloneable Clone(Cloner cloner) {
82      return new GrammarEnumerationAlgorithm(this, cloner);
83    }
84
85    public GrammarEnumerationAlgorithm() {
86      var provider = new HeuristicLab.Problems.Instances.DataAnalysis.NguyenInstanceProvider(seed: 1234);
87      var regProblem = provider.LoadData(provider.GetDataDescriptors().Single(x => x.Name.Contains("F9 ")));
88
89      Problem = new RegressionProblem() {
90        ProblemData = regProblem
91      };
92
93      Parameters.Add(new ValueParameter<IntValue>(MaxTreeSizeParameterName, "The number of clusters.", new IntValue(6)));
94      Parameters.Add(new ValueParameter<IntValue>(GuiUpdateIntervalParameterName, "Number of generated sentences, until GUI is refreshed.", new IntValue(4000)));
95
96      Parameters.Add(new ValueParameter<EnumValue<StorageType>>(SearchDataStructureParameterName, new EnumValue<StorageType>(StorageType.Stack)));
97    }
98
99    public GrammarEnumerationAlgorithm(GrammarEnumerationAlgorithm original, Cloner cloner) : base(original, cloner) { }
100    #endregion
101
102    protected override void Run(CancellationToken cancellationToken) {
103      #region init
104      InitResults();
105
106      dotFileBuilder = new StringBuilder();
107
108      AllSentences = new Dictionary<int, List<SymbolString>>();
109      ArchivedPhrases = new Dictionary<int, SymbolString>(); // Nodes in the search tree
110      DistinctSentences = new Dictionary<int, SymbolString>();
111      Expansions = 0;
112      EqualGeneratedSentences = 0;
113
114      Grammar = new Grammar(Problem.ProblemData.AllowedInputVariables.ToArray());
115
116      OpenPhrases = new SearchDataStore(SearchDataStructure); // Select search strategy
117      var phrase0 = new SymbolString(new[] { Grammar.StartSymbol });
118      #endregion
119
120      OpenPhrases.Store(Grammar.CalcHashCode(phrase0), phrase0);
121
122      while (OpenPhrases.Count > 0) {
123        if (cancellationToken.IsCancellationRequested) break;
124
125        StoredSymbolString fetchedPhrase = OpenPhrases.GetNext();
126        SymbolString currPhrase = fetchedPhrase.SymbolString;
127
128        if (dotFileBuilder.Length == 0) {
129          dotFileBuilder.AppendLine("digraph searchgraph {");
130          dotFileBuilder.AppendLine(fetchedPhrase.Hash + " [label=\"" + Grammar.PostfixToInfixParser(fetchedPhrase.SymbolString) + "\", shape=doublecircle];");
131        } else {
132          dotFileBuilder.AppendLine(fetchedPhrase.Hash + " [label=\"" + Grammar.PostfixToInfixParser(fetchedPhrase.SymbolString) + "\"];");
133        }
134
135        ArchivedPhrases.Add(fetchedPhrase.Hash, currPhrase);
136
137        // expand next nonterminal symbols
138        int nonterminalSymbolIndex = currPhrase.FindIndex(s => s is NonterminalSymbol);
139        NonterminalSymbol expandedSymbol = currPhrase[nonterminalSymbolIndex] as NonterminalSymbol;
140
141        foreach (Production productionAlternative in expandedSymbol.Alternatives) {
142          SymbolString newPhrase = new SymbolString(currPhrase);
143          newPhrase.RemoveAt(nonterminalSymbolIndex);
144          newPhrase.InsertRange(nonterminalSymbolIndex, productionAlternative);
145
146          Expansions++;
147          if (newPhrase.Count <= MaxTreeSize) {
148            var phraseHash = Grammar.CalcHashCode(newPhrase);
149
150            dotFileBuilder.AppendLine(fetchedPhrase.Hash + " -> " + phraseHash + " [label=\"" + expandedSymbol.StringRepresentation + "&rarr;" + productionAlternative + "\"];");
151
152            if (newPhrase.IsSentence()) { // Sentence was generated.
153              SaveToAllSentences(phraseHash, newPhrase);
154
155              if (!DistinctSentences.ContainsKey(phraseHash) || DistinctSentences[phraseHash].Count > newPhrase.Count) {
156                if (DistinctSentences.ContainsKey(phraseHash)) EqualGeneratedSentences++; // for analysis only
157
158                DistinctSentences[phraseHash] = newPhrase;
159                EvaluateSentence(newPhrase);
160
161                dotFileBuilder.AppendLine(phraseHash + " [label=\"" + Grammar.PostfixToInfixParser(newPhrase) + "\", style=\"filled\"];");
162              }
163              UpdateView(AllSentences, DistinctSentences, Expansions);
164
165            } else if (!OpenPhrases.Contains(phraseHash) && !ArchivedPhrases.ContainsKey(phraseHash)) {
166              OpenPhrases.Store(phraseHash, newPhrase);
167            }
168          }
169        }
170      }
171
172      dotFileBuilder.AppendLine(Grammar.CalcHashCode(BestTrainingSentence) + " [label=\"" + Grammar.PostfixToInfixParser(BestTrainingSentence) + "\", shape=Mcircle, style=\"filled,bold\"];");
173      dotFileBuilder.AppendLine("}");
174
175      System.IO.File.WriteAllText(Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory)+ @"\searchgraph.dot", dotFileBuilder.ToString());
176
177      UpdateView(AllSentences, DistinctSentences, Expansions, force: true);
178      UpdateFinalResults();
179    }
180
181    // Store sentence to "MultiDictionary"
182    private void SaveToAllSentences(int hash, SymbolString sentence) {
183      if (AllSentences.ContainsKey(hash))
184        AllSentences[hash].Add(sentence);
185      else
186        AllSentences[hash] = new List<SymbolString> { sentence };
187    }
188
189    #region Evaluation of generated models.
190
191    // Evaluate sentence within an algorithm run.
192    private void EvaluateSentence(SymbolString symbolString) {
193      SymbolicExpressionTree tree = Grammar.ParseSymbolicExpressionTree(symbolString);
194      SymbolicRegressionModel model = new SymbolicRegressionModel(
195        Problem.ProblemData.TargetVariable,
196        tree,
197        new SymbolicDataAnalysisExpressionTreeLinearInterpreter());
198
199      var probData = Problem.ProblemData;
200      var target = probData.TargetVariableTrainingValues;
201      var estVals = model.GetEstimatedValues(probData.Dataset, probData.TrainingIndices);
202      OnlineCalculatorError error;
203      var r2 = OnlinePearsonsRSquaredCalculator.Calculate(target, estVals, out error);
204      if (error != OnlineCalculatorError.None) r2 = 0.0;
205
206      var bestR2 = ((DoubleValue)Results[BestTrainingQualityName].Value).Value;
207      if (r2 > bestR2) {
208        ((DoubleValue)Results[BestTrainingQualityName].Value).Value = r2;
209        BestTrainingSentence = symbolString;
210      }
211    }
212
213    #endregion
214
215    #region Visualization in HL
216    // Initialize entries in result set.
217    private void InitResults() {
218      BestTrainingSentence = null;
219
220      Results.Add(new Result(BestTrainingQualityName, new DoubleValue(-1.0)));
221
222      Results.Add(new Result(GeneratedSentencesName, new IntValue(0)));
223      Results.Add(new Result(DistinctSentencesName, new IntValue(0)));
224      Results.Add(new Result(PhraseExpansionsName, new IntValue(0)));
225      Results.Add(new Result(GeneratedEqualSentencesName, new IntValue(0)));
226      Results.Add(new Result(AverageTreeLengthName, new DoubleValue(1.0)));
227    }
228
229    // Update the view for intermediate results in an algorithm run.
230    private int updates;
231    private void UpdateView(Dictionary<int, List<SymbolString>> allGenerated,
232        Dictionary<int, SymbolString> distinctGenerated, int expansions, bool force = false) {
233      updates++;
234
235      if (force || updates % GuiUpdateInterval == 0) {
236        var allGeneratedEnum = allGenerated.Values.SelectMany(x => x).ToArray();
237        ((IntValue)Results[GeneratedSentencesName].Value).Value = allGeneratedEnum.Length;
238        ((IntValue)Results[DistinctSentencesName].Value).Value = distinctGenerated.Count;
239        ((IntValue)Results[PhraseExpansionsName].Value).Value = expansions;
240        ((IntValue)Results[GeneratedEqualSentencesName].Value).Value = EqualGeneratedSentences;
241        ((DoubleValue)Results[AverageTreeLengthName].Value).Value = allGeneratedEnum.Select(sentence => sentence.Count).Average();
242      }
243    }
244
245    // Generate all Results after an algorithm run.
246    private void UpdateFinalResults() {
247      SymbolicExpressionTree tree = Grammar.ParseSymbolicExpressionTree(BestTrainingSentence);
248      SymbolicRegressionModel model = new SymbolicRegressionModel(
249        Problem.ProblemData.TargetVariable,
250        tree,
251        new SymbolicDataAnalysisExpressionTreeLinearInterpreter());
252
253      IRegressionSolution bestTrainingSolution = new RegressionSolution(model, Problem.ProblemData);
254      Results.AddOrUpdateResult(BestTrainingSolutionName, bestTrainingSolution);
255
256      // Print generated sentences.
257      string[,] sentencesMatrix = new string[AllSentences.Values.SelectMany(x => x).Count(), 3];
258
259      int i = 0;
260      foreach (var sentenceSet in AllSentences) {
261        foreach (var sentence in sentenceSet.Value) {
262          sentencesMatrix[i, 0] = sentence.ToString();
263          sentencesMatrix[i, 1] = Grammar.PostfixToInfixParser(sentence).ToString();
264          sentencesMatrix[i, 2] = sentenceSet.Key.ToString();
265          i++;
266        }
267      }
268      Results.Add(new Result("All generated sentences", new StringMatrix(sentencesMatrix)));
269
270      string[,] distinctSentencesMatrix = new string[DistinctSentences.Count, 3];
271      i = 0;
272      foreach (KeyValuePair<int, SymbolString> distinctSentence in DistinctSentences) {
273        distinctSentencesMatrix[i, 0] = distinctSentence.Key.ToString();
274        distinctSentencesMatrix[i, 1] = Grammar.PostfixToInfixParser(distinctSentence.Value).ToString();
275        distinctSentencesMatrix[i, 2] = distinctSentence.Key.ToString();
276        i++;
277      }
278      Results.Add(new Result("Distinct generated sentences", new StringMatrix(distinctSentencesMatrix)));
279    }
280    #endregion
281
282  }
283}
Note: See TracBrowser for help on using the repository browser.