[6256] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[14185] | 3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[6256] | 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 |
|
---|
[8704] | 22 | using System;
|
---|
[6256] | 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Linq;
|
---|
[8704] | 25 | using AutoDiff;
|
---|
[6256] | 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 {
|
---|
[6555] | 34 | [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
|
---|
[6256] | 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";
|
---|
[8823] | 41 | private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
|
---|
[13670] | 42 | private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
|
---|
[6256] | 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 | }
|
---|
[8823] | 56 | public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
|
---|
| 57 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
|
---|
| 58 | }
|
---|
[13670] | 59 | public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
|
---|
| 60 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
|
---|
| 61 | }
|
---|
[6256] | 62 |
|
---|
[13670] | 63 |
|
---|
[6256] | 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 | }
|
---|
[8823] | 76 | public bool UpdateConstantsInTree {
|
---|
| 77 | get { return UpdateConstantsInTreeParameter.Value.Value; }
|
---|
| 78 | set { UpdateConstantsInTreeParameter.Value.Value = value; }
|
---|
| 79 | }
|
---|
[6256] | 80 |
|
---|
[13670] | 81 | public bool UpdateVariableWeights {
|
---|
| 82 | get { return UpdateVariableWeightsParameter.Value.Value; }
|
---|
| 83 | set { UpdateVariableWeightsParameter.Value.Value = value; }
|
---|
| 84 | }
|
---|
| 85 |
|
---|
[6256] | 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() {
|
---|
[8938] | 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));
|
---|
[13916] | 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 });
|
---|
[6256] | 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));
|
---|
[13916] | 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 });
|
---|
[6256] | 103 | }
|
---|
| 104 |
|
---|
| 105 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 106 | return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
|
---|
| 107 | }
|
---|
| 108 |
|
---|
[8823] | 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)));
|
---|
[13670] | 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)));
|
---|
[8823] | 115 | }
|
---|
| 116 |
|
---|
[10291] | 117 | public override IOperation InstrumentedApply() {
|
---|
[6256] | 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,
|
---|
[13670] | 123 | constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree);
|
---|
[8938] | 124 |
|
---|
[6256] | 125 | if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
|
---|
| 126 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
[8664] | 127 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 128 | }
|
---|
| 129 | } else {
|
---|
| 130 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
[8664] | 131 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 132 | }
|
---|
| 133 | QualityParameter.ActualValue = new DoubleValue(quality);
|
---|
| 134 |
|
---|
[10291] | 135 | return base.InstrumentedApply();
|
---|
[6256] | 136 | }
|
---|
| 137 |
|
---|
| 138 | public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
|
---|
| 139 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
|
---|
| 140 | EstimationLimitsParameter.ExecutionContext = context;
|
---|
[8664] | 141 | ApplyLinearScalingParameter.ExecutionContext = context;
|
---|
[6256] | 142 |
|
---|
[9209] | 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)
|
---|
[8664] | 146 | double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 147 |
|
---|
| 148 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
|
---|
| 149 | EstimationLimitsParameter.ExecutionContext = null;
|
---|
[9209] | 150 | ApplyLinearScalingParameter.ExecutionContext = null;
|
---|
[6256] | 151 |
|
---|
| 152 | return r2;
|
---|
| 153 | }
|
---|
| 154 |
|
---|
[8823] | 155 | #region derivations of functions
|
---|
[8730] | 156 | // create function factory for arctangent
|
---|
| 157 | private readonly Func<Term, UnaryFunc> arctan = UnaryFunc.Factory(
|
---|
[8823] | 158 | eval: Math.Atan,
|
---|
| 159 | diff: x => 1 / (1 + x * x));
|
---|
[8730] | 160 | private static readonly Func<Term, UnaryFunc> sin = UnaryFunc.Factory(
|
---|
[8823] | 161 | eval: Math.Sin,
|
---|
| 162 | diff: Math.Cos);
|
---|
[8730] | 163 | private static readonly Func<Term, UnaryFunc> cos = UnaryFunc.Factory(
|
---|
[8823] | 164 | eval: Math.Cos,
|
---|
| 165 | diff: x => -Math.Sin(x));
|
---|
[8730] | 166 | private static readonly Func<Term, UnaryFunc> tan = UnaryFunc.Factory(
|
---|
[8823] | 167 | eval: Math.Tan,
|
---|
| 168 | diff: x => 1 + Math.Tan(x) * Math.Tan(x));
|
---|
[8730] | 169 | private static readonly Func<Term, UnaryFunc> erf = UnaryFunc.Factory(
|
---|
[8823] | 170 | eval: alglib.errorfunction,
|
---|
| 171 | diff: x => 2.0 * Math.Exp(-(x * x)) / Math.Sqrt(Math.PI));
|
---|
[8730] | 172 | private static readonly Func<Term, UnaryFunc> norm = UnaryFunc.Factory(
|
---|
[8823] | 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
|
---|
[8730] | 176 |
|
---|
| 177 |
|
---|
[13670] | 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) {
|
---|
[8704] | 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>();
|
---|
[14232] | 183 | List<string> categoricalVariableValues = new List<string>();
|
---|
[8704] | 184 |
|
---|
| 185 | AutoDiff.Term func;
|
---|
[14232] | 186 | if (!TryTransformToAutoDiff(tree.Root.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out func))
|
---|
[8828] | 187 | throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
|
---|
[14232] | 188 | if (variableNames.Count == 0) return 0.0; // gkronber: constant expressions always have a R² of 0.0
|
---|
[8704] | 189 |
|
---|
[13670] | 190 | AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(variables.ToArray(), parameters.ToArray());
|
---|
[8704] | 191 |
|
---|
[14232] | 192 | List<SymbolicExpressionTreeTerminalNode> terminalNodes = null; // gkronber only used for extraction of initial constants
|
---|
[13670] | 193 | if (updateVariableWeights)
|
---|
| 194 | terminalNodes = tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>().ToList();
|
---|
| 195 | else
|
---|
| 196 | terminalNodes = new List<SymbolicExpressionTreeTerminalNode>(tree.Root.IterateNodesPrefix().OfType<ConstantTreeNode>());
|
---|
| 197 |
|
---|
| 198 | //extract inital constants
|
---|
[8704] | 199 | double[] c = new double[variables.Count];
|
---|
| 200 | {
|
---|
| 201 | c[0] = 0.0;
|
---|
| 202 | c[1] = 1.0;
|
---|
| 203 | int i = 2;
|
---|
| 204 | foreach (var node in terminalNodes) {
|
---|
| 205 | ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
|
---|
| 206 | VariableTreeNode variableTreeNode = node as VariableTreeNode;
|
---|
[14237] | 207 | FactorVariableTreeNode factorVariableTreeNode = node as FactorVariableTreeNode;
|
---|
[8704] | 208 | if (constantTreeNode != null)
|
---|
| 209 | c[i++] = constantTreeNode.Value;
|
---|
[13670] | 210 | else if (updateVariableWeights && variableTreeNode != null)
|
---|
[8704] | 211 | c[i++] = variableTreeNode.Weight;
|
---|
[14237] | 212 | else if (updateVariableWeights && factorVariableTreeNode != null)
|
---|
| 213 | c[i++] = factorVariableTreeNode.Weight;
|
---|
[8704] | 214 | }
|
---|
[6256] | 215 | }
|
---|
[8938] | 216 | double[] originalConstants = (double[])c.Clone();
|
---|
| 217 | double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
[6256] | 218 |
|
---|
[8704] | 219 | alglib.lsfitstate state;
|
---|
| 220 | alglib.lsfitreport rep;
|
---|
| 221 | int info;
|
---|
[6256] | 222 |
|
---|
[12509] | 223 | IDataset ds = problemData.Dataset;
|
---|
[8704] | 224 | double[,] x = new double[rows.Count(), variableNames.Count];
|
---|
| 225 | int row = 0;
|
---|
| 226 | foreach (var r in rows) {
|
---|
| 227 | for (int col = 0; col < variableNames.Count; col++) {
|
---|
[14232] | 228 | if (ds.VariableHasType<double>(variableNames[col])) {
|
---|
| 229 | x[row, col] = ds.GetDoubleValue(variableNames[col], r);
|
---|
| 230 | } else if (ds.VariableHasType<string>(variableNames[col])) {
|
---|
| 231 | x[row, col] = ds.GetStringValue(variableNames[col], r) == categoricalVariableValues[col] ? 1 : 0;
|
---|
| 232 | } else throw new InvalidProgramException("found a variable of unknown type");
|
---|
[8704] | 233 | }
|
---|
| 234 | row++;
|
---|
| 235 | }
|
---|
| 236 | double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
|
---|
| 237 | int n = x.GetLength(0);
|
---|
| 238 | int m = x.GetLength(1);
|
---|
| 239 | int k = c.Length;
|
---|
[6256] | 240 |
|
---|
[8704] | 241 | alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
|
---|
| 242 | alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
|
---|
[6256] | 243 |
|
---|
[8704] | 244 | try {
|
---|
| 245 | alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
|
---|
[8938] | 246 | alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
|
---|
| 247 | //alglib.lsfitsetgradientcheck(state, 0.001);
|
---|
[8704] | 248 | alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
|
---|
| 249 | alglib.lsfitresults(state, out info, out c, out rep);
|
---|
[6256] | 250 | }
|
---|
[8730] | 251 | catch (ArithmeticException) {
|
---|
[8984] | 252 | return originalQuality;
|
---|
[8730] | 253 | }
|
---|
[8704] | 254 | catch (alglib.alglibexception) {
|
---|
[8984] | 255 | return originalQuality;
|
---|
[8704] | 256 | }
|
---|
[8823] | 257 |
|
---|
[8938] | 258 | //info == -7 => constant optimization failed due to wrong gradient
|
---|
[13670] | 259 | if (info != -7) UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
|
---|
[8938] | 260 | var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
| 261 |
|
---|
[13670] | 262 | if (!updateConstantsInTree) UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
|
---|
[8938] | 263 | if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
|
---|
[13670] | 264 | UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
|
---|
[8938] | 265 | return originalQuality;
|
---|
[8704] | 266 | }
|
---|
[8938] | 267 | return quality;
|
---|
[6256] | 268 | }
|
---|
| 269 |
|
---|
[13670] | 270 | private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
|
---|
[8938] | 271 | int i = 0;
|
---|
| 272 | foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
|
---|
| 273 | ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
|
---|
| 274 | VariableTreeNode variableTreeNode = node as VariableTreeNode;
|
---|
[14237] | 275 | FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
|
---|
[8938] | 276 | if (constantTreeNode != null)
|
---|
| 277 | constantTreeNode.Value = constants[i++];
|
---|
[13670] | 278 | else if (updateVariableWeights && variableTreeNode != null)
|
---|
[8938] | 279 | variableTreeNode.Weight = constants[i++];
|
---|
[14237] | 280 | else if (updateVariableWeights && factorVarTreeNode != null)
|
---|
| 281 | factorVarTreeNode.Weight = constants[i++];
|
---|
[8938] | 282 | }
|
---|
| 283 | }
|
---|
| 284 |
|
---|
[8704] | 285 | private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
|
---|
| 286 | return (double[] c, double[] x, ref double func, object o) => {
|
---|
| 287 | func = compiledFunc.Evaluate(c, x);
|
---|
| 288 | };
|
---|
| 289 | }
|
---|
[6256] | 290 |
|
---|
[8704] | 291 | private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
|
---|
| 292 | return (double[] c, double[] x, ref double func, double[] grad, object o) => {
|
---|
| 293 | var tupel = compiledFunc.Differentiate(c, x);
|
---|
| 294 | func = tupel.Item2;
|
---|
| 295 | Array.Copy(tupel.Item1, grad, grad.Length);
|
---|
[6256] | 296 | };
|
---|
| 297 | }
|
---|
| 298 |
|
---|
[14232] | 299 | private static bool TryTransformToAutoDiff(ISymbolicExpressionTreeNode node, List<AutoDiff.Variable> variables, List<AutoDiff.Variable> parameters,
|
---|
| 300 | List<string> variableNames, List<string> categoricalVariableValues, bool updateVariableWeights, out AutoDiff.Term term) {
|
---|
[8704] | 301 | if (node.Symbol is Constant) {
|
---|
| 302 | var var = new AutoDiff.Variable();
|
---|
| 303 | variables.Add(var);
|
---|
| 304 | term = var;
|
---|
| 305 | return true;
|
---|
| 306 | }
|
---|
[14237] | 307 | if (node.Symbol is Variable || node.Symbol is FactorVariable) {
|
---|
| 308 | var varNode = node as VariableTreeNodeBase;
|
---|
| 309 | var factorVarNode = node as FactorVariableTreeNode;
|
---|
| 310 | // factor variable values are only 0 or 1 and set in x accordingly
|
---|
[8704] | 311 | var par = new AutoDiff.Variable();
|
---|
| 312 | parameters.Add(par);
|
---|
| 313 | variableNames.Add(varNode.VariableName);
|
---|
[14237] | 314 | categoricalVariableValues.Add(factorVarNode != null ? factorVarNode.VariableValue : string.Empty);
|
---|
[13670] | 315 |
|
---|
| 316 | if (updateVariableWeights) {
|
---|
| 317 | var w = new AutoDiff.Variable();
|
---|
| 318 | variables.Add(w);
|
---|
| 319 | term = AutoDiff.TermBuilder.Product(w, par);
|
---|
| 320 | } else {
|
---|
| 321 | term = par;
|
---|
| 322 | }
|
---|
[8704] | 323 | return true;
|
---|
| 324 | }
|
---|
| 325 | if (node.Symbol is Addition) {
|
---|
| 326 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 327 | foreach (var subTree in node.Subtrees) {
|
---|
| 328 | AutoDiff.Term t;
|
---|
[14232] | 329 | if (!TryTransformToAutoDiff(subTree, variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8704] | 330 | term = null;
|
---|
| 331 | return false;
|
---|
| 332 | }
|
---|
| 333 | terms.Add(t);
|
---|
| 334 | }
|
---|
| 335 | term = AutoDiff.TermBuilder.Sum(terms);
|
---|
| 336 | return true;
|
---|
| 337 | }
|
---|
[8823] | 338 | if (node.Symbol is Subtraction) {
|
---|
| 339 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 340 | for (int i = 0; i < node.SubtreeCount; i++) {
|
---|
| 341 | AutoDiff.Term t;
|
---|
[14232] | 342 | if (!TryTransformToAutoDiff(node.GetSubtree(i), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8823] | 343 | term = null;
|
---|
| 344 | return false;
|
---|
| 345 | }
|
---|
| 346 | if (i > 0) t = -t;
|
---|
| 347 | terms.Add(t);
|
---|
| 348 | }
|
---|
[14036] | 349 | if (terms.Count == 1) term = -terms[0];
|
---|
| 350 | else term = AutoDiff.TermBuilder.Sum(terms);
|
---|
[8823] | 351 | return true;
|
---|
| 352 | }
|
---|
[8704] | 353 | if (node.Symbol is Multiplication) {
|
---|
[13900] | 354 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 355 | foreach (var subTree in node.Subtrees) {
|
---|
| 356 | AutoDiff.Term t;
|
---|
[14232] | 357 | if (!TryTransformToAutoDiff(subTree, variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[13869] | 358 | term = null;
|
---|
| 359 | return false;
|
---|
| 360 | }
|
---|
[13900] | 361 | terms.Add(t);
|
---|
[8704] | 362 | }
|
---|
[13900] | 363 | if (terms.Count == 1) term = terms[0];
|
---|
| 364 | else term = terms.Aggregate((a, b) => new AutoDiff.Product(a, b));
|
---|
[13869] | 365 | return true;
|
---|
[13900] | 366 |
|
---|
[8704] | 367 | }
|
---|
| 368 | if (node.Symbol is Division) {
|
---|
[13900] | 369 | List<AutoDiff.Term> terms = new List<Term>();
|
---|
| 370 | foreach (var subTree in node.Subtrees) {
|
---|
| 371 | AutoDiff.Term t;
|
---|
[14232] | 372 | if (!TryTransformToAutoDiff(subTree, variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[13869] | 373 | term = null;
|
---|
| 374 | return false;
|
---|
| 375 | }
|
---|
[13900] | 376 | terms.Add(t);
|
---|
[8704] | 377 | }
|
---|
[13900] | 378 | if (terms.Count == 1) term = 1.0 / terms[0];
|
---|
| 379 | else term = terms.Aggregate((a, b) => new AutoDiff.Product(a, 1.0 / b));
|
---|
[13869] | 380 | return true;
|
---|
[8704] | 381 | }
|
---|
| 382 | if (node.Symbol is Logarithm) {
|
---|
| 383 | AutoDiff.Term t;
|
---|
[14232] | 384 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8704] | 385 | term = null;
|
---|
| 386 | return false;
|
---|
| 387 | } else {
|
---|
| 388 | term = AutoDiff.TermBuilder.Log(t);
|
---|
| 389 | return true;
|
---|
| 390 | }
|
---|
| 391 | }
|
---|
| 392 | if (node.Symbol is Exponential) {
|
---|
| 393 | AutoDiff.Term t;
|
---|
[14232] | 394 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8704] | 395 | term = null;
|
---|
| 396 | return false;
|
---|
| 397 | } else {
|
---|
| 398 | term = AutoDiff.TermBuilder.Exp(t);
|
---|
| 399 | return true;
|
---|
| 400 | }
|
---|
[11680] | 401 | }
|
---|
| 402 | if (node.Symbol is Square) {
|
---|
[8730] | 403 | AutoDiff.Term t;
|
---|
[14232] | 404 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8730] | 405 | term = null;
|
---|
| 406 | return false;
|
---|
| 407 | } else {
|
---|
[11680] | 408 | term = AutoDiff.TermBuilder.Power(t, 2.0);
|
---|
[8730] | 409 | return true;
|
---|
| 410 | }
|
---|
[13869] | 411 | }
|
---|
| 412 | if (node.Symbol is SquareRoot) {
|
---|
[8730] | 413 | AutoDiff.Term t;
|
---|
[14232] | 414 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8730] | 415 | term = null;
|
---|
| 416 | return false;
|
---|
| 417 | } else {
|
---|
[11680] | 418 | term = AutoDiff.TermBuilder.Power(t, 0.5);
|
---|
[8730] | 419 | return true;
|
---|
| 420 | }
|
---|
[13869] | 421 | }
|
---|
| 422 | if (node.Symbol is Sine) {
|
---|
[8730] | 423 | AutoDiff.Term t;
|
---|
[14232] | 424 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8730] | 425 | term = null;
|
---|
| 426 | return false;
|
---|
| 427 | } else {
|
---|
[11680] | 428 | term = sin(t);
|
---|
[8730] | 429 | return true;
|
---|
| 430 | }
|
---|
[13869] | 431 | }
|
---|
| 432 | if (node.Symbol is Cosine) {
|
---|
[8730] | 433 | AutoDiff.Term t;
|
---|
[14232] | 434 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8730] | 435 | term = null;
|
---|
| 436 | return false;
|
---|
| 437 | } else {
|
---|
[11680] | 438 | term = cos(t);
|
---|
[8730] | 439 | return true;
|
---|
| 440 | }
|
---|
[13869] | 441 | }
|
---|
| 442 | if (node.Symbol is Tangent) {
|
---|
[11680] | 443 | AutoDiff.Term t;
|
---|
[14232] | 444 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[11680] | 445 | term = null;
|
---|
| 446 | return false;
|
---|
| 447 | } else {
|
---|
| 448 | term = tan(t);
|
---|
| 449 | return true;
|
---|
| 450 | }
|
---|
[13869] | 451 | }
|
---|
| 452 | if (node.Symbol is Erf) {
|
---|
[8730] | 453 | AutoDiff.Term t;
|
---|
[14232] | 454 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8730] | 455 | term = null;
|
---|
| 456 | return false;
|
---|
| 457 | } else {
|
---|
| 458 | term = erf(t);
|
---|
| 459 | return true;
|
---|
| 460 | }
|
---|
[13869] | 461 | }
|
---|
| 462 | if (node.Symbol is Norm) {
|
---|
[8730] | 463 | AutoDiff.Term t;
|
---|
[14232] | 464 | if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out t)) {
|
---|
[8730] | 465 | term = null;
|
---|
| 466 | return false;
|
---|
| 467 | } else {
|
---|
| 468 | term = norm(t);
|
---|
| 469 | return true;
|
---|
| 470 | }
|
---|
| 471 | }
|
---|
[8704] | 472 | if (node.Symbol is StartSymbol) {
|
---|
| 473 | var alpha = new AutoDiff.Variable();
|
---|
| 474 | var beta = new AutoDiff.Variable();
|
---|
| 475 | variables.Add(beta);
|
---|
| 476 | variables.Add(alpha);
|
---|
| 477 | AutoDiff.Term branchTerm;
|
---|
[14232] | 478 | if (TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, variableNames, categoricalVariableValues, updateVariableWeights, out branchTerm)) {
|
---|
[8704] | 479 | term = branchTerm * alpha + beta;
|
---|
| 480 | return true;
|
---|
| 481 | } else {
|
---|
| 482 | term = null;
|
---|
| 483 | return false;
|
---|
| 484 | }
|
---|
| 485 | }
|
---|
| 486 | term = null;
|
---|
| 487 | return false;
|
---|
| 488 | }
|
---|
[8730] | 489 |
|
---|
| 490 | public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
|
---|
| 491 | var containsUnknownSymbol = (
|
---|
| 492 | from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
|
---|
| 493 | where
|
---|
| 494 | !(n.Symbol is Variable) &&
|
---|
[14232] | 495 | !(n.Symbol is FactorVariable) &&
|
---|
[8730] | 496 | !(n.Symbol is Constant) &&
|
---|
| 497 | !(n.Symbol is Addition) &&
|
---|
| 498 | !(n.Symbol is Subtraction) &&
|
---|
| 499 | !(n.Symbol is Multiplication) &&
|
---|
| 500 | !(n.Symbol is Division) &&
|
---|
| 501 | !(n.Symbol is Logarithm) &&
|
---|
| 502 | !(n.Symbol is Exponential) &&
|
---|
[11680] | 503 | !(n.Symbol is SquareRoot) &&
|
---|
| 504 | !(n.Symbol is Square) &&
|
---|
[8730] | 505 | !(n.Symbol is Sine) &&
|
---|
| 506 | !(n.Symbol is Cosine) &&
|
---|
| 507 | !(n.Symbol is Tangent) &&
|
---|
| 508 | !(n.Symbol is Erf) &&
|
---|
| 509 | !(n.Symbol is Norm) &&
|
---|
| 510 | !(n.Symbol is StartSymbol)
|
---|
| 511 | select n).
|
---|
| 512 | Any();
|
---|
| 513 | return !containsUnknownSymbol;
|
---|
| 514 | }
|
---|
[6256] | 515 | }
|
---|
| 516 | }
|
---|