[7228] | 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 | using System.Text;
|
---|
| 11 |
|
---|
| 12 | namespace HeuristicLab.Optimization {
|
---|
| 13 |
|
---|
| 14 | [StorableClass]
|
---|
| 15 | public class Calculator : IDeepCloneable {
|
---|
| 16 |
|
---|
| 17 | #region Fields & Properties
|
---|
| 18 |
|
---|
| 19 | private List<string> tokens;
|
---|
| 20 |
|
---|
| 21 | [Storable]
|
---|
| 22 | public string Formula {
|
---|
| 23 | get { return string.Join(" ", tokens); }
|
---|
| 24 | set { tokens = Tokenize(value).ToList(); }
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | private static readonly Regex TokenRegex =
|
---|
| 28 | new Regex(@"""(\\""|[^""])*""|'(\\'|[^'])*'|[^\s]+");
|
---|
| 29 |
|
---|
| 30 | #endregion
|
---|
| 31 |
|
---|
| 32 | #region Construction & Cloning
|
---|
| 33 |
|
---|
| 34 | [StorableConstructor]
|
---|
| 35 | protected Calculator(bool deserializing) { }
|
---|
| 36 | public Calculator() { }
|
---|
| 37 | protected Calculator(Calculator original, Cloner cloner) {
|
---|
| 38 | cloner.RegisterClonedObject(original, this);
|
---|
| 39 | if (original.tokens != null)
|
---|
| 40 | tokens = original.tokens.ToList();
|
---|
| 41 | }
|
---|
| 42 | public IDeepCloneable Clone(Cloner cloner) {
|
---|
| 43 | return new Calculator(this, cloner);
|
---|
| 44 | }
|
---|
| 45 | public object Clone() {
|
---|
| 46 | return Clone(new Cloner());
|
---|
| 47 | }
|
---|
| 48 | #endregion
|
---|
| 49 |
|
---|
| 50 | private static IEnumerable<string> Tokenize(string s) {
|
---|
| 51 | return TokenRegex.Matches(s).Cast<Match>().Select(m => m.Value);
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | public IItem GetValue(IDictionary<string, IItem> variables) {
|
---|
| 55 | var stack = new Stack<object>();
|
---|
| 56 | int i = 0;
|
---|
| 57 | try {
|
---|
| 58 | for (; i<tokens.Count; i++) {
|
---|
| 59 | var token = tokens[i];
|
---|
| 60 | double d;
|
---|
| 61 | if (TryParse(token, out d)) {
|
---|
| 62 | stack.Push(d);
|
---|
| 63 | } else if (token.StartsWith("\"")) {
|
---|
| 64 | stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace("\\\"", "\"")));
|
---|
| 65 | } else if (token.StartsWith("'")) {
|
---|
| 66 | stack.Push(token.Substring(1, token.Length-2).Replace("\\'", "'"));
|
---|
| 67 | } else {
|
---|
| 68 | Apply(token, stack, variables);
|
---|
| 69 | }
|
---|
| 70 | }
|
---|
| 71 | } catch (Exception x) {
|
---|
| 72 | throw new Exception(string.Format(
|
---|
| 73 | "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine,
|
---|
| 74 | Formula, i, TokenWithContext(tokens, i, 3),
|
---|
| 75 | string.Join(Environment.NewLine, stack.Select(AsString))),
|
---|
| 76 | x);
|
---|
| 77 | }
|
---|
| 78 | if (stack.Count != 1)
|
---|
| 79 | throw new Exception(
|
---|
| 80 | string.Format("Invalid final evaluation stack size {0} (should be 1) in formula '{1}'",
|
---|
| 81 | stack.Count, Formula));
|
---|
| 82 | var result = stack.Pop();
|
---|
| 83 | if (result is string) return new StringValue((string)result);
|
---|
| 84 | if (result is double) return new DoubleValue((double)result);
|
---|
| 85 | if (result is bool) return new BoolValue((bool)result);
|
---|
| 86 | return null;
|
---|
| 87 | }
|
---|
| 88 |
|
---|
| 89 | private string TokenWithContext(List<string> tokens, int i, int context) {
|
---|
| 90 | var sb = new StringBuilder();
|
---|
| 91 | if (i > context+1)
|
---|
| 92 | sb.Append("... ");
|
---|
| 93 | int prefix = Math.Max(0, i - context);
|
---|
| 94 | sb.Append(string.Join(" ", tokens.GetRange(prefix, i - prefix)));
|
---|
| 95 | sb.Append(" ---> ").Append(tokens[i]).Append(" <--- ");
|
---|
| 96 | int postfix = Math.Min(tokens.Count, i + 1 + context);
|
---|
| 97 | sb.Append(string.Join(" ", tokens.GetRange(i + 1, postfix - (i + 1))));
|
---|
| 98 | if (postfix < tokens.Count)
|
---|
| 99 | sb.Append(" ...");
|
---|
| 100 | return sb.ToString();
|
---|
| 101 | }
|
---|
| 102 |
|
---|
| 103 |
|
---|
| 104 | private static void Apply(string token, Stack<object> stack, IDictionary<string, IItem> variables) {
|
---|
| 105 | switch (token) {
|
---|
| 106 | case "null": stack.Push(null); break;
|
---|
| 107 | case "true": stack.Push(true); break;
|
---|
| 108 | case "false": stack.Push(false); break;
|
---|
| 109 |
|
---|
| 110 | case "drop": stack.Pop(); break;
|
---|
| 111 | case "dup": stack.Push(stack.Peek()); break;
|
---|
| 112 | case "swap":
|
---|
| 113 | var top = stack.Pop();
|
---|
| 114 | var next = stack.Pop();
|
---|
| 115 | stack.Push(top);
|
---|
| 116 | stack.Push(next);
|
---|
| 117 | break;
|
---|
| 118 |
|
---|
| 119 | case "log": Apply(stack, x => Math.Log((double)x)); break;
|
---|
| 120 | case "+": Apply(stack, (x, y) => (double)x + (double)y); 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) => Math.Pow((double)x, (double)y)); break;
|
---|
| 125 | case "<": Apply(stack, (x, y) => (double)x < (double)y); break;
|
---|
| 126 | case ">": Apply(stack, (x, y) => (double)x > (double)y); break;
|
---|
| 127 |
|
---|
| 128 | case "==": Apply(stack, (x, y) => Equal(x, y)); break;
|
---|
| 129 | case "not": Apply(stack, x => !(bool)x); break;
|
---|
| 130 | case "isnull": Apply(stack, x => x == null); break;
|
---|
| 131 | case "if": Apply(stack, (then, else_, cond) => (bool)cond ? then : else_); break;
|
---|
| 132 |
|
---|
| 133 | case "ismatch": Apply(stack, (s, p) => new Regex((string)p).IsMatch((string)s)); break;
|
---|
| 134 | case "rename": Apply(stack, (s, p, r) => new Regex((string)p).Replace((string)s, (string)r)); break;
|
---|
| 135 |
|
---|
| 136 | default: stack.Push(GetVariableValue(variables, token)); break;
|
---|
| 137 | }
|
---|
| 138 | }
|
---|
| 139 |
|
---|
| 140 | #region Auxiliary Functions
|
---|
| 141 |
|
---|
| 142 | #region IItem value conversion
|
---|
| 143 | private static object GetIntValue(IItem value) {
|
---|
| 144 | var v = value as IntValue;
|
---|
| 145 | if (v != null) return (double)v.Value;
|
---|
| 146 | return null;
|
---|
| 147 | }
|
---|
| 148 |
|
---|
| 149 | private static object GetDoubleValue(IItem value) {
|
---|
| 150 | var v = value as DoubleValue;
|
---|
| 151 | if (v != null) return v.Value;
|
---|
| 152 | return null;
|
---|
| 153 | }
|
---|
| 154 |
|
---|
| 155 | private static object GetBoolValue(IItem value) {
|
---|
| 156 | var v = value as BoolValue;
|
---|
| 157 | if (v != null) return v.Value;
|
---|
| 158 | return null;
|
---|
| 159 | }
|
---|
| 160 |
|
---|
| 161 | private static object GetVariableValue(IDictionary<string, IItem> variables, string name) {
|
---|
| 162 | if (variables.ContainsKey(name)) {
|
---|
| 163 | var item = variables[name];
|
---|
| 164 | return
|
---|
| 165 | GetIntValue(item) ??
|
---|
| 166 | GetDoubleValue(item) ??
|
---|
| 167 | GetBoolValue(item) ??
|
---|
| 168 | item.ToString();
|
---|
| 169 | }
|
---|
| 170 | return null;
|
---|
| 171 | }
|
---|
| 172 | #endregion
|
---|
| 173 |
|
---|
| 174 | #region variadic equality
|
---|
| 175 | private static bool Equal(object a, object b) { return EqualNumber(a, b) || EqualBool(a, b) || EqualString(a, b) || a == b; }
|
---|
| 176 | private static bool EqualNumber(object a, object b) { return a is double && b is double && (double)a == (double)b; }
|
---|
| 177 | private static bool EqualBool(object a, object b) { return a is bool && b is bool && (bool)a == (bool)b; }
|
---|
| 178 | private static bool EqualString(object a, object b) { return a is string && b is string && ((string)a).Equals((string)b); }
|
---|
| 179 | #endregion
|
---|
| 180 |
|
---|
| 181 | #region stack calculation
|
---|
| 182 | private static void Apply(Stack<object> stack, Func<object, object> func) {
|
---|
| 183 | if (stack.Count < 1)
|
---|
| 184 | throw new InvalidOperationException("Stack is empty");
|
---|
| 185 | var a = stack.Pop();
|
---|
| 186 | try {
|
---|
| 187 | stack.Push(func(a));
|
---|
| 188 | } catch (Exception) {
|
---|
| 189 | stack.Push(a);
|
---|
| 190 | throw;
|
---|
| 191 | }
|
---|
| 192 | }
|
---|
| 193 |
|
---|
| 194 | private static void Apply(Stack<object> stack, Func<object, object, object> func) {
|
---|
| 195 | if (stack.Count < 2)
|
---|
| 196 | throw new InvalidOperationException("Stack contains less than two elements");
|
---|
| 197 | var b = stack.Pop();
|
---|
| 198 | var a = stack.Pop();
|
---|
| 199 | try {
|
---|
| 200 | stack.Push(func(a, b));
|
---|
| 201 | } catch (Exception) {
|
---|
| 202 | stack.Push(b);
|
---|
| 203 | stack.Push(a);
|
---|
| 204 | throw;
|
---|
| 205 | }
|
---|
| 206 | }
|
---|
| 207 |
|
---|
| 208 | private static void Apply(Stack<object> stack, Func<object, object, object, object> func) {
|
---|
| 209 | if (stack.Count < 3)
|
---|
| 210 | throw new InvalidOperationException("Stack contains less than three elements");
|
---|
| 211 | var c = stack.Pop();
|
---|
| 212 | var b = stack.Pop();
|
---|
| 213 | var a = stack.Pop();
|
---|
| 214 | try {
|
---|
| 215 | stack.Push(func(a, b, c));
|
---|
| 216 | } catch (Exception) {
|
---|
| 217 | stack.Push(a);
|
---|
| 218 | stack.Push(b);
|
---|
| 219 | stack.Push(c);
|
---|
| 220 | throw;
|
---|
| 221 | }
|
---|
| 222 | }
|
---|
| 223 | #endregion
|
---|
| 224 |
|
---|
| 225 | private static bool TryParse(string token, out double d) {
|
---|
| 226 | return double.TryParse(token,
|
---|
| 227 | NumberStyles.AllowDecimalPoint |
|
---|
| 228 | NumberStyles.AllowExponent |
|
---|
| 229 | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out d);
|
---|
| 230 | }
|
---|
| 231 |
|
---|
| 232 | private static string AsString(object o) {
|
---|
| 233 | if (o == null) return "null";
|
---|
| 234 | if (o is string) return string.Format("'{0}'", o);
|
---|
| 235 | return o.ToString();
|
---|
| 236 | }
|
---|
| 237 |
|
---|
| 238 | #endregion
|
---|
| 239 | }
|
---|
| 240 | }
|
---|