/*
 * The MIT License

   Conograph (powder auto-indexing program)

Copyright (c) <2012> <Ryoko Oishi-Tomiyasu, KEK>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 *
 */
#include <limits>
#include "gather_additional_Q.hh"
#include "../utility_data_structure/index_set.hh"
#include "../utility_func/zmath.hh"


// S_super is a Selling-reduced positive definite symmetric matrix.
// -(c1-c2)^2*S12 - (c1-c3)^2*S13 - (c2-c3)^2*S23 - c1^2*S14 - c2^2*S24 - c3^2*S34 <= maxQ
static void set_max_range(const SymMat<Double>& S_super, const Double& maxQ, 
		SymMat<Int4>& max_range)
{
	static const Int4 MAX_INT = numeric_limits<Int4>::max();
	static const Int4 SQUARE_MAX_INT = ifloor( sqrt( (Double)MAX_INT ) );
	static const Int4 ISIZE = 3;
	const Double min_dp = - maxQ / Double(MAX_INT);
	
	assert( S_super.size() == 4 );
	assert( max_range.size() == 3 );
	
	max_range = SQUARE_MAX_INT;

	for(Int4 i=0; i<ISIZE; i++)
	{
		for(Int4 i2=0; i2<i; i2++)
		{
			if( S_super(i, i2) < min_dp ) max_range(i,i2) = ifloor( sqrt( - maxQ / S_super(i, i2) ) );
		}
		if( S_super(i, ISIZE) < min_dp ) max_range(i,i) = ifloor( sqrt( - maxQ / S_super(i, ISIZE) ) );
	}

	Int4 num;
	bool flag = true;
	while( flag )
	{
		flag = false;
		
		for(Int4 i=0; i<ISIZE; i++)
		{
			for(Int4 i2=0; i2<i; i2++)
			{
				num = max_range(i,i)+max_range(i2,i2);
				for(Int4 k=0; k<ISIZE; k++)
				{
					// |ci - ci2| <= |ci - ck| + |ci2 - ck|
					num = min( max_range(i,k)+max_range(i2,k), num);
				}
				if( num < max_range(i,i2) )
				{
					max_range(i,i2) = num;
					flag = true;
				}
			}

			num = max_range(i,i);
			for(Int4 k=0; k<ISIZE; k++)
			{
				// |ci| <= |ci - ck| + |ck|
				num = min( max_range(i,k)+max_range(k,k), num );
			}
			if( num < max_range(i,i) )
			{
				max_range(i,i) = num;
				flag = true;
			}
			
		}
	}
}


static void set_candidate_Q(const Int4& index,
		const SymMat<Double>& S_super,
		const Double& minQ, const Double& maxQ,
		const SymMat<Int4>& max_range, 
		VecDat3<Int4>& hkl, vector<HKL_Q>& hkl_tray)
{
	const Int4 ISIZE = 3;

	if( index >= ISIZE )	// coef is determined.
	{
//		if( !checkFirstElementPositive(hkl) ) return;
		
		const Double Q = ( S_super(0,1)*(hkl[0]*hkl[1]) + S_super(0,2)*(hkl[0]*hkl[2]) + S_super(1,2)*(hkl[1]*hkl[2]) ) * 2.0
							+ S_super(0,0)*(hkl[0]*hkl[0]) + S_super(1,1)*(hkl[1]*hkl[1]) + S_super(2,2)*(hkl[2]*hkl[2]);
		
		if( Q >= minQ && maxQ >= Q )
		{
			hkl_tray.push_back(HKL_Q(hkl, Q));
		}
		return;
	}
	
	// coef[index] <= max_coef
	// coef[index] >= min_coef
	Int4 max_coef = max_range(index,index);
	Int4 min_coef = -max_range(index,index);
	for(Int4 k=0; k<index; k++)
	{
		// hkl[index] - hkl[k] <= max_range(k,index).
		max_coef = min( max_coef, max_range(k,index) + hkl[k] );

		// -max_range(k,index) <= hkl[index] - hkl[k].
		min_coef = -min( -min_coef, max_range(k,index) - hkl[k] );
	}
	if( index <= 0 )
	{
		hkl_tray.clear();
	}
	
	// First non-zero entry should be positive.
	bool non_zero_entry = false;
	for(Int4 i=0; i<index; i++)
	{
		if( hkl[i] != 0 )
		{
			non_zero_entry = true;
			break;
		}
	}
	if( !non_zero_entry ) min_coef = 0;

	for(Int4 ic=max_coef; ic>=min_coef; ic--)
	{
		hkl[index] = ic;
		set_candidate_Q(index+1, S_super, minQ, maxQ, max_range, hkl, hkl_tray);
	}
}


// On input, S_super = TransMat * S * transpose(TransMat).
void gatherQcal(const SymMat<Double>& S_super, 
		const Double& minQ, const Double& maxQ, const Int4& MAX_RANGE,
		vector<HKL_Q>& hkl_tray
	)
{
	SymMat<Int4> max_range(3);
	set_max_range(S_super, maxQ, max_range);

	if( max_range(0,0) > MAX_RANGE ) max_range(0,0) = MAX_RANGE;
	if( max_range(1,1) > MAX_RANGE ) max_range(1,1) = MAX_RANGE;
	if( max_range(2,2) > MAX_RANGE ) max_range(2,2) = MAX_RANGE;
	if( max_range(0,1) > MAX_RANGE ) max_range(0,1) = MAX_RANGE;
	if( max_range(0,2) > MAX_RANGE ) max_range(0,2) = MAX_RANGE;
	if( max_range(1,2) > MAX_RANGE ) max_range(1,2) = MAX_RANGE;

	VecDat3<Int4> hkl;
	set_candidate_Q(0, S_super, minQ, maxQ, max_range, hkl, hkl_tray);

	sort( hkl_tray.begin(), hkl_tray.end() );
}


void associateQcalWithQobs(const vector<HKL_Q>& hkl_tray,
		vector<QData>::const_iterator it_begin, vector<QData>::const_iterator it_end,
		vector< vector<HKL_Q>::const_iterator >& closest_hkl_tray)
{
	const Int4 num_obsQ = distance(it_begin, it_end);

	closest_hkl_tray.clear();
	closest_hkl_tray.resize( num_obsQ, hkl_tray.end() );
	if( hkl_tray.empty() )
	{
		return;
	}
	
	vector<QData>::const_iterator it;
	Int4 index;
	for(it=it_begin, index=0; it<it_end; it++, index++)
	{
		vector<HKL_Q>::const_iterator it2 = lower_bound( hkl_tray.begin(), hkl_tray.end(), HKL_Q(0, it->q) );
		if( it2 == hkl_tray.begin() ) closest_hkl_tray[index] = it2;
		else if( it2 == hkl_tray.end() ) closest_hkl_tray[index] = it2 - 1;
		else
		{
			const Double diff1_a = it->q - (it2-1)->Q();
			const Double diff1_b = it2->Q() - it->q;
//			const Double diff2_a = sqrt3_2(it->q) - sqrt3_2((it2-1)->Q());
//			const Double diff2_b = sqrt3_2(it2->Q()) - sqrt3_2(it->q);
			if( diff1_a > diff1_b )
			{
				closest_hkl_tray[index] = it2;
//				if( diff2_a < diff2_b ) closest_hkl_tray[index].push_back(it2-1);
			}
			else
			{
				closest_hkl_tray[index] = it2-1;
//				if( diff2_a > diff2_b ) closest_hkl_tray[index].push_back(it2);
			}
		}
	}
}


void associateQobsWithQcal(const vector<QData>& q_tray,
		vector<HKL_Q>::const_iterator it_begin, vector<HKL_Q>::const_iterator it_end,
		vector< vector<QData>::const_iterator >& closest_q_tray)
{
	closest_q_tray.clear();

	const Int4 num_calQ = distance(it_begin, it_end);
	closest_q_tray.resize( num_calQ, q_tray.end() );
	if( q_tray.empty() ) return;

	vector<HKL_Q>::const_iterator it;
	Int4 index;
	for(it=it_begin, index=0; it<it_end; it++, index++)
	{
		vector<QData>::const_iterator it2 = lower_bound( q_tray.begin(), q_tray.end(), QData(it->Q(), 0.0) );
		if( it2 == q_tray.begin() ) closest_q_tray[index] = it2;
		else if( it2 == q_tray.end() ) closest_q_tray[index] = it2 - 1;
		else
		{
			const Double diff1 = it->Q() - (it2-1)->q;
			const Double diff2 = it2->q - it->Q();
			if( diff1 > diff2 ) closest_q_tray[index] = it2;
			else closest_q_tray[index] = it2 - 1;
		}
	}
}
