Ayoub.hh 9.27 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

//
// David Chamont Comments
// The adjonction of an identity matrix before "echelon"
// prevent the use of xtensor ?
//

/**
*  @author Ayoub Chouak (@ntauth)
*/

#pragma once

#include <climits>
#include <vector>
#include <iostream>
#include <random>
#include <chrono>
#include <string>

#include "bench.hh"

template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
class AyoubInverter
{
    public:
    
        // types
        using RealType = Real ;
        using VectorType = Vector ;
        using MatrixType = Matrix ;
        using MatricesSetType = MatricesSet ;
        using size_type = typename MatricesSetType::shape_type::size_type ;

        static void invert( MatricesSetType & mats, size_type nbmats ) {
            for ( size_type i=0 ; i<nbmats ; ++i ) {
                auto matview = xt::view(mats,i,xt::all(),xt::all()) ;
                MatrixType mat = matview ;
                invert_gauss_jordan(mat) ;
                matview = mat ;
			}
		}

        /**
         *
         * @tparam Ty type of the matrix elements
         * @param mat0 the matrix whose row is to be swapped
         * @param mat1 the matrix whose row is to be swapped
         * @param row0 the index of the row of mat0 that is to be swapped
         * @param row1 the index of the row of mat1 that is to be swapped
         */
        static void swap_row(MatrixType & mat0, MatrixType& mat1, size_t row0, size_t row1);
        
        /**
         * @brief Reduces a matrix to the row echelon form
         * @tparam Ty matrix element type
         * @param mat the matrix to be reduced
         */
        static void reduce_echelon(MatrixType & mat);
        
        /**
         * @brief Inverts a matrix using the Gauss-Jordan method
         * @tparam Ty matrix element type
         * @param mat the matrix to be reduced
         */
        static void invert_gauss_jordan(MatrixType & mat);
        
};

template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
void AyoubInverter<Real,Vector,Matrix,MatricesSet>::invert_gauss_jordan(Matrix & mat)
{
    MatrixType mat_;

    // Get the matrix shape
    auto const & shape = mat.shape();

    // Augment the matrix by adjoining the identity matrix to the right
    typename MatrixType::shape_type am_shape = { shape[0], 2 * shape[0] };
    mat_ = MatrixType(am_shape);

    // Fill the original matrix
    for (size_t i = 0; i < am_shape[0]; i++)
        for (size_t j = 0; j < am_shape[0]; j++)
            mat_(i, j) = mat(i, j);

    // Fill the identity matrix
    for (size_t i = 0; i < am_shape[0]; i++)
        for (size_t j = am_shape[0]; j < am_shape[1]; j++)
            mat_(i, j) = (j - am_shape[0] == i) ? 1 : 0;

    // Reduce the augmented matrix to echelon form and extract the inverse
    reduce_echelon(mat_);

    // Copy the inverse to mat
    for (size_t i = 0; i < am_shape[0]; i++)
    {
        for (size_t j = am_shape[0]; j < am_shape[1]; j++) {
            mat(i, j - am_shape[0]) = mat_(i, j);
        }
    }
}

template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
void AyoubInverter<Real,Vector,Matrix,MatricesSet>::reduce_echelon( Matrix & mat )
{
    auto const & shape = mat.shape();
    size_t last_nz_idx = std::numeric_limits<size_t>::max();

    for (size_t col = 0; col < shape[1]; col++)
    {
        size_t nz_idx = std::numeric_limits<size_t>::max();
        bool  nz_found = false;

        for (size_t row = col; row < shape[0] && !nz_found; row++)
        {
            if (mat(row, col) != 0)
            {
                nz_idx = row;
                nz_found = true;
            }
        }

        if (nz_found)
        {
            // Move the row to allow for the zero rows to cascade down
            if (nz_idx != col)
                swap_row(mat, mat, nz_idx, col);


            RealType pivot = mat(col, col);

            // Reduce the row to echelon form by dividing each element by pivot
            for (size_t i = 0; i < shape[1]; i++)
            {
                mat(nz_idx, i) /= pivot;
            }

            // Apply a gauss move to zero out the elements in the rows above and below
            for (size_t i = 0; i < shape[0]; i++)
            {
                if (i != col && mat(i, col) != 0)
                {
                    RealType lambda = mat(i, col); // Reduction factor

                    for (size_t j = 0; j < shape[1]; j++)
                        mat(i, j) -= mat(col, j) * lambda;
                }
            }
        }
    }
}

template<typename Real, typename Vector, typename Matrix, typename MatricesSet>
void AyoubInverter<Real,Vector,Matrix,MatricesSet>::swap_row(Matrix& mat0, Matrix& mat1, size_t row0, size_t row1)
{
    VectorType x_view0 = xt::view(mat0, row0);
    VectorType x_view1 = xt::view(mat1, row1);
    auto const& shape0 = mat0.shape();
    auto const& shape1 = mat1.shape();

    // Make sure the rows are not out of bound
    xt::check_access(shape0, row0);
    xt::check_access(shape1, row1);

    // Make sure the row dimensions are compatible
    if (shape0[0] != shape1[0])
        throw std::string("Incompatible row dimension!");

    for (size_t i = 0; i < x_view0.size(); i++) {
        mat0(row0, i) = x_view1(i);
        mat1(row1, i) = x_view0(i);
    }
}

// Specialisation for xtensorf

template<typename Real>
class AyoubInverter<Real, xt::xtensorf<Real,xt::xshape<5>>, xt::xtensorf<Real,xt::xshape<5,5>>, xt::xtensorf<Real,xt::xshape<NB_RAND_MATRICES,5,5>>>
{
    public:
    
        // types
        using RealType = Real ;
        using VectorType = xt::xtensorf<Real,xt::xshape<5>> ;
        using MatrixType = xt::xtensorf<Real,xt::xshape<5,5>> ;
        using MatricesSetType = xt::xtensorf<Real,xt::xshape<NB_RAND_MATRICES,5,5>> ;
        using size_type = typename MatricesSetType::shape_type::size_type ;

        static void invert( MatricesSetType & mats, size_type nbmats ) {
            for ( size_type i=0 ; i<nbmats ; ++i ) {
                auto matview = xt::view(mats,i,xt::all(),xt::all()) ;
                MatrixType mat = matview ;
                invert_gauss_jordan(mat) ;
                matview = mat ;
			}
		}

        static void swap_row(xt::xtensorf<Real,xt::xshape<5,10>> & mat0, xt::xtensorf<Real,xt::xshape<5,10>>& mat1, size_t row0, size_t row1)
        {
            VectorType x_view0 = xt::view(mat0, row0);
            VectorType x_view1 = xt::view(mat1, row1);
            auto const& shape0 = mat0.shape();
            auto const& shape1 = mat1.shape();

            // Make sure the rows are not out of bound
            xt::check_access(shape0, row0);
            xt::check_access(shape1, row1);

            for (size_t i = 0; i < x_view0.size(); i++) {
                mat0(row0, i) = x_view1(i);
                mat1(row1, i) = x_view0(i);
            }
        }
        
        static void reduce_echelon(xt::xtensorf<Real,xt::xshape<5,10>> & mat)
        {
            auto const & shape = mat.shape();
            size_t last_nz_idx = std::numeric_limits<size_t>::max();

            for (size_t col = 0; col < shape[1]; col++)
            {
                size_t nz_idx = std::numeric_limits<size_t>::max();
                bool  nz_found = false;

                for (size_t row = col; row < shape[0] && !nz_found; row++)
                {
                    if (mat(row, col) != 0)
                    {
                        nz_idx = row;
                        nz_found = true;
                    }
                }

                if (nz_found)
                {
                    // Move the row to allow for the zero rows to cascade down
                    if (nz_idx != col)
                        swap_row(mat, mat, nz_idx, col);


                    Real pivot = mat(col, col);

                    // Reduce the row to echelon form by dividing each element by pivot
                    for (size_t i = 0; i < shape[1]; i++)
                    {
                        mat(nz_idx, i) /= pivot;
                    }

                    // Apply a gauss move to zero out the elements in the rows above and below
                    for (size_t i = 0; i < shape[0]; i++)
                    {
                        if (i != col && mat(i, col) != 0)
                        {
                            Real lambda = mat(i, col); // Reduction factor

                            for (size_t j = 0; j < shape[1]; j++)
                                mat(i, j) -= mat(col, j) * lambda;
                        }
                    }
                }
            }
        }
        
        static void invert_gauss_jordan(MatrixType & mat)
        {
            xt::xtensorf<Real,xt::xshape<5,10>> mat_;

            // Fill the original matrix
            for (size_t i = 0; i < 5; i++)
                for (size_t j = 0; j < 5; j++)
                    mat_(i, j) = mat(i, j);

            // Fill the identity matrix
            for (size_t i = 0; i < 5; i++)
                for (size_t j = 5; j < 10; j++)
                    mat_(i, j) = (j - 5 == i) ? 1 : 0;

            // Reduce the augmented matrix to echelon form and extract the inverse
            reduce_echelon(mat_);

            // Copy the inverse to mat
            for (size_t i = 0; i < 5; i++)
            {
                for (size_t j = 5; j < 10; j++) {
                    mat(i, j - 5) = mat_(i, j);
                }
            }
        }
        
};