function varargout = lineSearchGolden(getObjectCall, objectiveFunction, ...
    minGuess, maxGuess, tolGuess)
% golden line search (minimizer)
%
% Syntax: bestObject = lineSearchGolden(getObjectCall, objectiveFunction,
%                        minGuess, maxGuess, tolGuess)
%        [bestObject, bestGuess, bestObjectiveValue] = ...
% 
% The function tries to find an optimal object of arbitrary type:
%     bestObject = getObjectCall(bestPoint)
%   while minimizing the objective:
%     bestObjective = objectiveFunction(bestObject).
%
% The guesses are scalar variables (line search is not suited for nD 
%   optimization). The tolerance is absolute.
%
% THIS IS NO USER FUNCTION

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2012 Alexander Reinhold
%
% This program 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.
%
% This program 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 this program.  If not, see <http://www.gnu.org/licenses/>

% The solver uses the matrix lineSearchStat too keep it's state
%   information: x-position (1st column), objective value (2nd column); 
%   left bound (1st row), inner point (2nd row), right bound (3rd row).

%% the golden ratio
phi = (1+sqrt(5)) / 2;

%% an inner sample point
innerAngle = (phi-1)*minGuess + (2-phi)*maxGuess;

%% compute objective functions
minObjective = objectiveFunction(getObjectCall(minGuess));
maxObjective = objectiveFunction(getObjectCall(maxGuess));
bestObject = getObjectCall(innerAngle);
innerObjective = objectiveFunction(bestObject);

%% initialize line search status
lineSearchStat = [minGuess, minObjective; ...
    innerAngle, innerObjective; ...
    maxGuess, maxObjective];

%% iterate through golden line search (which is a minimizer)
while abs(lineSearchStat(1,1) - lineSearchStat(3,1)) > tolGuess
    [lineSearchStat bestObject] = iterateLineSearchGolden(...
        lineSearchStat, bestObject, getObjectCall, objectiveFunction);
end

%% assign output
switch nargout
    case 1
        varargout{1} = bestObject;
    case 3
        varargout{1} = bestObject;
        varargout{2} = lineSearchStat(2, 1);
        varargout{3} = lineSearchStat(2, 2);
end