/*
 * An implementation of Algorithm 1 from [1] for induction on degree for 
 * quaternary forms.
 *
 * 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 degree_induction.cpp
 *   g++ -fopenmp degree_induction.o -o"TV_D" -lblas -lgivaro
 *
 * The executable accepts 5 input arguments, and is called as follows:
 *      ./ExecutableName n t l i 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, t, l and i are integers specifying the configuration of interest,
 *     namely n the number of variables (only 3 is supported), t the degree, 
 *     l the induction step length, and i the number of planes P_j to specialize to.
 *
 * 
 * [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 BITS 13L
#define M13 ((1L<<BITS)-1L)
#define REDSKIP (((1L<<62L)-1L)/(M13*M13))

// Iterator over sorted multi-indices.
struct mlindex {
	vector_t idx_;
	int_t n_;

	mlindex(int_t d, int_t n) : idx_(d), n_(n) {
		idx_.fill(0);
	}

	mlindex& operator++() {
		const int_t d = idx_.innerSize();
		int_t i = d;
		while( 1+(--i) && !(idx_[i] = ++idx_[i] % n_));
		if(i < 0) { idx_[0] = -1; i = d; }
		while( ++i < d && (idx_[i]=idx_[i-1]) );
		return *this;
	}

	bool operator!=(mlindex const& idx) const {
		if(idx_.innerSize() != idx.idx_.innerSize()) return false;
		if(n_ != idx.n_) return false;
		return vector_t(idx_==idx.idx_).all();
	}

	mlindex begin() const {
		return mlindex(idx_.innerSize(), n_);
	}

	mlindex end() const {
		mlindex idx(idx_.innerSize(), n_);
		idx.idx_[0] = -1;
		return idx;
	}

	vector_t const& operator*() const {
		return idx_;
	}
};

// 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;
}

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

// Computes the linear index of a sorted multi-index.
template<int n>
int lidx(vector_t const& idx, matrix_t const& lookupTable ) {
	int_t off = lookupTable.col(idx.size()-1).middleRows(n+idx.size()-idx[0], idx[0]).sum();
	for(int_t p = 1, d = idx.size()-2; p < idx.size()-1; ++p, --d) {
		off += lookupTable.col(d).middleRows(n+d-idx[p]+1, idx[p]-idx[p-1]).sum();
	}
	off += idx[idx.size()-1]-idx[idx.size()-2];
	return off;
}


// 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;
}

// Computes the subabundant number of points of degree d at the i-th level,
// using an induction step length s.
inline int_t nb_points(const int_t& i, const int_t& d, const int_t& s, const int_t& n, const bool& sub) {
	if( i < 0) {
		return 0;
	}
	if( i == 0) {
		ldiv_t res = div(binomial(d+n,d), (long)(n*d+1));
		return res.quot - (res.rem==0) + (sub==false);
	}
	return nb_points(i-1,d,s,n,sub) - nb_points(i-1,d-s,s,n,sub);
}

// Computes the product of the degree-d polynomial x and the linear
// form l, storing the result in res.
template<int n, class Vector>
inline void fast_compressed_rank_one(
	vector_t& res,
	vector_t const& x, int_t d,
	Vector const& l,
	matrix_t const& lt
) {
	int_t li = 0;
	mlindex idxs(d,n+1);
	res.fill(0);
	vector_t ids(d+1);
	for( auto i : idxs ) {
		for(int_t j = 0; j < n+1; ++j) {
			std::merge( &i[0], &i[0]+d, &j, &j+1, &ids[0] );
			const int_t k = lidx<n>(ids, lt);
			res[ k ] = reduce(res[k] + x[li] * l[j]);
		}
		++li;
	}
}

// Computes the product of the degree-d polynomial with the monomial
// x_{shift[0]} ... x_{shift[end]}.
template<int n>
inline void fast_shift(
		vector_t& res,
		vector_t const& x, int_t d,
		vector_t const& shift,
		matrix_t const& lt
) {
	const int_t d2 = shift.size();
	mlindex idxs(d,n+1);
	vector_t ids(d+d2);
	res.fill(0);
	int_t li = 0;
	for( auto i : idxs) {
		std::merge( &i[0], &i[0]+d, &shift[0], &shift[0]+d2, &ids[0] );
		const int_t k = lidx<n>(ids, lt);
		res[ k ] = x[li];
		++li;
	}
}

// Fills a view on a matrix with random numbers.
template<class MatrixView>
inline void fill_random(MatrixView M) {
	const int_t m = M.rows();
	const int_t n = M.cols();
	for(int i = 0; i < m; ++i) {
		for(int j = 0; j < n; ++j) {
			M(i,j) = reduce(rand());
		}
	}
}

// Computes the rank of the tangent space to the split variety.
template< int n >
int fast_A_rank(const int& d, const int& l, const int& i, const bool& sub) {
	const int_t N = binomial(n+d,d);

	const int_t cs = binomial(d-l+n,d-l)*i + i*nb_points(i-1,d-l,l,n,sub)*l*(n+1) + nb_points(i,d,l,n,sub)*d*(n+1);
	std::cout << "Need a " << N << " x " << cs << " matrix." << std::endl;

	// Construct the lookup table for the linear indexing
	matrix_t lookupTableTmp(n+d+1,d+1);
	lookupTableTmp.fill(0);
	for(int_t dd = 0; dd <= d; ++dd) {
		for(int_t nn = 0; nn <= n; ++nn) {
			lookupTableTmp(dd+nn,dd) = binomial(dd+nn,dd);
		}
	}
	const matrix_t lookupTable(lookupTableTmp);

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

	vector_t t1(N);
	vector_t t2(N);
	vector_t* tv1 = &t1;
	vector_t* tv2 = &t2;

	// Compute the tangent space at the specialized points.
	matrix_t T( N, cs );
	T.fill(0);
	int c = 0;
	const int_t maxJJ = nb_points(i-1,d-l,l,n,sub);
	int_t lc = 0;
	for(int_t j = 0; j < i; ++j) {
		matrix_t G(n+1,d);
		fill_random( G.rightCols(l) );

		// Record specialized point.
		for( int_t ll = d-l; ll < d; ++ll ) {
			std::cout << "g_{" << j << "," << ll-(d-l) << "} = [" << G.col(ll).transpose() << "]" << std::endl;
		}

		// Compute G.
		tv1->topRows(n+1) = G.col(d-l);
		for(int_t ll = 1; ll < l; ++ll) {
			fast_compressed_rank_one<n>(*tv2, *tv1, ll, G.col(d-l+ll), lookupTable);
			std::swap(tv1, tv2);
		}
		const int_t gN = binomial(n+l,l);
		const vector_t g(tv1->topRows(gN));

		// Compute G R_(d-l)
		mlindex idx(d-l,n+1);
		for( auto mi : idx ) {
			tv1->topRows(gN) = g;
			fast_shift<n>( *tv2, *tv1, l, mi, lookupTable );
			++c;
			T.col(cs-c) = *tv2;
		}

		// Compute F G R_(1)
		for(int_t jj = 0; jj < maxJJ; ++jj) {
			fill_random( G.leftCols(d-l) );

			// Record specialized point.
			for(int_t ll = 0; ll < d-l; ++ll) {
				std::cout << "f_{" << j << "," << jj << "," << ll << "} = [" << G.col(ll).transpose() << "]" << std::endl;
			}

			// Compute F.
			tv1->topRows(n+1) = G.col(0);
			for(int_t ll = 1; ll < d-l; ++ll) {
				fast_compressed_rank_one<n>(*tv2, *tv1, ll, G.col(ll), lookupTable);
				std::swap(tv1, tv2);
			}
			const int_t fN = binomial(n+d-l,d-l);
			const vector_t f(tv1->topRows(fN));

			for(int_t k = 0; k < l; ++k) {
				matrix_t F(G);
				F.col(d-k-1).fill(0);

				// Compute G.
				tv1->topRows(fN) = f;
				for(int_t ll = d-l; ll < d; ++ll) {
					if(ll != d-k-1) {
						fast_compressed_rank_one<n>(*tv2, *tv1, ll-(ll>d-k-1), F.col(ll), lookupTable);
						std::swap(tv1, tv2);
					}
				}

				// Shift into the correct positions.
				vector_t shift(1);
				for(int_t kk = 0; kk < n+1; ++kk) {
					shift[0] = kk;
					fast_shift<n>(*tv2, *tv1, d-1, shift, lookupTable);
					T.col(kk*l*maxJJ*i + lc) = *tv2;
				}

				++lc;
			}
		}
	}

	// Compute the tangent space at the general points.
	const int_t maxJ = nb_points(i,d,l,n,sub);
	const int_t boff = (n+1)*l*maxJJ*i;
	matrix_t P(n+1,d);
	lc = 0;
	for(int_t j = 0; j < maxJ; ++j) {
		fill_random( P.leftCols(d) );

		// Record general points.
		for(int_t ll = 0; ll < d; ++ll) {
			std::cout << "l_{" << j << "," << ll << "} = [" << P.col(ll).transpose() << "]" << std::endl;
		}

		for(int_t k = 0; k < d; ++k) {
			matrix_t F(P);
			F.col(k).fill(0);

			// Compute polynomial.
			tv1->topRows(n+1) = F.col(0 + (k==0));
			for(int_t ll = 1+(k==0); ll < d; ++ll) {
				if(ll != k) {
					fast_compressed_rank_one<n>(*tv2, *tv1, ll-(ll>k), F.col(ll), lookupTable);
					std::swap(tv1, tv2);
				}
			}

			// Shift into the correct positions.
			vector_t shift(1);
			for(int_t kk = 0; kk < n+1; ++kk) {
				shift[0] = kk;
				fast_shift<n>(*tv2, *tv1, d-1, shift, lookupTable);
				T.col(kk*d*maxJ + lc + boff) = *tv2;
			}
			++lc;
		}
	}

	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 T in " << rc_time.count()/1000.0 << "s." << std::endl;

	// Compute rank.
	auto rk_start = std::chrono::system_clock::now();
	int rankT = fflas_gaussian_elimination(T);
	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 " << T.rows() << " x " << T.cols()
			<< " matrix T over F_" << M13 << " in "
			<< rk_time.count()/1000.0 << "s." <<std::endl;

	int_t g = 0;
	for(int_t j = 1; j <= i; ++j) {
		g += pow(-1, j-1) * binomial(i,j) * binomial(n+d-l*j,n);
	}

	int_t expRank = g + i*nb_points(i-1,d-l,l,n,sub)*l*(n) + nb_points(i,d,l,n,sub)*(n*d+1);
	if(!sub) {
		expRank = binomial(d+n,d);
	}
	std::cout << "Found " << rankT << " vs. " << expRank << " expected." << std::endl;
	std::cout << "T_" << i << "(" << n << ", " << d << ", "
			<< l << ") is ";
	if(rankT == 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 0;
}

int main(int argc, char* args[]) {
	Eigen::setNbThreads(0);

	auto seed = int(time(0));
	srand( seed );
	std::cout << "Using random seed: " << seed << std::endl;

	int n = atoi(args[1]);
	int d = atoi(args[2]);
	int l = atoi(args[3]);
	int i = atoi(args[4]);
	bool sub = bool(atoi(args[5]));


	if( (n == 3) && (d > 1) ) {
		fast_A_rank<3>(d,l,i,sub);
		return 0;
	} else if (d <= 1) {
		std::cerr << "The degree should be at least 2." << std::endl;
	} else {
		std::cerr << "Only n = 3 is supported!" << std::endl;
	}
	return 1;
}

