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