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(ex1,[demo/0,demo/2]). 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 FX is sin(X0), 28 G0 is cos(X0), 29 optimizer_set_g(Env,0,G0). 30 31% This is the call back function which is invoked to report the progress 32% if the last argument is set to anywhting else than 0, the optimizer will 33% stop right now 34progress(Env,FX,X_Norm,G_Norm,Step,_N,Iteration,Ls,0,_) :- 35 optimizer_get_x(Env,0,X0), 36 format('~d. Iteration : x0=~4f f(X)=~4f |X|=~4f |X\'|=~4f Step=~4f Ls=~4f~n',[Iteration,X0,FX,X_Norm,G_Norm,Step,Ls]). 37 38 39 40demo :- 41 demo(_Sol,_BestF). 42 43demo(BestX0,BestF):- 44 format('Optimizing the function f(x0) = sin(x0)~n',[]), 45 optimizer_initialize(1,ex1,evaluate,progress,[],Env), 46 47 48 StartX is 3.95801,% random_float*10, 49 format('We start the search at the random position x0=~5f~2n',[StartX]), 50 optimizer_set_x(Env,0,StartX), 51 52 optimizer_run(Env,BestF,Status), 53 optimizer_get_x(Env,0,BestX0), 54 optimizer_finalize(Env), 55 format('~2nOptimization done~nWe found a minimum at f(~f)=~f~2nLBFGS Status=~w~n',[BestX0,BestF,Status])