################################################################################
#
#	Compute the Eigenvector corresponding to the largest eigenvalue
#	of a A^t*A, where A is a rectangular matrix
#
#	This uses an exact algorithm for dim < 200 and an approximate algorithm
#	for larger dimensions.
#
#	The approximate algorithm may be desirable when some randomness, in the
#	case of ML algorithms, is desired.
#
#	Gaston H. Gonnet (Mon Feb 12 20:43:14 CET 2018)
#
################################################################################
LargestEigenvector := proc( A:matrix )
local V;

m := length(A);
n := length(A[1]);

# simple strategy from plot
if n < 50 then Option := 1
elif m < 1750 then Option := 3
else Option := 4 fi;

if Option = 1 then
     # compute Eigenvalues exactly
     AtA := CreateArray(1..n,1..n);
     At := transpose(A);
     for i1 to n do for i2 from i1 to n do
	AtA[i1,i2] := AtA[i2,i1] := At[i1] * At[i2]
     od od;
     Eigenvalues( AtA, V );
     [ seq( x[-1], x=V ) ]

elif Option = 2 then
     AtA := CreateArray(1..n,1..n);
     At := transpose(A);
     for i1 to n do for i2 from i1 to n do
	AtA[i1,i2] := AtA[i2,i1] := At[i1] * At[i2]
     od od;
     x0 := [ seq( Normal_Rand(), n )];
     for iter to 30 do
	x0 := AtA*x0;
	x0 := AtA*x0;
	x0 := AtA*x0;
	x1 := AtA*x0;
	nx1 := sqrt(x1^2);
	if nx1 = 0 then return(x1) fi;
	x1 := x1 / nx1;
	x0 := AtA*x1;  x0 := x0 / sqrt(x0^2);
	if (x1-x0)^2 < 1e-9 then break fi;
     od;
     x1

elif Option = 3 then
     x0 := [ seq( Normal_Rand(), n )];
     for iter to 30 do
	x0 := (A*x0)*A;
	x0 := (A*x0)*A;
	x0 := (A*x0)*A;
	x1 := (A*x0)*A;
	nx1 := sqrt(x1^2);
	if nx1 = 0 then return(x1) fi;
	x1 := x1 / nx1;
	x0 := (A*x1)*A;  x0 := x0 / sqrt(x0^2);
	if (x1-x0)^2 < 1e-9 then break fi;
     od;
     x1

elif Option = 4 then
     At := transpose(A);
     x0 := [ seq( Normal_Rand(), n )];
     for iter to 30 do
	c := A*x0;  x0 := At*c;
	c := A*x0;  x0 := At*c;
	c := A*x0;  x0 := At*c;
	c := A*x0;  x1 := At*c;
	nx1 := sqrt(x1^2);
	if nx1 = 0 then return(x1) fi;
	x1 := x1 / nx1;
	c := A*x1;  x0 := At*c;  x0 := x0 / sqrt(x0^2);
	if (x1-x0)^2 < 1e-9 then break fi;
     od;
     x1

else error( Option, 'not valid' )
fi
end:

################################################################################
