[TOC]
using System;
using System.Collections.Generic;
using System.Text;
using CenterSpace.NMath.Core;
using CenterSpace.NMath.Analysis;
namespace TrustRegionMinimizationExample
{
class TrustRegionMinimizationExample
{
/// <summary>
/// A .NET example in C# showing how to minimize a function using the Trust Region
/// method.
/// </summary>
static void Main(string[] args)
{
Console.WriteLine();
// Minimization in this context means finding the solution that evaluates to the vector with the smallest
// two norm (distance from origin).
// Wrap the function to minimize in a delegate. MyFunction() that has three input variables and four
// output variables
NMathFunctions.DoubleVectorDoubleVectorFunction f = new NMathFunctions.DoubleVectorDoubleVectorFunction(MyFunction);
int ydim = 4;
// Choose a starting point
DoubleVector start = new DoubleVector(50.0, 30.0, -1000.0);
// Create a minimizer with default tolerance and maximum iterations.
TrustRegionMinimizer minimizer = new TrustRegionMinimizer();
// Compute the solution and display the results.
DoubleVector solution = minimizer.Minimize(f, start, ydim);
Console.WriteLine("The minimizer started at ");
Console.WriteLine(start);
Console.WriteLine("with a residual of " + minimizer.InitialResidual);
Console.WriteLine();
Console.WriteLine("After " + minimizer.Iterations + " iterations, it reached a solution at");
Console.WriteLine(solution);
Console.WriteLine("with a residual of " + minimizer.FinalResidual);
Console.WriteLine();
Console.WriteLine("It stopped because " + minimizer.StopCriterion + ".");
// Add some constraints. Set a lower bound to (0, 0, 0) and an upper bound to (10, 10, 10)
DoubleVector lowerBounds = new DoubleVector(3);
DoubleVector upperBounds = new DoubleVector(3, 10.0);
// Minimize again, and display the result.
solution = minimizer.Minimize(f, start, ydim, lowerBounds, upperBounds);
Console.WriteLine();
Console.WriteLine("Lower bounds = " + lowerBounds);
Console.WriteLine("Upper bounds = " + upperBounds);
Console.WriteLine("The solution is at");
Console.WriteLine(solution);
Console.WriteLine("with a residual of " + minimizer.FinalResidual);
Console.WriteLine();
Console.WriteLine("Press Enter Key");
Console.Read();
} // Main
// The function to minimize
private static DoubleVector MyFunction(DoubleVector x)
{
DoubleVector y = new DoubleVector(4);
y[0] = 5 * x[1] * x[1] + x[2] * x[2];
y[1] = 4 * x[0] * x[0] - x[2] * x[2] + 45;
y[2] = x[0] * 3 * x[0] - x[1] * x[1] + 9;
y[3] = y[0] + y[1] + y[2] * y[2] - 43;
return y;
}
}
}
[TOC]