Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Tests/SymbolicExpressionImporter.cs @ 3733

Last change on this file since 3733 was 3733, checked in by gkronber, 14 years ago

Added test cases for arithmetic expression interpreter. And fixed minor problems in the interpreter. #791

File size: 4.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Text;
26using System.IO;
27using System.Diagnostics;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
29using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
31
32namespace HeuristicLab.Problems.DataAnalysis.Tests {
33  internal class SymbolicExpressionImporter {
34    private const string VARSTART = "var";
35    private Dictionary<string, Symbol> knownSymbols = new Dictionary<string, Symbol>()
36      {
37        {"+", new Addition()},
38        {"/", new Division()},
39        {"*", new Multiplication()},
40        {"-", new Subtraction()},
41
42      };
43    Constant constant = new Constant();
44    Variable variable = new Variable();
45    ProgramRootSymbol programRootSymbol = new ProgramRootSymbol();
46    StartSymbol startSymbol = new StartSymbol();
47
48    public SymbolicExpressionImporter() {
49    }
50
51    internal SymbolicExpressionTree Import(string str) {
52      str = str.Replace("(", " ( ").Replace(")", " ) ");
53      SymbolicExpressionTreeNode root = programRootSymbol.CreateTreeNode();
54      SymbolicExpressionTreeNode start = startSymbol.CreateTreeNode();
55      SymbolicExpressionTreeNode mainBranch = ParseSexp(new Queue<Token>(GetTokenStream(str)));
56      root.AddSubTree(start);
57      start.AddSubTree(mainBranch);
58      return new SymbolicExpressionTree(root);
59    }
60
61    private IEnumerable<Token> GetTokenStream(string str) {
62      return
63             from strToken in str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable()
64             let t = Token.Parse(strToken)
65             where t != null
66             select t;
67    }
68
69    private SymbolicExpressionTreeNode ParseSexp(Queue<Token> tokens) {
70      if (tokens.Peek().Symbol == TokenSymbol.LPAR) {
71        SymbolicExpressionTreeNode tree;
72        Expect(Token.LPAR, tokens);
73        if (tokens.Peek().StringValue.StartsWith(VARSTART)) {
74          tree = ParseVariable(tokens);
75        } else {
76          Token curToken = tokens.Dequeue();
77          tree = CreateTree(curToken);
78          while (!tokens.Peek().Equals(Token.RPAR)) {
79            tree.AddSubTree(ParseSexp(tokens));
80          }
81        }
82        Expect(Token.RPAR, tokens);
83        return tree;
84      } else if (tokens.Peek().Symbol == TokenSymbol.NUMBER) {
85        ConstantTreeNode t = (ConstantTreeNode)constant.CreateTreeNode();
86        t.Value = tokens.Dequeue().DoubleValue;
87        return t;
88      } else throw new FormatException("Expected function or constant symbol");
89    }
90
91    private SymbolicExpressionTreeNode ParseVariable(Queue<Token> tokens) {
92      Token varTok = tokens.Dequeue();
93      Debug.Assert(varTok.StringValue == "variable");
94      VariableTreeNode t = (VariableTreeNode)variable.CreateTreeNode();
95      t.Weight = tokens.Dequeue().DoubleValue;
96      t.VariableName = tokens.Dequeue().StringValue;
97      return t;
98    }
99
100    private SymbolicExpressionTreeNode CreateTree(Token token) {
101      if (token.Symbol != TokenSymbol.SYMB) throw new FormatException("Expected function symbol, but got: " + token.StringValue);
102      return knownSymbols[token.StringValue].CreateTreeNode();
103    }
104
105    private void Expect(Token token, Queue<Token> tokens) {
106      Token cur = tokens.Dequeue();
107      if (!token.Equals(cur)) throw new FormatException("Expected: " + token.StringValue + ", but got: " + cur.StringValue);
108    }
109  }
110}
Note: See TracBrowser for help on using the repository browser.