1%%% -*- Mode: Prolog; -*-
    2
    3
    4%  This file is part of YAP-LBFGS.
    5%  Copyright (C) 2009 Bernd Gutmann
    6%
    7%  YAP-LBFGS is free software: you can redistribute it and/or modify
    8%  it under the terms of the GNU General Public License as published by
    9%  the Free Software Foundation, either version 3 of the License, or
   10%  (at your option) any later version.
   11%
   12%  YAP-LBFGS is distributed in the hope that it will be useful,
   13%  but WITHOUT ANY WARRANTY; without even the implied warranty of
   14%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   15%  GNU General Public License for more details.
   16%
   17%  You should have received a copy of the GNU General Public License
   18%  along with YAP-LBFGS.  If not, see <http://www.gnu.org/licenses/>.
   19:- module(ex2,[demo/0,demo/3]).   20
   21:- use_module(library(lbfgs)).   22
   23
   24% This is the call back function which evaluates F and the gradient of F
   25evaluate(Env,FX,_N,_Step,_) :-
   26	optimizer_get_x(Env,0,X0),
   27	optimizer_get_x(Env,1,X1),
   28
   29	FX is (X0-2)*(X0-2) + (X1-1)*(X1-1),
   30	G0 is 2*(X0-2),
   31	G1 is 2*(X1-1),
   32	
   33	optimizer_set_g(Env,0,G0),
   34	optimizer_set_g(Env,1,G1).
   35
   36% This is the call back function which is invoked to report the progress
   37% if the last argument is set to anywhting else than 0, the optimizer will
   38% stop right now
   39progress(Env,FX,X_Norm,G_Norm,Step,_N,Iteration,Ls,0,_) :-
   40	optimizer_get_x(Env,0,X0),
   41	optimizer_get_x(Env,1,X1),
   42	format('~d. Iteration : (x0,x1)=(~4f,~4f)  f(X)=~4f  |X|=~4f  |X\'|=~4f  Step=~4f  Ls=~4f~n',[Iteration,X0,X1,FX,X_Norm,G_Norm,Step,Ls]).
   43
   44
   45
   46demo :-
   47	demo(_X0,_X1,_F).
   48
   49demo(BestX0,BestX1,BestF):-
   50	format('Optimizing the function f(x0,x1) = (x0-2)^2 + (x1-1)^2~n',[]),
   51	optimizer_initialize(2,ex2,evaluate,progress,[],Env),
   52
   53
   54	StartX0 is random_float*1000-500,
   55	StartX1 is random_float*1000-500,
   56
   57	format('We start the search at the random position (x0,x1)=(~5f,~5f)~2n',[StartX0,StartX1]),
   58	optimizer_set_x(Env,0,StartX0),
   59	optimizer_set_x(Env,1,StartX1),
   60	
   61	optimizer_run(Env,BestF,Status),
   62	optimizer_get_x(Env,0,BestX0),
   63	optimizer_get_x(Env,1,BestX1),
   64	
   65	optimizer_finalize(Env),
   66	format('~2nOptimization done~nWe found a minimum at f(~f,~f)=~f~2nLBFGS Status=~w~n',[BestX0,BestX1,BestF,Status])