Ibrahim.hh 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

//
// David Chamont Comments
// The use of reshape() prevent the simple replacement of xarray with xtensor.
// And the fact to set =0 for some Matrix ?
//

//
// Created by Ibrahim Radwan on 3/25/18.
//

#pragma once

#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xeval.hpp>

using namespace xt;
using namespace std;

#include "bench.hh"

/**
 * Notes:
 * [1] This program heavily uses matrices operations to get things done, which means for a better utilization,
 *      you may invert matrices in a bulky fashion
 * [2] Every function here works as if there're many matrices(e.g. depth)
 *
 */

template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
class IbrahimInverter
{
public :

        // types
        using RealType = Real ;
        using VectorType = Vector ;
        using MatrixType = Matrix ;
        using MatricesSetType = MatricesSet ;

        static void invert( MatricesSet & mats ) {
			mats = invertMatrices(mats) ;
		}


    /**
     * This function takes matrices and calculates their inverses
     *
     * @param matrices This array of shape (#matrices, dim, dim), where dim is the matrix length/width
     *
     * @return Array of shape (#matrices, dim, dim) contains the inverses
     */
    static MatricesSet invertMatrices(const MatricesSet &);

private:
    /**
     * Decompose the given matrices using Crout decomposition
     *
     * @param matrices Array of matrices to be decomposed
     * @param depth Count of the matrices
     * @param dim Size of the matrix
     *
     * @return pair of 2 arrays {@first contains all matrices L triangles}, {@second contains all matrices U triangles}
     */
    static pair<MatricesSet, MatricesSet> matricesLUDecomposition(const MatricesSet &matrices, const size_t depth, const size_t dim);

    /**
     * Calculate the value to be subtracted from the current L-Col
     *
     * @param L Matrices Lower triangle
     * @param R Matrices Upper triangle
     * @param LColIdx Index of the column we are calculating
     * @param dim Matrix dimension
     *
     * @return xarray the values to be subtracted from the original matrices columns
     */
    static Matrix getLColSubtractedValue(const MatricesSet &L, const MatricesSet &U, size_t LColIdx, size_t dim);

    /**
     * Calculate the value to be subtracted from the current L-Col
     *
     * @param L Matrices Lower triangle
     * @param R Matrices Upper triangle
     * @param URowIdx Index of the column we are calculating
     * @param dim Matrix dimension
     *
     * @return xarray the values to be subtracted from the original matrices columns
     */
    static Matrix getURowSubtractedValue(const MatricesSet &L, const MatricesSet &U, size_t URowIdx, size_t dim);

    /**
     * Calculate the intermediate solutions of the system
     *
     * @param L
     * @param U
     * @param depth Count of the matrices
     * @param dim Size of the matrix
     *
     * @return xarray The intermediate solutions array
     */
    static MatricesSet calculateIntermediateSolution(const MatricesSet &L, const MatricesSet &U, const size_t depth,
                                  const size_t dim);

    /**
     * Calculate the final solutions of the system
     *
     * @param L Lower triangle
     * @param U Upper triangle
     * @param D Intermediate solution matrix
     * @param depth Count of the matrices
     * @param dim Matrix dimension
     *
     * @return xarray The intermediate solutions array
     */
    static MatricesSet calculateFinalSolution(const MatricesSet &L, const MatricesSet &U,
                           const MatricesSet &D, const size_t depth, const size_t dim);
};

/**
 * Calculate matrices inverses
 *
 * Assumptions:
 * [1] The matrices are squares
 * [2] The given matrices are invertible (the non invertible ones
 *      will yeild a nan. matrix)
 *
 * The general idea is to follow the following steps:
 * [1] Decompose the given each matrix into its LU matrices (using Crout Decomposition)
 * [2] Calculate the intermediate solution
 * [3] Calculate the final solution (matrix inverse)
 *
 * The steps are being taken from this online article with some modifications:
 * https://www.gamedev.net/articles/programming/math-and-physics/matrix-inversion-using-lu-decomposition-r3637/
 *
 * @param matrices This array of shape (#matrices, dim, dim), where dim is the matrix length/width
 * @return xarray of shape (#matrices, dim, dim) contains the inverses
 */
template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
MatricesSet IbrahimInverter<Real,Vector,Matrix,MatricesSet>::invertMatrices(const MatricesSet &matrices)
{
    // Get matrices count (a.k.a depth), and each matrix dimension
    size_t depth = matrices.shape()[0];
    size_t dim = matrices.shape()[1];
    // Decompose matrices to LU matrices
    pair<MatricesSet, MatricesSet> && LU = matricesLUDecomposition(matrices, depth, dim);
    
    // Calculate intermediate solutions
    MatricesSet && D = calculateIntermediateSolution(LU.first, LU.second, depth, dim);

    // Return the final matrices
    return calculateFinalSolution(LU.first, LU.second, D, depth, dim);
}

/**
 * Decompose the given matrices using Crout decomposition
 *
 *
 * This function follows these steps:
 * [A0] The first L-col and U-row don't need some operations, so we skip those operation in case of i == 0
 * [A1] Fill the L, U matrices:
 *      [A11] First fill the L-col then the U-row (as U-row depends on the previous L-col)
 *
 * How L-cols are filled (check the document mentioned above for more info):
 * [B1] Multiply the previous L-cols with the corresponding U-col (Each L-col gets multiplied by a single value from the
 *      corresponding U-col)
 * [B2] Sum results from step 1
 * [B3] Subtract the result from step 2, from the corresponding original matrix column
 *
 * How U-rows are filled (check the document mentioned above for more info):
 * [C1] Multiply the previous R-rows with the corresponding L-row (Each U-row gets multiplied by a single value from the
 *      corresponding L-row)
 * [C2] Sum results from step 1
 * [C3] Subtract the result from step 2, from the corresponding original matrix column
 * [C4] Divide the result from step 3 by L(i,i) where i = index of the current U-row we fill
 *
 *
 * The formulas:
 * l(i1) = a(i1),                                       for i=1,2,⋯,n
 * u1j = a(1j)/l(11),                                   for j=2,3,⋯,n
 *
 * For j=2,3,⋯,n−1
 * l(ij) = a(ij)− ∑{k=[1, j−1]} l(ik) * u(kj),          for i=j,j+1,⋯,n
 *
 * u(jk) = a(jk) − (∑{i=[1,j−1]} l(ji)u(ik)) / l(jj),   for k=j+1,j+2,⋯,n
 *
 *
 * @param matrices Array of matrices to be decomposed
 * @param depth Count of the matrices
 * @param dim Size of the matrix
 *
 * @return pair of 2 xarrays {@first contains all matrices L triangles}, {@second contains all matrices U triangles}
 */
template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
pair<MatricesSet, MatricesSet> IbrahimInverter<Real,Vector,Matrix,MatricesSet>::matricesLUDecomposition(const MatricesSet &matrices, const size_t depth, const size_t dim)
{
    // Each matrix will have its own Lower triangle matrix and Upper triangle matrix
    // Crout assumes initial U as an eye matrix
    std::vector<std::size_t> matrices_shape { matrices.shape()[0], matrices.shape()[1], matrices.shape()[2] } ;
    MatricesSet L = xt::zeros<Real>(matrices_shape);
    MatricesSet U = xt::eye<Real>(matrices_shape);

    // In this loop we fill L, U
    // We use same loop to reduce complexity
    for (size_t i = 0; i < dim; ++i)
    {
        // ========================================
        // Fill L cols
        // ========================================

        // [B3] Update the L column
        auto && LCol = xt::view(L, xt::all(), xt::range(i, dim), i);
        Matrix LColSubtractedValue = getLColSubtractedValue(L, U, i, dim) ; // sans ca, ca plante avec les xt::xtsensor !
        Matrix NewLView = xt::view(matrices, xt::all(), xt::range(i, dim), i) ;
        Matrix NewLCol = NewLView - LColSubtractedValue ;
        LCol = NewLCol ;

        // ========================================
        // Fill U rows
        // ========================================

        // U rows finish calculations earlier than L-cols by 1 iteration
        if (dim - i - 1 <= 0) continue;

        // [C4] Get the corresponding L(i,i) value
        typename Matrix::shape_type shape { depth, 1 } ;
        Matrix LCorrespondingDivisorValue { shape } ;
        xt::view(LCorrespondingDivisorValue, xt::all(), 1)
         = xt::view(L, xt::all(), i, i) ;
        //Vector LCorrespondingDivisorValue= xt::view(L, xt::all(), i, i);
        //LCorrespondingDivisorValue.reshape({LCorrespondingDivisorValue.shape()[0], 1}); // Vector  => Matrix

        // [C3,4]
        auto && URow = xt::view(U, xt::all(), i, xt::range(i + 1, dim));
        Matrix NewRView = xt::view(matrices, xt::all(), i, xt::range(i + 1, dim)) ;
        Matrix URowSubtractedValue = getURowSubtractedValue(L, U, i, dim) ;
        Matrix NewURowNum = NewRView - URowSubtractedValue ;
        URow = NewURowNum / LCorrespondingDivisorValue ;

    /*if (i==0) {
        std::cout<< NewRView <<std::endl ;
        std::cout<< URowSubtractedValue <<std::endl ;
        std::cout<< NewURowNum <<std::endl ;
        exit(0) ;
    }*/
    }

    return make_pair(L, U);
}

/**
 * Calculate the value to be subtracted from the current L-Col
 *
 * @param L Matrices Lower triangle
 * @param R Matrices Upper triangle
 * @param LColIdx Index of the column we are calculating
 * @param dim Matrix dimension
 *
 * @return xarray the values to be subtracted from the original matrices columns
 */
template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
Matrix IbrahimInverter<Real,Vector,Matrix,MatricesSet>::getLColSubtractedValue(const MatricesSet &L, const MatricesSet &U, size_t LColIdx, size_t dim)
{
    Matrix LColSubtractedValue; // Value to be subtracted later from the corresponding original matrix column

    // [A0] For the first column we subtract nothing
    if (!LColIdx)
    {
        typename Matrix::shape_type shape { L.shape()[0], dim } ;
        LColSubtractedValue = xt::zeros<Real>(shape);
    } else
    {
        // [B1] Calculate the subtractedValue
        MatricesSet previousLCols = xt::view(L, xt::all(), xt::range(LColIdx, dim), xt::range(0, LColIdx));

        typename MatricesSet::shape_type shape { U.shape()[0], 1, LColIdx } ;
        MatricesSet UCol { shape } ;
        xt::view(UCol, xt::all(), 1, xt::all() )
         = xt::view(U, xt::all(), xt::range(0, LColIdx), LColIdx) ;
        //Matrix UCol = xt::view(U, xt::all(), xt::range(0, LColIdx), LColIdx);
        //UCol.reshape({UCol.shape()[0], 1, UCol.shape()[1]}); // Matrix => MatricesSet

        // [B2] Calculate the subtractedValue
        LColSubtractedValue = (sum((previousLCols * UCol), {2}));
    }

    return LColSubtractedValue;
}

/**
 * Calculate the value to be subtracted from the current L-Col
 *
 * @param L Matrices Lower triangle
 * @param R Matrices Upper triangle
 * @param URowIdx Index of the column we are calculating
 * @param dim Matrix dimension
 *
 * @return xarray the values to be subtracted from the original matrices columns
 */
template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
Matrix IbrahimInverter<Real,Vector,Matrix,MatricesSet>::getURowSubtractedValue(const MatricesSet &L, const MatricesSet &U, size_t URowIdx, size_t dim)
{
    Matrix URowSubtractedValue; // Value to be subtracted later from the corresponding original matrix column

    // [A0] For the first row we subtract nothing
    if (!URowIdx)
    {
        typename Matrix::shape_type shape { U.shape()[0], dim-1 } ;
        URowSubtractedValue = xt::zeros<Real>(shape) ;
    } else
    {
        // [C1] Calculate the subtractedValue
        MatricesSet previousURows = xt::view(U, xt::all(), xt::range(0, URowIdx), xt::range(URowIdx + 1, dim));

        typename MatricesSet::shape_type shape { L.shape()[0], URowIdx, 1 } ;
        MatricesSet LRow { shape } ;
        xt::view(LRow, xt::all(), xt::all(), 1 )
         = xt::view(L, xt::all(), URowIdx, xt::range(0, URowIdx)) ;

        //Matrix LRow = xt::view(L, xt::all(), URowIdx, xt::range(0, URowIdx));
        //LRow.reshape({LRow.shape()[0], LRow.shape()[1], 1}); // Matrix => MatricesSet

        // [C2]
        URowSubtractedValue = (sum((previousURows * LRow), {1}));
    }

    return URowSubtractedValue;
}

/**
 * Calculate the intermediate solutions of the system
 *
 *
 *
 * This function follows these steps:
 * [A0] First value in each depth-level doesn't require subtraction
 * [A1] Multiply previous D-values by corresponding L-row
 * [A2] Sum the values from step 1
 * [A3] Subtract the result from step 2 from the corresponding I (eye matrix) column
 * [A4] Divide the result by L(i,i) where i = idx of the current D value we calculate
 *
 *
 * The formulas:
 * d(1) = b(1) / l(11)
 * d(i) = b(i) − (∑{j=[1,i-1]} l(ij) * d(j)) / lii,     for i=2,3,⋯,n
 *
 * @param L
 * @param U
 * @param depth Count of the matrices
 * @param dim Size of the matrix
 *
 * @return xarray The intermediate solutions array
 */
template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
MatricesSet IbrahimInverter<Real,Vector,Matrix,MatricesSet>::calculateIntermediateSolution(const MatricesSet &L, const MatricesSet &U, const size_t depth,
                                                const size_t dim)
{
    // The eye matrix
    MatricesSet I = eye<Real>({depth, dim, dim});

    // Calculate D(intermediate solution) matrix
    MatricesSet D = zeros<Real>({depth, dim, dim});

    for (size_t i = 0; i < dim; ++i)
    {
        Matrix DSubtractedValue;
        // [A0] first value doesn't need subtraction
        if (!i)
        {
            DSubtractedValue = xt::zeros<Real>({1,1});
        } else
        {
            // A[1]
            MatricesSet previousDRows = (xt::view(D, xt::all(), xt::range(0, i), xt::all()));

            typename MatricesSet::shape_type shape { L.shape()[0], i, 1 } ;
            MatricesSet LRow { shape } ;
            xt::view(LRow, xt::all(), xt::all(), 1 )
            = xt::view(L, xt::all(), i, xt::range(0, i)) ;

            //xarray<Real> LRow = (xt::view(L, xt::all(), i, xt::range(0, i)));
            //LRow.reshape({LRow.shape()[0], LRow.shape()[1], 1}); // Matrix => MatricesSet

            // A[2]
            DSubtractedValue = (sum((previousDRows * LRow), {1}));
        }

        auto &&row = xt::view(D, xt::all(), i, xt::all());

        // A[3] get the divisor value
        typename Matrix::shape_type shape { depth, 1 } ;
        Matrix LCorrespondingDivisorValue { shape } ;
        xt::view(LCorrespondingDivisorValue, xt::all(), 1 )
        = xt::view(L, xt::all(), i, i) ;
        //Vector LCorrespondingDivisorValue = xt::view(L, xt::all(), i, i);
        //LCorrespondingDivisorValue.reshape({depth, 1}); // Vector => Matrix

        // A[3,4]
        row = ((xt::view(I, xt::all(), i, xt::all()) - DSubtractedValue) / LCorrespondingDivisorValue);
    }

    return D;
}

/**
 * Calculate the final solutions of the system
 *
 *
 *
 * This function follows these steps (we calculate from the end to the begining):
 * [A0] Final value in each depth-level doesn't require subtraction
 * [A1] Multiply next D-values by corresponding U-row
 * [A2] Sum the values from step 1
 * [A3] Subtract the result from step 2 from the corresponding D (intermediate matrix) value
 *
 *
 * The formulas:
 * x(n) = d(n)
 * x(i) = d(i) − ∑{j=[i+1,n]} u(ij)*x(j),               for i=n−1,n−2,⋯,1
 *
 * @param L Lower triangle
 * @param U Upper triangle
 * @param D Intermediate solution matrix
 * @param dim Matrix dimension
 *
 * @return xarray The intermediate solutions array
 */
template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
MatricesSet IbrahimInverter<Real,Vector,Matrix,MatricesSet>::calculateFinalSolution(const MatricesSet &L, const MatricesSet &U,
                                         const MatricesSet &D, const size_t depth, const size_t dim)
{
    // Calculate final solution matrix
    MatricesSet finalSolution = zeros<Real>({depth, dim, dim});

    // Calculate finalSolution array row by row
    for (int i = dim - 1; i >= 0; --i)
    {
        Matrix subtractedValue;

        // [A0]
        if (i == dim - 1)
        {
            // Last value doesn't require subtraction
            subtractedValue = xt::zeros<Real>({1,1});
        } else
        {
            // A[1]
            MatricesSet nextValues = (xt::view(finalSolution, xt::all(), xt::range(i + 1, dim), xt::all()));

            typename MatricesSet::shape_type shape { U.shape()[0], (dim-i-1), 1 } ;
            MatricesSet URow { shape } ;
            xt::view(URow, xt::all(), xt::all(), 1 )
            = xt::view(U, xt::all(), i, xt::range(i + 1, dim)) ;

            //MatricesSet URow = (xt::view(U, xt::all(), i, xt::range(i + 1, dim))); // Matrix
            //URow.reshape({URow.shape()[0], URow.shape()[1], 1}); // => MatricesSet

            // A[1,2]
            subtractedValue = (sum((nextValues * URow), {1}));
        }

        // A[3]
        auto &&row = xt::view(finalSolution, xt::all(), i, xt::all());
        row = xt::view(D, xt::all(), i, xt::all()) - subtractedValue;
    }

    return finalSolution;
}