Index: /branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/ConstrainedConstantOptimizationEvaluator.cs
===================================================================
--- /branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/ConstrainedConstantOptimizationEvaluator.cs	(revision 16914)
+++ /branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/ConstrainedConstantOptimizationEvaluator.cs	(revision 16914)
@@ -0,0 +1,502 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HEAL.Attic;
+
+namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
+  [Item("Constant Optimization Evaluator (with constraints)", "")]
+  [StorableType("A8958E06-C54A-4193-862E-8315C86EB5C1")]
+  public class ConstrainedConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
+    private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
+    private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
+    private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
+    private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
+    private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
+    private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
+
+    private const string FunctionEvaluationsResultParameterName = "Constants Optimization Function Evaluations";
+    private const string GradientEvaluationsResultParameterName = "Constants Optimization Gradient Evaluations";
+    private const string CountEvaluationsParameterName = "Count Function and Gradient Evaluations";
+
+    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
+      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
+    }
+    public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
+      get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
+    }
+    public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
+      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
+    }
+    public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
+      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
+    }
+    public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
+      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
+    }
+    public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
+      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
+    }
+
+    public IResultParameter<IntValue> FunctionEvaluationsResultParameter {
+      get { return (IResultParameter<IntValue>)Parameters[FunctionEvaluationsResultParameterName]; }
+    }
+    public IResultParameter<IntValue> GradientEvaluationsResultParameter {
+      get { return (IResultParameter<IntValue>)Parameters[GradientEvaluationsResultParameterName]; }
+    }
+    public IFixedValueParameter<BoolValue> CountEvaluationsParameter {
+      get { return (IFixedValueParameter<BoolValue>)Parameters[CountEvaluationsParameterName]; }
+    }
+
+
+    public IntValue ConstantOptimizationIterations {
+      get { return ConstantOptimizationIterationsParameter.Value; }
+    }
+    public DoubleValue ConstantOptimizationImprovement {
+      get { return ConstantOptimizationImprovementParameter.Value; }
+    }
+    public PercentValue ConstantOptimizationProbability {
+      get { return ConstantOptimizationProbabilityParameter.Value; }
+    }
+    public PercentValue ConstantOptimizationRowsPercentage {
+      get { return ConstantOptimizationRowsPercentageParameter.Value; }
+    }
+    public bool UpdateConstantsInTree {
+      get { return UpdateConstantsInTreeParameter.Value.Value; }
+      set { UpdateConstantsInTreeParameter.Value.Value = value; }
+    }
+
+    public bool UpdateVariableWeights {
+      get { return UpdateVariableWeightsParameter.Value.Value; }
+      set { UpdateVariableWeightsParameter.Value.Value = value; }
+    }
+
+    public bool CountEvaluations {
+      get { return CountEvaluationsParameter.Value.Value; }
+      set { CountEvaluationsParameter.Value.Value = value; }
+    }
+
+    public override bool Maximization {
+      get { return false; }
+    }
+
+    [StorableConstructor]
+    protected ConstrainedConstantOptimizationEvaluator(StorableConstructorFlag _) : base(_) { }
+    protected ConstrainedConstantOptimizationEvaluator(ConstrainedConstantOptimizationEvaluator original, Cloner cloner)
+      : base(original, cloner) {
+    }
+    public ConstrainedConstantOptimizationEvaluator()
+      : base() {
+      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)));
+      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)) { Hidden = true });
+      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1)));
+      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1)));
+      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 });
+      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
+
+      Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
+      Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
+      Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
+    }
+
+    public override IDeepCloneable Clone(Cloner cloner) {
+      return new ConstrainedConstantOptimizationEvaluator(this, cloner);
+    }
+
+    [StorableHook(HookType.AfterDeserialization)]
+    private void AfterDeserialization() { }
+
+    private static readonly object locker = new object();
+
+    public override IOperation InstrumentedApply() {
+      var solution = SymbolicExpressionTreeParameter.ActualValue;
+      double quality;
+      if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
+        IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
+        var counter = new EvaluationsCounter();
+        quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
+           constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree, counter: counter);
+
+        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
+          var evaluationRows = GenerateRowsToEvaluate();
+          quality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, double.MinValue, double.MaxValue, ProblemDataParameter.ActualValue, evaluationRows, applyLinearScaling: false);
+        }
+
+        if (CountEvaluations) {
+          lock (locker) {
+            FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
+            GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
+          }
+        }
+
+      } else {
+        var evaluationRows = GenerateRowsToEvaluate();
+        quality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, double.MinValue, double.MaxValue, ProblemDataParameter.ActualValue, evaluationRows, applyLinearScaling: false);
+      }
+      QualityParameter.ActualValue = new DoubleValue(quality);
+
+      return base.InstrumentedApply();
+    }
+
+    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
+      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
+      EstimationLimitsParameter.ExecutionContext = context;
+      ApplyLinearScalingParameter.ExecutionContext = context;
+      FunctionEvaluationsResultParameter.ExecutionContext = context;
+      GradientEvaluationsResultParameter.ExecutionContext = context;
+
+      // MSE evaluator is used on purpose instead of the const-opt evaluator, 
+      // because Evaluate() is used to get the quality of evolved models on 
+      // different partitions of the dataset (e.g., best validation model)
+      double mse = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, double.MinValue, double.MaxValue, problemData, rows, applyLinearScaling: false);
+
+      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
+      EstimationLimitsParameter.ExecutionContext = null;
+      ApplyLinearScalingParameter.ExecutionContext = null;
+      FunctionEvaluationsResultParameter.ExecutionContext = null;
+      GradientEvaluationsResultParameter.ExecutionContext = null;
+
+      return mse;
+    }
+
+    public class EvaluationsCounter {
+      public int FunctionEvaluations = 0;
+      public int GradientEvaluations = 0;
+    }
+
+    private static void GetParameterNodes(ISymbolicExpressionTree tree, out List<ISymbolicExpressionTreeNode> thetaNodes, out List<double> thetaValues) {
+      thetaNodes = new List<ISymbolicExpressionTreeNode>();
+      thetaValues = new List<double>();
+
+      var nodes = tree.IterateNodesPrefix().ToArray();
+      for (int i = 0; i < nodes.Length; ++i) {
+        var node = nodes[i];
+        if (node is VariableTreeNode variableTreeNode) {
+          thetaValues.Add(variableTreeNode.Weight);
+          thetaNodes.Add(node);
+        } else if (node is ConstantTreeNode constantTreeNode) {
+          thetaNodes.Add(node);
+          thetaValues.Add(constantTreeNode.Value);
+        }
+      }
+    }
+
+    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, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
+
+      if (!updateVariableWeights) throw new NotSupportedException("not updating variable weights is not supported");
+      if (!updateConstantsInTree) throw new NotSupportedException("not updating tree parameters is not supported");
+      if (applyLinearScaling) throw new NotSupportedException("linear scaling is not supported");
+
+      // we always update constants, so we don't need to calculate initial quality
+      // double originalQuality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
+
+      if (counter == null) counter = new EvaluationsCounter();
+      var rowEvaluationsCounter = new EvaluationsCounter();
+
+      var intervalConstraints = problemData.IntervalConstraints;
+      var dataIntervals = problemData.VariableRanges.VariableIntervals;
+
+      // convert constants to variables named theta...
+      var treeForDerivation = ReplaceConstWithVar(tree, out List<string> thetaNames, out List<double> thetaValues); // copies the tree
+
+      // create trees for relevant derivatives
+      Dictionary<string, ISymbolicExpressionTree> derivatives = new Dictionary<string, ISymbolicExpressionTree>();
+      var allThetaNodes = thetaNames.Select(_ => new List<ConstantTreeNode>()).ToArray();
+      var constraintTrees = new List<ISymbolicExpressionTree>();
+      foreach (var constraint in intervalConstraints.Constraints) {
+        if (constraint.IsDerivation) {
+          if (!problemData.AllowedInputVariables.Contains(constraint.Variable))
+            throw new ArgumentException($"Invalid constraint: the variable {constraint.Variable} does not exist in the dataset.");
+          var df = DerivativeCalculator.Derive(treeForDerivation, constraint.Variable);
+
+          // alglib requires constraint expressions of the form c(x) <= 0
+          // -> we make two expressions, one for the lower bound and one for the upper bound
+
+          if (constraint.Interval.UpperBound < double.PositiveInfinity) {
+            var df_smaller_upper = Subtract((ISymbolicExpressionTree)df.Clone(), CreateConstant(constraint.Interval.UpperBound));
+            // convert variables named theta back to constants
+            var df_prepared = ReplaceVarWithConst(df_smaller_upper, thetaNames, thetaValues, allThetaNodes);
+            constraintTrees.Add(df_prepared);
+          }
+          if (constraint.Interval.LowerBound > double.NegativeInfinity) {
+            var df_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)df.Clone());
+            // convert variables named theta back to constants
+            var df_prepared = ReplaceVarWithConst(df_larger_lower, thetaNames, thetaValues, allThetaNodes);
+            constraintTrees.Add(df_prepared);
+          }
+        } else {
+          if (constraint.Interval.UpperBound < double.PositiveInfinity) {
+            var f_smaller_upper = Subtract((ISymbolicExpressionTree)treeForDerivation.Clone(), CreateConstant(constraint.Interval.UpperBound));
+            // convert variables named theta back to constants
+            var df_prepared = ReplaceVarWithConst(f_smaller_upper, thetaNames, thetaValues, allThetaNodes);
+            constraintTrees.Add(df_prepared);
+          }
+          if (constraint.Interval.LowerBound > double.NegativeInfinity) {
+            var f_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)treeForDerivation.Clone());
+            // convert variables named theta back to constants
+            var df_prepared = ReplaceVarWithConst(f_larger_lower, thetaNames, thetaValues, allThetaNodes);
+            constraintTrees.Add(df_prepared);
+          }
+        }
+      }
+
+      var preparedTree = ReplaceVarWithConst(treeForDerivation, thetaNames, thetaValues, allThetaNodes);
+
+
+      // local function
+      void UpdateThetaValues(double[] theta) {
+        for (int i = 0; i < theta.Length; ++i) {
+          foreach (var constNode in allThetaNodes[i]) constNode.Value = theta[i];
+        }
+      }
+
+      // buffers for calculate_jacobian
+      var target = problemData.TargetVariableTrainingValues.ToArray();
+      var fi_eval = new double[target.Length];
+      var jac_eval = new double[target.Length, thetaValues.Count];
+
+      // define the callback used by the alglib optimizer
+      // the x argument for this callback represents our theta
+      // local function
+      void calculate_jacobian(double[] x, double[] fi, double[,] jac, object obj) {
+        UpdateThetaValues(x);
+
+        var autoDiffEval = new VectorAutoDiffEvaluator();
+        autoDiffEval.Evaluate(preparedTree, problemData.Dataset, problemData.TrainingIndices.ToArray(),
+          GetParameterNodes(preparedTree, allThetaNodes), fi_eval, jac_eval);
+
+        // calc sum of squared errors and gradient
+        var sse = 0.0;
+        var g = new double[x.Length];
+        for (int i = 0; i < target.Length; i++) {
+          var res = target[i] - fi_eval[i];
+          sse += 0.5 * res * res;
+          for (int j = 0; j < g.Length; j++) {
+            g[j] -= res * jac_eval[i, j];
+          }
+        }
+
+        fi[0] = sse / target.Length;
+        for (int j = 0; j < x.Length; j++) { jac[0, j] = g[j] / target.Length; }
+
+        var intervalEvaluator = new IntervalEvaluator();
+        for (int i = 0; i < constraintTrees.Count; i++) {
+          var interval = intervalEvaluator.Evaluate(constraintTrees[i], dataIntervals, GetParameterNodes(constraintTrees[i], allThetaNodes),
+            out double[] lowerGradient, out double[] upperGradient);
+
+          // we transformed this to a constraint c(x) <= 0, so only the upper bound is relevant for us
+          fi[i + 1] = interval.UpperBound;
+          for (int j = 0; j < x.Length; j++) {
+            jac[i + 1, j] = upperGradient[j];
+          }
+        }
+      }
+
+
+
+      alglib.minnlcstate state;
+      alglib.minnlcreport rep;
+      try {
+        alglib.minnlccreate(thetaValues.Count, thetaValues.ToArray(), out state);
+        alglib.minnlcsetalgoslp(state);        // SLP is more robust but slower
+        alglib.minnlcsetcond(state, 0, maxIterations);
+        var s = Enumerable.Repeat(1d, thetaValues.Count).ToArray();  // scale is set to unit scale
+        alglib.minnlcsetscale(state, s);
+
+        // set non-linear constraints: 0 equality constraints, constraintTrees inequality constraints
+        alglib.minnlcsetnlc(state, 0, constraintTrees.Count);
+
+        alglib.minnlcoptimize(state, calculate_jacobian, null, null);
+        alglib.minnlcresults(state, out double[] xOpt, out rep);
+
+
+        // counter.FunctionEvaluations += rep.nfev; TODO
+        counter.GradientEvaluations += rep.nfev;
+
+        if (rep.terminationtype != -8) {
+          // update parameters in tree
+          var pIdx = 0;
+          foreach (var node in tree.IterateNodesPostfix().OfType<ConstantTreeNode>()) {
+            node.Value = xOpt[pIdx++];
+          }
+
+          // note: we keep the optimized constants even when the tree is worse.
+        }
+
+      } catch (ArithmeticException) {
+        // eval MSE of original tree
+        return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
+
+      } catch (alglib.alglibexception) {
+        // eval MSE of original tree
+        return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
+      }
+
+
+      // evaluate tree with updated constants
+      return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
+    }
+
+    #region helper
+    private static ISymbolicExpressionTreeNode[] GetParameterNodes(ISymbolicExpressionTree tree, List<ConstantTreeNode>[] allNodes) {
+      // TODO better solution necessary
+      var treeConstNodes = tree.IterateNodesPostfix().OfType<ConstantTreeNode>().ToArray();
+      var paramNodes = new ISymbolicExpressionTreeNode[allNodes.Length];
+      for (int i = 0; i < paramNodes.Length; i++) {
+        paramNodes[i] = allNodes[i].SingleOrDefault(n => treeConstNodes.Contains(n));
+      }
+      return paramNodes;
+    }
+
+    private static ISymbolicExpressionTree ReplaceVarWithConst(ISymbolicExpressionTree tree, List<string> thetaNames, List<double> thetaValues, List<ConstantTreeNode>[] thetaNodes) {
+      var copy = (ISymbolicExpressionTree)tree.Clone();
+      var nodes = copy.IterateNodesPostfix().ToList();
+      for (int i = 0; i < nodes.Count; i++) {
+        var n = nodes[i] as VariableTreeNode;
+        if (n != null) {
+          var thetaIdx = thetaNames.IndexOf(n.VariableName);
+          if (thetaIdx >= 0) {
+            var parent = n.Parent;
+            if (thetaNodes[thetaIdx].Any()) {
+              // HACK: REUSE CONSTANT TREE NODE IN SEVERAL TREES
+              // we use this trick to allow autodiff over thetas when thetas occurr multiple times in the tree (e.g. in derived trees)
+              var constNode = thetaNodes[thetaIdx].First();
+              var childIdx = parent.IndexOfSubtree(n);
+              parent.RemoveSubtree(childIdx);
+              parent.InsertSubtree(childIdx, constNode);
+            } else {
+              var constNode = (ConstantTreeNode)CreateConstant(thetaValues[thetaIdx]);
+              var childIdx = parent.IndexOfSubtree(n);
+              parent.RemoveSubtree(childIdx);
+              parent.InsertSubtree(childIdx, constNode);
+              thetaNodes[thetaIdx].Add(constNode);
+            }
+          }
+        }
+      }
+      return copy;
+    }
+
+    private static ISymbolicExpressionTree ReplaceConstWithVar(ISymbolicExpressionTree tree, out List<string> thetaNames, out List<double> thetaValues) {
+      thetaNames = new List<string>();
+      thetaValues = new List<double>();
+      var copy = (ISymbolicExpressionTree)tree.Clone();
+      var nodes = copy.IterateNodesPostfix().ToList();
+
+      int n = 1;
+      for (int i = 0; i < nodes.Count; ++i) {
+        var node = nodes[i];
+        if (node is ConstantTreeNode constantTreeNode) {
+          var thetaVar = (VariableTreeNode)new Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
+          thetaVar.Weight = 1;
+          thetaVar.VariableName = $"θ{n++}";
+
+          thetaNames.Add(thetaVar.VariableName);
+          thetaValues.Add(constantTreeNode.Value);
+
+          var parent = constantTreeNode.Parent;
+          if (parent != null) {
+            var index = constantTreeNode.Parent.IndexOfSubtree(constantTreeNode);
+            parent.RemoveSubtree(index);
+            parent.InsertSubtree(index, thetaVar);
+          }
+        }
+      }
+      return copy;
+    }
+
+    private static ISymbolicExpressionTreeNode CreateConstant(double value) {
+      var constantNode = (ConstantTreeNode)new Constant().CreateTreeNode();
+      constantNode.Value = value;
+      return constantNode;
+    }
+
+    private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTree t, ISymbolicExpressionTreeNode b) {
+      var sub = MakeNode<Subtraction>(t.Root.GetSubtree(0).GetSubtree(0), b);
+      t.Root.GetSubtree(0).RemoveSubtree(0);
+      t.Root.GetSubtree(0).InsertSubtree(0, sub);
+      return t;
+    }
+    private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTreeNode b, ISymbolicExpressionTree t) {
+      var sub = MakeNode<Subtraction>(b, t.Root.GetSubtree(0).GetSubtree(0));
+      t.Root.GetSubtree(0).RemoveSubtree(0);
+      t.Root.GetSubtree(0).InsertSubtree(0, sub);
+      return t;
+    }
+
+    private static ISymbolicExpressionTreeNode MakeNode<T>(params ISymbolicExpressionTreeNode[] fs) where T : ISymbol, new() {
+      var node = new T().CreateTreeNode();
+      foreach (var f in fs) node.AddSubtree(f);
+      return node;
+    }
+    #endregion
+
+    private static void UpdateConstants(ISymbolicExpressionTreeNode[] nodes, double[] constants) {
+      if (nodes.Length != constants.Length) throw new InvalidOperationException();
+      for (int i = 0; i < nodes.Length; i++) {
+        if (nodes[i] is VariableTreeNode varNode) varNode.Weight = constants[i];
+        else if (nodes[i] is ConstantTreeNode constNode) constNode.Value = constants[i];
+      }
+    }
+
+    private static alglib.ndimensional_fvec CreateFunc(ISymbolicExpressionTree tree, VectorEvaluator eval, ISymbolicExpressionTreeNode[] parameterNodes, IDataset ds, string targetVar, int[] rows) {
+      var y = ds.GetDoubleValues(targetVar, rows).ToArray();
+      return (double[] c, double[] fi, object o) => {
+        UpdateConstants(parameterNodes, c);
+        var pred = eval.Evaluate(tree, ds, rows);
+        for (int i = 0; i < fi.Length; i++)
+          fi[i] = pred[i] - y[i];
+
+        var counter = (EvaluationsCounter)o;
+        counter.FunctionEvaluations++;
+      };
+    }
+
+    private static alglib.ndimensional_jac CreateJac(ISymbolicExpressionTree tree, VectorAutoDiffEvaluator eval, ISymbolicExpressionTreeNode[] parameterNodes, IDataset ds, string targetVar, int[] rows) {
+      var y = ds.GetDoubleValues(targetVar, rows).ToArray();
+      return (double[] c, double[] fi, double[,] jac, object o) => {
+        UpdateConstants(parameterNodes, c);
+        eval.Evaluate(tree, ds, rows, parameterNodes, fi, jac);
+
+        for (int i = 0; i < fi.Length; i++)
+          fi[i] -= y[i];
+
+        var counter = (EvaluationsCounter)o;
+        counter.GradientEvaluations++;
+      };
+    }
+    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
+      return TreeToAutoDiffTermConverter.IsCompatible(tree);
+    }
+  }
+}
Index: /branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Extensions.csproj
===================================================================
--- /branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Extensions.csproj	(revision 16913)
+++ /branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Extensions.csproj	(revision 16914)
@@ -9,5 +9,5 @@
     <AppDesignerFolder>Properties</AppDesignerFolder>
     <RootNamespace>HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Extensions</RootNamespace>
-    <AssemblyName>HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Extensions</AssemblyName>
+    <AssemblyName>HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Extensions-0.1</AssemblyName>
     <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
@@ -18,5 +18,5 @@
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-    <OutputPath>..\..\bin\</OutputPath>
+    <OutputPath>..\bin\</OutputPath>
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -26,5 +26,5 @@
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-    <OutputPath>..\..\bin\</OutputPath>
+    <OutputPath>..\bin\</OutputPath>
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -40,16 +40,21 @@
     <Reference Include="ALGLIB-3.15.0">
       <HintPath>..\bin\ALGLIB-3.15.0.dll</HintPath>
+      <Private>False</Private>
     </Reference>
     <Reference Include="HEAL.Attic">
       <HintPath>..\bin\HEAL.Attic.dll</HintPath>
+      <Private>False</Private>
     </Reference>
     <Reference Include="HeuristicLab.Problems.DataAnalysis-3.4">
       <HintPath>..\bin\HeuristicLab.Problems.DataAnalysis-3.4.dll</HintPath>
+      <Private>False</Private>
     </Reference>
     <Reference Include="HeuristicLab.Problems.DataAnalysis.Symbolic-3.4">
       <HintPath>..\bin\HeuristicLab.Problems.DataAnalysis.Symbolic-3.4.dll</HintPath>
+      <Private>False</Private>
     </Reference>
     <Reference Include="HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4">
       <HintPath>..\bin\HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.dll</HintPath>
+      <Private>False</Private>
     </Reference>
     <Reference Include="System" />
@@ -63,4 +68,6 @@
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="ConstrainedConstantOptimizationEvaluator.cs" />
+    <Compile Include="Plugin.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="SymbolicRegressionNewConstantOptimizationEvaluator.cs" />
@@ -75,32 +82,44 @@
       <Project>{958b43bc-cc5c-4fa2-8628-2b3b01d890b6}</Project>
       <Name>HeuristicLab.Collections-3.3</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Common\3.3\HeuristicLab.Common-3.3.csproj">
       <Project>{a9ad58b9-3ef9-4cc1-97e5-8d909039ff5c}</Project>
       <Name>HeuristicLab.Common-3.3</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Core\3.3\HeuristicLab.Core-3.3.csproj">
       <Project>{c36bd924-a541-4a00-afa8-41701378ddc5}</Project>
       <Name>HeuristicLab.Core-3.3</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Data\3.3\HeuristicLab.Data-3.3.csproj">
       <Project>{bbab9df5-5ef3-4ba8-ade9-b36e82114937}</Project>
       <Name>HeuristicLab.Data-3.3</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding\3.4\HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj">
       <Project>{06d4a186-9319-48a0-bade-a2058d462eea}</Project>
       <Name>HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Operators\3.3\HeuristicLab.Operators-3.3.csproj">
       <Project>{23da7ff4-d5b8-41b6-aa96-f0561d24f3ee}</Project>
       <Name>HeuristicLab.Operators-3.3</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Optimization\3.3\HeuristicLab.Optimization-3.3.csproj">
       <Project>{14ab8d24-25bc-400c-a846-4627aa945192}</Project>
       <Name>HeuristicLab.Optimization-3.3</Name>
+      <Private>False</Private>
     </ProjectReference>
     <ProjectReference Include="..\HeuristicLab.Parameters\3.3\HeuristicLab.Parameters-3.3.csproj">
       <Project>{56f9106a-079f-4c61-92f6-86a84c2d84b7}</Project>
       <Name>HeuristicLab.Parameters-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\HeuristicLab.PluginInfrastructure\3.3\HeuristicLab.PluginInfrastructure-3.3.csproj">
+      <Project>{94186a6a-5176-4402-ae83-886557b53cca}</Project>
+      <Name>HeuristicLab.PluginInfrastructure-3.3</Name>
     </ProjectReference>
   </ItemGroup>
