/*
    Theseus - maximum likelihood superpositioning of macromolecular structures

    Copyright (C) 2004-2015 Douglas L. Theobald

    This file is part of THESEUS.

    THESEUS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    THESEUS is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with THESEUS in the file 'COPYING'. If not, see
    <http://www.gnu.org/licenses/>.

    -/_|:|_|_\-
*/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include "pdbUtils.h"
#include "pdbStats.h"
#include "CovMat.h"
#include "DLTmath.h"
#include "ProcGSLSVDNu.h"


static double
CalcInnProdNormNu(const double **cds, const int *nu, const int len)
{
    int             i;
    double          sum;
    const double   *x = (const double *) cds[0],
                   *y = (const double *) cds[1],
                   *z = (const double *) cds[2];
    double          xi, yi, zi;

    sum = 0.0;
    i = len;
    while(i-- > 0)
    {
        xi = *x++;
        yi = *y++;
        zi = *z++;

        sum += *nu++ * (xi * xi + yi * yi + zi * zi);
    }

    return(sum);
}


static void
CalcRvanNu(const double **cds1, const double **cds2, const int *nu, const int len, double **Rmat)
{
    int             i;
    double          weight;
    const double   *x1 = cds1[0],
                   *y1 = cds1[1],
                   *z1 = cds1[2];
    const double   *x2 = cds2[0],
                   *y2 = cds2[1],
                   *z2 = cds2[2];
    double          x2i, y2i, z2i, x1i, y1i, z1i;
    double          Rmat00, Rmat01, Rmat02,
                    Rmat10, Rmat11, Rmat12,
                    Rmat20, Rmat21, Rmat22;

    Rmat00 = Rmat01 = Rmat02 =
    Rmat10 = Rmat11 = Rmat12 =
    Rmat20 = Rmat21 = Rmat22 = 0.0;

    i = len;
    while(i-- > 0)
    {
        //weight = *o1++ * *o2++;
        weight = *nu++;

        x1i = *x1++;
        y1i = *y1++;
        z1i = *z1++;

        x2i = weight * *x2++;
        y2i = weight * *y2++;
        z2i = weight * *z2++;

        Rmat00 += x2i * x1i;
        Rmat01 += x2i * y1i;
        Rmat02 += x2i * z1i;

        Rmat10 += y2i * x1i;
        Rmat11 += y2i * y1i;
        Rmat12 += y2i * z1i;

        Rmat20 += z2i * x1i;
        Rmat21 += z2i * y1i;
        Rmat22 += z2i * z1i;
    }

    Rmat[0][0] = Rmat00;
    Rmat[0][1] = Rmat01;
    Rmat[0][2] = Rmat02;
    Rmat[1][0] = Rmat10;
    Rmat[1][1] = Rmat11;
    Rmat[1][2] = Rmat12;
    Rmat[2][0] = Rmat20;
    Rmat[2][1] = Rmat21;
    Rmat[2][2] = Rmat22;
}


static void
CalcGSLSVD(double **Rmat, double **Umat, double *sigma, double **VTmat)
{
    svdGSLDest(Rmat, 3, sigma, VTmat);
    Mat3TransposeIp(VTmat);
    Mat3Cpy(Umat, (const double **) Rmat);
}


/* Takes U and V^t on input, calculates R = VU^t */
static int
CalcRotMat(double **rotmat, double **Umat, double **Vtmat)
{
    int         i, j, k;
    double      det;

    memset(&rotmat[0][0], 0, 9 * sizeof(double));

    det = Mat3Det((const double **)Umat) * Mat3Det((const double **)Vtmat);

    if (det > 0)
    {
        for (i = 0; i < 3; ++i)
            for (j = 0; j < 3; ++j)
                for (k = 0; k < 3; ++k)
                    rotmat[i][j] += (Vtmat[k][i] * Umat[j][k]);

        return(1);
    }
    else
    {
        for (i = 0; i < 3; ++i)
        {
            for (j = 0; j < 3; ++j)
            {
                for (k = 0; k < 2; ++k)
                    rotmat[i][j] += (Vtmat[k][i] * Umat[j][k]);

                rotmat[i][j] -= (Vtmat[2][i] * Umat[j][2]);
            }
        }

        return(-1);
    }
}


/* returns sum of squared residuals, E
   rmsd = sqrt(E/atom_num)  */
double
ProcGSLSVDvanNu(const double **cds1, const double **cds2, const int *nu,
                const int len, double **rotmat,
                double **Rmat, double **Umat, double **VTmat, double *sigma,
                double *norm1, double *norm2, double *innprod)
{
    double          det;

    *norm1 = CalcInnProdNormNu(cds1, nu, len);
    *norm2 = CalcInnProdNormNu(cds2, nu, len);
    CalcRvanNu(cds1, cds2, nu, len, Rmat);
    CalcGSLSVD(Rmat, Umat, sigma, VTmat);
    det = CalcRotMat(rotmat, Umat, VTmat);

/*     VerifyRotMat(rotmat, 1e-5); */
/*     printf("\n*************** sumdev = %8.2f ", sumdev); */
/*     printf("\nrotmat:"); */
/*     write_C_mat((const double **)rotmat, 3, 8, 0); */

    if (det < 0)
        *innprod = sigma[0] + sigma[1] - sigma[2];
    else
        *innprod = sigma[0] + sigma[1] + sigma[2];

/*     printf("\nRmat:"); */
/*     write_C_mat((const double **)Rmat, 3, 8, 0); */
/*     printf("\nUmat:"); */
/*     write_C_mat((const double **)Umat, 3, 8, 0); */
/*     printf("\nVTmat:"); */
/*     write_C_mat((const double **)VTmat, 3, 8, 0); */
/*     int i; */
/*     for (i = 0; i < 3; ++i) */
/*         printf("\nsigma[%d] = %8.2f ", i, sigma[i]); */

    return(*norm1 + *norm2 - 2.0 * *innprod);
}

