################################################################################
#
#	LinearProgramming: function to solve a simplex
#
#	LinearProgramming( A, b, c ) solves the problem of
#	finding a vector x such that Ax >= b and c*x is maximum.
#
#	This is the unconstrained problem, the variables in x can
#	be positive or negative, for the classical problem, x >= 0,
#	these conditions have to be stated explicitly.
#
#	If c is 'Feasibility' LinearProgramming will only attempt
#	to find a feasible solution, which is returned and do no
#	optimization.  This saves computation.
#
#	LinearProgramming returns:
#
#		[x,set(posint)] where x is the solution and the set is the
#				set of indices to rows of A which define
#				the corner x
#
#		SimplexHasNoSolution when there is no solution
#
#		SimplexIsSingular when it cannot find a subset of rows
#				from A which is non-singular
#
#		UnboundedSolution( x, d, inds ) where x + h*d, is a solution for
#				any h >= 0 and c*(x+h*d) grows unboundedly.
#				inds is the set of row indices or A which
#				define the corner x.
#
#	This function does not work well if the values are out of scale.
#	I.e. works well for an A with Z-normalized columns.
#
#	Gaston H. Gonnet (Sep 29th, 2011)
#		mayor update (Mon Nov  6 14:54:31 CET 2017)
#
################################################################################

LinearProgramming := proc(
	A:matrix(numeric),
	b:list(numeric),
	c:{list(numeric),'Feasibility'} )
m := length(A);
n := length(A[1]);
if length(b) <> m or type(c,list) and length(c) <> n then
    error('inconsistent dimensions' )
elif m < n then return( SimplexIsSingular ) fi;

# this thin interface is to provide normalization of columns and b vector and
# to add random noise to b so that the algorithm works in polynomial time.
At := transpose(A):
stds := CreateArray(1..n):
for i to n do
    stds[i] := std(At[i]);
    if stds[i]=0 then stds[i] := |avg(At[i])| fi;
    if stds[i]=0 then
	if printlevel > 3 then lprint( 'LP: cannot handle entirely null column') fi;
	return( SimplexIsSingular )
    fi;
    At[i] := At[i] / stds[i]
od;
stdb := std(b);
if stdb=0 then stdb := |avg(b)| fi;
if stdb=0 then stdb := 1 fi;
c2 := c;
if type(c2,list(numeric)) then c2 := zip( c/stds ) fi;
normA := transpose(At);

# Try twice in case of error, as randomization may produce funny results
to 6 do
    # the noise is added to insure that single point solutions are not lost
    b2 := [ seq( x/stdb - 1e-7*Rand(), x=b) ];
    r := traperror( LinearProgramming_inner( normA, b2, c2 ));
    if r <> lasterror then break fi;
od:
if r = lasterror then error(r) fi;

if r=SimplexHasNoSolution or r=SimplexIsSingular then r
elif type(r,[list(numeric),set(posint)]) then
     v := stdb*r[1];
     v := zip( v/stds );
     A2 := [ seq( A[i], i=r[2]) ];
     b2 := [ seq( b[i], i=r[2]) ];
     v := v - GaussElim( A2, A2*v-b2 );
     [ v, r[2] ]
elif type(r,UnboundedSolution(list(numeric),list(numeric),set(posint))) then
     A2 := [ seq( A[i], i=r[3]) ];
     b2 := [ seq( b[i], i=r[3]) ];
     v := GaussElim(A2,b2);
     v2 := stdb*r[2];
     v2 := zip( v2/stds );
     UnboundedSolution( v, v2, r[3] )
else error(snh012) fi;
end:


################################################################################
################################################################################
################################################################################
LinearProgramming_inner := proc(
	A:matrix(numeric),
	b:list(numeric),
	c:{list(numeric),'Feasibility'} )
m := length(A);
n := length(A[1]);

# find initial corner by adding a slack variable
A2 := [ seq( append( copy(A[i]), b[i] ), i = 1..m )];
x2 := [seq(0,n),1];
A2 := append(A2,x2):
b2 := append(copy(b),0);

perm := Shuffle([seq(i,i=1..m)]);
A3 := [A2[perm[1]]];
inds := [perm[1]];
# Gram-Schmidt orthogonalization to find independent subset
for i from 2 to m do
    Ai := A2[perm[i]];
    normAi := Ai^2;
    if normAi = 0 then next fi;
    dep := false;
    for w in A3 do
	Ai := Ai - (Ai*w) / (w^2) * w;
	if Ai^2 <= normAi*1e-8 then dep := true;  break fi;
    od;
    if dep then next
    else A3 := append(A3,Ai);  inds := append(inds,perm[i]) fi;
    if length(A3) >= n+1 then break fi;
od:


################################################################################
if length(A3) < n+1 then
    # The simplex is singular, this means there are columns which are linear
    # combination of other colums.  The problem becomes very complicated to
    # solve correctly as A2 is enhanced with the vector b.  In most cases,
    # if c <> 0, the solution is likely to be unbounded.
    # Give an error and force the user to decide.
    return( SimplexIsSingular );
fi;
inds := {op(inds)};


################################################################################
# randomize the rest of the rows to prevent crowding of the corner
for i to m do if not member(i,inds) then A2[i,n+1] := b2[i] + Rand() fi od;
if c='Feasibility' then newc := [ seq(0,n), -1 ]
else c1 := sum(|x|,x=c);  newc := [op(c),-1e3*(c1+1)] fi;

r := LinearProgramming_Iterate( A2, b2, newc, x2, inds );
if type(r,UnboundedSolution(list(numeric),list(numeric),set(posint))) then
     if |r[1,n+1]| > 1e-12 then return( SimplexHasNoSolution ) fi;
     return( UnboundedSolution( r[1,1..n], r[2,1..n], r[3] minus {m+1} ) )
elif |r[1,n+1]| > 1e-12 then return( SimplexHasNoSolution ) fi;

assert( r[2,-1] = m+1 );
return( [r[1,1..n], r[2] minus {m+1}] );

end:

################################################################################
################################################################################
################################################################################
LinearProgramming_Iterate := proc( A:matrix(numeric), b:list(numeric),
	c:list(numeric), x0:list(numeric), inds0:set(posint) )

inds := inds0;
x := x0;
m := length(A);
n := length(A[1]);
assert( c^2 > 0 );

# main loop, from a corner, determine a possible edge to travel
tol := 10*n*DBL_EPSILON*(sqrt(c^2)+1);
prevfunct := c*x;
for iter do
    A2 := [seq(A[i],i=inds)];
    A2invt := transpose( 1/A2 ):
    condA2 := (max(A2)-min(A2)) * (max(A2invt)-min(A2invt));
    assert( condA2 < 1e9 );

    # since we compute the inverse, we might as well refine the answer
    r0 := [seq(b[i],i=inds)] - A2*x;
    x := x + r0*A2invt;

    dirs := A2invt*c;
    r := A*x-b;

    # The solution has to be exact in at least n points
    assert( sum( If( |v| < 20*tol, 1, 0), v=r ) >= n );
    assert( min(r) > -condA2*tol );	# sanity check

    if max(dirs) <= tol then sts[LPiterations]+iter;  return([x,inds]) fi;  # reached cusp

    ############################################################################
    #
    #	Clarifications:  We are solving A*x >= b,  (A,b are the full problem)
    #
    #     Lets say that A2 and b2 are the submatrix/vector which consist only
    #     of the rows in inds.  Then A2*x = b2 (solves the subproblem exactly)
    #     and A*x >= b,
    #     i.e. x is a feasible solution of the simplex.
    #          x is a corner for being the exact solution.
    #
    #  If we select an edge to travel along it, it is going to be determined
    #  by a single row in A2 which will satisfy:
    #		A2[i] * (x+h*d[i]) = b2[i] + h, with h>0 or
    #		A2[i]*d[i] = 1, and A2[j]*d[i] = 0 for j <> i, or
    #		A2*d[i] = one(i) or
    #		d[i] = A2^(-1)*one(i), or
    #		d[i] is the ith column of A2^(-1).
    #
    #  We are interested in the directions d[i] which increase the functional,
    #  i.e. c*d[i] > 0.  The vector of all the increasaes is c*A2^(-1).
    #
    ############################################################################
    for jmax in sort( [seq(i,i=1..n)], x -> -dirs[x] ) do
	if dirs[jmax] <= tol then break fi;
	d := A2invt[jmax];
	d := d / sqrt(d*d);

        # find how far it can traverse the edge and which row will replace jmax
        best := [DBL_MAX,0];
        for i to m do if not member(i,inds) then
            Aid := A[i]*d;
	    if Aid >= -tol then next # no constraint on h (1)
            else h := -r[i] / Aid;
	         if h < best[1] then
		     # row i cuts the simplex smaller
		     if h <= tol then	# no advance on this edge, skip
			  best := [0];  break
		     else best := [h,i] fi
		 fi;
            fi
        fi od;
        if best[1] > tol then break fi;
    od:

    assert( best <> [0] );
    if best[1] = DBL_MAX then return( UnboundedSolution( x, d, inds ) ) fi;
    x := x + best[1]*d;
    newf := c*x;
    assert( newf > prevfunct );	# has to make progress
    if printlevel > 3 then
	printf( 'LP: replacing row %d by %d, c*x=%g, improv=%g, iter=%d\n',
	    inds[jmax], best[2], newf, newf-prevfunct, iter ) fi;
    assert( best[2] >= 1 and best[2] <= m );
    inds := (inds minus {inds[jmax]}) union {best[2]};
    prevfunct := newf;
od;
end:
