Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MathNetNumerics-Exploration-2789/HeuristicLab.Algorithms.DataAnalysis.Experimental/TreeToAutoDiffTermConverter.cs @ 15311

Last change on this file since 15311 was 15311, checked in by gkronber, 7 years ago

#2789 exploration of alglib solver for non-linear optimization with non-linear constraints

File size: 12.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Linq;
25using System.Runtime.Serialization;
26using AutoDiff;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28
29namespace HeuristicLab.Algorithms.DataAnalysis.Experimental {
30  public class TreeToAutoDiffTermConverter {
31    public delegate double ParametricFunction(double[] vars, double[] @params);
32
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));
66
67    private static readonly Func<Term, UnaryFunc> sin = UnaryFunc.Factory(
68      eval: Math.Sin,
69      diff: Math.Cos);
70
71    private static readonly Func<Term, UnaryFunc> cos = UnaryFunc.Factory(
72      eval: Math.Cos,
73      diff: x => -Math.Sin(x));
74
75    private static readonly Func<Term, UnaryFunc> tan = UnaryFunc.Factory(
76      eval: Math.Tan,
77      diff: x => 1 + Math.Tan(x) * Math.Tan(x));
78
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));
82
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
87    #endregion
88
89    public static bool TryConvertToAutoDiff(ISymbolicExpressionTree tree, bool makeVariableWeightsVariable,
90      out List<DataForVariable> parameters, out double[] initialConstants,
91      out ParametricFunction func,
92      out ParametricFunctionGradient func_grad,
93      out ParametricFunctionGradient func_grad_for_vars) {
94
95      // use a transformator object which holds the state (variable list, parameter list, ...) for recursive transformation of the tree
96      var transformator = new TreeToAutoDiffTermConverter(makeVariableWeightsVariable);
97      AutoDiff.Term term;
98      try {
99        term = transformator.ConvertToAutoDiff(tree.Root.GetSubtree(0));
100        var parameterEntries = transformator.parameters.ToArray(); // guarantee same order for keys and values
101        var compiledTerm = term.Compile(
102          transformator.variables.ToArray(),
103          parameterEntries.Select(kvp => kvp.Value).ToArray());
104       
105        parameters = new List<DataForVariable>(parameterEntries.Select(kvp => kvp.Key));
106        initialConstants = transformator.initialConstants.ToArray();
107        func = (vars, @params) => compiledTerm.Evaluate(vars, @params);
108        func_grad = (vars, @params) => compiledTerm.Differentiate(vars, @params);
109        func_grad_for_vars = (vars, @params) => compiledTerm.Differentiate(@params,vars);
110        return true;
111      } catch (ConversionException) {
112        func = null;
113        func_grad = null;
114        func_grad_for_vars = null;
115        parameters = null;
116        initialConstants = null;
117      }
118      return false;
119    }
120
121    // state for recursive transformation of trees
122    private readonly
123    List<double> initialConstants;
124    private readonly Dictionary<DataForVariable, AutoDiff.Variable> parameters;
125    private readonly List<AutoDiff.Variable> variables;
126    private readonly bool makeVariableWeightsVariable;
127
128    private TreeToAutoDiffTermConverter(bool makeVariableWeightsVariable) {
129      this.makeVariableWeightsVariable = makeVariableWeightsVariable;
130      this.initialConstants = new List<double>();
131      this.parameters = new Dictionary<DataForVariable, AutoDiff.Variable>();
132      this.variables = new List<AutoDiff.Variable>();
133    }
134
135    private AutoDiff.Term ConvertToAutoDiff(ISymbolicExpressionTreeNode node) {
136      if (node.Symbol is Constant) {
137        initialConstants.Add(((ConstantTreeNode)node).Value);
138        var var = new AutoDiff.Variable();
139        variables.Add(var);
140        return var;
141      }
142      if (node.Symbol is Variable || node.Symbol is BinaryFactorVariable) {
143        var varNode = node as VariableTreeNodeBase;
144        var factorVarNode = node as BinaryFactorVariableTreeNode;
145        // factor variable values are only 0 or 1 and set in x accordingly
146        var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty;
147        var par = FindOrCreateParameter(parameters, varNode.VariableName, varValue);
148
149        if (makeVariableWeightsVariable) {
150          initialConstants.Add(varNode.Weight);
151          var w = new AutoDiff.Variable();
152          variables.Add(w);
153          return AutoDiff.TermBuilder.Product(w, par);
154        } else {
155          return varNode.Weight * par;
156        }
157      }
158      if (node.Symbol is FactorVariable) {
159        var factorVarNode = node as FactorVariableTreeNode;
160        var products = new List<Term>();
161        foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName)) {
162          var par = FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue);
163
164          initialConstants.Add(factorVarNode.GetValue(variableValue));
165          var wVar = new AutoDiff.Variable();
166          variables.Add(wVar);
167
168          products.Add(AutoDiff.TermBuilder.Product(wVar, par));
169        }
170        return AutoDiff.TermBuilder.Sum(products);
171      }
172      if (node.Symbol is LaggedVariable) {
173        var varNode = node as LaggedVariableTreeNode;
174        var par = FindOrCreateParameter(parameters, varNode.VariableName, string.Empty, varNode.Lag);
175
176        if (makeVariableWeightsVariable) {
177          initialConstants.Add(varNode.Weight);
178          var w = new AutoDiff.Variable();
179          variables.Add(w);
180          return AutoDiff.TermBuilder.Product(w, par);
181        } else {
182          return varNode.Weight * par;
183        }
184      }
185      if (node.Symbol is Addition) {
186        List<AutoDiff.Term> terms = new List<Term>();
187        foreach (var subTree in node.Subtrees) {
188          terms.Add(ConvertToAutoDiff(subTree));
189        }
190        return AutoDiff.TermBuilder.Sum(terms);
191      }
192      if (node.Symbol is Subtraction) {
193        List<AutoDiff.Term> terms = new List<Term>();
194        for (int i = 0; i < node.SubtreeCount; i++) {
195          AutoDiff.Term t = ConvertToAutoDiff(node.GetSubtree(i));
196          if (i > 0) t = -t;
197          terms.Add(t);
198        }
199        if (terms.Count == 1) return -terms[0];
200        else return AutoDiff.TermBuilder.Sum(terms);
201      }
202      if (node.Symbol is Multiplication) {
203        List<AutoDiff.Term> terms = new List<Term>();
204        foreach (var subTree in node.Subtrees) {
205          terms.Add(ConvertToAutoDiff(subTree));
206        }
207        if (terms.Count == 1) return terms[0];
208        else return terms.Aggregate((a, b) => new AutoDiff.Product(a, b));
209      }
210      if (node.Symbol is Division) {
211        List<AutoDiff.Term> terms = new List<Term>();
212        foreach (var subTree in node.Subtrees) {
213          terms.Add(ConvertToAutoDiff(subTree));
214        }
215        if (terms.Count == 1) return 1.0 / terms[0];
216        else return terms.Aggregate((a, b) => new AutoDiff.Product(a, 1.0 / b));
217      }
218      if (node.Symbol is Logarithm) {
219        return AutoDiff.TermBuilder.Log(
220          ConvertToAutoDiff(node.GetSubtree(0)));
221      }
222      if (node.Symbol is Exponential) {
223        return AutoDiff.TermBuilder.Exp(
224          ConvertToAutoDiff(node.GetSubtree(0)));
225      }
226      if (node.Symbol is Square) {
227        return AutoDiff.TermBuilder.Power(
228          ConvertToAutoDiff(node.GetSubtree(0)), 2.0);
229      }
230      if (node.Symbol is SquareRoot) {
231        return AutoDiff.TermBuilder.Power(
232          ConvertToAutoDiff(node.GetSubtree(0)), 0.5);
233      }
234      if (node.Symbol is Sine) {
235        return sin(
236          ConvertToAutoDiff(node.GetSubtree(0)));
237      }
238      if (node.Symbol is Cosine) {
239        return cos(
240          ConvertToAutoDiff(node.GetSubtree(0)));
241      }
242      if (node.Symbol is Tangent) {
243        return tan(
244          ConvertToAutoDiff(node.GetSubtree(0)));
245      }
246      if (node.Symbol is Erf) {
247        return erf(
248          ConvertToAutoDiff(node.GetSubtree(0)));
249      }
250      if (node.Symbol is Norm) {
251        return norm(
252          ConvertToAutoDiff(node.GetSubtree(0)));
253      }
254      if (node.Symbol is StartSymbol) {
255        var alpha = new AutoDiff.Variable();
256        var beta = new AutoDiff.Variable();
257        variables.Add(beta);
258        variables.Add(alpha);
259        return ConvertToAutoDiff(node.GetSubtree(0)) * alpha + beta;
260      }
261      throw new ConversionException();
262    }
263
264
265    // for each factor variable value we need a parameter which represents a binary indicator for that variable & value combination
266    // each binary indicator is only necessary once. So we only create a parameter if this combination is not yet available.
267    private static Term FindOrCreateParameter(Dictionary<DataForVariable, AutoDiff.Variable> parameters,
268      string varName, string varValue = "", int lag = 0) {
269      var data = new DataForVariable(varName, varValue, lag);
270
271      AutoDiff.Variable par = null;
272      if (!parameters.TryGetValue(data, out par)) {
273        // not found -> create new parameter and entries in names and values lists
274        par = new AutoDiff.Variable();
275        parameters.Add(data, par);
276      }
277      return par;
278    }
279
280    public static bool IsCompatible(ISymbolicExpressionTree tree) {
281      var containsUnknownSymbol = (
282        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
283        where
284          !(n.Symbol is Variable) &&
285          !(n.Symbol is BinaryFactorVariable) &&
286          !(n.Symbol is FactorVariable) &&
287          !(n.Symbol is LaggedVariable) &&
288          !(n.Symbol is Constant) &&
289          !(n.Symbol is Addition) &&
290          !(n.Symbol is Subtraction) &&
291          !(n.Symbol is Multiplication) &&
292          !(n.Symbol is Division) &&
293          !(n.Symbol is Logarithm) &&
294          !(n.Symbol is Exponential) &&
295          !(n.Symbol is SquareRoot) &&
296          !(n.Symbol is Square) &&
297          !(n.Symbol is Sine) &&
298          !(n.Symbol is Cosine) &&
299          !(n.Symbol is Tangent) &&
300          !(n.Symbol is Erf) &&
301          !(n.Symbol is Norm) &&
302          !(n.Symbol is StartSymbol)
303        select n).Any();
304      return !containsUnknownSymbol;
305    }
306    #region exception class
307    [Serializable]
308    public class ConversionException : Exception {
309
310      public ConversionException() {
311      }
312
313      public ConversionException(string message) : base(message) {
314      }
315
316      public ConversionException(string message, Exception inner) : base(message, inner) {
317      }
318
319      protected ConversionException(
320        SerializationInfo info,
321        StreamingContext context) : base(info, context) {
322      }
323    }
324    #endregion
325  }
326}
Note: See TracBrowser for help on using the repository browser.