Index: branches/3087_Ceres_Integration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.csproj
===================================================================
--- branches/3087_Ceres_Integration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.csproj	(revision 18006)
+++ branches/3087_Ceres_Integration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.csproj	(revision 18009)
@@ -102,4 +102,9 @@
       <SpecificVersion>False</SpecificVersion>
       <HintPath>..\..\bin\ALGLIB-3.17.0.dll</HintPath>
+      <Private>False</Private>
+    </Reference>
+    <Reference Include="HeuristicLab.Problems.DataAnalysis.Symbolic.NativeInterpreter-0.1, Version=0.0.0.1, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\bin\HeuristicLab.Problems.DataAnalysis.Symbolic.NativeInterpreter-0.1.dll</HintPath>
       <Private>False</Private>
     </Reference>
Index: branches/3087_Ceres_Integration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs
===================================================================
--- branches/3087_Ceres_Integration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs	(revision 18006)
+++ branches/3087_Ceres_Integration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs	(revision 18009)
@@ -23,9 +23,12 @@
 using System.Collections.Generic;
 using System.Linq;
+
 using HEAL.Attic;
+
 using HeuristicLab.Common;
 using HeuristicLab.Core;
 using HeuristicLab.Data;
 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
+using HeuristicLab.NativeInterpreter;
 using HeuristicLab.Optimization;
 using HeuristicLab.Parameters;
@@ -209,135 +212,55 @@
       bool updateConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
 
-      // Numeric constants in the tree become variables for parameter optimization.
-      // Variables in the tree become parameters (fixed values) for parameter optimization.
-      // For each parameter (variable in the original tree) we store the 
-      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
-      // A dictionary is used to find parameters
-      double[] initialConstants;
-      var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
-
-      TreeToAutoDiffTermConverter.ParametricFunction func;
-      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
-      if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initialConstants, out func, out func_grad))
-        throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
-      if (parameters.Count == 0) return 0.0; // constant expressions always have a R² of 0.0 
-      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
-
-      // extract inital constants
-      double[] c;
-      if (applyLinearScaling) {
-        c = new double[initialConstants.Length + 2];
-        c[0] = 0.0;
-        c[1] = 1.0;
-        Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
-      } else {
-        c = (double[])initialConstants.Clone();
-      }
-
       double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
 
-      if (counter == null) counter = new EvaluationsCounter();
-      var rowEvaluationsCounter = new EvaluationsCounter();
-
-      alglib.lsfitstate state;
-      alglib.lsfitreport rep;
-      int retVal;
-
-      IDataset ds = problemData.Dataset;
-      double[,] x = new double[rows.Count(), parameters.Count];
-      int row = 0;
-      foreach (var r in rows) {
-        int col = 0;
-        foreach (var info in parameterEntries) {
-          if (ds.VariableHasType<double>(info.variableName)) {
-            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
-          } else if (ds.VariableHasType<string>(info.variableName)) {
-            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
-          } else throw new InvalidProgramException("found a variable of unknown type");
-          col++;
-        }
-        row++;
-      }
-      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
-      int n = x.GetLength(0);
-      int m = x.GetLength(1);
-      int k = c.Length;
-
-      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
-      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
-      alglib.ndimensional_rep xrep = (p, f, obj) => iterationCallback(p, f, obj);
-
-      try {
-        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
-        alglib.lsfitsetcond(state, 0.0, maxIterations);
-        alglib.lsfitsetxrep(state, iterationCallback != null);
-        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, xrep, rowEvaluationsCounter);
-        alglib.lsfitresults(state, out retVal, out c, out rep);
-      } catch (ArithmeticException) {
-        return originalQuality;
-      } catch (alglib.alglibexception) {
-        return originalQuality;
-      }
-
-      counter.FunctionEvaluations += rowEvaluationsCounter.FunctionEvaluations / n;
-      counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n;
-
-      //retVal == -7  => constant optimization failed due to wrong gradient
-      //          -8  => optimizer detected  NAN / INF  in  the target
-      //                 function and/ or gradient
-      if (retVal != -7 && retVal != -8) {
-        if (applyLinearScaling) {
-          var tmp = new double[c.Length - 2];
-          Array.Copy(c, 2, tmp, 0, tmp.Length);
-          UpdateConstants(tree, tmp, updateVariableWeights);
-        } else UpdateConstants(tree, c, updateVariableWeights);
-      }
+      var nodesToOptimize = new HashSet<ISymbolicExpressionTreeNode>();
+      var originalNodeValues = new Dictionary<ISymbolicExpressionTreeNode, double>();
+
+      foreach (var node in tree.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
+        if (node is VariableTreeNode && !updateVariableWeights) {
+          continue;
+        }
+        if (node is ConstantTreeNode && node.Parent.Symbol is Power && node.Parent.GetSubtree(0) == node) {
+          // do not optimize exponents
+          continue;
+        }
+        nodesToOptimize.Add(node);
+        if (node is ConstantTreeNode constant) {
+          originalNodeValues[node] = constant.Value;
+        } else if (node is VariableTreeNode variable) {
+          originalNodeValues[node] = variable.Weight;
+        }
+      }
+
+      var options = new SolverOptions {
+        Iterations = maxIterations
+      };
+      var summary = new OptimizationSummary();
+      var optimizedNodeValues = ParameterOptimizer.OptimizeTree(tree, problemData.Dataset, problemData.TrainingIndices, problemData.TargetVariable, nodesToOptimize, options, ref summary);
+
+      counter.FunctionEvaluations += summary.ResidualEvaluations;
+      counter.GradientEvaluations += summary.JacobianEvaluations;
+
+      // check if the fitting of the parameters was successful
+      UpdateNodeValues(optimizedNodeValues);
+      
       var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
-
-      if (!updateConstantsInTree) UpdateConstants(tree, initialConstants, updateVariableWeights);
-
-      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
-        UpdateConstants(tree, initialConstants, updateVariableWeights);
-        return originalQuality;
-      }
-      return quality;
-    }
-
-    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
-      int i = 0;
-      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
-        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
-        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
-        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
-        if (constantTreeNode != null) {
-          if (constantTreeNode.Parent.Symbol is Power 
-              && constantTreeNode.Parent.GetSubtree(1) == constantTreeNode) continue; // exponents in powers are not optimizated (see TreeToAutoDiffTermConverter)
-          constantTreeNode.Value = constants[i++];
-        } else if (updateVariableWeights && variableTreeNodeBase != null)
-          variableTreeNodeBase.Weight = constants[i++];
-        else if (factorVarTreeNode != null) {
-          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
-            factorVarTreeNode.Weights[j] = constants[i++];
-        }
-      }
-    }
-
-    private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
-      return (double[] c, double[] x, ref double fx, object o) => {
-        fx = func(c, x);
-        var counter = (EvaluationsCounter)o;
-        counter.FunctionEvaluations++;
-      };
-    }
-
-    private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
-      return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
-        var tuple = func_grad(c, x);
-        fx = tuple.Item2;
-        Array.Copy(tuple.Item1, grad, grad.Length);
-        var counter = (EvaluationsCounter)o;
-        counter.GradientEvaluations++;
-      };
-    }
+      if (quality < originalQuality || !updateConstantsInTree) {
+        UpdateNodeValues(originalNodeValues);
+      }
+      return Math.Max(quality, originalQuality);
+    }
+
+    private static void UpdateNodeValues(IDictionary<ISymbolicExpressionTreeNode, double> values) {
+      foreach (var item in values) {
+        var node = item.Key;
+        if (node is ConstantTreeNode constant) {
+          constant.Value = item.Value;
+        } else if (node is VariableTreeNode variable) {
+          variable.Weight = item.Value;
+        }
+      }
+    }
+
     public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
       return TreeToAutoDiffTermConverter.IsCompatible(tree);
