public static void Sample1() { // Variables. The string names are added for convenience when printing out the optimal point with Point.ToString(). Variable x = new Variable("x"); Variable y = new Variable("y"); // Rosenbrock function http://en.wikipedia.org/wiki/Rosenbrock_function. Function f = Function.Sqr(1.0 - x) + 100.0 * Function.Sqr(y - Function.Sqr(x)); // Use the BFGS optimizer. BfgsOptimizer o = new BfgsOptimizer(); // Specify variables and objective functions and add constraints. Derivatives are computed automatically. o.Variables.Add(x, y); o.VariableConstraints.Add(x >= 0.0, y >= 0.0); o.ObjectiveFunction = f; // Start optimizer from a random point. Random r = new Random(1); IOptimizerResult or = o.Run(x | r.NextDouble(), y | r.NextDouble()); // Show convergence status and optimal point and value. Console.WriteLine(or.Status); Console.WriteLine(or.OptimalPoint); Console.WriteLine(or.OptimalValue); // The result object also contains BFGS convergence status. Console.WriteLine(((BfgsOptimizerResult)or).ConvergenceStatus); // We may use Prepare if we need to run the optimizer from multiple starting points. PreparedOptimizer o2 = o.Prepare(); for (int i = 0; i < 10; i++) { IOptimizerResult or2 = o2.Run(x | r.NextDouble(), y | r.NextDouble()); Console.WriteLine(or2.OptimalPoint); } }
public InnerBfgsOptimizer(BfgsOptimizer optimizer) : base(optimizer) { function = ObjectiveFunction * ObjectiveFunctionScaling; n = Variables.Count; if (optimizer.BfgsCorrections.HasValue) { m = optimizer.BfgsCorrections.Value; if (m < 0 || m > n) { throw new OptimizerException("Invalid number of BFGS corrections."); } } else { // Use the maximally recommended number of corrections in the BFGS scheme. m = Math.Min(7, n); } gradient = new Function[n]; for (int i = 0; i < n; i++) { gradient[i] = function.Derivative(Variables[i]); } epsG = optimizer.EpsG; epsF = optimizer.EpsF; epsX = optimizer.EpsX; maxIterations = optimizer.MaxIterations; nbd = new int[n + 1]; l = new double[n + 1]; u = new double[n + 1]; foreach (VariableConstraint constraint in VariableConstraints) { int i = Variables.IndexOf(constraint.Variable) + 1; double minValue = constraint.MinValue; double maxValue = constraint.MaxValue; if (!double.IsNegativeInfinity(minValue)) { // Has lower boundary. nbd[i] = 1; l[i] = minValue; } if (!double.IsPositiveInfinity(maxValue)) { // Has upper boundary. nbd[i] = 3; u[i] = maxValue; } if (!double.IsNegativeInfinity(minValue) && !double.IsPositiveInfinity(maxValue)) { // Has both lower and upper boundaries (values are already defined). nbd[i] = 2; } } }