#
#	EarlyAbort exploration of a space of k-dimensional solutions out
#	of a n-dimensional space
#
#	f( k-dim-permutation ) is the objective function.  It must return a
#	list where the first value is the optimization objective, to be
#	maximized.  The rest of the elements of the list are not inspected.
#
#	Early abort returns a list with 3 components: [f(best), dim, best],
#	where best is a k-dimensional vector of posint.
#
#	Original version - no weighting of replacement based on previous gains
#
#	Gaston H. Gonnet (Thu Jan 14 09:54:55 CET 2016)
#
################################################################################
EarlyAbortO := proc(
	f : procedure,
	k : posint,
	n : posint ;
	(lim=DBL_MAX) : numeric,
	guess : list(posint) )
global BestSolution, Iters;


assert( k<n );
if type(guess,list(posint)) then
     if length(guess) >= k then inds := guess[1..k]
     else oth := Shuffle( {seq(i,i=1..n)} minus {op(guess)} );
	  inds := [ op(guess), op( 1..k-length(guess), oth )]
     fi;
else inds := sort( Shuffle( [ seq(i,i=1..n) ] )[1..k] ) fi:
best := [[-DBL_MAX]];

if k=1 then # specialize for 1 dimension
    for i to n do
	x := f( [i] );
	if x[1] > best[1,1] then
	    best := [x,k,[i]];
	    if printlevel > 2 then dprint(best) fi;
	    if lim-x[1] <= 100*DBL_EPSILON*(|x[1]|+|lim|) then i := i+1;  break fi;
	fi;
    od;
    Iters := [k,[i-1]];
    BestSolution := best;
    return( best );
fi;
Iters := [];

for i to k*(n-k) do
    if i=1 then
	notin := {seq(i,i=1..n)} minus {op(inds)};
	pairs := Shuffle([seq(seq(iout=iin,iin=notin),iout=1..k)]) fi:
    inds2 := copy(inds);
    inds2[pairs[i,1]] := pairs[i,2];
    inds2 := sort(inds2);
    x := f( inds2 );
    if x[1] > best[1,1] then
        inds := inds2;
        best := [x,k,inds];
	if printlevel > 2 then dprint(best) fi;
	if lim-x[1] <= 100*DBL_EPSILON*(|x[1]|+|lim|) then i := i+1;  break fi;
	Iters := append(Iters,i);
	i := 0;
    fi;
    if printlevel > 3 and mod(sum(Iters)+i,500) = 0 then
	lprint( 'EarlyAbort iterations:', i, Iters ) fi;
od:
Iters := [k,append(Iters,i-1)];
BestSolution := best;
end:



#
#	EarlyAbortR exploration of a space of k-dimensional solutions out
#	of a n-dimensional space
#
#	f( k-dim-permutation ) is the objective function.  It returns a list
#	where the first value is the optimization objective, to be maximized.
#	The rest of the elements of the list are not inspected.
#
#	Early abort returns a list with 3 components: [f(best), dim, best],
#	where best is a k-dimensional vector of posint.
#
#	Identical to EarlyAbort but allows dimensions to be repeated
#
#	Gaston H. Gonnet (Tue Feb 23 17:57:33 UYT 2016)
#
EarlyAbortR := proc(
	f : procedure,
	k : posint,
	n : posint ;
	(lim=DBL_MAX) : numeric,
	guess : list(posint) )
global BestSolution, Iters;


assert( k<n );
if type(guess,list(posint)) then
     if length(guess) >= k then inds := guess[1..k]
     else oth := Shuffle( {seq(i,i=1..n)} minus {op(guess)} );
	  inds := [ op(guess), op( 1..k-length(guess), oth )]
     fi;
else inds := sort( Shuffle( [ seq(i,i=1..n) ] )[1..k] ) fi:
best := [[-DBL_MAX]];

if k=1 then # specialize for 1 dimension
    for i to n do
	x := f( [i] );
	if x[1] > best[1,1] then
	    best := [x,k,[i]];
	    if printlevel > 2 then dprint(best) fi;
	    if lim-x[1] <= 100*DBL_EPSILON*(|x[1]|+|lim|) then i := i+1;  break fi;
	fi;
    od;
    Iters := [k,[i-1]];
    BestSolution := best;
    return( best );
fi;
Iters := [];

all := {seq(i,i=1..n)};
for i to k*n do
    if i=1 then
	pairs := Shuffle([seq(seq(iout=iin,iin=all),iout=1..k)]) fi:
    if inds[pairs[i,1]] = pairs[i,2] then next fi;
    inds2 := copy(inds);
    inds2[pairs[i,1]] := pairs[i,2];
    if EarlyAbortNoSort <> true then
	inds2 := sort(inds2);
    fi;
    x := f( inds2 );
    if x[1] > best[1,1] then
        inds := inds2;
        best := [x,k,inds];
	if printlevel > 2 then dprint(best) fi;
	if lim-x[1] <= 100*DBL_EPSILON*(|x[1]|+|lim|) then i := i+1;  break fi;
	Iters := append(Iters,i);
	i := 0;
    fi;
od:
Iters := [k,append(Iters,i-1)];
BestSolution := best;
end:


#
#	EarlyAbort exploration of a space of k-dimensional solutions out
#	of a n-dimensional space
#
#	f( k-dim-permutation ) is the objective function.  It returns a list
#	where the first value is the optimization objective, to be maximized.
#	The rest of the elements of the list are not inspected.
#
#	Early abort returns a list with 3 components: [f(best), dim, best],
#	where best is a k-dimensional vector of posint.
#
#	Weighting of replacements based on previous functional increases.
#
#	Gaston H. Gonnet (Thu Jan 14 09:54:55 CET 2016)
#	weighted version (Fri Sep  2 13:16:38 CEST 2016)
#
EarlyAbort := proc(
	f : procedure,
	k : posint,
	n : posint ;
	(lim=DBL_MAX) : numeric,
	guess : list(posint) )
global BestSolution, Iters;


assert( k<n );
knk := k*(n-k);
if type(guess,list(posint)) then
     if length(guess) >= k then inds := guess[1..k]
     else oth := Shuffle( {seq(i,i=1..n)} minus {op(guess)} );
	  inds := [ op(guess), op( 1..k-length(guess), oth )]
     fi;
else inds := sort( Shuffle( [ seq(i,i=1..n) ] )[1..k] ) fi:
best := [[-DBL_MAX]];

if k=1 then # specialize for 1 dimension
    for i to n do
	x := f( [i] );
	if x[1] > best[1,1] then
	    best := [x,k,[i]];
	    if printlevel > 2 then dprint(best) fi;
	    if lim-x[1] <= 100*DBL_EPSILON*(|x[1]|+|lim|) then i := i+1;  break fi;
	fi;
    od;
    Iters := [k,[i-1]];
    BestSolution := best;
    return( best );
fi;
Iters := [];

improv := CreateArray(1..n,1..2);
for i to knk do
    if i=1 then
	for j to n do improv[j,1] := improv[j,2] := 0 od;
	st := Stat('functional');
	notin := {seq(i,i=1..n)} minus {op(inds)};
	pairs := Shuffle([seq(seq(iout+1000*iin,iin=notin),iout=1..k)]) fi:

    # select a good pair
    goodp := [-DBL_MAX];
    stm := st[Mean] + EAstd*sqrt(st[Variance]);
    jin := max( i, knk-30 );
    for j from jin to min( knk, jin+30 ) do
	v1 := improv[inds[mod(pairs[j],1000)]];
	v2 := improv[floor(pairs[j]/1000)];
	v := If( v1[1]=0, stm, v1[2]/v1[1] ) + If( v2[1]=0, stm, v2[2]/v2[1] );
	if v1[1]=0 and v2[1]=0 or v > goodp[1] then goodp := [v,pairs[j],j] fi;
    od:
    pairs[goodp[3]] := pairs[i];
    iout := inds[mod(goodp[2],1000)];
    iin := floor(goodp[2]/1000);

    inds2 := copy(inds);
    inds2[mod(goodp[2],1000)] := iin;
    if EarlyAbortNoSort <> true then inds2 := sort(inds2) fi;
    x := f( inds2 );

    improv[iout,1] := improv[iout,1]+1;  improv[iout,2] := improv[iout,2]+x[1];
    improv[iin,1] := improv[iin,1]+1;  improv[iin,2] := improv[iin,2]+x[1];
    st+x[1];

    if x[1] > best[1,1] then
        inds := inds2;
        best := [x,k,inds];
	if printlevel > 2 then dprint(best) fi;
	if lim-x[1] <= 100*DBL_EPSILON*(|x[1]|+|lim|) then i := i+1;  break fi;
	Iters := append(Iters,i);
	i := 0;
    fi;
    if printlevel > 3 and mod(sum(Iters)+i,500) = 0 then
	lprint( 'EarlyAbort iterations:', i, Iters ) fi;
od:
Iters := [k,append(Iters,i-1)];
BestSolution := best;
end:
