Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Optimization/3.3/Calculator.cs @ 15557

Last change on this file since 15557 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

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