Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HLScript/HeuristicLab.Optimization/3.3/RunCollectionModification/Calculator.cs @ 12246

Last change on this file since 12246 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 9.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Globalization;
25using System.Linq;
26using System.Text;
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 {
44      get { return tokens == null ? string.Empty : string.Join(" ", tokens); }
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 {
79        for (; i < tokens.Count; i++) {
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("'")) {
87            stack.Push(token.Substring(1, token.Length - 2).Replace("\\'", "'"));
88          } else {
89            Apply(token, stack, variables);
90          }
91        }
92      }
93      catch (Exception x) {
94        throw new Exception(string.Format(
95          "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine,
96          Formula, i, TokenWithContext(tokens, i, 3),
97          string.Join(Environment.NewLine, stack.Select(AsString))),
98          x);
99      }
100      if (stack.Count != 1)
101        throw new Exception(
102          string.Format("Invalid final evaluation stack size {0} (should be 1) in formula '{1}'",
103          stack.Count, Formula));
104      var result = stack.Pop();
105      if (result is string) return new StringValue((string)result);
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();
113      if (i > context + 1)
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) {
128        case "null": stack.Push(null); break;
129        case "true": stack.Push(true); break;
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
141        case "log": Apply(stack, x => Math.Log((double)x)); break;
142        case "+": Apply(stack, (x, y) => (double)x + (double)y); break;
143        case "-": Apply(stack, (x, y) => (double)x - (double)y); break;
144        case "*": Apply(stack, (x, y) => (double)x * (double)y); break;
145        case "/": Apply(stack, (x, y) => (double)x / (double)y); break;
146        case "^": Apply(stack, (x, y) => Math.Pow((double)x, (double)y)); break;
147        case "<": Apply(stack, (x, y) => (double)x < (double)y); break;
148        case ">": Apply(stack, (x, y) => (double)x > (double)y); break;
149
150        case "==": Apply(stack, (x, y) => Equal(x, y)); break;
151        case "not": Apply(stack, x => !(bool)x); break;
152        case "isnull": Apply(stack, x => x == null); break;
153        case "if": Apply(stack, (then, else_, cond) => (bool)cond ? then : else_); break;
154
155        case "ismatch": Apply(stack, (s, p) => new Regex((string)p).IsMatch((string)s)); break;
156        case "rename": Apply(stack, (s, p, r) => new Regex((string)p).Replace((string)s, (string)r)); break;
157
158        default: stack.Push(GetVariableValue(variables, token)); break;
159      }
160    }
161
162    #region Auxiliary Functions
163
164    #region IItem value conversion
165    private static object GetIntValue(IItem value) {
166      var v = value as IntValue;
167      if (v != null) return (double)v.Value;
168      return null;
169    }
170
171    private static object GetDoubleValue(IItem value) {
172      var v = value as DoubleValue;
173      if (v != null) return v.Value;
174      return null;
175    }
176
177    private static object GetBoolValue(IItem value) {
178      var v = value as BoolValue;
179      if (v != null) return v.Value;
180      return null;
181    }
182
183    private static object GetVariableValue(IDictionary<string, IItem> variables, string name) {
184      if (variables.ContainsKey(name)) {
185        var item = variables[name];
186        return
187          GetIntValue(item) ??
188          GetDoubleValue(item) ??
189          GetBoolValue(item) ??
190          item.ToString();
191      }
192      return null;
193    }
194    #endregion
195
196    #region variadic equality
197    private static bool Equal(object a, object b) { return EqualNumber(a, b) || EqualBool(a, b) || EqualString(a, b) || a == b; }
198    private static bool EqualNumber(object a, object b) { return a is double && b is double && (double)a == (double)b; }
199    private static bool EqualBool(object a, object b) { return a is bool && b is bool && (bool)a == (bool)b; }
200    private static bool EqualString(object a, object b) { return a is string && b is string && ((string)a).Equals((string)b); }
201    #endregion
202
203    #region stack calculation
204    private static void Apply(Stack<object> stack, Func<object, object> func) {
205      if (stack.Count < 1)
206        throw new InvalidOperationException("Stack is empty");
207      var a = stack.Pop();
208      try {
209        stack.Push(func(a));
210      }
211      catch (Exception) {
212        stack.Push(a);
213        throw;
214      }
215    }
216
217    private static void Apply(Stack<object> stack, Func<object, object, object> func) {
218      if (stack.Count < 2)
219        throw new InvalidOperationException("Stack contains less than two elements");
220      var b = stack.Pop();
221      var a = stack.Pop();
222      try {
223        stack.Push(func(a, b));
224      }
225      catch (Exception) {
226        stack.Push(b);
227        stack.Push(a);
228        throw;
229      }
230    }
231
232    private static void Apply(Stack<object> stack, Func<object, object, object, object> func) {
233      if (stack.Count < 3)
234        throw new InvalidOperationException("Stack contains less than three elements");
235      var c = stack.Pop();
236      var b = stack.Pop();
237      var a = stack.Pop();
238      try {
239        stack.Push(func(a, b, c));
240      }
241      catch (Exception) {
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.