fml  0.1-0
Fused Matrix Library
invert.hh
1 // This file is part of fml which is released under the Boost Software
2 // License, Version 1.0. See accompanying file LICENSE or copy at
3 // https://www.boost.org/LICENSE_1_0.txt
4 
5 #ifndef FML_MPI_LINALG_INVERT_H
6 #define FML_MPI_LINALG_INVERT_H
7 #pragma once
8 
9 
10 #include <stdexcept>
11 
12 #include "../../_internals/linalgutils.hh"
13 #include "../../cpu/cpuvec.hh"
14 
15 #include "../internals/mpi_utils.hh"
16 
17 #include "../mpimat.hh"
18 
19 #include "internals/scalapack.hh"
20 #include "lu.hh"
21 
22 
23 namespace fml
24 {
25 namespace linalg
26 {
46  template <typename REAL>
48  {
49  if (!x.is_square())
50  throw std::runtime_error("'x' must be a square matrix");
51 
52  // Factor x = LU
53  cpuvec<int> p;
54  int info;
55  lu(x, p, info);
56  linalgutils::check_info(info, "getrf");
57 
58  // Invert
59  const len_t n = x.nrows();
60  REAL tmp;
61  int liwork;
62  scalapack::getri(n, x.data_ptr(), x.desc_ptr(), p.data_ptr(), &tmp, -1, &liwork, -1, &info);
63  int lwork = std::max(1, (int)tmp);
64  cpuvec<REAL> work(lwork);
65  cpuvec<int> iwork(liwork);
66 
67  scalapack::getri(n, x.data_ptr(), x.desc_ptr(), p.data_ptr(), work.data_ptr(), lwork, iwork.data_ptr(), liwork, &info);
68  linalgutils::check_info(info, "getri");
69  }
70 
71 
72 
89  template <typename REAL>
90  void trinv(const bool upper, const bool unit_diag, mpimat<REAL> &x)
91  {
92  if (!x.is_square())
93  throw std::runtime_error("'x' must be a square matrix");
94 
95  const len_t n = x.nrows();
96 
97  int info;
98  char uplo = (upper ? 'U' : 'L');
99  char diag = (unit_diag ? 'U' : 'N');
100  scalapack::trtri(uplo, diag, n, x.data_ptr(), x.desc_ptr(), &info);
101  linalgutils::check_info(info, "trtri");
102 
103  uplo = (uplo == 'U' ? 'L' : 'U');
104  mpi_utils::tri2zero(uplo, false, x.get_grid(), n, n, x.data_ptr(), x.desc_ptr());
105  }
106 }
107 }
108 
109 
110 #endif
fml::mpimat
Matrix class for data distributed over MPI in the 2-d block cyclic format.
Definition: mpimat.hh:40
fml::unimat::is_square
bool is_square() const
Is the matrix square?
Definition: unimat.hh:34
fml::univec::data_ptr
T * data_ptr()
Pointer to the internal array.
Definition: univec.hh:28
fml::unimat::nrows
len_t nrows() const
Number of rows.
Definition: unimat.hh:36
fml::linalg::lu
void lu(cpumat< REAL > &x, cpuvec< int > &p, int &info)
Computes the PLU factorization with partial pivoting.
Definition: lu.hh:48
fml::cpuvec
Vector class for data held on a single CPU.
Definition: cpuvec.hh:31
fml::unimat::data_ptr
REAL * data_ptr()
Pointer to the internal array.
Definition: unimat.hh:40
fml
Core namespace.
Definition: dimops.hh:10
fml::linalg::trinv
void trinv(const bool upper, const bool unit_diag, cpumat< REAL > &x)
Compute the matrix inverse of a triangular matrix.
Definition: invert.hh:87
fml::linalg::invert
void invert(cpumat< REAL > &x)
Compute the matrix inverse.
Definition: invert.hh:46