Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RegressionBenchmarks/HeuristicLab.Optimization/3.3/Calculator.cs @ 7077

Last change on this file since 7077 was 6908, checked in by epitzer, 13 years ago

#1622 Fix quote handling and simplify tokenizer in Calculator and provide better error message.

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