Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization/3.3/RunCollectionModification/Calculator.cs @ 8778

Last change on this file since 8778 was 8778, checked in by ascheibe, 11 years ago

#1890 fixed a NullReferenceException when serializing a calculator that has not been assigned a formula

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