Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Optimization/3.3/Calculator.cs @ 6889

Last change on this file since 6889 was 6889, checked in by abeham, 13 years ago

#1614

  • put TestRandom class into HeuristicLab.Tests and removed the duplicates
  • readded QAPLIB unit test which disappeared after the last merge
  • readded deep cloning test which also disappeared
File size: 8.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.RegularExpressions;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Optimization {
33
34  [StorableClass]
35  public class Calculator : IDeepCloneable {
36
37    #region Fields & Properties
38
39    private List<string> tokens;
40
41    [Storable]
42    public string Formula {
43      get { return string.Join(" ", tokens); }
44      set { tokens = Tokenize(value).ToList(); }
45    }
46
47    private static readonly Regex TokenRegex =
48      new Regex(@"[a-zA-Z0-9._]+|""([^""]|\\"")*""|'([^']|\\')*'|[-+*/<>^]|dup|swap|drop|log|true|false|if|==|not|isnull|null|ismatch|rename");
49
50    #endregion
51
52    #region Construction & Cloning
53
54    [StorableConstructor]
55    protected Calculator(bool deserializing) { }
56    public Calculator() { }
57    protected Calculator(Calculator original, Cloner cloner) {
58      cloner.RegisterClonedObject(original, this);
59      if (original.tokens != null)
60        tokens = original.tokens.ToList();
61    }
62    public IDeepCloneable Clone(Cloner cloner) {
63      return new Calculator(this, cloner);
64    }
65    public object Clone() {
66      return Clone(new Cloner());
67    }
68    #endregion
69
70    private static IEnumerable<string> Tokenize(string s) {
71      return TokenRegex.Matches(s).Cast<Match>().Select(m => m.Value);
72    }
73
74    public IItem GetValue(IDictionary<string, IItem> variables) {
75      var stack = new Stack<object>();
76      int i = 0;
77      try {
78        for (; i<tokens.Count; i++) {
79          var token = tokens[i];
80          double d;
81          if (TryParse(token, out d)) {
82            stack.Push(d);
83          } else if (token.StartsWith("\"")) {
84            stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace(@"\""", @"""")));
85          } else if (token.StartsWith("'")) {
86            stack.Push(token.Substring(1, token.Length-2).Replace("\'", "'"));
87          } else {
88            Apply(token, stack, variables);
89          }
90        }
91      } catch (Exception x) {
92        throw new Exception(string.Format(
93          "Calculation Failed at token #{1}: '{2}' {0}current stack is: {0}{3}", Environment.NewLine,
94          i, tokens[i], string.Join(Environment.NewLine, stack.Select(AsString))),
95          x);
96      }
97      if (stack.Count != 1) throw new Exception(string.Format("Invalid final evaluation stack size {0} (should be 1)", stack.Count));
98      var result = stack.Pop();
99      if (result is string) return new StringValue((string)result);
100      if (result is double) return new DoubleValue((double)result);
101      if (result is bool) return new BoolValue((bool)result);
102      return null;
103    }
104
105    private static void Apply(string token, Stack<object> stack, IDictionary<string, IItem> variables) {
106      switch (token) {
107        case "null":  stack.Push(null); break;
108        case "true":  stack.Push(true); break;
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));
189      } catch (Exception) {
190        stack.Push(a);
191        throw;
192      }
193    }
194
195    private static void Apply(Stack<object> stack, Func<object, object, object> func) {
196      if (stack.Count < 2)
197        throw new InvalidOperationException("Stack contains less than two elements");
198      var b = stack.Pop();
199      var a = stack.Pop();
200      try {
201        stack.Push(func(a, b));
202      } catch (Exception) {
203        stack.Push(b);
204        stack.Push(a);
205        throw;
206      }
207    }
208
209    private static void Apply(Stack<object> stack, Func<object, object, object, object> func) {
210      if (stack.Count < 3)
211        throw new InvalidOperationException("Stack contains less than three elements");
212      var c = stack.Pop();
213      var b = stack.Pop();
214      var a = stack.Pop();
215      try {
216        stack.Push(func(a, b, c));
217      } catch (Exception) {
218        stack.Push(a);
219        stack.Push(b);
220        stack.Push(c);
221        throw;
222      }
223    }
224    #endregion
225
226    private static bool TryParse(string token, out double d) {
227      return double.TryParse(token,
228                             NumberStyles.AllowDecimalPoint |
229                             NumberStyles.AllowExponent |
230                             NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out d);
231    }
232
233    private static string AsString(object o) {
234      if (o == null) return "null";
235      if (o is string) return string.Format("'{0}'", o);
236      return o.ToString();
237    }
238
239    #endregion
240  }
241}
Note: See TracBrowser for help on using the repository browser.