Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2886_SymRegGrammarEnumeration/HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration/GrammarEnumeration/Grammar.cs @ 15859

Last change on this file since 15859 was 15851, checked in by lkammere, 7 years ago

#2886: Remove cosine terminal symbols.

File size: 9.2 KB
Line 
1using System.Collections.Generic;
2using System.Diagnostics;
3using System.Linq;
4using HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration.GrammarEnumeration;
5using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
6using HeuristicLab.Problems.DataAnalysis.Symbolic;
7
8namespace HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration {
9  public class Grammar {
10
11    public Symbol StartSymbol { get; }
12
13    public Hasher<int> Hasher { get; }
14
15    #region Symbols
16
17    public IReadOnlyDictionary<Symbol, IReadOnlyList<Production>> Productions { get; }
18
19    public NonterminalSymbol Var;
20    public IReadOnlyList<VariableTerminalSymbol> VarTerminals;
21
22    public NonterminalSymbol Expr;
23    public NonterminalSymbol Term;
24    public NonterminalSymbol Factor;
25    public NonterminalSymbol LogFactor;
26    public NonterminalSymbol ExpFactor;
27    public NonterminalSymbol SinFactor;
28
29    public NonterminalSymbol SimpleExpr;
30    public NonterminalSymbol SimpleTerm;
31
32    public NonterminalSymbol InvExpr;
33    public NonterminalSymbol InvTerm;
34
35    public TerminalSymbol Addition;
36    public TerminalSymbol Multiplication;
37    public TerminalSymbol Log;
38    public TerminalSymbol Exp;
39    public TerminalSymbol Sin;
40    public TerminalSymbol Inv;
41
42    public TerminalSymbol Const;
43
44    #endregion
45
46    #region HL Symbols for Parsing ExpressionTrees
47
48    private ISymbol constSy;
49    private ISymbol varSy;
50
51    private ISymbol addSy;
52    private ISymbol mulSy;
53    private ISymbol logSy;
54    private ISymbol expSy;
55    private ISymbol divSy;
56    private ISymbol sinSy;
57
58    private ISymbol rootSy;
59    private ISymbol startSy;
60
61    private InfixExpressionFormatter infixExpressionFormatter;
62    #endregion
63
64    public Grammar(string[] variables) {
65      #region Define Symbols
66      Var = new NonterminalSymbol("Var");
67
68      Expr = new NonterminalSymbol("Expr");
69      Term = new NonterminalSymbol("Term");
70      Factor = new NonterminalSymbol("Factor");
71      LogFactor = new NonterminalSymbol("LogFactor");
72      ExpFactor = new NonterminalSymbol("ExpFactor");
73      SinFactor = new NonterminalSymbol("SinFactor");
74
75      SimpleExpr = new NonterminalSymbol("SimpleExpr");
76      SimpleTerm = new NonterminalSymbol("SimpleTerm");
77
78      InvExpr = new NonterminalSymbol("InvExpr");
79      InvTerm = new NonterminalSymbol("InvTerm");
80
81      Addition = new TerminalSymbol("+");
82      Multiplication = new TerminalSymbol("*");
83      Log = new TerminalSymbol("log");
84      Exp = new TerminalSymbol("exp");
85      Sin = new TerminalSymbol("sin");
86      Inv = new TerminalSymbol("inv");
87
88      Const = new TerminalSymbol("c");
89      #endregion
90
91      #region Production rules
92      StartSymbol = Expr;
93
94      Dictionary<Symbol, IReadOnlyList<Production>> productions = new Dictionary<Symbol, IReadOnlyList<Production>>();
95
96      // Map each variable to a separate production rule of the "Var" nonterminal symbol.
97      VarTerminals = variables.Select(v => new VariableTerminalSymbol(v)).ToArray();
98      productions[Var] = VarTerminals.Select(v => new Production(v)).ToArray();
99
100      productions[Expr] = new[] {
101        new Production(Const, Term, Multiplication, Expr, Addition),
102        new Production(Const, Term, Multiplication, Const, Addition)
103      };
104
105      productions[Term] = new[] {
106        new Production(Factor, Term, Multiplication),
107        new Production(Factor),
108        new Production(InvExpr, Inv)
109      };
110
111      productions[Factor] = new[] {
112        new Production(Var),
113        new Production(LogFactor),
114        new Production(ExpFactor),
115        new Production(SinFactor),
116      };
117
118      productions[LogFactor] = new[] { new Production(SimpleExpr, Log) };
119      productions[ExpFactor] = new[] { new Production(Const, SimpleTerm, Multiplication, Exp) };
120      productions[SinFactor] = new[] { new Production(SimpleExpr, Sin) };
121
122      productions[SimpleExpr] = new[] {
123        new Production(Const, SimpleTerm, Multiplication, SimpleExpr, Addition),
124        new Production(Const, SimpleTerm, Multiplication, Const, Addition)
125      };
126
127      productions[SimpleTerm] = new[] {
128        new Production(Var, SimpleTerm, Multiplication),
129        new Production(Var)
130      };
131
132      productions[InvExpr] = new[] {
133        new Production(Const, InvTerm, Multiplication, InvExpr, Addition),
134        new Production(Const, InvTerm, Multiplication, Const, Addition)
135      };
136
137      productions[InvTerm] = new[] {
138        new Production(Factor, InvTerm, Multiplication),
139        new Production(Factor)
140      };
141
142      Productions = productions;
143      #endregion
144
145      #region Parsing to SymbolicExpressionTree
146      var symbolicExpressionGrammar = new TypeCoherentExpressionGrammar();
147      symbolicExpressionGrammar.ConfigureAsDefaultRegressionGrammar();
148
149      constSy = symbolicExpressionGrammar.Symbols.OfType<Constant>().First();
150      varSy = symbolicExpressionGrammar.Symbols.OfType<Variable>().First();
151      addSy = symbolicExpressionGrammar.Symbols.OfType<Addition>().First();
152      mulSy = symbolicExpressionGrammar.Symbols.OfType<Multiplication>().First();
153      logSy = symbolicExpressionGrammar.Symbols.OfType<Logarithm>().First();
154      expSy = symbolicExpressionGrammar.Symbols.OfType<Exponential>().First();
155      divSy = symbolicExpressionGrammar.Symbols.OfType<Division>().First();
156      sinSy = symbolicExpressionGrammar.Symbols.OfType<Sine>().First();
157
158      rootSy = symbolicExpressionGrammar.Symbols.OfType<ProgramRootSymbol>().First();
159      startSy = symbolicExpressionGrammar.Symbols.OfType<StartSymbol>().First();
160
161      infixExpressionFormatter = new InfixExpressionFormatter();
162      #endregion
163
164      Hasher = new IntHasher(this);
165    }
166
167    #region Parse to SymbolicExpressionTree
168
169    public string ToInfixString(SymbolString sentence) {
170      Debug.Assert(sentence.Any(), "Trying to evaluate empty sentence!");
171      Debug.Assert(sentence.All(s => s is TerminalSymbol), "Trying to evaluate symbol sequence with nonterminalsymbols!");
172
173      return infixExpressionFormatter.Format(ParseSymbolicExpressionTree(sentence));
174    }
175
176    public SymbolicExpressionTree ParseSymbolicExpressionTree(SymbolString sentence) {
177      Debug.Assert(sentence.Any(), "Trying to evaluate empty sentence!");
178      Debug.Assert(sentence.All(s => s is TerminalSymbol), "Trying to evaluate symbol sequence with nonterminalsymbols!");
179
180      var rootNode = rootSy.CreateTreeNode();
181      var startNode = startSy.CreateTreeNode();
182      rootNode.AddSubtree(startNode);
183
184      Stack<TerminalSymbol> parseStack = new Stack<TerminalSymbol>(sentence.OfType<TerminalSymbol>());
185      startNode.AddSubtree(ParseSymbolicExpressionTree(parseStack));
186
187      return new SymbolicExpressionTree(rootNode);
188    }
189
190    public ISymbolicExpressionTreeNode ParseSymbolicExpressionTree(Stack<TerminalSymbol> parseStack) {
191      TerminalSymbol currentSymbol = parseStack.Pop();
192
193      ISymbolicExpressionTreeNode parsedSubTree = null;
194
195      if (currentSymbol == Addition) {
196        parsedSubTree = addSy.CreateTreeNode();
197        ISymbolicExpressionTreeNode rightSubtree = ParseSymbolicExpressionTree(parseStack);
198        if (rightSubtree is ConstantTreeNode) {
199          ((ConstantTreeNode)rightSubtree).Value = 0.0;
200        }
201        parsedSubTree.AddSubtree(rightSubtree); // left part
202
203        ISymbolicExpressionTreeNode leftSubtree = ParseSymbolicExpressionTree(parseStack);
204        if (leftSubtree is ConstantTreeNode) {
205          ((ConstantTreeNode)leftSubtree).Value = 0.0;
206        }
207        parsedSubTree.AddSubtree(leftSubtree); // right part
208
209      } else if (currentSymbol == Multiplication) {
210        parsedSubTree = mulSy.CreateTreeNode();
211        parsedSubTree.AddSubtree(ParseSymbolicExpressionTree(parseStack)); // left part
212        parsedSubTree.AddSubtree(ParseSymbolicExpressionTree(parseStack)); // right part
213
214      } else if (currentSymbol == Log) {
215        parsedSubTree = logSy.CreateTreeNode();
216        parsedSubTree.AddSubtree(ParseSymbolicExpressionTree(parseStack));
217
218      } else if (currentSymbol == Exp) {
219        parsedSubTree = expSy.CreateTreeNode();
220        parsedSubTree.AddSubtree(ParseSymbolicExpressionTree(parseStack));
221
222      } else if (currentSymbol == Sin) {
223        parsedSubTree = sinSy.CreateTreeNode();
224        parsedSubTree.AddSubtree(ParseSymbolicExpressionTree(parseStack));
225
226      } else if (currentSymbol == Inv) {
227        parsedSubTree = divSy.CreateTreeNode();
228        ConstantTreeNode dividend = (ConstantTreeNode)constSy.CreateTreeNode();
229        dividend.Value = 1.0;
230        parsedSubTree.AddSubtree(dividend);
231        parsedSubTree.AddSubtree(ParseSymbolicExpressionTree(parseStack));
232
233      } else if (currentSymbol == Const) {
234        ConstantTreeNode constNode = (ConstantTreeNode)constSy.CreateTreeNode();
235        constNode.Value = 1.0;
236        parsedSubTree = constNode;
237
238      } else if (currentSymbol is VariableTerminalSymbol) {
239        VariableTreeNode varNode = (VariableTreeNode)varSy.CreateTreeNode();
240        varNode.Weight = 1.0;
241        varNode.VariableName = currentSymbol.StringRepresentation;
242        parsedSubTree = varNode;
243      }
244
245      Debug.Assert(parsedSubTree != null);
246      return parsedSubTree;
247    }
248    #endregion
249  }
250}
Note: See TracBrowser for help on using the repository browser.