Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12091 was 12091, checked in by pfleck, 9 years ago

#2344

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