################################################################################
#
#	Conjugate Gradient Minimization
#
#	From https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method
#
#	This version uses f (only the functional, no gradient) and does a
#	finite number of steps of Brent minimization.  When f is much cheaper
#	than fp to compute, this is advantageous.
#
#	This function is particularly suited for minimizing L2 norms of errors,
#	that is the objective function decreases to 0.  It does not normalize
#	in any way, so pre-normalization is required.
#
#	Global variables that affect its behaviour:
#
#	CGMode - the type of conjugate gradient algorithm: FR, PR, HS and DY
#	CGMaxTime - in seconds
#	CGRestart - probability of restarting (beta_n=0) at each iteration
#	CGepslim - if |f(x)| < CGepslim then terminate
#	CGKSec - posint, number of secant iterations to find minimum in SD
#
#	Gaston H. Gonnet (Mon Jan 21 19:27:07 UTC 2019, Ceeqit office)
#
################################################################################

ConjugateGradientMinimize2 := proc(
	f : procedure,  # f(x) -> f(x)
	fp : procedure, # fp(x) -> [f(x), f'(x)]
	iniguess : list(numeric)
	)

nx := length(iniguess);
xn := iniguess;
h := 1e-6;
phi := 1.618033988749895;
beta_n := 0;
t1 := time();


for N from 0 while time()-t1 < CGMaxTime do
    # 1. Calculate the steepest direction:
    fn, delxn := op(fp(xn));

    # 2. Compute \beta_n according to one of the formulas below,
    if N = 0 then beta_n := 0
    elif Rand() < CGRestart then beta_n := 0
    elif CGMode = 'FR' then
	beta_n := delxn^2 / delxnm1^2
    elif CGMode = 'PR' then
	beta_n := max( 0, delxn*(delxn-delxnm1) / delxnm1^2 )
    elif CGMode = 'HS' then
	beta_n := max( 0, delxn*(delxn-delxnm1) / (snm1*(delxn-delxnm1)) )
    elif CGMode = 'DY' then
	beta_n := max( 0, delxn^2 / (snm1*(delxn-delxnm1)) )
    else error(snh8692) fi;
    if beta_n > 1e10 then beta_n := 0 fi;

    # 3. Update the conjugate direction:
    sn := If( N=0, -delxn, beta_n * sn - delxn );

    # 4. Perform a line search: optimize \alpha_n
    # perform a Brent style minimization with the previous h increment
    x0 := xn;  f0 := fn;
    x1 := x0 + h*sn;  f1 := f(x1);

    if f1 >= f0 then
	 x2 := x1;  f2 := f1;
	 x1 := x0 + h/(1+phi) * sn;  f1 := f(x1);
	 h := h/phi;
    else do  # exponential search
	     h := phi*h;
	     x2 := x1 + h*sn;  f2 := f(x2);
	     if f2 >= f1 then break fi;
	     x0 := x1;  f0 := f1;  x1 := x2;  f1 := f2;
	     lprint( 'expon search', f0,f1,f2, h );
	 od;
    fi:

    # run a fixed number of Brent steps
    to 10 do
	assert( f0 >= f1 and f2 >= f1 );
	assert( ||(x2[1]-x1[1]) / sn[1]| - h| < 1e-15 );
	assert( ||(x1[1]-x0[1]) / sn[1]| - h/phi| < 1e-15 );
	x3 := x0-x1+x2;  f3 := f(x3);
	if f3 <= f1 then
	     x0 := x1;  f0 := f1;  x1 := x3;  f1 := f3;
	else x2 := x0;  f2 := f0;  x0 := x3;  f0 := f3;
	fi;
	h := h/phi;
	lprint( f0,f1,f2, h );
    od:

    # 5. Update the position: x_{n+1}=x_{n}+\alpha_n s_n
    h := |(sum(xn)-sum(x1)) / sum(sn)|;
    xn := x1;  fn := f1;
    delxnm1 := delxn;
    if printlevel >= 3 then printf(
	'iter=%d, beta_n=%.5g, f(x)=%.8g, alpha_n=%.4g\n', N, beta_n, fn, h ) fi;

od:
fn, delxn := op(fp(xn));
[xn,fn,delxn]
end:
################################################################################



################################################################################
#
#	Conjugate Gradient Minimization
#
#	From https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method
#
#	This version uses only fp and does a finite number of iterations
#	(using the derivative and the secant method) to find the minimum
#	in each direction.
#
#	Gaston H. Gonnet (Mon Jan 21 19:27:07 UTC 2019, Ceeqit office)
#
################################################################################

ConjugateGradientMinimize := proc(
	fp : procedure, # fp(x) -> [f(x), f'(x)]
	iniguess : list(numeric)
	)
global CGMaxTime, CGMode, CGRestart;

nx := length(iniguess);
xn := iniguess;
h := 1e-6;
epslim := 1e-4;  if type( CGepslim, positive) then epslim := CGepslim fi;
KSec := 2;  if type( CGKSec, posint) then KSec := CGKSec fi;
if not type(CGMaxTime,positive) then CGMaxTime := 3600 fi;
if not type(CGRestart,nonnegative) then CGRestart := 0.001 fi;
if not assigned(CGMode) then CGMode := 'HS' fi;
t1 := time();


for N from 0 to 3000 while time()-t1 < CGMaxTime do
    # 1. Calculate the steepest direction:
    fn, delxn := op(fp(xn));
    #if |fn| > 10000 then error('functional should not be so large') fi;
    delxn2 := delxn^2;
    if |fn| < epslim or delxn2 < 1e-12 or fn < -1e50 or delxn2 > 1e200 then
	return( [xn,fn,delxn] ) fi;

    # 2. Compute \beta_n according to one of the formulas below,
    if N = 0 then beta_n := 0
    elif Rand() < CGRestart then beta_n := 0
    elif CGMode = 'FR' then
	beta_n := delxn^2 / delxnm1^2
    elif CGMode = 'PR' then
	beta_n := max( 0, delxn*(delxn-delxnm1) / delxnm1^2 )
    elif CGMode = 'HS' then
	den := snm1 * (delxn-delxnm1);
	beta_n := If( den=0, 0, max( 0, delxn*(delxn-delxnm1) / den ))
    elif CGMode = 'DY' then
	beta_n := max( 0, delxn^2 / (snm1*(delxn-delxnm1)) )
    else error(snh8692) fi;
    if beta_n > 1e10 then beta_n := 0 fi;
    ############################################################################

    # 3. Update the conjugate direction:
    sn := If( N=0, -delxn, beta_n * sn - delxn );

    # 4. Perform a line search: optimize \alpha_n
    x0 := xlo := 0;  fx0 := sn*delxn;  flo := fn;
    if fx0 > -1e-6 then # not descending enough, restart CG
	beta_n := 0;
	sn := -delxn;
	fx0 := sn*delxn;
	if fx0 > -1e-6 then break fi;
    fi;
    ############################################################################

    # use the Secant method and compute the gradient to find minimum
    x1 := h;
    xffs := [[x0,fn,fx0]];
    lolim := 0;  uplim := 100*h; # protect method from going out of range
    to KSec do
	f1, grad1 := op(fp( xn + x1*sn ));
	if f1 < flo then xlo := x1;  flo := f1 fi;
	fx1 := sn*grad1;
	xffs := append( xffs, [x1,f1,fx1] );
	if |fx0| < 1e-8 or fx0 = fx1 then break fi; # sufficiently flat, must be at min
	if fx1 >= 0 or f1 >= fn then uplim := x1 fi;
	if fx1 < 0 and f1 < fn then lolim := x1 fi;
	x2 := x1 - fx1 * (x0 - x1) / (fx0 - fx1);
	if x2 < lolim or x2 > uplim then
	     x2 := (lolim+uplim) / 2 fi; # if outside range, reinsert in range
	x0 := x1;  fx0 := fx1;  x1 := x2;
	if |x1-x0| <= 1e-5*x1 then break fi;	# final eps < 1e-8, exit
    od;
    x1 := xlo;  f1 := flo;
    ############################################################################

    if f1 >= fn then
	# trouble! if it was not reset already, reset CG and retry
	if sn <> -delxn then
	    for i to length(sn) do sn[i] := 0 od;
	    next
	fi;

	xffs := sort(xffs);
	assert( length(xffs) > 1 and type(xffs[1],[0,numeric,negative]) );
	xffs1 := xffs[1];
	for xffs2 in xffs while xffs2[2] <= fn*(1+4*DBL_EPSILON) and xffs2[3] < 0 do od;
	# run a fixed number of binary search iterations
	to 10 do
	    x3 := ( xffs1[1] + xffs2[1] ) / 2;
	    f3, grad3 := op(fp( xn + x3*sn ));
	    fx3 := sn*grad3;
	    xffs := append( xffs, [x3,f3,fx3] );
	    if fx3 < 0 and f3 < fn then xffs1 := [x3,f3,fx3]
	    else xffs2 := [x3,f3,fx3] fi;
	    if printlevel > 3 then
		printf( 'binary search: %a .. %a\n', xffs1, xffs2 ) fi;
	    if xffs2[1] < 1e-9 then break fi;
	od:
	if xffs1[2] < xffs2[2] then x1,f1 := op(1..2,xffs1)
	else x1,f1 := op(1..2,xffs2) fi;
    fi;
    if x1 < 1e-9 or f1 > fn then break fi; # if it could not decrease exit
    ############################################################################


    # 5. Update the position: x_{n+1}=x_{n}+\alpha_n s_n
    h := x1;
    xn := xn + x1*sn;
    delxnm1 := delxn;
    snm1 := sn;
    if printlevel > 4 or printlevel = 4 and mod(N,10) = 0 then
        printf( 'iter=%d, f(x)=%.8g, |f''(x)|=%.4g, |sn|=%.4g, beta_n=%.5g, alpha_n=%.4g\n',
	    N, fn, sqrt(grad1^2/(nx-1)), sqrt(sn^2/(nx-1)), beta_n, h ) fi;
    if h < 1e-12 then break fi;

od:
fn, delxn := op(fp(xn));
[xn,fn,delxn]
end:
################################################################################



################################################################################
#
#	SteepestDescentMinimize - use SD with accelerators to find minimum
#
#	Gaston H. Gonnet (Thu Dec 20 16:27:01 UTC 2018, Vorhaldenstrasse)
#
################################################################################
SD_accel := Shuffle( [ [5,1], [5,2], [6,1], [7,1], [7,2], [8,1], [10,1],
	[10,0.5], [11,1], [20,0.5], [30,0.5] ] );
SD_K, SDup, SDup2, SDup3, SDdown := op( RandL(
    [[3, 1.2, 1.7, 1.1, 5], [3, 1.3, 1.7, 1.05, 4], [3, 1.2, 1.6, 1, 4],
    [3, 1.2, 1.6, 1.05, 4], [3, 1.3, 1.5, 1, 3], [3, 1.3, 1.7, 1.05, 5]] ));

SteepestDescentMinimize := proc(
	f : procedure,	# f(x) -> f(x)
	fp : procedure,	# fp(x) -> [f(x), f'(x)]
	iniguess : list(numeric)
	)
global SD_K, SDMaxTime;

if printlevel > 4 then
    printf( 'SD_accel=%A, SD_K=%d, SDup=%.10g, SDup2=%.10g, SDup3=%.10g, SDdown=%.10g, SDMaxTime=%a\n',
	SD_accel, SD_K, SDup, SDup2, SDup3, SDdown, SDMaxTime ) fi;
nx := length(iniguess);
f0, grad := op(fp(iniguess));
xs := [iniguess];  grads := [grad];  fs := [f0];  gs := [sqrt(grad^2)];
if gs=[0] then return( [iniguess,f0,grad] ) fi;
h := 1e-6;
if not type(SDMaxTime,positive) then SDMaxTime := 3600 fi;

for iter to 3000 while time() < SDMaxTime do

    # selection of which step to use
    if mod(iter,SD_K) = 0 then
	ac := SD_accel[ mod(iter/SD_K,length(SD_accel)) + 1];
	if length(xs) >= ac[1] then
	    if ac[2] = 1 then typ := 'xs' . ac[1]
	    elif ac[2] < 1 then
		 typ := sprintf( 'xs%d/%g', ac[1], 1/ac[2] )
	    else typ := sprintf( 'xs%d*%g', ac[1], ac[2] ) fi;
	    x1 := (1+ac[2]) * xs[-1] - ac[2] * xs[-ac[1]];
	else typ := 'hincr';  x1 := xs[-1] - h*grads[-1] fi
    else typ := 'hincr';  x1 := xs[-1] - h*grads[-1]
    fi:

    f1, grad1 := op(fp( x1 ));
    g1 := sqrt(grad1^2);
    if printlevel > 4 or printlevel = 4 and mod(iter,10) = 0 then
        printf( 'iter=%d, f(x)=%.8g, |x|=%.5g, |f''(x)|=%.5g, h=%.4g, typ=%a\n',
	    iter, f1, sqrt(x1^2/(nx-1)), g1/sqrt(nx-1), h, typ ) fi;

    # post evaluation analysis
    if |f1| < 1e-4 or f1 < -1e50 then return( [x1, f1, grad1] ) fi;
    if f1 >= fs[-1] then
	 if typ='hincr' then h := h/SDdown fi;
	 if h < 1e-9 or h > 1e20 then return( [xs[-1], fs[-1], grads[-1]] ) fi;

    else
	if typ <> 'hincr' then
	elif f1-fs[-1] < -0.5*gs[-1]^2*h then # within 50% of expected or better
	     if f1-fs[-1] < -0.9*gs[-1]^2*h then h := SDup*h
	     else h := SDup3*h fi;
	elif g1 > gs[-1] then
	     h := h/SDup2;
	fi;
	fs := append(fs,f1);
	xs := append(xs,x1):
	gs := append(gs,g1);
	grads := append(grads,grad1):
	if length(fs) > 100 then
	     fs := fs[-50..-1];
	     gs := gs[-50..-1];
	     xs := xs[-50..-1];
	     grads := grads[-50..-1];
	fi;
	
    fi:
    assert( length(xs) = length(fs) and length(xs) = length(grads) and
	length(xs) = length(gs) );

od:
[xs[-1],fs[-1],grads[-1]]
end:
################################################################################
