/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * 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_Ren2017.h"
#include "cmath"

#define GCTL_MAG_TETRA_TOL 1e-16

void gctl::callink_magnetic_para_direct(array<magtet_ren17> &in_tet, array<magtet_para_ren17> &out_para, const array<point3dc> &magz)
{
	point3dc v1, v2, v3, ne, nf;

	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(...)");
		}

		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].nf[f] = nf;

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

			out_para[i].mag_amp[f] = dot(magz[i], nf);
		}

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

void gctl::callink_magnetic_para_earth(array<magtet_ren17> &in_tet, array<magtet_para_ren17> &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(...)");
	}

	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(...)");
		}

		// magnetic susceptibility is taken as one here
		mag_z.x = cos(I)*cos(A)*field_tense;
		mag_z.y = cos(I)*sin(A)*field_tense;
		mag_z.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].nf[f] = nf;

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

			out_para[i].mag_amp[f] = dot(mag_z, nf);
		}

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

void gctl::callink_magnetic_para_earth_sph(array<magtet_ren17> &in_tet, array<magtet_para_ren17> &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*M_PI/180.0;
	double A = declina_deg*M_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
		mag_z = field_tense * mag_z.rotate((90.0 - s.lat)*M_PI/180.0, 0.0, (90.0 + s.lon)*M_PI/180.0).normal();
		if (mag_vec != nullptr) mag_vec->at(i) = mag_z;

		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].nf[f] = nf;

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

			out_para[i].mag_amp[f] = dot(mag_z, nf);
		}

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

void gctl::callink_magnetic_para_earth_sph(magtet_ren17 &in_tet, magtet_para_ren17 &out_para, 
	double inclina_deg, double declina_deg, 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("[gctl::callink_magnetic_para_earth_sph] Invalid parameters.");
	}

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

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

	if (in_tet.vert[0] == nullptr || in_tet.vert[1] == nullptr || in_tet.vert[2] == nullptr || in_tet.vert[3] == nullptr)
	{
		throw runtime_error("[gctl::callink_magnetic_para_earth_sph] Invalid vertex pointer.");
	}

	// 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.center());
	// magnetic susceptibility is taken as one here
	// rotate the local coordinate system to the regular status
	mag_z = field_tense * mag_z.rotate((90.0 - s.lat)*M_PI/180.0, 0.0, (90.0 + s.lon)*M_PI/180.0).normal();
	if (mag_vec != nullptr) *mag_vec = mag_z;

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

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

		out_para.mag_amp[f] = dot(mag_z, nf);
	}

	in_tet.att = &out_para;
	return;
}

// declare algorithm for individual element and observation point
double magkernel_tetrahedron_potential_sig(const gctl::magtet_ren17 &ele_ptr, const gctl::point3dc &op_ptr);
gctl::point3dc magkernel_tetrahedron_gradient_sig(const gctl::magtet_ren17 &ele_ptr, const gctl::point3dc &op_ptr);
gctl::tensor magkernel_tetrahedron_tensor_sig(const gctl::magtet_ren17 &ele_ptr, const gctl::point3dc &op_ptr);

// define functions
void gctl::magkernel(matrix<double> &out_kernel, const array<magtet_ren17> &ele, 
	const array<point3dc> &obsp, verbose_type_e verbose)
{
	int i, j;
	int o_size = obsp.size();
	int e_size = ele.size();

	out_kernel.resize(o_size, e_size);

	gctl::progress_bar bar(o_size, "magkernel_potential");
	for (i = 0; i < o_size; i++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(i);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(i);

#pragma omp parallel for private (j) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			out_kernel[i][j] = magkernel_tetrahedron_potential_sig(ele[j], obsp[i]);
		}
	}
	return;
}

void gctl::magkernel(matrix<point3dc> &out_kernel, const array<magtet_ren17> &ele, 
	const array<point3dc> &obsp, verbose_type_e verbose)
{
	int i, j;
	int o_size = obsp.size();
	int e_size = ele.size();
	point3dc pc;

	out_kernel.resize(o_size, e_size);

	gctl::progress_bar bar(o_size, "magkernel_gradient");
	for (i = 0; i < o_size; i++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(i);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(i);

#pragma omp parallel for private (j, pc) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			pc = magkernel_tetrahedron_gradient_sig(ele[j], obsp[i]);
			out_kernel[i][j] = pc;
		}
	}
	return;
}

void gctl::magkernel(matrix<tensor> &out_kernel, const array<magtet_ren17> &ele, 
	const array<point3dc> &obsp, verbose_type_e verbose)
{
	int i, j;
	int o_size = obsp.size();
	int e_size = ele.size();

	out_kernel.resize(o_size, e_size);

	gctl::progress_bar bar(o_size, "magkernel_tensor");
	for (i = 0; i < o_size; i++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(i);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(i);

#pragma omp parallel for private (j) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			out_kernel[i][j] = magkernel_tetrahedron_tensor_sig(ele[j], obsp[i]);
		}
	}
	return;
}

void gctl::magkernel(matrix<double> &out_kernel, const array<magtet_ren17> &ele, const array<point3dc> &obsp, 
    double geo_declina, double geo_inclina, verbose_type_e verbose)
{
	int i, j;
	int o_size = obsp.size();
	int e_size = ele.size();

	// note that we use regular right-hand cartesian coordinates here, not the reversed z-axis one.
    double hax_f = cos(M_PI*geo_inclina/180.0)*sin(M_PI*geo_declina/180.0);
    double hay_f = cos(M_PI*geo_inclina/180.0)*cos(M_PI*geo_declina/180.0);
    double za_f  = sin(M_PI*geo_inclina/180.0);

	out_kernel.resize(o_size, e_size);

	point3dc tmp_grad;
	gctl::progress_bar bar(o_size, "magkernel_deltaT");
	for (i = 0; i < o_size; i++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(i);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(i);

#pragma omp parallel for private (j, tmp_grad) shared (hax_f, hay_f, za_f) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			tmp_grad = magkernel_tetrahedron_gradient_sig(ele[j], obsp[i]);
			out_kernel[i][j] = hax_f*tmp_grad.x + hay_f*tmp_grad.y + za_f*tmp_grad.z;
		}
	}
	return;
}

void gctl::magkernel(matrix<point3dc> &out_kernel, const array<magtet_ren17> &ele, 
	const array<point3ds> &obsp, verbose_type_e verbose)
{
	int i, j;
	point3dc obsp_c;
	tensor R;
	int o_size = obsp.size();
	int e_size = ele.size();

	out_kernel.resize(o_size, e_size);

	gctl::progress_bar bar(o_size, "magkernel_gradient");
	for (i = 0; i < o_size; i++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(i);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(i);

#pragma omp parallel for private (j, obsp_c) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			obsp_c = s2c(obsp[i]);
			out_kernel[i][j] = magkernel_tetrahedron_gradient_sig(ele[j], obsp_c);
		}
	}

	for (i = 0; i < o_size; i++)
	{
		R[0][0] = sin((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][1] = sin((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][2] = cos((0.5-obsp[i].lat/180.0)*M_PI);

		R[1][0] = cos((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][1] = cos((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][2] = -1.0*sin((0.5-obsp[i].lat/180.0)*M_PI);

		R[2][0] = -1.0*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][1] = cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][2] = 0.0;

#pragma omp parallel for private (j) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			out_kernel[i][j] = R * out_kernel[i][j];
			out_kernel[i][j].x *= -1.0;
		}
	}
	return;
}

void gctl::magkernel(matrix<tensor> &out_kernel, const array<magtet_ren17> &ele, 
	const array<point3ds> &obsp, verbose_type_e verbose)
{
	int i, j;
	point3dc obsp_c;
	tensor R, R_T;
	int o_size = obsp.size();
	int e_size = ele.size();

	out_kernel.resize(o_size, e_size);

	gctl::progress_bar bar(o_size, "magkernel_tensor");
	for (i = 0; i < o_size; i++)
	{
		if (verbose == gctl::FullMsg) bar.progressed(i);
		else if (verbose == gctl::ShortMsg) bar.progressed_simple(i);

#pragma omp parallel for private (j, obsp_c) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			obsp_c = s2c(obsp[i]);
			out_kernel[i][j] = magkernel_tetrahedron_tensor_sig(ele[j], obsp_c);
		}
	}

	for (i = 0; i < o_size; i++)
	{
		R[0][0] = sin((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][1] = sin((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][2] = cos((0.5-obsp[i].lat/180.0)*M_PI);

		R[1][0] = cos((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][1] = cos((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][2] = -1.0*sin((0.5-obsp[i].lat/180.0)*M_PI);

		R[2][0] = -1.0*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][1] = cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][2] = 0.0;

		R_T = R.transpose();

#pragma omp parallel for private (j) schedule(guided)
		for (j = 0; j < e_size; j++)
		{
			out_kernel[i][j] = R*(out_kernel[i][j]*R_T);
			out_kernel[i][j][0][0] *= -1.0;
			out_kernel[i][j][0][1] *= -1.0;
			out_kernel[i][j][0][2] *= -1.0;
			out_kernel[i][j][1][0] *= -1.0;
			out_kernel[i][j][2][0] *= -1.0;
		}
	}
	return;
}

gctl::point3dc gctl::magkernel_single(const magtet_ren17 &ele, const point3ds &obsp)
{
	tensor R;
	R[0][0] = sin((0.5-obsp.lat/180.0)*M_PI)*cos((2.0+obsp.lon/180.0)*M_PI);
	R[0][1] = sin((0.5-obsp.lat/180.0)*M_PI)*sin((2.0+obsp.lon/180.0)*M_PI);
	R[0][2] = cos((0.5-obsp.lat/180.0)*M_PI);

	R[1][0] = cos((0.5-obsp.lat/180.0)*M_PI)*cos((2.0+obsp.lon/180.0)*M_PI);
	R[1][1] = cos((0.5-obsp.lat/180.0)*M_PI)*sin((2.0+obsp.lon/180.0)*M_PI);
	R[1][2] = -1.0*sin((0.5-obsp.lat/180.0)*M_PI);

	R[2][0] = -1.0*sin((2.0+obsp.lon/180.0)*M_PI);
	R[2][1] = cos((2.0+obsp.lon/180.0)*M_PI);
	R[2][2] = 0.0;

	point3dc obsp_c = s2c(obsp);
	point3dc out_k = magkernel_tetrahedron_gradient_sig(ele, obsp_c);

	out_k = R * out_k;
	out_k.x *= -1.0;
	return out_k;
}

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

	out_obs.resize(o_size, 0.0);

	gctl::progress_bar bar(e_size, "magobser_potential");
	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] += magkernel_tetrahedron_potential_sig(ele[j], obsp[i]);
		}
	}
	return;
}

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

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

	gctl::progress_bar bar(e_size, "magobser_gradient");
	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, pc) schedule(guided)
		for (i = 0; i < o_size; i++)
		{
			pc = magkernel_tetrahedron_gradient_sig(ele[j], obsp[i]);
			out_obs[i] = out_obs[i] + pc;
		}
	}
	return;
}

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

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

	gctl::progress_bar bar(e_size, "magobser_tensor");
	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] + magkernel_tetrahedron_tensor_sig(ele[j], obsp[i]);
		}
	}
	return;
}

void gctl::magobser(array<double> &out_obs, const array<magtet_ren17> &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, 0.0);

	gctl::progress_bar bar(e_size, "magobser_potential");
	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] += sus[j] * magkernel_tetrahedron_potential_sig(ele[j], obsp[i]);
		}
	}
	return;
}

void gctl::magobser(array<point3dc> &out_obs, const array<magtet_ren17> &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();
	point3dc pc;

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

	gctl::progress_bar bar(e_size, "magobser_gradient");
	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, pc) schedule(guided)
		for (i = 0; i < o_size; i++)
		{
			pc = sus[j] * magkernel_tetrahedron_gradient_sig(ele[j], obsp[i]);
			out_obs[i] = out_obs[i] + pc;
		}
	}
	return;
}

void gctl::magobser(array<tensor> &out_obs, const array<magtet_ren17> &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, tensor(0.0));

	gctl::progress_bar bar(e_size, "magobser_tensor");
	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_tetrahedron_tensor_sig(ele[j], obsp[i]);
		}
	}
	return;
}

void gctl::magobser(array<point3dc> &out_obs, const array<magtet_ren17> &ele, const array<point3ds> &obsp, 
    const array<double> &sus, verbose_type_e verbose)
{
	int i, j;
	point3dc obsp_c;
	gctl::tensor R;
	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_gradient");
	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, obsp_c) schedule(guided)
		for (i = 0; i < o_size; i++)
		{
			obsp_c = s2c(obsp[i]);
			out_obs[i] = out_obs[i] + sus[j] * magkernel_tetrahedron_gradient_sig(ele[j], obsp_c);
		}
	}

#pragma omp parallel for private (i, R) schedule(guided)
	for (i = 0; i < o_size; i++)
	{
		R[0][0] = sin((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][1] = sin((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][2] = cos((0.5-obsp[i].lat/180.0)*M_PI);

		R[1][0] = cos((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][1] = cos((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][2] = -1.0*sin((0.5-obsp[i].lat/180.0)*M_PI);

		R[2][0] = -1.0*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][1] = cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][2] = 0.0;

		out_obs[i] = R * out_obs[i];
		out_obs[i].x *= -1.0;
	}
	return;
}

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

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

	gctl::progress_bar bar(e_size, "magobser_tensor");
	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, obsp_c) schedule(guided)
		for (i = 0; i < o_size; i++)
		{
			obsp_c = s2c(obsp[i]);
			out_obs[i] = out_obs[i] + sus[j] * magkernel_tetrahedron_tensor_sig(ele[j], obsp_c);
		}
	}

#pragma omp parallel for private (i, R, R_T) schedule(guided)
	for (i = 0; i < o_size; i++)
	{
		R[0][0] = sin((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][1] = sin((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[0][2] = cos((0.5-obsp[i].lat/180.0)*M_PI);

		R[1][0] = cos((0.5-obsp[i].lat/180.0)*M_PI)*cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][1] = cos((0.5-obsp[i].lat/180.0)*M_PI)*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[1][2] = -1.0*sin((0.5-obsp[i].lat/180.0)*M_PI);

		R[2][0] = -1.0*sin((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][1] = cos((2.0+obsp[i].lon/180.0)*M_PI);
		R[2][2] = 0.0;

		R_T = R.transpose();

		out_obs[i] = R*(out_obs[i]*R_T);
		out_obs[i][0][0] *= -1.0;
		out_obs[i][0][1] *= -1.0;
		out_obs[i][0][2] *= -1.0;
		out_obs[i][1][0] *= -1.0;
		out_obs[i][2][0] *= -1.0;
	}
	return;
}

double magkernel_tetrahedron_potential_sig(const gctl::magtet_ren17 &tet, const gctl::point3dc &site)
{
	double Rij_minus, Rij_plus, Sij_plus, Sij_minus, Rij0, mij0, wi0;
	double part1, part2, k0, absw, beta;
	gctl::point3dc oi;

	// get attribute pointer
	if (tet.att == nullptr) throw gctl::runtime_error("Magnetization parameter not set. from gctl::magkernel_tetrahedron_potential_sig(...)");
	gctl::magtet_para_ren17 *mpara = tet.att;

	double out_pot = 0.0;
	for (int f = 0; f < 4; ++f)
	{
		k0 = 0.0;
		for (int j = 0; j < 3; ++j)
		{
			Rij_minus = (site - *tet.fget(f, j)).module();
			Rij_plus  = (site - *tet.fget(f, (j+1)%3)).module();

			if (j == 0)
			{
				wi0 = gctl::dot(site - *tet.fget(f, j), mpara->nf[f]);
				absw = std::abs(wi0);
			}

			oi = site - wi0*mpara->nf[f];
			Sij_minus = gctl::dot(*tet.fget(f, j) - oi, mpara->te[3*f+j]);
		    Sij_plus  = gctl::dot(*tet.fget(f, (j+1)%3) - oi, mpara->te[3*f+j]);
		    mij0 = gctl::dot(*tet.fget(f, j) - oi, mpara->ne[3*f+j]);
		    Rij0 = std::sqrt(wi0*wi0 + mij0*mij0);

			part2 = 0.0;
			if (absw > GCTL_MAG_TETRA_TOL)
			{
				beta = std::atan((mij0*Sij_plus)/(Rij0*Rij0+absw*Rij_plus))
					- std::atan((mij0*Sij_minus)/(Rij0*Rij0+absw*Rij_minus));
				part2 = absw*beta;
			}

			part1 = 0.0;
			if (std::abs(mij0) > GCTL_MAG_TETRA_TOL)
			{
				part1 = mij0*std::log((Rij_plus+Sij_plus)/(Rij_minus+Sij_minus));
			}

			k0 += (part1 - part2);
		}

		// nT -> T 1e-9 / 4*pi*e-7 = 1/(400*pi)*100 = 1/(4*pi) -> A/m
		out_pot += 1.0/(4.0*GCTL_Pi)*k0*mpara->mag_amp[f];
	}

	return out_pot;
}

gctl::point3dc magkernel_tetrahedron_gradient_sig(const gctl::magtet_ren17 &tet, const gctl::point3dc &site)
{
	double Rij_minus, Rij_plus, Sij_plus, Sij_minus, Rij0, mij0, wi0;
	double beta, Aij, sig, absw;
	gctl::point3dc oi, k1, part1, part2;

	// get attribute pointer
	if (tet.att == nullptr) throw gctl::runtime_error("Magnetization parameter not set. from gctl::magkernel_tetrahedron_gradient_sig(...)");
	gctl::magtet_para_ren17 *mpara = tet.att;

	gctl::point3dc out_grad(0.0, 0.0, 0.0);
	for (int f = 0; f < 4; ++f)
	{
		k1.set(0.0, 0.0, 0.0);
		for (int j = 0; j < 3; ++j)
		{
			Rij_minus = (site - *tet.fget(f, j)).module();
			Rij_plus  = (site - *tet.fget(f, (j+1)%3)).module();

			if (j == 0)
			{
				wi0 = gctl::dot(site - *tet.fget(f, j), mpara->nf[f]);
				sig = gctl::sign(wi0);
				absw = std::abs(wi0);
			}

			oi = site - wi0*mpara->nf[f];
			Sij_minus = gctl::dot(*tet.fget(f, j) - oi, mpara->te[3*f+j]);
			Sij_plus  = gctl::dot(*tet.fget(f, (j+1)%3) - oi, mpara->te[3*f+j]);
			mij0 = gctl::dot(*tet.fget(f, j) - oi, mpara->ne[3*f+j]);
			Rij0 = std::sqrt(wi0*wi0 + mij0*mij0);

			part2.set(0.0, 0.0, 0.0);
			if (absw > GCTL_MAG_TETRA_TOL)
			{
				beta = atan((mij0*Sij_plus)/(Rij0*Rij0 + absw*Rij_plus))
					- atan((mij0*Sij_minus)/(Rij0*Rij0 + absw*Rij_minus));

				part2 = sig*beta*mpara->nf[f];
			}

			if (std::abs(Rij0) > GCTL_MAG_TETRA_TOL)
			{
				Aij = std::log((long double)(Rij_plus+Sij_plus)) - std::log((long double)(Rij_minus+Sij_minus));
			}
			else if (Sij_plus > 0.0 && Sij_minus > 0.0)
			{
				Aij = std::log(Sij_plus) - std::log(Sij_minus);
			}
			else if (Sij_plus < 0.0 && Sij_minus < 0.0)
			{
				Aij = std::log(-1.0*Sij_minus) - std::log(-1.0*Sij_plus);
			}
			else
			{
				throw gctl::runtime_error("Observation site on edge. From magtet::mag_gradient()");
			}

			part1 = Aij * mpara->ne[3*f+j];
			k1 = k1 - (part1 + part2);
		}

		// nT -> T 1e-9 / 4*pi*e-7 = 1/(400*pi)*100 = 1/(4*pi) -> A/m
		out_grad = out_grad - 1.0/(4.0*GCTL_Pi)*k1*mpara->mag_amp[f];
	}
	return out_grad;
}

gctl::tensor magkernel_tetrahedron_tensor_sig(const gctl::magtet_ren17 &tet, const gctl::point3dc &site)
{
	double Rij_minus, Rij_plus, Sij_plus, Sij_minus, Rij0, mij0, wi0;
	double beta, sig, absw;
	double factor_n_mij, factor_tij;
	gctl::point3dc oi, grad_Aij;
	gctl::point3dc grad_Rij_plus, grad_Rij_minus, grad_Sij_plus, grad_Sij_minus;
	gctl::point3dc grad_mij0, grad_Rij0, grad_abs_wi0;
	gctl::point3dc grad_a_plus, grad_b_plus, grad_a_minus, grad_b_minus;
	gctl::point3dc grad_betaij_plus, grad_betaij_minus, grad_betaij;
	double a_plus, b_plus, a_minus, b_minus;
	double k3;
	gctl::tensor tmp_k, k2;

	// get attribute pointer
	if (tet.att == nullptr) throw gctl::runtime_error("Magnetization parameter not set. from gctl::magkernel_tetrahedron_tensor_sig(...)");
	gctl::magtet_para_ren17 *mpara = tet.att;

	gctl::tensor out_tensor(0.0);
	for (int f = 0; f < 4; ++f)
	{
		k2.set(0.0);
		k3 = 0.0;
		for (int j = 0; j < 3; ++j)
		{
			Rij_minus = (site - *tet.fget(f, j)).module();
			Rij_plus  = (site - *tet.fget(f, (j+1)%3)).module();

			if (j == 0)
			{
				wi0 = gctl::dot(site - *tet.fget(f, j), mpara->nf[f]);
				sig = gctl::sign(wi0);
				absw = std::abs(wi0);
			}

			oi = site - wi0*mpara->nf[f];
			Sij_minus = gctl::dot(*tet.fget(f, j) - oi, mpara->te[3*f+j]);
			Sij_plus  = gctl::dot(*tet.fget(f, (j+1)%3) - oi, mpara->te[3*f+j]);
			mij0 = gctl::dot(*tet.fget(f, j) - oi, mpara->ne[3*f+j]);
			Rij0 = std::sqrt(wi0*wi0 + mij0*mij0);

			if (std::abs(Rij0) > GCTL_MAG_TETRA_TOL)
			{
				factor_n_mij = -1.0*(Sij_plus/(Rij0*Rij0*Rij_plus) - Sij_minus/(Rij0*Rij0*Rij_minus));
				factor_tij   = -1.0/Rij_plus + 1.0/Rij_minus;
				grad_Aij = (wi0*factor_n_mij)*mpara->nf[f] + factor_tij*mpara->te[3*f+j] 
					- (mij0*factor_n_mij)*mpara->ne[3*f+j];
			}
			else
			{
				factor_tij   = -1.0/Rij_plus + 1.0/Rij_minus;
				grad_Aij = factor_tij*mpara->te[3*f+j];
			}

			//tmp_k = gctl::kron(grad_Aij, ne_[e][3*f+j]);
			tmp_k = gctl::kron(mpara->ne[3*f+j], grad_Aij);
			k2 = k2 - tmp_k;

			if (absw > GCTL_MAG_TETRA_TOL)
			{
				grad_Rij_plus  = (1.0/Rij_plus)*(site - *tet.fget(f, (j+1)%3));
				grad_Rij_minus = (1.0/Rij_minus)*(site - *tet.fget(f, j));
				grad_Sij_plus  = -1.0*mpara->te[3*f+j];
				grad_Sij_minus = -1.0*mpara->te[3*f+j];
				grad_mij0    = -1.0*mpara->ne[3*f+j];
				grad_Rij0    = (1.0/Rij0)*(wi0*mpara->nf[f] - mij0*mpara->ne[3*f+j]);
				grad_abs_wi0 = sig*mpara->nf[f];
				a_plus = Rij0*Rij0 + absw*Rij_plus;
				b_plus = mij0*Sij_plus;
				grad_a_plus = (2.0*Rij0)*grad_Rij0 + Rij_plus*grad_abs_wi0 + absw*grad_Rij_plus;
				grad_b_plus = Sij_plus*grad_mij0 + mij0*grad_Sij_plus;
				a_minus = Rij0*Rij0 + absw*Rij_minus;
				b_minus = mij0*Sij_minus;
				grad_a_minus = (2.0*Rij0)*grad_Rij0 + Rij_minus*grad_abs_wi0 + absw*grad_Rij_minus;
				grad_b_minus = Sij_minus*grad_mij0 + mij0*grad_Sij_minus;
				grad_betaij_plus  = (1.0/(a_plus*a_plus + b_plus*b_plus))*(a_plus*grad_b_plus - b_plus*grad_a_plus);
				grad_betaij_minus = (1.0/(a_minus*a_minus + b_minus*b_minus))*(a_minus*grad_b_minus - b_minus*grad_a_minus);

				grad_betaij = grad_betaij_plus - grad_betaij_minus;

				tmp_k = gctl::kron(grad_betaij, mpara->nf[f]);
				k2 = k2 - sig*tmp_k;
			}
			else
			{
				if (std::abs(mij0) > GCTL_MAG_TETRA_TOL)
				{
					k3 += (-1.0/mij0)*(Sij_plus/Rij_plus - Sij_minus/Rij_minus);
				}
			}
		}

		if (k3 != 0.0)
		{
			tmp_k = gctl::kron(mpara->nf[f], mpara->nf[f]);
			k2 = k2 - k3*tmp_k;
		}

		// nT -> T 1e-9 / 4*pi*e-7 = 1/(400*pi)*100 = 1/(4*pi) -> A/m
		out_tensor = out_tensor - 1.0/(4.0*GCTL_Pi)*k2*mpara->mag_amp[f];
	}

	return out_tensor;
}
