// day2-ex3.cxx - Cholesky decomposition
//
// to compile:
//
// g++ -std=c++17 -Wall -Wextra -pedantic -I$(root-config --incdir) -O2 -g -o day2-ex3 day2-ex3.cxx

#include <algorithm> // std::swap
#include <cmath>     // std::sqrt
#include <cstdio>    // std::printf
#include <type_traits> // std::enable_if_t, std::is_const_v
#include <vector>

/** @brief PackedMatrixAdapter
 *
 * In Cholesky decomposition, it's useful to work with packed matrix storage.
 * One essentially only stores the lower half of the matrix, i.e. the
 * diagonale and below. The elements are stored in a plain array at these
 * indices (for a 4 by 4 matrix):
 *
 * 0 1 3 6
 * 1 2 4 7
 * 3 4 5 8
 * 6 7 8 9
 *
 * The packed array stores these elements:
 *
 * M[0][0], M[1][0], M[1][1], M[2][0], M[2][1], M[2][2],
 * M[3][0], M[3][1], M[3][2], M[3][3]
 *
 * In other words, matrix element i, j is stored in the packed array at index
 * i * (i + 1) / 2 + j for j <= i (otherwise, swap i and j).
 *
 * The PackedMatrixAdapter takes a pointer to the beginning of the packed
 * storage, and allows it to be accessed with the familiar indexing operators.
 *
 * @tparam T    type of underlying packed storage
 */
template <class T>
class PackedMatrixAdapter {
private:
    T *_m = nullptr;
public:
    /// constructor
    PackedMatrixAdapter(T* m) noexcept : _m(m) {}
    /// helper class standing in for a row
    template <class S>
    class RowProxy {
        private:
            S* _m = nullptr;
            std::size_t _i = 0;
        public:
            /// constructor
            RowProxy(S* m, std::size_t i) noexcept : _m(m), _i(i) {}

            // there are two versions of the indexing operator, one which is
            // basically read-only access (with the const qualifier below)
            S operator[](std::size_t j) const noexcept
            {
                std::size_t i = _i;
                if (j > i) std::swap(i, j);
                return _m[i * (i + 1) / 2 + j];
            }
            // this is the second indexing operator, which allows read/write
            // access, but only if the underlying packed storage allows
            // modification, i.e. is not const (that's what the
            // std::enable_if_t<...> does - it becomes S& if S is not const,
            // and disables the method overload if S is const)
            template <class U = S>
            std::enable_if_t<!std::is_const_v<U>, U>&
            operator[](std::size_t j) noexcept
            {
                std::size_t i = _i;
                if (j > i) std::swap(i, j);
                return _m[i * (i + 1) / 2 + j];
            }
    };
    /// read-only access to the packed storage
    RowProxy<const T> operator[](std::size_t i) const noexcept
    {
        return {_m, i};
    }
    /// read-write access to packed storage if it's non-const
    template <class S = T>
    std::enable_if_t<!std::is_const_v<S>, RowProxy<S>>
    operator[](std::size_t i) noexcept
    {
        return {_m, i};
    }
};

/** @brief calculate Cholesky decomposition of matrix m
 *
 * The Matrix m (symmetric positive) is decomposed into a lower triangular
 * matrix times its transpose. The decomposition is achieved in-place, so m is
 * modified in the process. If the matrix is numerically so close to singular
 * that decomposition is impossible, the method returns false.
 *
 * @tparam T    type of packed storage underlying m
 *
 * @param n     size of the matrix
 * @param m     pointer to the beginning of the packed storage of matrix m
 *
 * @returns     true on success, false if m is not positive definite
 *
 * @note        on successful return, m contains decomposed matrix l
 * @note        routine modifies m in place, even if not successful
 */
template <class T>
bool choleskyDecomp(std::size_t n, T* m)
{
    PackedMatrixAdapter<T> M(m);
    for (std::size_t j = 0; n != j; ++j) {
        double diag = M[j][j];
        for (std::size_t k = j; k--; )
            diag -= M[j][k] * M[j][k];
        if (diag <= 0) return false;
        M[j][j] = diag = std::sqrt(diag);
        diag = 1 / diag;
        for (std::size_t i = j + 1; n != i; ++i) {
            double tmp = M[i][j];
            for (std::size_t k = 0; j != k; ++k)
                tmp -= M[i][k] * M[j][k];
            M[i][j] = tmp * diag;
        }
    }
    return true;
}

/** @brief solve L L^T x = b, return solution in b
 *
 * @tparam T    data type for packed storage of L and for elements of b
 *
 * @param n     size of matrix (n x n) and b
 * @param l     packed storage for lower triangular matrix L
 * @param b     vector b
 *
 * @note on return, b contains the solution x
 */
template <class T>
void solve(std::size_t n, const T* l, T* b)
{
    PackedMatrixAdapter<const T> L(l);
    // solve L y = b
    for (std::size_t i = 0; n != i; ++i) {
        T tmp = b[i];
        for (std::size_t j = 0; i != j; ++j)
            tmp -= L[i][j] * b[j];
        b[i] = tmp / L[i][i];
    }
    // solve L^T x = y, save in b
    for (std::size_t i = n; i--; ) {
        T tmp = b[i];
        for (std::size_t j = n; --j != i;)
            tmp -= L[i][j] * b[j];
        b[i] = tmp / L[i][i];
    }
}

/** @brief invert matrix M = L L^T
 *
 * @tparam T    type of underlying packed storage of l
 *
 * @param n     size of the matrix (n x n)
 * @param l     packed storage of matrix L
 *
 * @note        modifies l, the lower left part of M^-1 is stored in packed
 *              storage pointed to be l
 */
template <class T>
void invert(std::size_t n, T* l)
{
    std::vector<T> mat(l, l + n * (n + 1) / 2);
    PackedMatrixAdapter<T> Li(l);
    std::vector<T> tmp;
    tmp.reserve(n);
    for (std::size_t i = 0; n != i; ++i) {
        tmp.assign(n, 0);
        tmp[i] = 1;
        solve(n, mat.data(), tmp.data());
        for (std::size_t j = 0; j <= i; ++j)
            Li[i][j] = tmp[j];
    }
}

enum MatType {
    Lower = 1,
    Upper = 2,
    Symmetric = Lower | Upper
};

/// print a matrix (packed storage)
template <class T>
void printmat(std::size_t n, const T* m, MatType t = Symmetric)
{
    PackedMatrixAdapter<const T> M(m);
    for (std::size_t i = 0; n != i; ++i) {
        std::printf("[");
        for (std::size_t j = 0; n != j; ++j)
            std::printf(" %g", ((t & Lower) && (j <= i))   ? M[i][j]
                               : ((t & Upper) && (i <= j)) ? M[i][j]
                                                           : 0);
        std::printf(" ]\n");
    }
}

int main()
{
    const double m[6] = {
          4,
         12,  37,
        -16, -43, 98 
    };
    double l[6];
    std::copy(std::begin(m), std::end(m), std::begin(l));
    
    std::printf("M = \n");
    printmat(3, m);

    bool res = choleskyDecomp(3, l);
    std::printf("\ncholeskyDecomp returns %s\n\n", res ? "true" : "false");

    std::printf("L = \n");
    printmat(3, l, Lower);

    double inv[6], tmp[6];
    std::copy(std::begin(l), std::end(l), inv);
    invert(3, inv);

    std::printf("\nM^-1 = \n");
    printmat(3, inv);

    PackedMatrixAdapter<const double> M(m);
    PackedMatrixAdapter<double> Mi(inv);
    PackedMatrixAdapter<double> T(tmp);
    for (std::size_t i = 0; 3 != i; ++i) {
        for (std::size_t j = 0; j <= i; ++j) {
            double tmp = 0;
            for (std::size_t k = 0; 3 != k; ++k)
                tmp += M[i][k] * Mi[k][j];
            T[i][j] = tmp;
        }
    }

    std::printf("\nT = \n");
    printmat(3, tmp);

    return 0;
}
