/*
 * An implementation of Algorithm 1 from [1] for verifying r-generic 
 * identifiability of Segre varieties. 
 *
 * Requires the Eigen library version 3.2.1, which can be obtained freely from
 * http://eigen.tuxfamily.org/.
 *
 * The code will check whether the Segre variety of the provided size is 
 * r-identifiable, for r corresponding to the largest value for which the
 * sufficient condition of [1] can be applied. The executable should be called
 * providing the dimensions, in order of decreasing size, as arguments.
 * For example: ./ExecutableName 6 6 3  will verify generic r-identifiability of
 * 6x6x3 tensors.
 *
 * Default compilation that should work on an up-to-date linux distribution:
 *   g++ -I/path-to-eigen -O2 -DNDEBUG generic_identifiability.cpp
 *
 * [1] L. Chiantini, G. Ottaviani, and N. Vannieuwenhoven, An algorithm for 
 *     generic and low-rank specific identifiability of complex tensors, 2014.
 */

#include <Eigen/Eigen>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <unsupported/Eigen/KroneckerProduct>
#include <vector>
#include <iostream>

#define int_t long
#define vector_t Eigen::Matrix<int_t,Eigen::Dynamic,1>
#define matrix_t Eigen::Matrix<int_t,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor>

// Choose a field size equal to a Mersenne prime, for the sake of efficiency.
// Allowed choices for BITS are: {5,7,13,17,19}
#define BITS 13
#define M13 ((1L<<BITS)-1L)

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Helper routines
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Reduce a number to its canonical representation in Z_p.
// Assumes that p is a Mersenne prime.
inline int_t reduce(int_t a) {
	assert(a >= 0);
	a = (a & M13) + (a >> BITS);
	while( a > M13 )
		a = (a & M13) + (a >> BITS);
	if(a == M13) a = 0;
	return a;
}

// Make the input positive.
inline int_t positive(int_t k) {
	if(k < 0) {
		const int f = (-k) / M13;
		k += (f+1)*M13;
		if(k == M13) {
			k = 0;
		}
	}
	if(k < 0) { std::cout << "k = " << k << std::endl; assert(false); }
	return k;
}

// Compute the multiplicative inverse of the input.
int_t inv(int_t const& n) {
	assert(n <= M13);
	assert(n > 0);
	int a = M13;
	int b = n;
	int x = 0;
	int px = 1;
	int y = 1;
	int py = 0;
	while ( b ) {
		div_t d = div(a, b);
		a = b;
		b = d.rem;
		int tmp = px;
		px = x;
		x = tmp - d.quot*x;
		tmp = py;
		py = y;
		y = tmp - d.quot*y;
	}
	return positive(py);
}
// Compute the kronecker product in Z_p.
template<class Mat1, class Mat2>
matrix_t kron(Mat1 const& a, Mat2 const& b) {
	matrix_t R( a.rows()*b.rows(), a.cols()*b.cols() );
	R = Eigen::kroneckerProduct(a, b);
	for(int j = 0; j < R.cols(); ++j) {
		for(int i = 0; i < R.rows(); ++i) {
			R(i) = reduce( R(i,j) );
		}
	}
	return R;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Routines to generate points
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Generate some random points on the Segre variety.
std::vector<matrix_t> random_points_segre( vector_t dims ) {
	const int d = dims.rows();
	const int r = ceil( (1.0*dims.prod()) / (dims.sum()-d+1) ) - 1;
	std::cout << "Generating " << r << " points." << std::endl;

	std::vector<matrix_t> Pts;
	for(int i = 0; i < d; ++i) {
		matrix_t M( dims[i], r );
		for(int j = 0; j < M.cols(); ++j) {
			for(int i = 0; i < M.rows(); ++i) {
				M(i,j) = reduce( rand() );
//				M(i,j) = M(i,j) ? M(i,j) : 1;
			}
		}
//		M.col(0).fill(0);
//		M(0,0) = 1;
		Pts.push_back(M);
	}

	return Pts;
}

// Construct the specific tensor from Section 5.2 in [1].
std::vector<matrix_t> specific_tensor_6pt2() {
	std::cout << "Generating the specific rank-7 tensor in C^{5 x 5 x 5} "
		<< "from section 6.2" << std::endl;
	std::vector<matrix_t> Pts;
	matrix_t M1( 5,7 );
	matrix_t M2( 5,7 );
	matrix_t M3( 5,7 );
	M1.fill(0);
	M2.fill(0);
	M3.fill(0);

	// p1
	M1(0,0) = 1; M2(0,0) = 1; M3(0,0) = 1;

	// p2
	M1(1,1) = 1; M2(1,1) = 1; M3(1,1) = 1;

	// p3
	M1(2,2) = 1; M2(2,2) = 1; M3(2,2) = 1;

	// p4
	M1(3,3) = 1; M2(3,3) = 1; M3(3,3) = 1;

	// p5
	M1(4,4) = 1; M2(4,4) = 1; M3(4,4) = 1;

	// p6
	M1.col(5).fill(1);
	for(int i = 0; i < 5; ++i)
		M2(i,5) = i+1;
	M3(0,5) = 1;
	M3(1,5) = 5;
	M3(2,5) = 7;
	M3(3,5) = -5 + M13;
	M3(4,5) = -7 + M13;

	// p7
	M1(0,6) = 4;
	M1(1,6) = 3;
	M1(2,6) = 2;
	M1(3,6) = -1 + M13;
	M1(4,6) = -2 + M13;
	M2(0,6) = 11;
	M2(1,6) = 13;
	M2(2,6) = 12;
	M2(3,6) = 15;
	M2(4,6) = 14;
	M3(0,6) = -2 + M13;
	M3(1,6) = 6;
	M3(2,6) = 5;
	M3(3,6) = -3 + M13;
	M3(4,6) = 6;

	std::cout << "M1 = \n" << M1 << std::endl;
	std::cout << "M2 = \n" << M2 << std::endl;
	std::cout << "M3 = \n" << M3 << std::endl;

	Pts.push_back(M1);
	Pts.push_back(M2);
	Pts.push_back(M3);
	return Pts;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Jacobian and Hessian construction routines.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Construct the tangent space matrix.
template<bool Compressed>
matrix_t tangent_space( std::vector< matrix_t > const& F ) {
	int d = F.size();
	int r = F[0].cols();
	vector_t dims(d);
	for(int i = 0; i < d; ++i) {
		dims[i] = F[i].rows();
	}

	const int rows = dims.prod();
	const int cols = r * (dims.sum() - Compressed*(d - 1));
	matrix_t T( rows, cols );

	int off = 0;
	for(int l = 0; l < d; ++l) {
	    int kni = dims[l];
	    for(int rk = 0; rk < r; ++rk) {
	    	const int startcol = Compressed ? 1 - (l==0) : 0;
	        for(int icol = startcol; icol < kni; ++icol) {
	            matrix_t Tl(1,1);
	            Tl.fill(1);
	            for(int k = 0; k < l; ++k) {
	                matrix_t cpy( F[k].col(rk) );
	            	matrix_t res( kron(cpy, Tl) );
	            	Tl.resize(res.rows(), res.cols());
	            	Tl = res;
	            }
				matrix_t cpy(matrix_t::Identity(kni,kni).col(icol));
				matrix_t res( kron(cpy, Tl) );
				Tl.resize(res.rows(), res.cols());
				Tl = res;
	            matrix_t Tr(1,1);
	            Tr.fill(1);
	            for(int k = l+1; k < d; ++k) {
	            	matrix_t cpy( F[k].col(rk) );
	                matrix_t res( kron(cpy, Tr) );
	                Tr.resize(res.rows(), res.cols());
					Tr = res;
	            }

	            T.col(off) = kron(Tr,Tl).col(0);
	            off = off + 1;
	        }
	    }
	}
	return T;
}


// Construct the (i,j) block of the Hessian, given the coefficients of a
// Cartesian equation in w as a column vector.
matrix_t general_hessian_block(int i, int j, vector_t dims, matrix_t w, std::vector<matrix_t> const& pt, int pt_idx) {
	if( i == j) {
		return matrix_t::Constant(dims(i), dims(i), 0);
	}
	assert(i < j);

	typedef Eigen::Matrix<int_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> matrix_t_col;
	matrix_t_col v(w);

	int_t remd = dims.prod();
	for(int m = 0; m < i; ++m) {
		remd /= dims(m);
		v.resize( dims(m), remd );
		vector_t tmp( pt[m].col(pt_idx).transpose() * v );
		v.resize(1, remd);
		v = tmp;
		for(int kkk = 0; kkk < remd; ++kkk) { v(kkk) = reduce( v(kkk) ); }
	}
	for(int m = dims.size()-1; m > j; --m) {
		remd /= dims(m);
		v.resize( remd, dims(m) );
		vector_t tmp( v * pt[m].col(pt_idx) );
		v.resize(remd, 1);
		v = tmp;
		for(int kkk = 0; kkk < remd; ++kkk) { v(kkk) = reduce( v(kkk) ); }
	}

	remd /= dims(i);
	v.resize( dims(i), remd );

	matrix_t R( dims(i), dims(j) );
	R.fill(-99);
	for(int r = 0; r < v.rows(); ++r) {
		int dim = remd;
		matrix_t_col copy( v.row(r) );
		for(int m = i+1; m < j; ++m) {
			dim /= dims(m);
			copy.resize( dims(m), dim );
			vector_t tmp( pt[m].col(pt_idx).transpose() * copy );
			copy.resize( 1, dim );
			copy = tmp;
			for(int kkk = 0; kkk < dim; ++kkk) { copy(kkk) = reduce( copy(kkk) ); }
		}
		copy.resize(1, copy.size());
		assert( copy.size() == dims(j) );
		R.row(r) = copy.rightCols(dims(j));
	}

	return R;
}

// Constructs the stacked Hessian of the Cartesian equations whose coefficients
// are given as the rows of the matrix N in the given point.
matrix_t general_hessian(vector_t dims, matrix_t& N, std::vector<matrix_t> const& pt, int pt_idx) {
	matrix_t H = matrix_t::Zero(
		N.rows() * dims.sum(), dims.sum()
	);
	for( int nr = 0; nr < N.rows(); ++nr) {
		matrix_t currow( N.row(nr).transpose() );
		int corr = nr*dims.sum();
		int roff = 0;
		for(int r = 0; r < dims.size(); ++r) {
			int coff = dims.head(r+1).sum();
			for(int c = r+1; c < dims.size(); ++c) {
				matrix_t M( general_hessian_block(r,c,dims,currow,pt,pt_idx) );
				assert(M.rows() == dims(r));
				assert(M.cols() == dims(c));
				H.block(roff+corr,coff,dims(r),dims(c)) = M;
				H.block(coff+corr,roff,dims(c),dims(r)) = M.transpose();
				coff += dims(c);
			}
			roff += dims(r);
		}
	}
	return H;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Gaussian elimination and null space extraction routines.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Gaussian elimination. Overwrites the input.
int_t gaussian_elimination( matrix_t& A, int colbound = -1 ) {
	const int rows = A.rows();
	const int cols = A.cols();

	if(colbound < 0) {
		colbound = cols;
	}

	int rank = 0;
	vector_t tmp( A.row(0) );
	int pc = 0;
	int pr = 0;
	while( (pc < cols) && (pr < rows) ) {
		int_t piv = reduce( positive(A(pr,pc)) );
		if(piv == 0) {
			// Look for a nonzero pivot.
			for(int rs = pr+1; rs < rows; ++rs) {
				assert( A(rs,pc) < M13 );
				if( A(rs,pc) ) {
					piv = reduce( positive(A(rs,pc)) );
					tmp = A.row(pr);
					A.row(pr)  = A.row(rs);
					A.row(rs) = tmp;
					break;
				}
			}
			// Didn't find a pivot, go to next column.
			if(!piv) {
				++pc;
				continue;
			}
		}

		// Compute inverse of pivot.
		int_t scal = inv(piv);
		assert(scal > 0);
		assert((scal * piv) % M13 == 1);
		A.row(pr).rightCols(cols-pc) *= scal;
		for(int cs = pc; cs < cols; ++cs) {
			assert( A(pr,cs) >= 0 );
			A(pr,cs) = reduce( A(pr,cs) );
		}

		// Lower sweep.
		for(int r = pr+1; r < rows; ++r) {
			if( A(r,pc) ) {
				A.row(r).rightCols(cols-pc) -=
					A(r,pc) * A.row(pr).rightCols(cols-pc);
				for(int cs = pc; cs < cols; ++cs) {
					A(r,cs) = reduce(positive(A(r,cs)));
				}
			}
		}

		// If we're still in the nonextended part, increase rank.
		if(pc < colbound) {
			++rank;
		}
		++pr;
		++pc;
	}

	return rank;
}
// Construct a basis for the null space of a matrix.
matrix_t null( matrix_t const& A ) {
	const int rows = A.rows();
	const int cols = A.cols();

	matrix_t Te( rows, rows+cols );
	Te.leftCols(cols) = A;
	Te.rightCols(rows) = matrix_t( matrix_t::Identity(rows,rows) );

	int rank = gaussian_elimination(Te, cols);
	assert(rank <= rows);
	assert(rank <= cols);

	std::cout << "Rank of " << Te.rows() << " x " << Te.cols() <<
		" tangent space matrix is claimed to be " << rank << std::endl;

	return matrix_t( Te.block(rank,cols,rows-rank, rows) );;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Driver routines.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Verifies the example from Section 5.2 in [1].
int verify_specific_example_S62() {
	// Generate the points.
	std::vector<matrix_t> points( specific_tensor_6pt2() );

	// Construct tangent space matrix.
	time_t ts_start = clock();
	matrix_t Ts( tangent_space<false>(points) );
	time_t ts_end = clock();
	std::cout << "Construction of the tangent space matrix took " <<
			(ts_end-ts_start)/(1000000.0) << "s." << std::endl;

	// Compute null space.
	time_t ge_start = clock();
	matrix_t N = null( Ts );
	time_t ge_end = clock();
	std::cout << "Null space computation took " <<
			(ge_end-ge_start)/(1000000.0) << "s." << std::endl;

	std::cout << "Null space matrix is of size " << N.rows() << " x "
		<< N.cols() << std::endl;

	vector_t dims(3);
	dims.fill(5);
	const int d = dims.size();
	const int r = points[0].cols();
	const int pi = dims.prod();
	const int sigma = dims.sum() - d;

	// In the specific identifiability case, checking the Hessian criterion 
	// at every point is necessary.
	bool alliswell = true;
	for(int idx = 0; idx < points[0].cols(); ++idx) {
		time_t he_start = clock();
		matrix_t H = general_hessian(dims,N,points,idx);
		int rank = gaussian_elimination(H);
		time_t he_end = clock();
		std::cout << "Hessian construction and rank computation took " <<
			(he_end-he_start)/(1000000.0) << "s." << std::endl;
		std::cout << "Stacked Hessian matrix is of size " << H.rows() << " x "
			<< H.cols() << std::endl;

		if(rank == sigma) {
			std::cout << dims.transpose() << " has a zero-dimensional contact variety at point " << idx << "." << std::endl;
		} else {
			std::cout << dims.transpose() << " at point " << idx << " is ";
			if( dims[0] > 1 + (N.rows() * ( dims.tail(d-1).sum() - (d-1) )) ) {
				const int expdef =
					dims[0]- 1 - (N.rows() * ( dims.tail(d-1).sum() - (d-1) ));
				if( sigma-rank == expdef ) {
					std::cout << "(FAKE) (" << rank << ", kernel=" <<
						N.rows() << ", def=" << sigma-rank << ")" << std::endl;
				} else {
					alliswell = false;
					std::cout << "(S-UNBALANCED - SPORADIC) (rank=" << rank <<
						", kernel=" << N.rows() << ", exp=" << expdef << "def=" <<
						sigma-rank << ")" << std::endl;
				}
			} else {
				alliswell = false;
				std::cout << "(SPORADIC) (rank=" << rank << ", kernel=" <<
					N.rows() << ", def=" << sigma-rank << ")" << std::endl;
			}
		}
		std::cout << std::flush;
	}
	
	if(alliswell) {
		std::cout << "IDENTIFIABLE" << std::endl;
	} else {
		std::cout << "HESSIAN CRITERION FAILED" << std::endl;
	}

	return 0;
}

template<bool Compressed>
int verify_generic_identifiability_segre(vector_t const& dims) {
	// Generate random points.
	std::vector<matrix_t> points( random_points_segre(dims) );

	// Construct tangent space matrix.
	time_t ts_start = clock();
	matrix_t Ts( tangent_space<Compressed>(points) );
	time_t ts_end = clock();
	std::cout << "Construction of the tangent space took " <<
			(ts_end-ts_start)/(1000000.0) << "s." << std::endl;

	// Compute null space.
	time_t ge_start = clock();
	matrix_t N = null( Ts );
	time_t ge_end = clock();
	std::cout << "Null space computation took " <<
			(ge_end-ge_start)/(1000000.0) << "s." << std::endl;

	const int d = dims.size();
	const int r = points[0].cols();
	const int pi = dims.prod();
	const int sigma = dims.sum() - d;

	// Check if it is one of the sporadic defective cases.
	if( N.rows() > pi - r*(sigma+1) ) {
		int def = N.rows() - (pi - r*(sigma+1));
		std::cout << dims.transpose() << " is defective (defect = " << def
			<< ")" << std::endl;
		std::cout << std::flush;
		return 0;
	}

	// To be absolutely certain, we verify the Hessian criterion at each of 
	// the points. This is in general not necessary, by the remark following
	// Proposition 2.3.
	bool alliswell = true;
	for(int idx = 0; idx < points[0].cols(); ++idx) {
		time_t he_start = clock();
		matrix_t H = general_hessian(dims,N,points,idx);
		int rank = gaussian_elimination(H);
		time_t he_end = clock();
		std::cout << "Hessian construction and rank computation took " <<
			(he_end-he_start)/(1000000.0) << "s." << std::endl;
		std::cout << "Stacked Hessian matrix is of size " << H.rows() << " x "
			<< H.cols() << std::endl;

		if(rank == sigma) {
			std::cout << dims.transpose() << " has a zero-dimensional contact variety at point " << idx << "."  << std::endl;
		} else {
			std::cout << dims.transpose() << " at point " << idx << " is ";
			if( dims[0] > 1 + (N.rows() * ( dims.tail(d-1).sum() - (d-1) )) ) {
				const int expdef =
					dims[0]- 1 - (N.rows() * ( dims.tail(d-1).sum() - (d-1) ));
				if( sigma-rank == expdef ) {
					std::cout << "(FAKE) (" << rank << ", kernel=" <<
						N.rows() << ", def=" << sigma-rank << ")" << std::endl;
				} else {
					alliswell = false;
					std::cout << "(S-UNBALANCED - SPORADIC) (rank=" << rank <<
						", kernel=" << N.rows() << ", exp=" << expdef << "def=" <<
						sigma-rank << ")" << std::endl;
				}
			} else {
				alliswell = false;
				std::cout << "(SPORADIC) (rank=" << rank << ", kernel=" <<
					N.rows() << ", def=" << sigma-rank << ")" << std::endl;
			}
		}
		std::cout << std::flush;
	}

	if(alliswell) {
		std::cout << "IDENTIFIABLE" << std::endl;
	} else {
		std::cout << "HESSIAN CRITERION FAILED" << std::endl;
	}

	return 0;
}

int main(int argc, char* args[]) {

	srand( time(0) );

	int d = argc-1;
	vector_t dims(d);
	for(int i = 0; i < d; ++i) {
		dims[i] = atoi(args[i+1]);
	}

	// Check sorted.
	for(int i = 1; i < dims.size(); ++i) {
		assert( dims[i-1] >= dims[i] );
	}

	// Check for the known cases.
	if( dims[0] > dims.tail(d-1).prod() - dims.tail(d-1).sum() + (d-1) ) {
		std::cout << dims.transpose() << " is unbalanced." << std::endl;
		return 0;
	}

	verify_generic_identifiability_segre<true>(dims);
//	verify_specific_example_S62();
	return 0;
}
