1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2015 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.Linq;
|
---|
25 | using AutoDiff;
|
---|
26 | using HeuristicLab.Common;
|
---|
27 | using HeuristicLab.Core;
|
---|
28 | using HeuristicLab.Data;
|
---|
29 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
30 | using HeuristicLab.Parameters;
|
---|
31 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
32 |
|
---|
33 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
|
---|
34 | [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
|
---|
35 | [StorableClass]
|
---|
36 | public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
|
---|
37 | private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
|
---|
38 | private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
|
---|
39 | private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
|
---|
40 | private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
|
---|
41 | private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
|
---|
42 | private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
|
---|
43 |
|
---|
44 | public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
|
---|
45 | get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
|
---|
46 | }
|
---|
47 | public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
|
---|
48 | get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
|
---|
49 | }
|
---|
50 | public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
|
---|
51 | get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
|
---|
52 | }
|
---|
53 | public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
|
---|
54 | get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
|
---|
55 | }
|
---|
56 | public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
|
---|
57 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
|
---|
58 | }
|
---|
59 | public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
|
---|
60 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
|
---|
61 | }
|
---|
62 |
|
---|
63 |
|
---|
64 | public IntValue ConstantOptimizationIterations {
|
---|
65 | get { return ConstantOptimizationIterationsParameter.Value; }
|
---|
66 | }
|
---|
67 | public DoubleValue ConstantOptimizationImprovement {
|
---|
68 | get { return ConstantOptimizationImprovementParameter.Value; }
|
---|
69 | }
|
---|
70 | public PercentValue ConstantOptimizationProbability {
|
---|
71 | get { return ConstantOptimizationProbabilityParameter.Value; }
|
---|
72 | }
|
---|
73 | public PercentValue ConstantOptimizationRowsPercentage {
|
---|
74 | get { return ConstantOptimizationRowsPercentageParameter.Value; }
|
---|
75 | }
|
---|
76 | public bool UpdateConstantsInTree {
|
---|
77 | get { return UpdateConstantsInTreeParameter.Value.Value; }
|
---|
78 | set { UpdateConstantsInTreeParameter.Value.Value = value; }
|
---|
79 | }
|
---|
80 |
|
---|
81 | public bool UpdateVariableWeights {
|
---|
82 | get { return UpdateVariableWeightsParameter.Value.Value; }
|
---|
83 | set { UpdateVariableWeightsParameter.Value.Value = value; }
|
---|
84 | }
|
---|
85 |
|
---|
86 | public override bool Maximization {
|
---|
87 | get { return true; }
|
---|
88 | }
|
---|
89 |
|
---|
90 | [StorableConstructor]
|
---|
91 | protected SymbolicRegressionConstantOptimizationEvaluator(bool deserializing) : base(deserializing) { }
|
---|
92 | protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
|
---|
93 | : base(original, cloner) {
|
---|
94 | }
|
---|
95 | public SymbolicRegressionConstantOptimizationEvaluator()
|
---|
96 | : base() {
|
---|
97 | Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the constant of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10), true));
|
---|
98 | Parameters.Add(new FixedValueParameter<DoubleValue>(ConstantOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the constant optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0), true) { Hidden = true });
|
---|
99 | Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1), true));
|
---|
100 | Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1), true));
|
---|
101 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)) { Hidden = true });
|
---|
102 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)) { Hidden = true });
|
---|
103 | }
|
---|
104 |
|
---|
105 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
106 | return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
|
---|
107 | }
|
---|
108 |
|
---|
109 | [StorableHook(HookType.AfterDeserialization)]
|
---|
110 | private void AfterDeserialization() {
|
---|
111 | if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
|
---|
112 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
|
---|
113 | if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
|
---|
114 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)));
|
---|
115 | }
|
---|
116 |
|
---|
117 | public override IOperation InstrumentedApply() {
|
---|
118 | var solution = SymbolicExpressionTreeParameter.ActualValue;
|
---|
119 | double quality;
|
---|
120 | if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
|
---|
121 | IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
|
---|
122 | quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
|
---|
123 | constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree);
|
---|
124 |
|
---|
125 | if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
|
---|
126 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
127 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
128 | }
|
---|
129 | } else {
|
---|
130 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
131 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
132 | }
|
---|
133 | QualityParameter.ActualValue = new DoubleValue(quality);
|
---|
134 |
|
---|
135 | return base.InstrumentedApply();
|
---|
136 | }
|
---|
137 |
|
---|
138 | public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
|
---|
139 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
|
---|
140 | EstimationLimitsParameter.ExecutionContext = context;
|
---|
141 | ApplyLinearScalingParameter.ExecutionContext = context;
|
---|
142 |
|
---|
143 | // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
|
---|
144 | // because Evaluate() is used to get the quality of evolved models on
|
---|
145 | // different partitions of the dataset (e.g., best validation model)
|
---|
146 | double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
147 |
|
---|
148 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
|
---|
149 | EstimationLimitsParameter.ExecutionContext = null;
|
---|
150 | ApplyLinearScalingParameter.ExecutionContext = null;
|
---|
151 |
|
---|
152 | return r2;
|
---|
153 | }
|
---|
154 |
|
---|
155 | #region derivations of functions
|
---|
156 | // create function factory for arctangent
|
---|
157 | private readonly Func<Term, UnaryFunc> arctan = UnaryFunc.Factory(
|
---|
158 | eval: Math.Atan,
|
---|
159 | diff: x => 1 / (1 + x * x));
|
---|
160 | private static readonly Func<Term, UnaryFunc> sin = UnaryFunc.Factory(
|
---|
161 | eval: Math.Sin,
|
---|
162 | diff: Math.Cos);
|
---|
163 | private static readonly Func<Term, UnaryFunc> cos = UnaryFunc.Factory(
|
---|
164 | eval: Math.Cos,
|
---|
165 | diff: x => -Math.Sin(x));
|
---|
166 | private static readonly Func<Term, UnaryFunc> tan = UnaryFunc.Factory(
|
---|
167 | eval: Math.Tan,
|
---|
168 | diff: x => 1 + Math.Tan(x) * Math.Tan(x));
|
---|
169 | private static readonly Func<Term, UnaryFunc> erf = UnaryFunc.Factory(
|
---|
170 | eval: alglib.errorfunction,
|
---|
171 | diff: x => 2.0 * Math.Exp(-(x * x)) / Math.Sqrt(Math.PI));
|
---|
172 | private static readonly Func<Term, UnaryFunc> norm = UnaryFunc.Factory(
|
---|
173 | eval: alglib.normaldistribution,
|
---|
174 | diff: x => -(Math.Exp(-(x * x)) * Math.Sqrt(Math.Exp(x * x)) * x) / Math.Sqrt(2 * Math.PI));
|
---|
175 | #endregion
|
---|
176 |
|
---|
177 |
|
---|
178 | public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling, int maxIterations, bool updateVariableWeights = true, double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue, bool updateConstantsInTree = true) {
|
---|
179 |
|
---|
180 | List<AutoDiff.Variable> variables = new List<AutoDiff.Variable>();
|
---|
181 | List<AutoDiff.Variable> parameters = new List<AutoDiff.Variable>();
|
---|
182 | List<string> variableNames = new List<string>();
|
---|
183 |
|
---|
184 | AutoDiff.Term func;
|
---|
185 | if (!TryTransformToAutoDiff(tree.Root.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out func))
|
---|
186 | throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
|
---|
187 | if (variableNames.Count == 0) return 0.0;
|
---|
188 |
|
---|
189 | AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(variables.ToArray(), parameters.ToArray());
|
---|
190 |
|
---|
191 | List<SymbolicExpressionTreeTerminalNode> terminalNodes = null;
|
---|
192 | if (updateVariableWeights)
|
---|
193 | terminalNodes = tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>().ToList();
|
---|
194 | else
|
---|
195 | terminalNodes = new List<SymbolicExpressionTreeTerminalNode>(tree.Root.IterateNodesPrefix().OfType<ConstantTreeNode>());
|
---|
196 |
|
---|
197 | //extract inital constants
|
---|
198 | double[] c = new double[variables.Count];
|
---|
199 | {
|
---|
200 | c[0] = 0.0;
|
---|
201 | c[1] = 1.0;
|
---|
202 | int i = 2;
|
---|
203 | foreach (var node in terminalNodes) {
|
---|
204 | ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
|
---|
205 | VariableTreeNode variableTreeNode = node as VariableTreeNode;
|
---|
206 | if (constantTreeNode != null)
|
---|
207 | c[i++] = constantTreeNode.Value;
|
---|
208 | else if (updateVariableWeights && variableTreeNode != null)
|
---|
209 | c[i++] = variableTreeNode.Weight;
|
---|
210 | }
|
---|
211 | }
|
---|
212 | double[] originalConstants = (double[])c.Clone();
|
---|
213 | double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
214 |
|
---|
215 | alglib.lsfitstate state;
|
---|
216 | alglib.lsfitreport rep;
|
---|
217 | int info;
|
---|
218 |
|
---|
219 | IDataset ds = problemData.Dataset;
|
---|
220 | double[,] x = new double[rows.Count(), variableNames.Count];
|
---|
221 | int row = 0;
|
---|
222 | foreach (var r in rows) {
|
---|
223 | for (int col = 0; col < variableNames.Count; col++) {
|
---|
224 | x[row, col] = ds.GetDoubleValue(variableNames[col], r);
|
---|
225 | }
|
---|
226 | row++;
|
---|
227 | }
|
---|
228 | double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
|
---|
229 | int n = x.GetLength(0);
|
---|
230 | int m = x.GetLength(1);
|
---|
231 | int k = c.Length;
|
---|
232 |
|
---|
233 | alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
|
---|
234 | alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
|
---|
235 |
|
---|
236 | try {
|
---|
237 | alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
|
---|
238 | alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
|
---|
239 | //alglib.lsfitsetgradientcheck(state, 0.001);
|
---|
240 | alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
|
---|
241 | alglib.lsfitresults(state, out info, out c, out rep);
|
---|
242 | }
|
---|
243 | catch (ArithmeticException) {
|
---|
244 | return originalQuality;
|
---|
245 | }
|
---|
246 | catch (alglib.alglibexception) {
|
---|
247 | return originalQuality;
|
---|
248 | }
|
---|
249 |
|
---|
250 | //info == -7 => constant optimization failed due to wrong gradient
|
---|
251 | if (info != -7) UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
|
---|
252 | var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
253 |
|
---|
254 | if (!updateConstantsInTree) UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
|
---|
255 | if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
|
---|
256 | UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
|
---|
257 | return originalQuality;
|
---|
258 | }
|
---|
259 | return quality;
|
---|
260 | }
|
---|
261 |
|
---|
262 | private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
|
---|
263 | int i = 0;
|
---|
264 | foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
|
---|
265 | ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
|
---|
266 | VariableTreeNode variableTreeNode = node as VariableTreeNode;
|
---|
267 | if (constantTreeNode != null)
|
---|
268 | constantTreeNode.Value = constants[i++];
|
---|
269 | else if (updateVariableWeights && variableTreeNode != null)
|
---|
270 | variableTreeNode.Weight = constants[i++];
|
---|
271 | }
|
---|
272 | }
|
---|
273 |
|
---|
274 | private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
|
---|
275 | return (double[] c, double[] x, ref double func, object o) => {
|
---|
276 | func = compiledFunc.Evaluate(c, x);
|
---|
277 | };
|
---|
278 | }
|
---|
279 |
|
---|
280 | private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
|
---|
281 | return (double[] c, double[] x, ref double func, double[] grad, object o) => {
|
---|
282 | var tupel = compiledFunc.Differentiate(c, x);
|
---|
283 | func = tupel.Item2;
|
---|
284 | Array.Copy(tupel.Item1, grad, grad.Length);
|
---|
285 | };
|
---|
286 | }
|
---|
287 |
|
---|
288 | private static bool TryTransformToAutoDiff(ISymbolicExpressionTreeNode node, List<AutoDiff.Variable> variables, List<AutoDiff.Variable> parameters, List<string> variableNames, bool updateVariableWeights, out AutoDiff.Term term) {
|
---|
289 | if (node.Symbol is Constant) {
|
---|
290 | var var = new AutoDiff.Variable();
|
---|
291 | variables.Add(var);
|
---|
292 | term = var;
|
---|
293 | return true;
|
---|
294 | }
|
---|
295 | if (node.Symbol is Variable) {
|
---|
296 | var varNode = node as VariableTreeNode;
|
---|
297 | var par = new AutoDiff.Variable();
|
---|
298 | parameters.Add(par);
|
---|
299 | variableNames.Add(varNode.VariableName);
|
---|
300 |
|
---|
301 | if (updateVariableWeights) {
|
---|
302 | var w = new AutoDiff.Variable();
|
---|
303 | variables.Add(w);
|
---|
304 | term = AutoDiff.TermBuilder.Product(w, par);
|
---|
305 | } else {
|
---|
306 | term = par;
|
---|
307 | }
|
---|
308 | return true;
|
---|
309 | }
|
---|
310 | if (node.Symbol is Addition) {
|
---|
311 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
312 | foreach (var subTree in node.Subtrees) {
|
---|
313 | AutoDiff.Term t;
|
---|
314 | if (!TryTransformToAutoDiff(subTree, variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
315 | term = null;
|
---|
316 | return false;
|
---|
317 | }
|
---|
318 | terms.Add(t);
|
---|
319 | }
|
---|
320 | term = AutoDiff.TermBuilder.Sum(terms);
|
---|
321 | return true;
|
---|
322 | }
|
---|
323 | if (node.Symbol is Subtraction) {
|
---|
324 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
325 | for (int i = 0; i < node.SubtreeCount; i++) {
|
---|
326 | AutoDiff.Term t;
|
---|
327 | if (!TryTransformToAutoDiff(node.GetSubtree(i), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
328 | term = null;
|
---|
329 | return false;
|
---|
330 | }
|
---|
331 | if (i > 0) t = -t;
|
---|
332 | terms.Add(t);
|
---|
333 | }
|
---|
334 | if (terms.Count == 1) term = -terms[0];
|
---|
335 | else term = AutoDiff.TermBuilder.Sum(terms);
|
---|
336 | return true;
|
---|
337 | }
|
---|
338 | if (node.Symbol is Multiplication) {
|
---|
339 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
340 | foreach (var subTree in node.Subtrees) {
|
---|
341 | AutoDiff.Term t;
|
---|
342 | if (!TryTransformToAutoDiff(subTree, variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
343 | term = null;
|
---|
344 | return false;
|
---|
345 | }
|
---|
346 | terms.Add(t);
|
---|
347 | }
|
---|
348 | if (terms.Count == 1) term = terms[0];
|
---|
349 | else term = terms.Aggregate((a, b) => new AutoDiff.Product(a, b));
|
---|
350 | return true;
|
---|
351 |
|
---|
352 | }
|
---|
353 | if (node.Symbol is Division) {
|
---|
354 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
355 | foreach (var subTree in node.Subtrees) {
|
---|
356 | AutoDiff.Term t;
|
---|
357 | if (!TryTransformToAutoDiff(subTree, variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
358 | term = null;
|
---|
359 | return false;
|
---|
360 | }
|
---|
361 | terms.Add(t);
|
---|
362 | }
|
---|
363 | if (terms.Count == 1) term = 1.0 / terms[0];
|
---|
364 | else term = terms.Aggregate((a, b) => new AutoDiff.Product(a, 1.0 / b));
|
---|
365 | return true;
|
---|
366 | }
|
---|
367 | if (node.Symbol is Logarithm) {
|
---|
368 | AutoDiff.Term t;
|
---|
369 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
370 | term = null;
|
---|
371 | return false;
|
---|
372 | } else {
|
---|
373 | term = AutoDiff.TermBuilder.Log(t);
|
---|
374 | return true;
|
---|
375 | }
|
---|
376 | }
|
---|
377 | if (node.Symbol is Exponential) {
|
---|
378 | AutoDiff.Term t;
|
---|
379 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
380 | term = null;
|
---|
381 | return false;
|
---|
382 | } else {
|
---|
383 | term = AutoDiff.TermBuilder.Exp(t);
|
---|
384 | return true;
|
---|
385 | }
|
---|
386 | }
|
---|
387 | if (node.Symbol is Square) {
|
---|
388 | AutoDiff.Term t;
|
---|
389 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
390 | term = null;
|
---|
391 | return false;
|
---|
392 | } else {
|
---|
393 | term = AutoDiff.TermBuilder.Power(t, 2.0);
|
---|
394 | return true;
|
---|
395 | }
|
---|
396 | }
|
---|
397 | if (node.Symbol is SquareRoot) {
|
---|
398 | AutoDiff.Term t;
|
---|
399 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
400 | term = null;
|
---|
401 | return false;
|
---|
402 | } else {
|
---|
403 | term = AutoDiff.TermBuilder.Power(t, 0.5);
|
---|
404 | return true;
|
---|
405 | }
|
---|
406 | }
|
---|
407 | if (node.Symbol is Sine) {
|
---|
408 | AutoDiff.Term t;
|
---|
409 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
410 | term = null;
|
---|
411 | return false;
|
---|
412 | } else {
|
---|
413 | term = sin(t);
|
---|
414 | return true;
|
---|
415 | }
|
---|
416 | }
|
---|
417 | if (node.Symbol is Cosine) {
|
---|
418 | AutoDiff.Term t;
|
---|
419 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
420 | term = null;
|
---|
421 | return false;
|
---|
422 | } else {
|
---|
423 | term = cos(t);
|
---|
424 | return true;
|
---|
425 | }
|
---|
426 | }
|
---|
427 | if (node.Symbol is Tangent) {
|
---|
428 | AutoDiff.Term t;
|
---|
429 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
430 | term = null;
|
---|
431 | return false;
|
---|
432 | } else {
|
---|
433 | term = tan(t);
|
---|
434 | return true;
|
---|
435 | }
|
---|
436 | }
|
---|
437 | if (node.Symbol is Erf) {
|
---|
438 | AutoDiff.Term t;
|
---|
439 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
440 | term = null;
|
---|
441 | return false;
|
---|
442 | } else {
|
---|
443 | term = erf(t);
|
---|
444 | return true;
|
---|
445 | }
|
---|
446 | }
|
---|
447 | if (node.Symbol is Norm) {
|
---|
448 | AutoDiff.Term t;
|
---|
449 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out t)) {
|
---|
450 | term = null;
|
---|
451 | return false;
|
---|
452 | } else {
|
---|
453 | term = norm(t);
|
---|
454 | return true;
|
---|
455 | }
|
---|
456 | }
|
---|
457 | if (node.Symbol is StartSymbol) {
|
---|
458 | var alpha = new AutoDiff.Variable();
|
---|
459 | var beta = new AutoDiff.Variable();
|
---|
460 | variables.Add(beta);
|
---|
461 | variables.Add(alpha);
|
---|
462 | AutoDiff.Term branchTerm;
|
---|
463 | if (TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, updateVariableWeights, out branchTerm)) {
|
---|
464 | term = branchTerm * alpha + beta;
|
---|
465 | return true;
|
---|
466 | } else {
|
---|
467 | term = null;
|
---|
468 | return false;
|
---|
469 | }
|
---|
470 | }
|
---|
471 | term = null;
|
---|
472 | return false;
|
---|
473 | }
|
---|
474 |
|
---|
475 | public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
|
---|
476 | var containsUnknownSymbol = (
|
---|
477 | from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
|
---|
478 | where
|
---|
479 | !(n.Symbol is Variable) &&
|
---|
480 | !(n.Symbol is Constant) &&
|
---|
481 | !(n.Symbol is Addition) &&
|
---|
482 | !(n.Symbol is Subtraction) &&
|
---|
483 | !(n.Symbol is Multiplication) &&
|
---|
484 | !(n.Symbol is Division) &&
|
---|
485 | !(n.Symbol is Logarithm) &&
|
---|
486 | !(n.Symbol is Exponential) &&
|
---|
487 | !(n.Symbol is SquareRoot) &&
|
---|
488 | !(n.Symbol is Square) &&
|
---|
489 | !(n.Symbol is Sine) &&
|
---|
490 | !(n.Symbol is Cosine) &&
|
---|
491 | !(n.Symbol is Tangent) &&
|
---|
492 | !(n.Symbol is Erf) &&
|
---|
493 | !(n.Symbol is Norm) &&
|
---|
494 | !(n.Symbol is StartSymbol)
|
---|
495 | select n).
|
---|
496 | Any();
|
---|
497 | return !containsUnknownSymbol;
|
---|
498 | }
|
---|
499 | }
|
---|
500 | }
|
---|