Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.2/sources/HeuristicLab.GP.Tests/SymbolicExpressionImporter.cs @ 3581

Last change on this file since 3581 was 2674, checked in by gkronber, 15 years ago

Added weights for open parameters. #833 (Genetic Programming based search for equations (modeling with multiple target variables))

File size: 7.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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 HeuristicLab.GP.Interfaces;
27using System.IO;
28using System.Diagnostics;
29using HeuristicLab.GP.StructureIdentification;
30
31namespace HeuristicLab.GP.Test {
32  class SymbolicExpressionImporter {
33    private const string DIFFSTART = "dif";
34    private const string VARSTART = "var";
35    private const string OPENPARAMSTART = "open-param";
36    private Dictionary<string, IFunction> knownFunctions = new Dictionary<string, IFunction>()
37      {
38        {"+", new Addition()},
39        {"and", new And()},
40        {"mean", new Average()},
41        {"cos", new Cosinus()},
42        {"/", new Division()},
43        {"equ", new Equal()},
44        {"exp", new Exponential()},
45        {">", new GreaterThan()},
46        {"if", new IfThenElse()},
47        {"<", new LessThan()},
48        {"log", new Logarithm()},
49        {"*", new Multiplication()},
50        {"not", new Not()},
51        {"or", new Or()},
52        {"expt", new Power()},
53        {"sign", new Signum()},
54        {"sin",new Sinus()},
55        {"sqrt", new Sqrt()},
56        {"-", new Subtraction()},
57        {"tan", new Tangens()},
58        {"xor", new Xor()},
59        {"open-param", new HeuristicLab.GP.StructureIdentification.Networks.OpenParameter()},
60        {"open-+", new HeuristicLab.GP.StructureIdentification.Networks.OpenAddition()},
61        {"open--", new HeuristicLab.GP.StructureIdentification.Networks.OpenSubtraction()},
62        {"open-*", new HeuristicLab.GP.StructureIdentification.Networks.OpenMultiplication()},
63        {"open-/", new HeuristicLab.GP.StructureIdentification.Networks.OpenDivision()},
64        {"open-log", new HeuristicLab.GP.StructureIdentification.Networks.OpenLog()},
65        {"open-exp", new HeuristicLab.GP.StructureIdentification.Networks.OpenExp()},
66        //{"open-sqr", new HeuristicLab.GP.StructureIdentification.Networks.OpenSqr()},
67        //{"open-sqrt", new HeuristicLab.GP.StructureIdentification.Networks.OpenSqrt()},
68        {"f1-+", new HeuristicLab.GP.StructureIdentification.Networks.AdditionF1()},
69        {"f1--", new HeuristicLab.GP.StructureIdentification.Networks.SubtractionF1()},
70        {"f1-/", new HeuristicLab.GP.StructureIdentification.Networks.DivisionF1()},
71        {"f1-*", new HeuristicLab.GP.StructureIdentification.Networks.MultiplicationF1()},
72        {"cycle", new HeuristicLab.GP.StructureIdentification.Networks.Cycle()},
73        {"flip", new HeuristicLab.GP.StructureIdentification.Networks.Flip()},
74
75      };
76    Constant constant = new Constant();
77    HeuristicLab.GP.StructureIdentification.Variable variable = new HeuristicLab.GP.StructureIdentification.Variable();
78    Differential differential = new Differential();
79    HeuristicLab.GP.StructureIdentification.Networks.OpenParameter openParam = new HeuristicLab.GP.StructureIdentification.Networks.OpenParameter();
80    public SymbolicExpressionImporter() {
81    }
82
83    internal IFunctionTree Import(string str) {
84      str = str.Replace("(", " ( ").Replace(")", " ) ");
85      return ParseSexp(new Queue<Token>(GetTokenStream(str)));
86    }
87
88    private IEnumerable<Token> GetTokenStream(string str) {
89      return
90             from strToken in str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable()
91             let t = Token.Parse(strToken)
92             where t != null
93             select t;
94    }
95
96    private HeuristicLab.GP.Interfaces.IFunctionTree ParseSexp(Queue<Token> tokens) {
97      if (tokens.Peek().Symbol == TokenSymbol.LPAR) {
98        IFunctionTree tree;
99        Expect(Token.LPAR, tokens);
100        if (tokens.Peek().StringValue.StartsWith(VARSTART)) {
101          tree = ParseVariable(tokens);
102        } else if (tokens.Peek().StringValue.StartsWith(DIFFSTART)) {
103          tree = ParseDifferential(tokens);
104        } else if (tokens.Peek().StringValue.StartsWith(OPENPARAMSTART)) {
105          tree = ParseOpenParameter(tokens);
106        } else {
107          Token curToken = tokens.Dequeue();
108          tree = CreateTree(curToken);
109          while (!tokens.Peek().Equals(Token.RPAR)) {
110            tree.AddSubTree(ParseSexp(tokens));
111          }
112        }
113        Expect(Token.RPAR, tokens);
114        return tree;
115      } else if (tokens.Peek().Symbol == TokenSymbol.NUMBER) {
116        ConstantFunctionTree t = (ConstantFunctionTree)constant.GetTreeNode();
117        t.Value = tokens.Dequeue().DoubleValue;
118        return t;
119      } else throw new FormatException("Expected function or constant symbol");
120    }
121
122    private IFunctionTree ParseOpenParameter(Queue<Token> tokens) {
123      Token tok = tokens.Dequeue();
124      Debug.Assert(tok.StringValue == "open-param");
125      HeuristicLab.GP.StructureIdentification.Networks.OpenParameterFunctionTree t = (HeuristicLab.GP.StructureIdentification.Networks.OpenParameterFunctionTree)openParam.GetTreeNode();
126      t.Weight = tokens.Dequeue().DoubleValue;
127      t.VariableName = tokens.Dequeue().StringValue;
128      t.SampleOffset = (int)tokens.Dequeue().DoubleValue;
129      return t;
130    }
131
132    private IFunctionTree ParseDifferential(Queue<Token> tokens) {
133      Token diffTok = tokens.Dequeue();
134      Debug.Assert(diffTok.StringValue == "differential");
135      VariableFunctionTree t = (VariableFunctionTree)differential.GetTreeNode();
136      t.Weight = tokens.Dequeue().DoubleValue;
137      t.VariableName = tokens.Dequeue().StringValue;
138      t.SampleOffset = (int)tokens.Dequeue().DoubleValue;
139      return t;
140    }
141
142    private IFunctionTree ParseVariable(Queue<Token> tokens) {
143      Token varTok = tokens.Dequeue();
144      Debug.Assert(varTok.StringValue == "variable");
145      VariableFunctionTree t = (VariableFunctionTree)variable.GetTreeNode();
146      t.Weight = tokens.Dequeue().DoubleValue;
147      t.VariableName = tokens.Dequeue().StringValue;
148      t.SampleOffset = (int)tokens.Dequeue().DoubleValue;
149      return t;
150    }
151
152    private IFunctionTree CreateTree(Token token) {
153      if (token.Symbol != TokenSymbol.SYMB) throw new FormatException("Expected function symbol, but got: " + token.StringValue);
154      return knownFunctions[token.StringValue].GetTreeNode();
155    }
156
157    private void Expect(Token token, Queue<Token> tokens) {
158      Token cur = tokens.Dequeue();
159      if (!token.Equals(cur)) throw new FormatException("Expected: " + token.StringValue + ", but got found: " + cur.StringValue);
160    }
161  }
162}
Note: See TracBrowser for help on using the repository browser.