/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * Geophysical Computational Tools & Library (GCTL)
 *
 * Copyright (c) 2022  Yi Zhang (yizhang-geo@zju.edu.cn)
 *
 * GCTL is distributed under a dual licensing scheme. You can redistribute 
 * it and/or modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation, either version 2 
 * of the License, or (at your option) any later version. You should have 
 * received a copy of the GNU Lesser General Public License along with this 
 * program. If not, see <http://www.gnu.org/licenses/>.
 * 
 * If the terms and conditions of the LGPL v.2. would prevent you from using 
 * the GCTL, please consider the option to obtain a commercial license for a 
 * fee. These licenses are offered by the GCTL's original author. As a rule, 
 * licenses are provided "as-is", unlimited in time for a one time fee. Please 
 * send corresponding requests to: yizhang-geo@zju.edu.cn. Please do not forget 
 * to include some description of your company and the realm of its activities. 
 * Also add information on how to contact you by electronic and paper mail.
 ******************************************************/

#include "mkernel_tetrahedron.h"

void gctl::callink_magnetic_para(array<mag_tetrahedron> &in_tet, array<magtet_para> &out_para, const array<point3dc> &mag_B)
{
	point3dc v1, v2, v3, ne, nf, mag_z;

	out_para.resize(in_tet.size());
	for (int i = 0; i < in_tet.size(); ++i)
	{
		if (in_tet[i].vert[0] == nullptr || in_tet[i].vert[1] == nullptr || 
			in_tet[i].vert[2] == nullptr || in_tet[i].vert[3] == nullptr)
		{
			throw runtime_error("Invalid vertex pointer. From callink_magnetic_para(...)");
		}

		// magnetic susceptibility is taken as one here
        out_para[i].B = mag_B[i];

		for (int f = 0; f < 4; ++f)
		{
			v1 = *in_tet[i].fget(f, 1) - *in_tet[i].fget(f, 0);
			v2 = *in_tet[i].fget(f, 2) - *in_tet[i].fget(f, 0);
			nf = cross(v1, v2).normal();
			out_para[i].F[f] = kron(nf, nf);

			for (int e = 0; e < 3; ++e)
			{
				v3 = *in_tet[i].fget(f, (e+1)%3) - *in_tet[i].fget(f, e);
				out_para[i].edglen[e+f*3] = v3.module();
				out_para[i].E[e+f*3] = kron(nf, cross(v3, nf).normal());
			}
		}

		in_tet[i].att = out_para.get(i);
	}
	return;
}

void gctl::callink_magnetic_para_earth(array<mag_tetrahedron> &in_tet, array<magtet_para> &out_para, 
	double inclina_deg, double declina_deg, double field_tense)
{
	if (declina_deg < -180.0 || declina_deg > 180.0 || 
		inclina_deg < -90 || inclina_deg > 90 || field_tense < 0.0)
	{
		throw invalid_argument("Invalid parameters. From gctl::callink_magnetic_para_earth(...)");
	}

	point3dc v1, v2, v3, ne, nf, mag_z;
	double I = inclina_deg*GCTL_Pi/180.0;
	double A = (90 - declina_deg)*GCTL_Pi/180.0;

	out_para.resize(in_tet.size());
	for (int i = 0; i < in_tet.size(); ++i)
	{
		if (in_tet[i].vert[0] == nullptr || in_tet[i].vert[1] == nullptr || 
			in_tet[i].vert[2] == nullptr || in_tet[i].vert[3] == nullptr)
		{
			throw runtime_error("Invalid vertex pointer. From callink_magnetic_para_earth(...)");
		}

		// magnetic susceptibility is taken as one here
		out_para[i].B.x = cos(I)*cos(A)*field_tense;
		out_para[i].B.y = cos(I)*sin(A)*field_tense;
		out_para[i].B.z = sin(I)*field_tense;

		for (int f = 0; f < 4; ++f)
		{
			v1 = *in_tet[i].fget(f, 1) - *in_tet[i].fget(f, 0);
			v2 = *in_tet[i].fget(f, 2) - *in_tet[i].fget(f, 0);
			nf = cross(v1, v2).normal();
			out_para[i].F[f] = kron(nf, nf);

			for (int e = 0; e < 3; ++e)
			{
				v3 = *in_tet[i].fget(f, (e+1)%3) - *in_tet[i].fget(f, e);
				out_para[i].edglen[e+f*3] = v3.module();
				out_para[i].E[e+f*3] = kron(nf, cross(v3, nf).normal());
			}
		}

		in_tet[i].att = out_para.get(i);
	}
	return;
}

void gctl::callink_magnetic_para_earth_sph(array<mag_tetrahedron> &in_tet, array<magtet_para> &out_para, 
	double inclina_deg, double declina_deg, array<point3dc> *mag_vec, double field_tense)
{
	if (declina_deg < -180.0 || declina_deg > 180.0 || 
		inclina_deg < -90 || inclina_deg > 90 || field_tense < 0.0)
	{
		throw invalid_argument("Invalid parameters. From gctl::callink_magnetic_para_earth_sph(...)");
	}

	point3dc v1, v2, v3, ne, nf, mag_z;
	point3ds s;

	double I = inclina_deg*GCTL_Pi/180.0;
	double A = declina_deg*GCTL_Pi/180.0;

	if (mag_vec != nullptr) mag_vec->resize(in_tet.size());
	out_para.resize(in_tet.size());
	for (int i = 0; i < in_tet.size(); ++i)
	{
		if (in_tet[i].vert[0] == nullptr || in_tet[i].vert[1] == nullptr || 
			in_tet[i].vert[2] == nullptr || in_tet[i].vert[3] == nullptr)
		{
			throw runtime_error("Invalid vertex pointer. From callink_magnetic_para_earth_sph(...)");
		}

		// magnetization vector at the local coordinates
		// note here the postive direction of the inclination angle is downward
		// note here the postive direction of the declination angle is clockwise
		mag_z.x = cos(I)*sin(A);
		mag_z.y = cos(I)*cos(A);
		mag_z.z = -1.0*sin(I);

		s = c2s(in_tet[i].center());
		// magnetic susceptibility is taken as one here
		// rotate the local coordinate system to the regular status
		out_para[i].B = field_tense * mag_z.rotate((90.0 - s.lat)*GCTL_Pi/180.0, 0.0, (90.0 + s.lon)*GCTL_Pi/180.0).normal();
		if (mag_vec != nullptr) mag_vec->at(i) = out_para[i].B;

		for (int f = 0; f < 4; ++f)
		{
			v1 = *in_tet[i].fget(f, 1) - *in_tet[i].fget(f, 0);
			v2 = *in_tet[i].fget(f, 2) - *in_tet[i].fget(f, 0);
			nf = cross(v1, v2).normal();
			out_para[i].F[f] = kron(nf, nf);

			for (int e = 0; e < 3; ++e)
			{
				v3 = *in_tet[i].fget(f, (e+1)%3) - *in_tet[i].fget(f, e);
				out_para[i].edglen[e+f*3] = v3.module();
				out_para[i].E[e+f*3] = kron(nf, cross(v3, nf).normal());
			}
		}

		in_tet[i].att = out_para.get(i);
	}
	return;
}

gctl::point3dc gctl::magkernel_single(const gctl::mag_tetrahedron &a_ele, const gctl::point3dc &a_op)
{
    int f,e;
	double Le,wf;
	double dv1,dv2;
	gctl::point3dc r_ijk[3];
	gctl::tensor face_sum(0.0);
	gctl::tensor edge_sum(0.0);
	double L_ijk[3];

	gctl::magtet_para* gp = a_ele.att;

	int *v_order = a_ele.vec_order;

	for (f = 0; f < 4; f++)
	{
		r_ijk[0] = *a_ele.vert[v_order[3*f]] - a_op;
		r_ijk[1] = *a_ele.vert[v_order[3*f+1]] - a_op;
		r_ijk[2] = *a_ele.vert[v_order[3*f+2]] - a_op;

		L_ijk[0] = r_ijk[0].module();
		L_ijk[1] = r_ijk[1].module();
		L_ijk[2] = r_ijk[2].module();

		wf =2*atan2(dot(r_ijk[0], cross(r_ijk[1],r_ijk[2])),
					L_ijk[0]*L_ijk[1]*L_ijk[2] + L_ijk[0]*dot(r_ijk[1],r_ijk[2]) + 
					L_ijk[1]*dot(r_ijk[2],r_ijk[0]) + L_ijk[2]*dot(r_ijk[0],r_ijk[1]));

		face_sum = face_sum + wf * gp->F[f];

		for (e = 0; e < 3; e++)
		{
			dv1 = distance(*a_ele.vert[v_order[e+3*f]], a_op);
			dv2 = distance(*a_ele.vert[v_order[(e+1)%3+3*f]], a_op);

			Le = log((dv1+dv2+gp->edglen[e+3*f])/(dv1+dv2-gp->edglen[e+3*f]));

			edge_sum = edge_sum + Le  * gp->E[e+3*f];
		}
	}

	// 位场正演中通常z方向取垂直向下为正方向
	// nT -> T 1e-9 / 4*pi*e-7 = 1/(400*pi)*100 = 1/(4*pi) -> A/m
	gctl::tensor gt = -1.0/(4.0*GCTL_Pi)*(face_sum - edge_sum);
	gctl::point3dc out_b = gt*gp->B;
	return out_b;
}

gctl::point3dc gctl::magkernel_single(const gctl::mag_tetrahedron &a_ele, const gctl::point3ds &a_op, tensor *R_ptr)
{
	int f,e;
	double Le,wf;
	double dv1,dv2;
	gctl::point3dc r_ijk[3];
	gctl::tensor R;
	gctl::tensor face_sum(0.0);
	gctl::tensor edge_sum(0.0);
	double L_ijk[3];

	if (R_ptr != nullptr) R = *R_ptr;
	else R = transform_matrix(a_op);

	gctl::magtet_para* gp = a_ele.att;
	gctl::point3dc pc = s2c(a_op);
	int *v_order = a_ele.vec_order;

	for (f = 0; f < 4; f++)
	{
		r_ijk[0] = *a_ele.vert[v_order[3*f]] - pc;
		r_ijk[1] = *a_ele.vert[v_order[3*f+1]] - pc;
		r_ijk[2] = *a_ele.vert[v_order[3*f+2]] - pc;

		L_ijk[0] = r_ijk[0].module();
		L_ijk[1] = r_ijk[1].module();
		L_ijk[2] = r_ijk[2].module();

		wf = 2*atan2(dot(r_ijk[0], cross(r_ijk[1],r_ijk[2])),
					L_ijk[0]*L_ijk[1]*L_ijk[2] + L_ijk[0]*dot(r_ijk[1],r_ijk[2]) + 
					L_ijk[1]*dot(r_ijk[2],r_ijk[0]) + L_ijk[2]*dot(r_ijk[0],r_ijk[1]));

		face_sum = face_sum + wf * gp->F[f];

		for (e = 0; e < 3; e++)
		{
			dv1 = distance(*a_ele.vert[v_order[e+3*f]], pc);
			dv2 = distance(*a_ele.vert[v_order[(e+1)%3+3*f]], pc);

			Le = log((dv1+dv2+gp->edglen[e+3*f])/(dv1+dv2-gp->edglen[e+3*f]));

			edge_sum = edge_sum + Le  * gp->E[e+3*f];
		}
	}

	// nT -> T 1e-9 / 4*pi*e-7 = 1/(400*pi)*100 = 1/(4*pi) -> A/m
	gctl::tensor gt = -1.0/(4.0*GCTL_Pi)*(face_sum - edge_sum);
	gctl::point3dc out_c = R*(gt*gp->B);
	out_c.x *= -1.0;
	return out_c;
}

void gctl::magobser(array<point3dc> &out_obs, const array<mag_tetrahedron> &ele, 
	const array<point3dc> &obsp, const array<double> &sus, verbose_type_e verbose)
{
	int i, j;
	int o_size = obsp.size();
	int e_size = ele.size();

	out_obs.resize(o_size, point3dc(0.0, 0.0, 0.0));

	gctl::progress_bar bar(e_size, "magobser_componments");
	for (j = 0; j < e_size; j++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(j);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(j);

#pragma omp parallel for private (i) schedule(guided)
		for (i = 0; i < o_size; i++)
		{
			out_obs[i] = out_obs[i] + sus[j]*magkernel_single(ele[j], obsp[i]);;
		}
	}
	return;
}

void gctl::magobser(array<point3dc> &out_obs, const array<mag_tetrahedron> &ele, 
	const array<point3ds> &obsp, const array<double> &sus, verbose_type_e verbose)
{
	int i, j;
	int o_size = obsp.size();
	int e_size = ele.size();

	out_obs.resize(o_size, point3dc(0.0, 0.0, 0.0));
	array<tensor> Rs(o_size);
#pragma omp parallel for private (i) schedule(guided)
	for (i = 0; i < o_size; i++)
	{
		Rs[i] = transform_matrix(obsp[i]);
	}

	gctl::progress_bar bar(e_size, "magobser_componments");
	for (j = 0; j < e_size; j++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(j);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(j);

#pragma omp parallel for private (i) schedule(guided)
		for (i = 0; i < o_size; i++)
		{
			out_obs[i] = out_obs[i] + sus[j] * magkernel_single(ele[j], obsp[i], Rs.get(i));
		}
	}
	return;
}