/** @file  psMatrix.c
 *
 *  @brief Provides functions for linear algebra operations on psImages and psVectors.
 *
 *  Functions are provided to:
 *      Transpose a psImage
 *      Compute LUD
 *      Solve LUD
 *      Matrix inversion
 *      Calculate determinant
 *      Matrix addition
 *      Matrix subtraction
 *      Matrix multiplication
 *      Calculate Eigenvectors
 *      Convert matrix to vector
 *      Convert vector to matrix
 *
 *  These functions treat psImages as if they were matrices, therefore there is no psMatrix.
 *
 *  @author Ross Harman, MHPCC
 *
 *  @version $Revision: 1.22 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2005-01-17 22:17:29 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 */

/******************************************************************************/
/*  INCLUDE FILES                                                             */
/******************************************************************************/
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_eigen.h>

#include "psMemory.h"
#include "psError.h"
#include "psImage.h"
#include "psVector.h"
#include "psMatrix.h"
#include "psConstants.h"
#include "psDataManipErrors.h"


/*****************************************************************************/
/* DEFINE STATEMENTS                                                         */
/*****************************************************************************/

/** Preprocessor macro to generate error for image dimensionality not set to PS_DIMEN_IMAGE */
#define PS_CHECK_DIMEN_AND_TYPE(NAME, PS_DIMEN, RETURN)                                             \
if (NAME->type.dimen != PS_DIMEN) {                                                                 \
    psError(PS_ERR_BAD_PARAMETER_TYPE, true,                                                        \
            "Invalid operation. %s has incorrect dimensionality %d.", #NAME, PS_DIMEN);             \
    return RETURN;                                                                                  \
} else if(NAME->type.type!=PS_TYPE_F64 && NAME->type.type!=PS_TYPE_F32) {                           \
    psError(PS_ERR_BAD_PARAMETER_TYPE, true,                                                        \
            "Invalid operation. %s not PS_TYPE_F64.", #NAME);                                       \
    return RETURN;                                                                                  \
}

/** Preprocessor macro to check that input is not equal to output */
#define PS_CHECK_POINTERS(NAME1, NAME2, RETURN)                                                     \
if (NAME1 == NAME2) {                                                                               \
    psError(PS_ERR_BAD_PARAMETER_VALUE, true,                                                       \
            "Invalid operation: Pointer to %s is same as %s.", #NAME1, #NAME2);                     \
    return RETURN;                                                                                  \
}

/** Preprocessor macro to check that an image is square */
#define PS_CHECK_SQUARE(NAME, RETURN)                                                               \
if (NAME->numCols != NAME->numRows) {                                                               \
    psError(PS_ERR_BAD_PARAMETER_SIZE, true, "Invalid operation: %s not square array.", #NAME);     \
    return RETURN;                                                                                  \
}

/** Preprocessor macro to initalize a GSL matrix. */
#define PS_GSL_MATRIX_INITIALIZE(LHS_NAME, RHS_NAME)                                                \
LHS_NAME.size1 = numRows;                                                                           \
LHS_NAME.size2 = numCols;                                                                           \
LHS_NAME.tda   = numCols;                                                                           \
LHS_NAME.data  = RHS_NAME;


/*****************************************************************************/
/* FILE STATIC FUNCTIONS                                                     */
/*****************************************************************************/

static void  psVectorToGslVector(gsl_vector *outGslVector, const psVector *inVector);
static void gslVectorToPsVector(psVector *outVector, gsl_vector *inGslVector);
static void  psImageToGslMatrix(gsl_matrix *outGslMatrix, const psImage *inImage);
static void gslMatrixToPsImage(psImage *outImage, gsl_matrix *inGslMatrix);

/** Static function to copy psF32 or psF64 vector data to a GSL vector */
static void  psVectorToGslVector(gsl_vector *outGslVector, const psVector *inVector)
{
    psU32 i = 0;
    psU32 n = 0;


    n = inVector->n;
    for(i=0; i<n; i++) {
        if(inVector->type.type == PS_TYPE_F32) {
            outGslVector->data[i] = (psF64)inVector->data.F32[i];
        } else {
            outGslVector->data[i] = inVector->data.F64[i];
        }
    }
}

/** Static function to copy GSL vector data to a psF32 or psF64 vector */
static void gslVectorToPsVector(psVector *outVector, gsl_vector *inGslVector)
{
    psU32 i = 0;
    psU32 n = 0;


    n = outVector->n;
    for(i=0; i<n; i++) {
        if(outVector->type.type == PS_TYPE_F32) {
            outVector->data.F32[i] = (psF32)inGslVector->data[i];
        } else {
            outVector->data.F64[i] = inGslVector->data[i];
        }
    }
}

/** Static function to copy psF32 or psF64 image data to a GSL matrix */
static void  psImageToGslMatrix(gsl_matrix *outGslMatrix, const psImage *inImage)
{
    psU32 i = 0;
    psU32 j = 0;
    psU32 numRows = 0;
    psU32 numCols = 0;


    numRows = inImage->numRows;
    numCols = inImage->numCols;
    for(i=0; i<numRows; i++) {
        for(j=0; j<numCols; j++) {
            if(inImage->type.type == PS_TYPE_F32) {
                outGslMatrix->data[i*numCols+j] = (psF64)inImage->data.F32[i][j];
            } else {
                outGslMatrix->data[i*numCols+j] = inImage->data.F64[i][j];
            }
        }
    }
}

/** Static function to copy GSL matrix data to a psF32 or psF64 image */
static void gslMatrixToPsImage(psImage *outImage, gsl_matrix *inGslMatrix)
{
    psU32 i = 0;
    psU32 j = 0;
    psU32 numRows = 0;
    psU32 numCols = 0;


    numRows = outImage->numRows;
    numCols = outImage->numCols;
    for(i=0; i<numRows; i++) {
        for(j=0; j<numCols; j++) {
            if(outImage->type.type == PS_TYPE_F32) {
                outImage->data.F32[i][j] = (psF32)inGslMatrix->data[i*numCols+j];
            } else {
                outImage->data.F64[i][j] = inGslMatrix->data[i*numCols+j];
            }
        }
    }
}


/*****************************************************************************/
/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
/*****************************************************************************/

psImage* psMatrixLUD(psImage* outImage, psVector** outPerm, psImage* inImage)
{
    psS32 signum = 0;
    psS32 numRows = 0;
    psS32 numCols = 0;
    gsl_matrix *lu = NULL;
    gsl_permutation perm;


    #define psMatrixLUD_EXIT {psFree(outImage); return NULL;}

    // Error checks
    PS_IMAGE_CHECK_NULL_GENERAL(inImage, psMatrixLUD_EXIT);
    PS_CHECK_POINTERS(inImage, outImage, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, outImage);
    PS_PTR_CHECK_NULL_GENERAL(outPerm, psMatrixLUD_EXIT);
    psImageRecycle(outImage, inImage->numCols, inImage->numRows, inImage->type.type);
    PS_CHECK_SQUARE(inImage, outImage);
    PS_CHECK_SQUARE(outImage, outImage);

    // Initialize data
    numRows = inImage->numRows;
    numCols = inImage->numCols;

    // Initialize GSL data
    perm.size = numCols;
    if (sizeof(size_t) == 4) {
        *outPerm = psVectorRecycle(*outPerm, numCols, PS_TYPE_S32);
    } else if (sizeof(size_t) == 8) {
        *outPerm = psVectorRecycle(*outPerm, numCols, PS_TYPE_S64);
    } else {
        psError(PS_ERR_UNKNOWN, true,
                "Failed to allocate the permutation vector; "
                "could not determine the cooresponding data type.");
        psMatrixLUD_EXIT;
    }

    (*outPerm)->n = numCols;
    perm.data = (*outPerm)->data.V;
    lu = gsl_matrix_alloc(numRows, numCols);

    // Copy psImage data into GSL matrix data
    psImageToGslMatrix(lu, inImage);

    // Calculate LU decomposition
    gsl_linalg_LU_decomp(lu, &perm, &signum);

    // Copy GSL matrix data to psImage data
    gslMatrixToPsImage(outImage, lu);

    // Free GSL data
    gsl_matrix_free(lu);

    return outImage;
}

psVector* psMatrixLUSolve(psVector* outVector, const psImage* inImage, const psVector* inVector,
                          const psVector* inPerm)
{
    psS32 numRows = 0;
    psS32 numCols = 0;
    gsl_matrix *lu;
    gsl_permutation perm;
    gsl_vector *b = NULL;
    gsl_vector *x = NULL;

    // Error checks
    PS_CHECK_POINTERS(outVector, inVector, outVector);
    PS_CHECK_POINTERS(inVector, inPerm, outVector);
    PS_CHECK_POINTERS(outVector, inPerm, outVector);
    PS_IMAGE_CHECK_NULL(inImage, outVector);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, outVector);
    PS_IMAGE_CHECK_EMPTY(inImage, outVector);
    PS_VECTOR_CHECK_NULL(outVector, outVector);
    PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_VECTOR, outVector);
    PS_VECTOR_CHECK_NULL(inVector, outVector);
    PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_VECTOR, outVector);
    PS_VECTOR_CHECK_NULL(inPerm, outVector);
    psVectorRecycle(outVector, inImage->numRows, inImage->type.type);

    // Initialize data
    numRows = inImage->numRows;
    numCols = inImage->numCols;

    // Initialize GSL data
    lu = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(lu, inImage);
    b = gsl_vector_alloc(inVector->n);
    psVectorToGslVector(b, inVector);
    x = gsl_vector_alloc(inVector->n);

    outVector->n = numCols;
    perm.size = inPerm->n;
    perm.data = inPerm->data.V;

    // Solve for {x} in equation: {b} = [A]{x}
    gsl_linalg_LU_solve(lu, &perm, b, x);

    // Copy GSL vector data to psVector data
    gslVectorToPsVector(outVector, x);

    // Free GSL data
    gsl_vector_free(b);
    gsl_vector_free(x);
    gsl_matrix_free(lu);

    return outVector;
}

psImage* psMatrixInvert(psImage* outImage, const psImage* inImage, psF32 *det)
{
    psS32 signum = 0;
    psS32 numRows = 0;
    psS32 numCols = 0;
    gsl_matrix *inv = NULL;
    gsl_matrix *lu = NULL;
    gsl_permutation *perm = NULL;

    // Error checks
    PS_PTR_CHECK_NULL(det, outImage);
    PS_CHECK_POINTERS(inImage, outImage, outImage);
    PS_IMAGE_CHECK_NULL(inImage, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, outImage);
    PS_IMAGE_CHECK_EMPTY(inImage, outImage);
    psImageRecycle(outImage, inImage->numCols, inImage->numRows, inImage->type.type);
    PS_CHECK_SQUARE(inImage, outImage);
    PS_CHECK_SQUARE(outImage, outImage);

    // Initialize data
    numRows = inImage->numRows;
    numCols = inImage->numCols;

    // Initialize GSL data
    perm = gsl_permutation_alloc(numRows);
    lu = gsl_matrix_alloc(numRows, numCols);
    inv = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(lu, inImage);

    // Invert data and calculate determinant
    gsl_linalg_LU_decomp(lu, perm, &signum);
    gsl_linalg_LU_invert(lu, perm, inv);
    *det = (float)gsl_linalg_LU_det(lu, signum);

    // Copy GSL matrix data to psImage data
    gslMatrixToPsImage(outImage, inv);

    // Free GSL structs
    gsl_permutation_free(perm);
    gsl_matrix_free(lu);
    gsl_matrix_free(inv);

    return outImage;
}

psF32 *psMatrixDeterminant(const psImage* inImage)
{
    psS32 signum = 0;
    psS32 numRows = 0;
    psS32 numCols = 0;
    psF32 *det = NULL;
    gsl_matrix *lu = NULL;
    gsl_permutation *perm = NULL;

    // Error checks
    PS_IMAGE_CHECK_NULL(inImage, NULL);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, NULL);
    PS_IMAGE_CHECK_EMPTY(inImage, NULL);
    PS_CHECK_SQUARE(inImage, 0);

    // Initialize data
    numRows = inImage->numRows;
    numCols = inImage->numCols;

    // Allocate GSL structs
    perm = gsl_permutation_alloc(numRows);
    lu = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(lu, inImage);

    // Calculate determinant
    det = (psF32*)psAlloc(sizeof(psF32));
    gsl_linalg_LU_decomp(lu, perm, &signum);
    *det = (psF32)gsl_linalg_LU_det(lu, signum);

    // Free GSL structs
    gsl_permutation_free(perm);
    gsl_matrix_free(lu);

    return det;
}

psImage* psMatrixMultiply(psImage* outImage, psImage* inImage1, psImage* inImage2)
{
    psS32 numRows = 0;
    psS32 numCols = 0;
    gsl_matrix *m1 = NULL;
    gsl_matrix *m2 = NULL;
    gsl_matrix *m3 = NULL;

    // Error checks
    PS_CHECK_POINTERS(inImage1, outImage, outImage);
    PS_CHECK_POINTERS(inImage1, inImage2, outImage);
    PS_IMAGE_CHECK_NULL(inImage1, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage1, PS_DIMEN_IMAGE, outImage);
    PS_IMAGE_CHECK_EMPTY(inImage1, outImage);
    PS_IMAGE_CHECK_NULL(inImage2, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage2, PS_DIMEN_IMAGE, outImage);
    PS_IMAGE_CHECK_EMPTY(inImage2, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage1, PS_DIMEN_IMAGE, outImage);
    psImageRecycle(outImage, inImage2->numCols, inImage2->numRows, inImage2->type.type);
    PS_CHECK_SQUARE(inImage1, outImage);
    PS_CHECK_SQUARE(inImage2, outImage);
    PS_CHECK_SQUARE(outImage, outImage);

    // Initialize data
    numRows = inImage1->numRows;
    numCols = inImage1->numCols;

    // Initialize GSL data
    m1 = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(m1, inImage1);
    m2 = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(m2, inImage2);
    m3 = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(m3, outImage);

    // Perform multiplication
    gsl_linalg_matmult(m1, m2, m3);

    // Copy GSL matrix data to psImage data
    gslMatrixToPsImage(outImage, m3);

    // Free GSL structs
    gsl_matrix_free(m1);
    gsl_matrix_free(m2);
    gsl_matrix_free(m3);

    return outImage;
}

psImage* psMatrixTranspose(psImage* outImage, const psImage* inImage)
{
    psU32 i = 0;
    psU32 j = 0;
    psS32 numRowsIn = 0;
    psS32 numColsIn = 0;
    psS32 numRowsOut = 0;
    psS32 numColsOut = 0;


    // Error checks
    PS_CHECK_POINTERS(inImage, outImage, outImage);
    PS_IMAGE_CHECK_NULL(inImage, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, outImage);
    PS_IMAGE_CHECK_EMPTY(inImage, outImage);
    outImage = psImageRecycle(outImage, inImage->numCols, inImage->numRows, inImage->type.type);

    // Initialize data
    numRowsIn = inImage->numRows;
    numColsIn = inImage->numCols;
    numRowsOut = outImage->numRows;
    numColsOut = outImage->numCols;

    if(numRowsIn!=numColsOut && numRowsOut!=numColsIn) {
        psError(PS_ERR_BAD_PARAMETER_VALUE, true, PS_ERRORTEXT_psMatrix_TRANSPOSE_MISMATCH);
    }

    if(outImage->type.type == PS_TYPE_F32) {
        for(i=0; i<numRowsOut; i++) {
            for(j=0; j<numColsOut; j++) {
                outImage->data.F32[i][j] = inImage->data.F32[j][i];
            }
        }
    } else {
        for(i=0; i<numRowsOut; i++) {
            for(j=0; j<numColsOut; j++) {
                outImage->data.F64[i][j] = inImage->data.F64[j][i];
            }
        }
    }

    return outImage;
}

psImage* psMatrixEigenvectors(psImage* outImage, psImage* inImage)
{
    psS32 numRows = 0;
    psS32 numCols = 0;
    gsl_vector *eVals = NULL;
    gsl_eigen_symmv_workspace *w = NULL;
    gsl_matrix *out = NULL;
    gsl_matrix *in = NULL;


    // Error checks
    PS_CHECK_POINTERS(inImage, outImage, outImage);
    PS_IMAGE_CHECK_NULL(inImage, outImage);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, outImage);
    PS_IMAGE_CHECK_EMPTY(inImage, outImage);
    psImageRecycle(outImage, inImage->numCols, inImage->numRows, inImage->type.type);

    // Initialize data
    numRows = inImage->numRows;
    numCols = inImage->numCols;

    in = gsl_matrix_alloc(numRows, numCols);
    psImageToGslMatrix(in, inImage);
    out = gsl_matrix_alloc(numRows, numCols);

    // Allocate GSL structs
    eVals = gsl_vector_alloc(numRows);
    w = gsl_eigen_symmv_alloc(numRows);

    // Non-square matrices not allowed
    PS_CHECK_SQUARE(inImage, outImage);
    PS_CHECK_SQUARE(outImage, outImage);

    // Calculate Eigenvalues and Eigenvectors...Eigenvalues not currently used
    gsl_eigen_symmv(in, eVals, out, w);

    // Copy GSL matrix data to psImage data
    gslMatrixToPsImage(outImage, out);

    // Free GSL structs
    gsl_matrix_free(in);
    gsl_matrix_free(out);
    gsl_eigen_symmv_free(w);
    gsl_vector_free(eVals);

    return outImage;
}

psVector* psMatrixToVector(psVector* outVector, const psImage* inImage)
{
    psS32 size = 0;

    #define psMatrixToVector_EXIT {psFree(outVector); return NULL;}

    // Error checks
    PS_IMAGE_CHECK_NULL_GENERAL(inImage, psMatrixToVector_EXIT);
    PS_CHECK_DIMEN_AND_TYPE(inImage, PS_DIMEN_IMAGE, outVector);
    PS_IMAGE_CHECK_EMPTY_GENERAL(inImage, psMatrixToVector_EXIT);

    if (inImage->numRows == 1) {
        // Create transposed row vector
        psVectorRecycle(outVector, inImage->numCols, inImage->type.type);
        outVector->type.dimen = PS_DIMEN_TRANSV;
    } else if (inImage->numCols == 1) {
        // Create non-transposed column vector
        psVectorRecycle(outVector, inImage->numRows, inImage->type.type);
    } else {
        psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                "Image does not have dim with 1 col or 1 row: (%d x %d).",
                inImage->numRows, inImage->numCols);
        return outVector;
    }

    PS_VECTOR_CHECK_NULL(outVector, outVector);

    // More checks
    if (outVector->type.dimen == PS_DIMEN_VECTOR) {
        PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_VECTOR, outVector);

        if (outVector->n == 0) {
            outVector->n = inImage->numRows;
        }

        if (outVector->n != inImage->numRows) {
            psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                    "Image and vector sizes differ: (%d vs %d).",
                    inImage->numRows, outVector->n);
            return outVector;
        }

        size = PSELEMTYPE_SIZEOF(inImage->type.type) * inImage->numRows;

    } else if (outVector->type.dimen == PS_DIMEN_TRANSV) {
        PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_TRANSV, outVector);

        if (outVector->n == 0) {
            outVector->n = inImage->numCols;
        }

        if (outVector->n != inImage->numCols) {
            psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                    "Image and vector sizes differ: (%d vs %d).",
                    inImage->numCols, outVector->n);
            return outVector;
        }

        size = PSELEMTYPE_SIZEOF(inImage->type.type) * inImage->numCols;
    }

    memcpy(outVector->data.V, inImage->data.V[0], size);

    return outVector;
}

psImage* psVectorToMatrix(psImage* outImage, const psVector* inVector)
{
    psS32 size = 0;

    // Error checks
    PS_VECTOR_CHECK_NULL(inVector, outImage);

    if (inVector->type.dimen == PS_DIMEN_VECTOR) {
        PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_VECTOR, outImage);
        PS_VECTOR_CHECK_EMPTY(inVector, outImage);
        psImageRecycle(outImage, 1, inVector->n, PS_TYPE_F64);
        // More checks for PS_DIMEN_VECTOR
        if (outImage->numCols > 1) {
            psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                    "Image has more than 1 column: numCols = %d.",
                    outImage->numCols);
            return outImage;
        } else if (outImage->numRows != inVector->n) {
            psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                    "Image and vector sizes differ: (%d vs %d).",
                    outImage->numRows, inVector->n);
            return outImage;
        }

        size = PSELEMTYPE_SIZEOF(outImage->type.type) * outImage->numRows;

    } else if (inVector->type.dimen == PS_DIMEN_TRANSV) {
        PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_TRANSV, outImage);
        PS_VECTOR_CHECK_EMPTY(inVector, outImage);
        psImageRecycle(outImage, inVector->n, 1, PS_TYPE_F64);
        // More checks for PS_DIMEN_TRANSV
        if (outImage->numRows > 1) {
            psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                    "Image has more than 1 row: numRows = %d.",
                    outImage->numRows);
            return outImage;
        } else if (outImage->numCols != inVector->n) {
            psError(PS_ERR_BAD_PARAMETER_SIZE, true,
                    "Image and vector sizes differ: (%d vs %d).",
                    outImage->numCols, inVector->n);
            return outImage;
        }

        size = PSELEMTYPE_SIZEOF(outImage->type.type) * outImage->numCols;
    }

    PS_IMAGE_CHECK_NULL(outImage, outImage);
    PS_CHECK_DIMEN_AND_TYPE(outImage, PS_DIMEN_IMAGE, outImage);

    memcpy(outImage->data.V[0], inVector->data.V, size);

    return outImage;
}
