1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Globalization;
|
---|
25 | using System.Linq;
|
---|
26 | using System.Text;
|
---|
27 | using System.Text.RegularExpressions;
|
---|
28 | using HeuristicLab.Common;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Data;
|
---|
31 | using HEAL.Attic;
|
---|
32 |
|
---|
33 | namespace HeuristicLab.Optimization {
|
---|
34 |
|
---|
35 | [StorableType("6C41AF6F-5F02-4510-B1B5-222651C4021B")]
|
---|
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(StorableConstructorFlag _) { }
|
---|
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 | } catch (Exception x) {
|
---|
93 | throw new Exception(string.Format(
|
---|
94 | "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine,
|
---|
95 | Formula, i, TokenWithContext(tokens, i, 3),
|
---|
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);
|
---|
105 | if (result is int) return new IntValue((int)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(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;
|
---|
149 |
|
---|
150 | case "toint": Apply(stack, x => Convert.ToInt32(x)); break;
|
---|
151 | case "todouble": Apply(stack, x => Convert.ToDouble(x)); break;
|
---|
152 |
|
---|
153 | case "[]": Apply(stack, (a, i) => GetArrayValueAtIndex(a, Convert.ToInt32(i))); break;
|
---|
154 |
|
---|
155 | case "==": Apply(stack, (x, y) => Equal(x, y)); break;
|
---|
156 | case "not": Apply(stack, x => !Convert.ToBoolean(x)); break;
|
---|
157 | case "isnull": Apply(stack, x => x == null); break;
|
---|
158 | case "if": Apply(stack, (then, else_, cond) => Convert.ToBoolean(cond) ? then : else_); break;
|
---|
159 |
|
---|
160 | case "ismatch": Apply(stack, (s, p) => new Regex(Convert.ToString(p)).IsMatch(Convert.ToString(s))); break;
|
---|
161 | case "rename": Apply(stack, (s, p, r) => new Regex(Convert.ToString(p)).Replace(Convert.ToString(s), Convert.ToString(r))); break;
|
---|
162 |
|
---|
163 | default: stack.Push(GetVariableValue(variables, token)); break;
|
---|
164 | }
|
---|
165 | }
|
---|
166 |
|
---|
167 | #region Auxiliary Functions
|
---|
168 |
|
---|
169 | #region IItem value conversion
|
---|
170 | private static object GetIntValue(IItem value) {
|
---|
171 | var v = value as IntValue;
|
---|
172 | if (v != null) return (double)v.Value;
|
---|
173 | return null;
|
---|
174 | }
|
---|
175 |
|
---|
176 | private static object GetDoubleValue(IItem value) {
|
---|
177 | var v = value as DoubleValue;
|
---|
178 | if (v != null) return v.Value;
|
---|
179 | return null;
|
---|
180 | }
|
---|
181 |
|
---|
182 | private static object GetBoolValue(IItem value) {
|
---|
183 | var v = value as BoolValue;
|
---|
184 | if (v != null) return v.Value;
|
---|
185 | return null;
|
---|
186 | }
|
---|
187 |
|
---|
188 | private static object GetArrayValue(IItem value) {
|
---|
189 | if (value is IntArray || value is DoubleArray || value is BoolArray || value is StringArray)
|
---|
190 | return value;
|
---|
191 | return null;
|
---|
192 | }
|
---|
193 |
|
---|
194 | private static object GetVariableValue(IDictionary<string, IItem> variables, string name) {
|
---|
195 | if (variables.ContainsKey(name)) {
|
---|
196 | var item = variables[name];
|
---|
197 | return
|
---|
198 | GetIntValue(item) ??
|
---|
199 | GetDoubleValue(item) ??
|
---|
200 | GetBoolValue(item) ??
|
---|
201 | GetArrayValue(item) ??
|
---|
202 | item.ToString();
|
---|
203 | }
|
---|
204 | return null;
|
---|
205 | }
|
---|
206 |
|
---|
207 | private static object GetArrayValueAtIndex(object array, int index) {
|
---|
208 | if (array is IntArray)
|
---|
209 | return ((IntArray)array)[index];
|
---|
210 | if (array is DoubleArray)
|
---|
211 | return ((DoubleArray)array)[index];
|
---|
212 | if (array is BoolArray)
|
---|
213 | return ((BoolArray)array)[index];
|
---|
214 | if (array is StringArray)
|
---|
215 | return ((StringArray)array)[index];
|
---|
216 | throw new NotSupportedException(string.Format("Type {0} is not a supported array type", array.GetType().Name));
|
---|
217 | }
|
---|
218 | #endregion
|
---|
219 |
|
---|
220 | #region variadic equality
|
---|
221 | private static bool Equal(object a, object b) { return EqualIntegerNumber(a, b) || EqualFloatingNumber(a, b) || EqualBool(a, b) || EqualString(a, b) || a == b; }
|
---|
222 | private static bool EqualIntegerNumber(object a, object b) { return a is int && b is int && (int)a == (int)b; }
|
---|
223 | private static bool EqualFloatingNumber(object a, object b) { return a is double && b is double && (double)a == (double)b; }
|
---|
224 | private static bool EqualBool(object a, object b) { return a is bool && b is bool && (bool)a == (bool)b; }
|
---|
225 | private static bool EqualString(object a, object b) { return a is string && b is string && ((string)a).Equals((string)b); }
|
---|
226 | #endregion
|
---|
227 |
|
---|
228 | #region stack calculation
|
---|
229 | private static void Apply(Stack<object> stack, Func<object, object> func) {
|
---|
230 | if (stack.Count < 1)
|
---|
231 | throw new InvalidOperationException("Stack is empty");
|
---|
232 | var a = stack.Pop();
|
---|
233 | try {
|
---|
234 | stack.Push(func(a));
|
---|
235 | } catch (Exception) {
|
---|
236 | stack.Push(a);
|
---|
237 | throw;
|
---|
238 | }
|
---|
239 | }
|
---|
240 |
|
---|
241 | private static void Apply(Stack<object> stack, Func<object, object, object> func) {
|
---|
242 | if (stack.Count < 2)
|
---|
243 | throw new InvalidOperationException("Stack contains less than two elements");
|
---|
244 | var b = stack.Pop();
|
---|
245 | var a = stack.Pop();
|
---|
246 | try {
|
---|
247 | stack.Push(func(a, b));
|
---|
248 | } catch (Exception) {
|
---|
249 | stack.Push(b);
|
---|
250 | stack.Push(a);
|
---|
251 | throw;
|
---|
252 | }
|
---|
253 | }
|
---|
254 |
|
---|
255 | private static void Apply(Stack<object> stack, Func<object, object, object, object> func) {
|
---|
256 | if (stack.Count < 3)
|
---|
257 | throw new InvalidOperationException("Stack contains less than three elements");
|
---|
258 | var c = stack.Pop();
|
---|
259 | var b = stack.Pop();
|
---|
260 | var a = stack.Pop();
|
---|
261 | try {
|
---|
262 | stack.Push(func(a, b, c));
|
---|
263 | } catch (Exception) {
|
---|
264 | stack.Push(a);
|
---|
265 | stack.Push(b);
|
---|
266 | stack.Push(c);
|
---|
267 | throw;
|
---|
268 | }
|
---|
269 | }
|
---|
270 | #endregion
|
---|
271 |
|
---|
272 | private static bool TryParse(string token, out double d) {
|
---|
273 | return double.TryParse(token,
|
---|
274 | NumberStyles.AllowDecimalPoint |
|
---|
275 | NumberStyles.AllowExponent |
|
---|
276 | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out d);
|
---|
277 | }
|
---|
278 |
|
---|
279 | private static string AsString(object o) {
|
---|
280 | if (o == null) return "null";
|
---|
281 | if (o is string) return string.Format("'{0}'", o);
|
---|
282 | return o.ToString();
|
---|
283 | }
|
---|
284 |
|
---|
285 | #endregion
|
---|
286 | }
|
---|
287 | }
|
---|