/*
 * An implementation of Algorithm 2 from [1] for induction on dimension for cubics.
 *
 * Dependencies
 *   - Requires the Eigen library version 3.3.4, which can be obtained freely
 *     from http://eigen.tuxfamily.org/
 *   - Requires the FFLAS-FFPACK library version 2.2.2, which can be obtained
 *     freely from https://linbox-team.github.io/fflas-ffpack/
 *   - Requires the OpenMP library version 4.5, which is included in the GCC
 *     compiler version 7.4.
 *   - Requires an implementation of the BLAS interface, such as OpenBLAS 0.2.20.
 *
 * This code can be compiled with the following command that should work on an
 * up-to-date linux distribution:
 *   g++ -I/path-to-eigen -c -O3 -DNDEBUG dimension_induction.cpp
 *   g++ -fopenmp dimension_induction.o -o"TV_N" -lblas -lgivaro
 *
 * The executable accepts 6 input arguments, and is called as follows:
 *      ./ExecutableName n s a1 a2 a3 b
 *
 * where:
 *   * b is either 0 or 1. A "1" indicates that the code should check that the
 *     configuration is subabundant and true, while a "0" asks the code to check
 *     whether the configuration is superabundant and true.
 *   * n, s, a1, a2, and a3 are integers specifying the configuration of interest,
 *     namely n the number of variables, s the number of general points, and a1, 
 *     a2 and a3 respectively the number of points specialized to P_1, P_2 and P_3.
 *
 * 
 * [1] Torrance and Vannieuwenhoven, Secant varieties of the Chow variety are nondefective
 *     for cubics and quaternary forms, 2020.
 */

#define EIGEN_INITIALIZE_MATRICES_BY_ZERO

#include <eigen3/Eigen/Eigen>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Sparse>
#include <eigen3/unsupported/Eigen/KroneckerProduct>
#include <fflas-ffpack/fflas-ffpack.h>
#include <vector>
#include <iostream>
#include <omp.h>
#include <chrono>

#define int_t int32_t
#define vector_t Eigen::Matrix<int_t,Eigen::Dynamic,1>
#define matrix_t Eigen::Matrix<int_t,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor>
#define sparse_matrix_t Eigen::SparseMatrix<int_t,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>
#define BITS 13L
#define M13 ((1L<<BITS)-1L)
#define REDSKIP (((1L<<62L)-1L)/(M13*M13))


// Reduce a number to its canonical representation in Z_p.
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;
}

// Compute the kronecker product of two vectors a and b 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;
}

// Computes the linear index of a given multilinear index 0 <= i,j,k < n
inline const int lidx(
		int const& i, int const& j, int const& k, int const& n
) {
	return n*n*k + n*j + i;
}

// Construct the symmetric product of the vectors a, b, and c.
vector_t compressed_rank_one(
		vector_t const& a, vector_t const& b, vector_t const& c
) {
	const int n = a.size()-1;
	int N = (n+3)*(n+2)*(n+1) / 6;
	vector_t z(N);
	z.fill(0);
	vector_t v( kron(a, kron(b,c)).col(0) );

	int idx = 0;
	for(int i = 0; i < n+1; ++i) {
		for(int j = i; j < n+1; ++j) {
			for(int k = j; k < n+1; ++k) {
				z[idx] += v(lidx(i,j,k,n+1));
				v[lidx(i,j,k,n+1)] = 0;
				z[idx] += v(lidx(i,k,j,n+1));
				v[lidx(i,k,j,n+1)] = 0;
				z[idx] += v(lidx(j,i,k,n+1));
				v[lidx(j,i,k,n+1)] = 0;
				z[idx] += v(lidx(j,k,i,n+1));
				v[lidx(j,k,i,n+1)] = 0;
				z[idx] += v(lidx(k,i,j,n+1));
				v[lidx(k,i,j,n+1)] = 0;
				z[idx] += v[lidx(k,j,i,n+1)];
				v[lidx(k,j,i,n+1)] = 0;

				z[idx] = reduce( z[idx] );
				++idx;
			}
		}
	}
	return z;
}

// Compute the rank of A over the finite field Z_8191.
int_t fflas_gaussian_elimination( matrix_t& A ) {
	Givaro::ModularBalanced<int_t> F8191(M13);
	int_t* ptrA = A.data();
	const int m = A.rows();
	const int n = A.cols();
	const int rank = FFPACK::Rank(F8191, m, n, ptrA, A.outerStride() );
	return rank;
}

// Construct a boolean vector where a 1 at position z indicates that e_z is in
// the standard basis of S_3(U_l).
vector_t symm_pow_block_compact( int const& n, int const& l) {
	const int low = 27*l;
	const int high = low+27;
	const int N = (n+3)*(n+2)*(n+1) / 6;
	vector_t z( N );
	z.fill(0);
	int idx = 0;
	for(int i = 0; i < n+1; ++i) {
		for(int j = i; j < n+1; ++j) {
			for(int k = j; k < n+1; ++k) {
				if( (
						!(low <= i && i < high) &&
						!(low <= j && j < high) &&
						!(low <= k && k < high)
				) ) {
					z[idx] = 1;
				}
				++idx;
			}
		}
	}
	return z;
}

// Computes the binomial coefficient n choose d.
inline long binomial(const int& n, const int& d) {
	if(d > n) { return 0; }
	long r = 1;
	for(int k = n; k > n-d; --k)
		r *= k;
	for(int k = 2; k <= d; ++k)
		r /= k;
	return r;
}

// Computes the rank of a matrix representation of the subspace A_{K,s_b}(t).
int A_rank(int const& n, int const& s, vector_t const& a, int const& sub) {
	using std::max;

	const int N = (n+3)*(n+2)*(n+1) / 6;
	vector_t iset( N );
	iset.fill(0);

	// Compute the row indices Y.
	for(int i = 0; i < 3; ++i) {
		if(a[i] > 0) {
			iset += symm_pow_block_compact(n,i);
		}
	}
	for(int i = 0; i < iset.rows(); ++i) {
		iset[i] = int(iset[i] == 0);
	}
	int rankSP = iset.rows() - iset.sum();

	int nnc = 0;
	const int_t sc = (max((int_t)0,(int_t)a[0])+max((int_t)0,(int_t)a[1])+max((int_t)0,(int_t)a[2]))*81;
	const int_t gc = max(0,s)*(3*(n + 1));

	auto rc_start = std::chrono::system_clock::now();

	// Compute the tangent space to the specialized points (R2)
	matrix_t S( N, sc+gc );
	S.fill(0);
	for(int kk = 0; kk < 3; ++kk) {
		for(int i = 0; i < a[kk]; ++i) {
			vector_t k(n+1);
			vector_t l(n+1);
			vector_t m(n+1);
			k.fill(0);
			l.fill(0);
			m.fill(0);
			for(int ii=0; ii<n+1; ++ii) {
				if( ii < 27*kk || ii >= 27*(kk+1) ) {
					k[ii] = reduce( rand() );
					l[ii] = reduce( rand() );
					m[ii] = reduce( rand() );
				}
			}
			std::cout << "k_{" << kk << "," << i << "} = ["
					<< k.transpose() << "]" << std::endl;
			std::cout << "l_{" << kk << "," << i << "} = ["
					<< l.transpose() << "]" << std::endl;
			std::cout << "m_{" << kk << "," << i << "} = ["
					<< m.transpose() << "]" << std::endl;


			#pragma omp parallel for
			for(int kkk = 0; kkk < 27; ++kkk) {
				vector_t ek( n+1 );
				ek.fill(0);
				ek[ 27*kk + kkk ] = 1;
				S.col( nnc + 3*kkk + 0 ) = compressed_rank_one(k,l,ek);
				S.col( nnc + 3*kkk + 1 ) = compressed_rank_one(k,m,ek);
				S.col( nnc + 3*kkk + 2 ) = compressed_rank_one(l,m,ek);
			}
			nnc += 81;
		}
	}

	// Compute the tangent space to the regular points (R1)
	for(int i = 0; i < s; ++i) {
		vector_t k(n+1);
		vector_t l(n+1);
		vector_t m(n+1);
		for(int ii=0; ii<n+1; ++ii) {
			k[ii] = reduce( rand() );
			l[ii] = reduce( rand() );
			m[ii] = reduce( rand() );
		}
		std::cout << "k_" << i << " = [" << k.transpose() << "]" << std::endl;
		std::cout << "l_" << i << " = [" << l.transpose() << "]" << std::endl;
		std::cout << "m_" << i << " = [" << m.transpose() << "]" << std::endl;
		#pragma omp parallel for
		for(int kk = 0; kk < n+1; ++kk) {
			vector_t ek( n+1 );
			ek.fill(0);
			ek[kk] = 1;
			S.col( nnc + 3*kk + 0 ) = compressed_rank_one(k,l,ek);
			S.col( nnc + 3*kk + 1 ) = compressed_rank_one(k,m,ek);
			S.col( nnc + 3*kk + 2 ) = compressed_rank_one(l,m,ek);
		}
		nnc += 3*(n+1);
	}

	// Compute the compressed representation R(Y).
	int j = 0;
	matrix_t M(iset.sum(), S.cols());
	for(int i = 0; i < S.rows(); ++i) {
		if(iset[i] == 1) {
			M.row(j) = S.row(i);
			++j;
		}
	}

	// Expected dimension.
	int expRank = 81*a.sum() + s*(3*n+1);
	int sgn = 1;
	int k = int(a[0] > 0) + int(a[1] > 0) + int(a[2] > 0);
	for(int i = 1; i <= k; ++i) {
		expRank += sgn * binomial(k, i) * binomial(n-27*i+3,3);
		sgn *= -1;
	}
	if(!sub) {
		expRank = binomial(n+3,3);
	}

	auto rc_end = std::chrono::system_clock::now();
	auto rc_time = std::chrono::duration_cast<std::chrono::milliseconds>(rc_end - rc_start);
	std::cout << "Constructed R(Y) in " << rc_time.count()/1000.0 << "s." << std::endl;

	// Compute rank.
	auto rk_start = std::chrono::system_clock::now();
	int rankS = fflas_gaussian_elimination(M);
	auto rk_end = std::chrono::system_clock::now();
	auto rk_time = std::chrono::duration_cast<std::chrono::milliseconds>(rk_end - rk_start);

	// Reporting.
	std::cout << "Computed the rank of the " << M.rows() << " x " << M.cols()
			<< " matrix R(Y) over F_" << M13 << " in "
			<< rk_time.count()/1000.0 << "s." <<std::endl;
	int rank = rankSP + rankS;

	std::cout << "Found " << rankSP << " + " << rankS << " = " << rank
			<< " vs. " << expRank << " expected." << std::endl;
	std::cout << "T(" << n << ", " << s << "; "
			<< a[0] << ", " << a[1] << ", " << a[2] << ") is ";
	if(rank == expRank) {
		std::cout << "TRUE";
		if(sub) {
			std::cout << " (SUBABUNDANT)";
		} else {
			std::cout << " (SUPERABUNDANT)";
		}
	} else {
		std::cout << "FALSE";
		if(sub) {
			std::cout << " (NOT SUBABUNDANT)";
		} else {
			std::cout << " (NOT SUPERABUNDANT)";
		}
	}
	std::cout << std::endl;

	return rankSP+rankS;
}

int main(int argc, char* args[]) {
	auto seed = int(time(0));
	srand( seed );
	std::cout << "Using random seed: " << seed << std::endl;

	int n = atoi(args[1]);
	int s = atoi(args[2]);
	vector_t a( 3 );
	a[0] = atoi(args[3]);
	a[1] = atoi(args[4]);
	a[2] = atoi(args[5]);
	int sub = atoi(args[6]);

	// Construct tangent space matrix.
	auto ts_start = std::chrono::system_clock::now();
	A_rank(n,s,a,sub);
	auto ts_end = std::chrono::system_clock::now();
	auto time = std::chrono::duration_cast<std::chrono::milliseconds>(ts_end - ts_start);
	std::cout << "Total computation took " << time.count()/1000.0 << "s." << std::endl;

	return 0;
}
