C# .Net Program to Find a Function Minimum

Using the Hooke-Jeeves Directional Search Method

by Namir Shammas

The following program calculates the minimum point of a multi-variable function using the Hooke-Jeeves directional search method.

Click here to download a ZIP file containing the project files for this program.

The program prompts you to either use the predefined default input values or to enter the following for each variable:

1. Guess for the minimum point.

2. Initial search step value.

3. The minimum search step value.

In case you choose the default input values, the program displays these values and proceeds to find the optimum point. In the case you select being prompted, the program displays the name of each input variable along with its default value. You can then either enter a new value or simply press Enter to use the default value. This approach allows you to quickly and efficiently change only a few input values if you so desire.

The program displays the following final results:

1. The coordinates of the minimum value.

2. The minimum function value.

3. The number of iterations

The current code finds the minimum for the following function:

f(x1,x2) = x1 - x2 + 2 * x1 ^ 2 + 2 * x1 * x2 + x2 ^ 2

Using, for each variable, an initial value of 0,  initial step size of 0.1, minimum step size of 1e-7, and using a function tolerance of 1e-7. Here is the sample console screen:

Here is the listing for the main module.  The module contains several test functions: 

using System.Diagnostics;
using System.Data;
using System.Collections;
using Microsoft.VisualBasic;
using System.Collections.Generic;
using System;

namespace Optim_HookJeevesSearch
{
	sealed class Module1
	{
		
		static public void Main()
		{
			int nNumVars = 2;
			double[] fX = new double[] { 0, 0 };
			double[] fParam = new double[] { 0, 0 };
			double[] fStepSize = new double[] { 0.1, 0.1 };
			double[] fMinStepSize = new double[] { 0.0000001, 0.0000001 };
			int nIter = 0;
			double fEpsFx = 0.0000001;
			int i;
			object fBestF;
			string sAnswer;
			CHookJeevesSearch1 oOpt;
			MyFxDelegate MyFx = new MyFxDelegate( Fx3);
			SayFxDelegate SayFx = new SayFxDelegate( SayFx3);
			
			oOpt = new CHookJeevesSearch1();
			
			Console.WriteLine("Hooke-Jeeves Search Optimization");
			Console.WriteLine("Finding the minimum of function:");
			Console.WriteLine(SayFx());
			Console.Write("Use default input values? (Y/N) ");
			sAnswer = Console.ReadLine();
			if (sAnswer.ToUpper() == "Y")
			{
				for (i = 0; i < nNumVars; i++)
				{
					Console.WriteLine("X({0}) = {1}", i + 1, fX[i]);
					Console.WriteLine("Step size({0}) = {1}", i + 1, fStepSize[i]);
					Console.WriteLine("Min step Size ({0}) = {1}", i + 1, fMinStepSize[i]);
				}
				Console.WriteLine("Function tolerance = {0}", fEpsFx);
			}
			else
			{
				for (i = 0; i < nNumVars; i++)
				{
					fX[i] = GetIndexedDblInput("X", i + 1, fX[i]);
					fStepSize[i] = GetIndexedDblInput("Step size", i + 1, fStepSize[i]);
					fMinStepSize[i] = GetIndexedDblInput("Min step size", i + 1, fMinStepSize[i]);
				}
				fEpsFx = GetDblInput("Function tolerance", fEpsFx);
			}
			
			Console.WriteLine("******** FINAL RESULTS *************");
			fBestF = oOpt.CalcOptim(nNumVars, ref fX, ref fParam, ref fStepSize, ref fMinStepSize, fEpsFx, ref nIter, MyFx);
			Console.WriteLine("Optimum at");
			for (i = 0; i < nNumVars; i++)
			{
				Console.WriteLine("X({0}) = {1}", i + 1, fX[i]);
			}
			Console.WriteLine("Function value = {0}", fBestF);
			Console.WriteLine("Number of iterations = {0}", nIter);
			Console.WriteLine();
			Console.Write("Press Enter to end the program ...");
			Console.ReadLine();
		}
		
		static public double GetDblInput(string sPrompt, double fDefInput)
		{
			string sInput;
			
			Console.Write("{0}? ({1}): ", sPrompt, fDefInput);
			sInput = Console.ReadLine();
			if (sInput.Trim(null).Length > 0)
			{
				return double.Parse(sInput);
			}
			else
			{
				return fDefInput;
			}
		}
		
		static public int GetIntInput(string sPrompt, int nDefInput)
		{
			string sInput;
			
			Console.Write("{0}? ({1}): ", sPrompt, nDefInput);
			sInput = Console.ReadLine();
			if (sInput.Trim(null).Length > 0)
			{
				return  (int) double.Parse(sInput);
			}
			else
			{
				return nDefInput;
			}
		}
		
		static public double GetIndexedDblInput(string sPrompt, int nIndex, double fDefInput)
		{
			string sInput;
			
			Console.Write("{0}({1})? ({2}): ", sPrompt, nIndex, fDefInput);
			sInput = Console.ReadLine();
			if (sInput.Trim(null).Length > 0)
			{
				return double.Parse(sInput);
			}
			else
			{
				return fDefInput;
			}
		}
		
		static public int GetIndexedIntInput(string sPrompt, int nIndex, int nDefInput)
		{
			string sInput;
			
			Console.Write("{0}({1})? ({2}): ", sPrompt, nIndex, nDefInput);
			sInput = Console.ReadLine();
			if (sInput.Trim(null).Length > 0)
			{
				return  (int) double.Parse(sInput);
			}
			else
			{
				return nDefInput;
			}
		}

        static public string SayFx1()
        {
            return "F(X) = 10 + (X(1) - 2) ^ 2 + (X(2) + 5) ^ 2";
        }

        static public double Fx1(int N, ref double[] X, ref double[] fParam)
        {
            return 10 + Math.Pow(X[0] - 2, 2) + Math.Pow(X[1] + 5, 2);
        }

        static public string SayFx2()
        {
            return "F(X) = 100 * (X(1) - X(2) ^ 2) ^ 2 + (X(2) - 1) ^ 2";
        }

        static public double Fx2(int N, ref double[] X, ref double[] fParam)
        {
            return Math.Pow(100 * (X[0] - X[1] * X[1]), 2) + Math.Pow((X[1] - 1), 2);
        }

        static public string SayFx3()
        {
            return "F(X) = X(1) - X(2) + 2 * X(1) ^ 2 + 2 * X(1) * X(2) + X(2) ^ 2";
        }

        static public double Fx3(int N, ref double[] X, ref double[] fParam)
        {
            return X[0] - X[1] + 2 * X[0] * X[0] + 2 * X[0] * X[1] + X[1] * X[1];
        }
	}	
}

Notice that the user-defined functions have accompanying helper functions to display the mathematical expression of the function being optimized. For example, function Fx1 has the helper function SayFx1 to list the function optimized in Fx1. Please observe the following rules::

The program uses the following class to optimize the objective function:

using System.Diagnostics;
using System.Data;
using System.Collections;
using Microsoft.VisualBasic;
using System.Collections.Generic;
using System;

namespace Optim_HookJeevesSearch
{
	public delegate double MyFxDelegate(int nNumVars, ref double[] fX, ref double[] fParam);
	public delegate string SayFxDelegate();
	
	public class CHookJeevesSearch1
	{
		
		MyFxDelegate m_MyFx;
		
		protected double MyFxEx(int nNumVars, ref double[] fX, ref double[] fParam, ref double[] fDeltaX, double fLambda)
		{
			int i;			
			double[] fXX = new double[nNumVars];
			
			for (i = 0; i < nNumVars; i++)
			{
				fXX[i] = fX[i] + fLambda * fDeltaX[i];
			}
			
            return m_MyFx(nNumVars, ref fXX, ref fParam);
		}
		
		protected bool LinSearch_DirectSearch(int nNumVars, ref double[] fX, ref double[] fParam, ref double fLambda, ref double[] fDeltaX, double fInitStep, double fMinStep)
		{
			double F1, F2;

            F1 = MyFxEx(nNumVars, ref fX, ref fParam, ref fDeltaX, fLambda);
			
			do
			{
                F2 = MyFxEx(nNumVars, ref fX, ref fParam, ref fDeltaX, fLambda + fInitStep);
				if (F2 < F1)
				{
					F1 = F2;
					fLambda += fInitStep;
				}
				else
				{
                    F2 = MyFxEx(nNumVars, ref fX, ref fParam, ref fDeltaX, fLambda - fInitStep);
					if (F2 < F1)
					{
						F1 = F2;
						fLambda -= fInitStep;
					}
					else
					{
						// reduce search step size
						fInitStep /= 10;
					}
				}
			} while (!(fInitStep < fMinStep));
			
			return true;
			
		}
		
		public double CalcOptim(int nNumVars, ref double[] fX, ref double[] fParam, ref double[] fStepSize, ref double[] fMinStepSize, double fEpsFx, ref int nIter, MyFxDelegate MyFx)
		{
			int i;
			double[] fXnew = new double[nNumVars];
			double[] fDeltaX = new double[nNumVars];
			double F, fXX, fLambda, fBestF, fLastBestF;
			bool bStop, bMadeAnyMove;
			bool[] bMoved = new bool[nNumVars];
			
			m_MyFx = MyFx;
			
			for (i = 0; i < nNumVars; i++)
			{
				fXnew[i] = fX[i];
			}
			// calculate function value at initial point
            fBestF = MyFx(nNumVars, ref fXnew, ref fParam);
			fLastBestF = 100 * fBestF + 100;
			
			nIter = 1;
			do
			{
				
				nIter++;
				
				for (i = 0; i < nNumVars; i++)
				{
					fX[i] = fXnew[i];
				}
				
				for (i = 0; i < nNumVars; i++)
				{
					bMoved[i] = false;
					do
					{
						fXX = fXnew[i];
						fXnew[i] = fXX + fStepSize[i];
                        F = MyFx(nNumVars, ref fXnew, ref fParam);
						if (F < fBestF)
						{
							fBestF = F;
							bMoved[i] = true;
						}
						else
						{
							fXnew[i] = fXX - fStepSize[i];
                            F = MyFx(nNumVars, ref fXnew, ref fParam);
							if (F < fBestF)
							{
								fBestF = F;
								bMoved[i] = true;
							}
							else
							{
								fXnew[i] = fXX;
								break;
							}
						}
					} while (true);
				}
				
				// moved in any direction?
				bMadeAnyMove = true;
				for (i = 0; i < nNumVars; i++)
				{
					if (! bMoved[i])
					{
						bMadeAnyMove = false;
						break;
					}
				}
				
				if (bMadeAnyMove)
				{
					for (i = 0; i < nNumVars; i++)
					{
						fDeltaX[i] = fXnew[i] - fX[i];
					}
					
					fLambda = 0;
					if (LinSearch_DirectSearch(nNumVars, ref fX, ref fParam, ref fLambda, ref fDeltaX, 0.1, 0.0001))
					{
						for (i = 0; i < nNumVars; i++)
						{
							fXnew[i] = fX[i] + fLambda * fDeltaX[i];
						}
					}
				}

                fBestF = MyFx(nNumVars, ref fXnew, ref fParam);
				
				// reduce the step size for the dimensions that had no moves
				for (i = 0; i < nNumVars; i++)
				{
					if (! bMoved[i])
					{
						fStepSize[i] /= 2;
					}
				}
				
				// test function value convergence
				if (Math.Abs(fBestF - fLastBestF) < fEpsFx)
				{
					break;
				}
				
				fLastBestF = fBestF;
				
				bStop = true;
				for (i = 0; i < nNumVars; i++)
				{
					if (fStepSize[i] >= fMinStepSize[i])
					{
						bStop = false;
						break;
					}
				}
				
			} while (!bStop);
			
			for (i = 0; i < nNumVars; i++)
			{
				fX[i] = fXnew[i];
			}
			
			return fBestF;
			
		}
	}
	
}

BACK

Copyright (c) Namir Shammas. All rights reserved.