Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Optimization/3.3/Calculator.cs @ 6878

Last change on this file since 6878 was 6878, checked in by abeham, 13 years ago

#1614

  • updated branch from trunk
File size: 8.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.RegularExpressions;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using System.Globalization;
31
32namespace HeuristicLab.Optimization {
33
34  [StorableClass]
35  public class Calculator : IDeepCloneable {
36
37    #region Fields & Properties
38
39    private List<string> tokens;
40
41    [Storable]
42    public string Formula {
43      get { return string.Join(" ", tokens); }
44      set { tokens = Tokenize(value).ToList(); }
45    }
46
47    private static readonly Regex TokenRegex =
48      new Regex(@"[a-zA-Z0-9._]+|""([^""]|\\"")*""|'([^']|\\')*'|[-+*/<>^]|dup|swap|drop|log|true|false|if|==|not|isnull|null|ismatch|rename");
49
50    #endregion
51
52    #region Construction & Cloning
53
54    [StorableConstructor]
55    protected Calculator(bool deserializing) { }
56    public Calculator() { }
57    protected Calculator(Calculator original, Cloner cloner) {
58      cloner.RegisterClonedObject(original, this);
59      tokens = original.tokens.ToList();
60    }
61    public IDeepCloneable Clone(Cloner cloner) {
62      return new Calculator(this, cloner);
63    }
64    public object Clone() {
65      return Clone(new Cloner());
66    }
67    #endregion
68
69    private static IEnumerable<string> Tokenize(string s) {
70      return TokenRegex.Matches(s).Cast<Match>().Select(m => m.Value);
71    }
72
73    public IItem GetValue(IDictionary<string, IItem> variables) {
74      var stack = new Stack<object>();
75      int i = 0;
76      try {
77        for (; i<tokens.Count; i++) {
78          var token = tokens[i];
79          double d;
80          if (TryParse(token, out d)) {
81            stack.Push(d);
82          } else if (token.StartsWith("\"")) {
83            stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace(@"\""", @"""")));
84          } else if (token.StartsWith("'")) {
85            stack.Push(token.Substring(1, token.Length-2).Replace("\'", "'"));
86          } else {
87            Apply(token, stack, variables);
88          }
89        }
90      } catch (Exception x) {
91        throw new Exception(string.Format(
92          "Calculation Failed at token #{1}: '{2}' {0}current stack is: {0}{3}", Environment.NewLine,
93          i, tokens[i], string.Join(Environment.NewLine, stack.Select(AsString))),
94          x);
95      }
96      if (stack.Count != 1) throw new Exception(string.Format("Invalid final evaluation stack size {0} (should be 1)", stack.Count));
97      var result = stack.Pop();
98      if (result is string) return new StringValue((string)result);
99      if (result is double) return new DoubleValue((double)result);
100      if (result is bool) return new BoolValue((bool)result);
101      return null;
102    }
103
104    private static void Apply(string token, Stack<object> stack, IDictionary<string, IItem> variables) {
105      switch (token) {
106        case "null":  stack.Push(null); break;
107        case "true":  stack.Push(true); break;
108        case "false": stack.Push(false); break;
109
110        case "drop": stack.Pop(); break;
111        case "dup": stack.Push(stack.Peek()); break;
112        case "swap":
113          var top = stack.Pop();
114          var next = stack.Pop();
115          stack.Push(top);
116          stack.Push(next);
117          break;
118
119        case "log": Apply(stack, x => Math.Log((double)x)); break;
120        case "+": Apply(stack, (x, y) => (double)x + (double)y); break;
121        case "-": Apply(stack, (x, y) => (double)x - (double)y); break;
122        case "*": Apply(stack, (x, y) => (double)x * (double)y); break;
123        case "/": Apply(stack, (x, y) => (double)x / (double)y); break;
124        case "^": Apply(stack, (x, y) => Math.Pow((double)x, (double)y)); break;
125        case "<": Apply(stack, (x, y) => (double)x < (double)y); break;
126        case ">": Apply(stack, (x, y) => (double)x > (double)y); break;
127
128        case "==": Apply(stack, (x, y) => Equal(x, y)); break;
129        case "not": Apply(stack, x => !(bool)x); break;
130        case "isnull": Apply(stack, x => x == null); break;
131        case "if": Apply(stack, (then, else_, cond) => (bool)cond ? then : else_); break;
132
133        case "ismatch": Apply(stack, (s, p) => new Regex((string)p).IsMatch((string)s)); break;
134        case "rename": Apply(stack, (s, p, r) => new Regex((string)p).Replace((string)s, (string)r)); break;
135
136        default: stack.Push(GetVariableValue(variables, token)); break;
137      }
138    }
139
140    #region Auxiliary Functions
141
142    #region IItem value conversion
143    private static object GetIntValue(IItem value) {
144      var v = value as IntValue;
145      if (v != null) return (double)v.Value;
146      return null;
147    }
148
149    private static object GetDoubleValue(IItem value) {
150      var v = value as DoubleValue;
151      if (v != null) return v.Value;
152      return null;
153    }
154
155    private static object GetBoolValue(IItem value) {
156      var v = value as BoolValue;
157      if (v != null) return v.Value;
158      return null;
159    }
160
161    private static object GetVariableValue(IDictionary<string, IItem> variables, string name) {
162      if (variables.ContainsKey(name)) {
163        var item = variables[name];
164        return
165          GetIntValue(item) ??
166          GetDoubleValue(item) ??
167          GetBoolValue(item) ??
168          item.ToString();
169      }
170      return null;
171    }
172    #endregion
173
174    #region variadic equality
175    private static bool Equal(object a, object b) { return EqualNumber(a, b) || EqualBool(a, b) || EqualString(a, b) || a == b; }
176    private static bool EqualNumber(object a, object b) { return a is double && b is double && (double)a == (double)b; }
177    private static bool EqualBool(object a, object b) { return a is bool && b is bool && (bool)a == (bool)b; }
178    private static bool EqualString(object a, object b) { return a is string && b is string && ((string)a).Equals((string)b); }
179    #endregion
180
181    #region stack calculation
182    private static void Apply(Stack<object> stack, Func<object, object> func) {
183      if (stack.Count < 1)
184        throw new InvalidOperationException("Stack is empty");
185      var a = stack.Pop();
186      try {
187        stack.Push(func(a));
188      } catch (Exception) {
189        stack.Push(a);
190        throw;
191      }
192    }
193
194    private static void Apply(Stack<object> stack, Func<object, object, object> func) {
195      if (stack.Count < 2)
196        throw new InvalidOperationException("Stack contains less than two elements");
197      var b = stack.Pop();
198      var a = stack.Pop();
199      try {
200        stack.Push(func(a, b));
201      } catch (Exception) {
202        stack.Push(b);
203        stack.Push(a);
204        throw;
205      }
206    }
207
208    private static void Apply(Stack<object> stack, Func<object, object, object, object> func) {
209      if (stack.Count < 3)
210        throw new InvalidOperationException("Stack contains less than three elements");
211      var c = stack.Pop();
212      var b = stack.Pop();
213      var a = stack.Pop();
214      try {
215        stack.Push(func(a, b, c));
216      } catch (Exception) {
217        stack.Push(a);
218        stack.Push(b);
219        stack.Push(c);
220        throw;
221      }
222    }
223    #endregion
224
225    private static bool TryParse(string token, out double d) {
226      return double.TryParse(token,
227                             NumberStyles.AllowDecimalPoint |
228                             NumberStyles.AllowExponent |
229                             NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out d);
230    }
231
232    private static string AsString(object o) {
233      if (o == null) return "null";
234      if (o is string) return string.Format("'{0}'", o);
235      return o.ToString();
236    }
237
238    #endregion
239  }
240}
Note: See TracBrowser for help on using the repository browser.