[14843] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[15583] | 3 | * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[14843] | 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.Linq;
|
---|
[14950] | 25 | using System.Runtime.Serialization;
|
---|
[14843] | 26 | using AutoDiff;
|
---|
| 27 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
| 28 |
|
---|
| 29 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
| 30 | public class TreeToAutoDiffTermConverter {
|
---|
| 31 | public delegate double ParametricFunction(double[] vars, double[] @params);
|
---|
[14950] | 32 |
|
---|
[14843] | 33 | public delegate Tuple<double[], double> ParametricFunctionGradient(double[] vars, double[] @params);
|
---|
| 34 |
|
---|
| 35 | #region helper class
|
---|
| 36 | public class DataForVariable {
|
---|
| 37 | public readonly string variableName;
|
---|
| 38 | public readonly string variableValue; // for factor vars
|
---|
| 39 | public readonly int lag;
|
---|
| 40 |
|
---|
| 41 | public DataForVariable(string varName, string varValue, int lag) {
|
---|
| 42 | this.variableName = varName;
|
---|
| 43 | this.variableValue = varValue;
|
---|
| 44 | this.lag = lag;
|
---|
| 45 | }
|
---|
| 46 |
|
---|
| 47 | public override bool Equals(object obj) {
|
---|
| 48 | var other = obj as DataForVariable;
|
---|
| 49 | if (other == null) return false;
|
---|
| 50 | return other.variableName.Equals(this.variableName) &&
|
---|
| 51 | other.variableValue.Equals(this.variableValue) &&
|
---|
| 52 | other.lag == this.lag;
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | public override int GetHashCode() {
|
---|
| 56 | return variableName.GetHashCode() ^ variableValue.GetHashCode() ^ lag;
|
---|
| 57 | }
|
---|
| 58 | }
|
---|
| 59 | #endregion
|
---|
| 60 |
|
---|
| 61 | #region derivations of functions
|
---|
| 62 | // create function factory for arctangent
|
---|
| 63 | private static readonly Func<Term, UnaryFunc> arctan = UnaryFunc.Factory(
|
---|
| 64 | eval: Math.Atan,
|
---|
| 65 | diff: x => 1 / (1 + x * x));
|
---|
[14950] | 66 |
|
---|
[14843] | 67 | private static readonly Func<Term, UnaryFunc> sin = UnaryFunc.Factory(
|
---|
| 68 | eval: Math.Sin,
|
---|
| 69 | diff: Math.Cos);
|
---|
[14950] | 70 |
|
---|
[14843] | 71 | private static readonly Func<Term, UnaryFunc> cos = UnaryFunc.Factory(
|
---|
[14950] | 72 | eval: Math.Cos,
|
---|
| 73 | diff: x => -Math.Sin(x));
|
---|
| 74 |
|
---|
[14843] | 75 | private static readonly Func<Term, UnaryFunc> tan = UnaryFunc.Factory(
|
---|
| 76 | eval: Math.Tan,
|
---|
| 77 | diff: x => 1 + Math.Tan(x) * Math.Tan(x));
|
---|
[14950] | 78 |
|
---|
[14843] | 79 | private static readonly Func<Term, UnaryFunc> erf = UnaryFunc.Factory(
|
---|
| 80 | eval: alglib.errorfunction,
|
---|
| 81 | diff: x => 2.0 * Math.Exp(-(x * x)) / Math.Sqrt(Math.PI));
|
---|
[14950] | 82 |
|
---|
[14843] | 83 | private static readonly Func<Term, UnaryFunc> norm = UnaryFunc.Factory(
|
---|
| 84 | eval: alglib.normaldistribution,
|
---|
| 85 | diff: x => -(Math.Exp(-(x * x)) * Math.Sqrt(Math.Exp(x * x)) * x) / Math.Sqrt(2 * Math.PI));
|
---|
| 86 |
|
---|
[16239] | 87 | private static readonly Func<Term, UnaryFunc> abs = UnaryFunc.Factory(
|
---|
| 88 | eval: Math.Abs,
|
---|
| 89 | diff: x => Math.Sign(x)
|
---|
| 90 | );
|
---|
| 91 |
|
---|
[14843] | 92 | #endregion
|
---|
| 93 |
|
---|
[15447] | 94 | public static bool TryConvertToAutoDiff(ISymbolicExpressionTree tree, bool makeVariableWeightsVariable, bool addLinearScalingTerms,
|
---|
[14843] | 95 | out List<DataForVariable> parameters, out double[] initialConstants,
|
---|
| 96 | out ParametricFunction func,
|
---|
| 97 | out ParametricFunctionGradient func_grad) {
|
---|
| 98 |
|
---|
| 99 | // use a transformator object which holds the state (variable list, parameter list, ...) for recursive transformation of the tree
|
---|
[15447] | 100 | var transformator = new TreeToAutoDiffTermConverter(makeVariableWeightsVariable, addLinearScalingTerms);
|
---|
[14843] | 101 | AutoDiff.Term term;
|
---|
[14950] | 102 | try {
|
---|
| 103 | term = transformator.ConvertToAutoDiff(tree.Root.GetSubtree(0));
|
---|
[14843] | 104 | var parameterEntries = transformator.parameters.ToArray(); // guarantee same order for keys and values
|
---|
[14950] | 105 | var compiledTerm = term.Compile(transformator.variables.ToArray(),
|
---|
| 106 | parameterEntries.Select(kvp => kvp.Value).ToArray());
|
---|
[14843] | 107 | parameters = new List<DataForVariable>(parameterEntries.Select(kvp => kvp.Key));
|
---|
| 108 | initialConstants = transformator.initialConstants.ToArray();
|
---|
| 109 | func = (vars, @params) => compiledTerm.Evaluate(vars, @params);
|
---|
| 110 | func_grad = (vars, @params) => compiledTerm.Differentiate(vars, @params);
|
---|
[14950] | 111 | return true;
|
---|
| 112 | } catch (ConversionException) {
|
---|
[14843] | 113 | func = null;
|
---|
| 114 | func_grad = null;
|
---|
| 115 | parameters = null;
|
---|
| 116 | initialConstants = null;
|
---|
| 117 | }
|
---|
[14950] | 118 | return false;
|
---|
[14843] | 119 | }
|
---|
| 120 |
|
---|
| 121 | // state for recursive transformation of trees
|
---|
[14950] | 122 | private readonly
|
---|
| 123 | List<double> initialConstants;
|
---|
[14843] | 124 | private readonly Dictionary<DataForVariable, AutoDiff.Variable> parameters;
|
---|
| 125 | private readonly List<AutoDiff.Variable> variables;
|
---|
| 126 | private readonly bool makeVariableWeightsVariable;
|
---|
[15447] | 127 | private readonly bool addLinearScalingTerms;
|
---|
[14843] | 128 |
|
---|
[15447] | 129 | private TreeToAutoDiffTermConverter(bool makeVariableWeightsVariable, bool addLinearScalingTerms) {
|
---|
[14843] | 130 | this.makeVariableWeightsVariable = makeVariableWeightsVariable;
|
---|
[15447] | 131 | this.addLinearScalingTerms = addLinearScalingTerms;
|
---|
[14843] | 132 | this.initialConstants = new List<double>();
|
---|
| 133 | this.parameters = new Dictionary<DataForVariable, AutoDiff.Variable>();
|
---|
| 134 | this.variables = new List<AutoDiff.Variable>();
|
---|
| 135 | }
|
---|
| 136 |
|
---|
[14950] | 137 | private AutoDiff.Term ConvertToAutoDiff(ISymbolicExpressionTreeNode node) {
|
---|
[14843] | 138 | if (node.Symbol is Constant) {
|
---|
| 139 | initialConstants.Add(((ConstantTreeNode)node).Value);
|
---|
| 140 | var var = new AutoDiff.Variable();
|
---|
| 141 | variables.Add(var);
|
---|
[14950] | 142 | return var;
|
---|
[14843] | 143 | }
|
---|
| 144 | if (node.Symbol is Variable || node.Symbol is BinaryFactorVariable) {
|
---|
| 145 | var varNode = node as VariableTreeNodeBase;
|
---|
| 146 | var factorVarNode = node as BinaryFactorVariableTreeNode;
|
---|
| 147 | // factor variable values are only 0 or 1 and set in x accordingly
|
---|
| 148 | var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty;
|
---|
| 149 | var par = FindOrCreateParameter(parameters, varNode.VariableName, varValue);
|
---|
| 150 |
|
---|
| 151 | if (makeVariableWeightsVariable) {
|
---|
| 152 | initialConstants.Add(varNode.Weight);
|
---|
| 153 | var w = new AutoDiff.Variable();
|
---|
| 154 | variables.Add(w);
|
---|
[14950] | 155 | return AutoDiff.TermBuilder.Product(w, par);
|
---|
[14843] | 156 | } else {
|
---|
[14950] | 157 | return varNode.Weight * par;
|
---|
[14843] | 158 | }
|
---|
| 159 | }
|
---|
| 160 | if (node.Symbol is FactorVariable) {
|
---|
| 161 | var factorVarNode = node as FactorVariableTreeNode;
|
---|
| 162 | var products = new List<Term>();
|
---|
| 163 | foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName)) {
|
---|
| 164 | var par = FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue);
|
---|
| 165 |
|
---|
| 166 | initialConstants.Add(factorVarNode.GetValue(variableValue));
|
---|
| 167 | var wVar = new AutoDiff.Variable();
|
---|
| 168 | variables.Add(wVar);
|
---|
| 169 |
|
---|
| 170 | products.Add(AutoDiff.TermBuilder.Product(wVar, par));
|
---|
| 171 | }
|
---|
[14950] | 172 | return AutoDiff.TermBuilder.Sum(products);
|
---|
[14843] | 173 | }
|
---|
| 174 | if (node.Symbol is LaggedVariable) {
|
---|
| 175 | var varNode = node as LaggedVariableTreeNode;
|
---|
| 176 | var par = FindOrCreateParameter(parameters, varNode.VariableName, string.Empty, varNode.Lag);
|
---|
| 177 |
|
---|
| 178 | if (makeVariableWeightsVariable) {
|
---|
| 179 | initialConstants.Add(varNode.Weight);
|
---|
| 180 | var w = new AutoDiff.Variable();
|
---|
| 181 | variables.Add(w);
|
---|
[14950] | 182 | return AutoDiff.TermBuilder.Product(w, par);
|
---|
[14843] | 183 | } else {
|
---|
[14950] | 184 | return varNode.Weight * par;
|
---|
[14843] | 185 | }
|
---|
| 186 | }
|
---|
| 187 | if (node.Symbol is Addition) {
|
---|
| 188 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 189 | foreach (var subTree in node.Subtrees) {
|
---|
[14950] | 190 | terms.Add(ConvertToAutoDiff(subTree));
|
---|
[14843] | 191 | }
|
---|
[14950] | 192 | return AutoDiff.TermBuilder.Sum(terms);
|
---|
[14843] | 193 | }
|
---|
| 194 | if (node.Symbol is Subtraction) {
|
---|
| 195 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 196 | for (int i = 0; i < node.SubtreeCount; i++) {
|
---|
[14950] | 197 | AutoDiff.Term t = ConvertToAutoDiff(node.GetSubtree(i));
|
---|
[14843] | 198 | if (i > 0) t = -t;
|
---|
| 199 | terms.Add(t);
|
---|
| 200 | }
|
---|
[14950] | 201 | if (terms.Count == 1) return -terms[0];
|
---|
| 202 | else return AutoDiff.TermBuilder.Sum(terms);
|
---|
[14843] | 203 | }
|
---|
| 204 | if (node.Symbol is Multiplication) {
|
---|
| 205 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 206 | foreach (var subTree in node.Subtrees) {
|
---|
[14950] | 207 | terms.Add(ConvertToAutoDiff(subTree));
|
---|
[14843] | 208 | }
|
---|
[14950] | 209 | if (terms.Count == 1) return terms[0];
|
---|
| 210 | else return terms.Aggregate((a, b) => new AutoDiff.Product(a, b));
|
---|
[14843] | 211 | }
|
---|
| 212 | if (node.Symbol is Division) {
|
---|
| 213 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 214 | foreach (var subTree in node.Subtrees) {
|
---|
[14950] | 215 | terms.Add(ConvertToAutoDiff(subTree));
|
---|
[14843] | 216 | }
|
---|
[14950] | 217 | if (terms.Count == 1) return 1.0 / terms[0];
|
---|
| 218 | else return terms.Aggregate((a, b) => new AutoDiff.Product(a, 1.0 / b));
|
---|
[14843] | 219 | }
|
---|
[16239] | 220 | if (node.Symbol is Absolute) {
|
---|
[16236] | 221 | var x1 = ConvertToAutoDiff(node.GetSubtree(0));
|
---|
[16239] | 222 | return abs(x1);
|
---|
| 223 | }
|
---|
| 224 | if (node.Symbol is AnalyticalQuotient) {
|
---|
| 225 | var x1 = ConvertToAutoDiff(node.GetSubtree(0));
|
---|
[16236] | 226 | var x2 = ConvertToAutoDiff(node.GetSubtree(1));
|
---|
| 227 | return x1 / (TermBuilder.Power(1 + x2 * x2, 0.5));
|
---|
| 228 | }
|
---|
[14843] | 229 | if (node.Symbol is Logarithm) {
|
---|
[14950] | 230 | return AutoDiff.TermBuilder.Log(
|
---|
| 231 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 232 | }
|
---|
| 233 | if (node.Symbol is Exponential) {
|
---|
[14950] | 234 | return AutoDiff.TermBuilder.Exp(
|
---|
| 235 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 236 | }
|
---|
| 237 | if (node.Symbol is Square) {
|
---|
[14950] | 238 | return AutoDiff.TermBuilder.Power(
|
---|
| 239 | ConvertToAutoDiff(node.GetSubtree(0)), 2.0);
|
---|
[14843] | 240 | }
|
---|
| 241 | if (node.Symbol is SquareRoot) {
|
---|
[14950] | 242 | return AutoDiff.TermBuilder.Power(
|
---|
| 243 | ConvertToAutoDiff(node.GetSubtree(0)), 0.5);
|
---|
[14843] | 244 | }
|
---|
[16239] | 245 | if (node.Symbol is Cube) {
|
---|
| 246 | return AutoDiff.TermBuilder.Power(
|
---|
| 247 | ConvertToAutoDiff(node.GetSubtree(0)), 3.0);
|
---|
| 248 | }
|
---|
| 249 | if (node.Symbol is CubeRoot) {
|
---|
| 250 | return AutoDiff.TermBuilder.Power(
|
---|
| 251 | ConvertToAutoDiff(node.GetSubtree(0)), 1.0/3.0);
|
---|
| 252 | }
|
---|
[14843] | 253 | if (node.Symbol is Sine) {
|
---|
[14950] | 254 | return sin(
|
---|
| 255 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 256 | }
|
---|
| 257 | if (node.Symbol is Cosine) {
|
---|
[14950] | 258 | return cos(
|
---|
| 259 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 260 | }
|
---|
| 261 | if (node.Symbol is Tangent) {
|
---|
[14950] | 262 | return tan(
|
---|
| 263 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 264 | }
|
---|
| 265 | if (node.Symbol is Erf) {
|
---|
[14950] | 266 | return erf(
|
---|
| 267 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 268 | }
|
---|
| 269 | if (node.Symbol is Norm) {
|
---|
[14950] | 270 | return norm(
|
---|
| 271 | ConvertToAutoDiff(node.GetSubtree(0)));
|
---|
[14843] | 272 | }
|
---|
| 273 | if (node.Symbol is StartSymbol) {
|
---|
[15447] | 274 | if (addLinearScalingTerms) {
|
---|
[15481] | 275 | // scaling variables α, β are given at the beginning of the parameter vector
|
---|
[15447] | 276 | var alpha = new AutoDiff.Variable();
|
---|
| 277 | var beta = new AutoDiff.Variable();
|
---|
| 278 | variables.Add(beta);
|
---|
| 279 | variables.Add(alpha);
|
---|
[15481] | 280 | var t = ConvertToAutoDiff(node.GetSubtree(0));
|
---|
[15480] | 281 | return t * alpha + beta;
|
---|
[15447] | 282 | } else return ConvertToAutoDiff(node.GetSubtree(0));
|
---|
[14843] | 283 | }
|
---|
[14950] | 284 | throw new ConversionException();
|
---|
[14843] | 285 | }
|
---|
| 286 |
|
---|
| 287 |
|
---|
| 288 | // for each factor variable value we need a parameter which represents a binary indicator for that variable & value combination
|
---|
| 289 | // each binary indicator is only necessary once. So we only create a parameter if this combination is not yet available
|
---|
| 290 | private static Term FindOrCreateParameter(Dictionary<DataForVariable, AutoDiff.Variable> parameters,
|
---|
| 291 | string varName, string varValue = "", int lag = 0) {
|
---|
| 292 | var data = new DataForVariable(varName, varValue, lag);
|
---|
| 293 |
|
---|
| 294 | AutoDiff.Variable par = null;
|
---|
| 295 | if (!parameters.TryGetValue(data, out par)) {
|
---|
| 296 | // not found -> create new parameter and entries in names and values lists
|
---|
| 297 | par = new AutoDiff.Variable();
|
---|
| 298 | parameters.Add(data, par);
|
---|
| 299 | }
|
---|
| 300 | return par;
|
---|
| 301 | }
|
---|
| 302 |
|
---|
| 303 | public static bool IsCompatible(ISymbolicExpressionTree tree) {
|
---|
| 304 | var containsUnknownSymbol = (
|
---|
| 305 | from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
|
---|
| 306 | where
|
---|
[14950] | 307 | !(n.Symbol is Variable) &&
|
---|
| 308 | !(n.Symbol is BinaryFactorVariable) &&
|
---|
| 309 | !(n.Symbol is FactorVariable) &&
|
---|
| 310 | !(n.Symbol is LaggedVariable) &&
|
---|
| 311 | !(n.Symbol is Constant) &&
|
---|
| 312 | !(n.Symbol is Addition) &&
|
---|
| 313 | !(n.Symbol is Subtraction) &&
|
---|
| 314 | !(n.Symbol is Multiplication) &&
|
---|
| 315 | !(n.Symbol is Division) &&
|
---|
| 316 | !(n.Symbol is Logarithm) &&
|
---|
| 317 | !(n.Symbol is Exponential) &&
|
---|
| 318 | !(n.Symbol is SquareRoot) &&
|
---|
| 319 | !(n.Symbol is Square) &&
|
---|
| 320 | !(n.Symbol is Sine) &&
|
---|
| 321 | !(n.Symbol is Cosine) &&
|
---|
| 322 | !(n.Symbol is Tangent) &&
|
---|
| 323 | !(n.Symbol is Erf) &&
|
---|
| 324 | !(n.Symbol is Norm) &&
|
---|
[16239] | 325 | !(n.Symbol is StartSymbol) &&
|
---|
| 326 | !(n.Symbol is Absolute) &&
|
---|
| 327 | !(n.Symbol is AnalyticalQuotient) &&
|
---|
| 328 | !(n.Symbol is Cube) &&
|
---|
| 329 | !(n.Symbol is CubeRoot)
|
---|
[14843] | 330 | select n).Any();
|
---|
| 331 | return !containsUnknownSymbol;
|
---|
| 332 | }
|
---|
[14950] | 333 | #region exception class
|
---|
| 334 | [Serializable]
|
---|
| 335 | public class ConversionException : Exception {
|
---|
| 336 |
|
---|
| 337 | public ConversionException() {
|
---|
| 338 | }
|
---|
| 339 |
|
---|
| 340 | public ConversionException(string message) : base(message) {
|
---|
| 341 | }
|
---|
| 342 |
|
---|
| 343 | public ConversionException(string message, Exception inner) : base(message, inner) {
|
---|
| 344 | }
|
---|
| 345 |
|
---|
| 346 | protected ConversionException(
|
---|
| 347 | SerializationInfo info,
|
---|
| 348 | StreamingContext context) : base(info, context) {
|
---|
| 349 | }
|
---|
| 350 | }
|
---|
| 351 | #endregion
|
---|
[14843] | 352 | }
|
---|
| 353 | }
|
---|