fml  0.1-0
Fused Matrix Library
linalg_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_CPU_LINALG_LINALG_INVERT_H
6 #define FML_CPU_LINALG_LINALG_INVERT_H
7 #pragma once
8 
9 
10 #include <cmath>
11 #include <stdexcept>
12 
13 #include "../../_internals/linalgutils.hh"
14 #include "../../_internals/omp.hh"
15 
16 #include "../internals/cpu_utils.hh"
17 
18 #include "../cpumat.hh"
19 #include "../cpuvec.hh"
20 
21 #include "lapack.hh"
22 #include "linalg_lu.hh"
23 
24 
25 namespace fml
26 {
27 namespace linalg
28 {
45  template <typename REAL>
47  {
48  const len_t n = x.nrows();
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  REAL tmp;
60  lapack::getri(n, x.data_ptr(), n, p.data_ptr(), &tmp, -1, &info);
61  int lwork = (int) tmp;
62  cpuvec<REAL> work(lwork);
63 
64  lapack::getri(n, x.data_ptr(), n, p.data_ptr(), work.data_ptr(), lwork, &info);
65  linalgutils::check_info(info, "getri");
66  }
67 
68 
69 
86  template <typename REAL>
87  void trinv(const bool upper, const bool unit_diag, cpumat<REAL> &x)
88  {
89  if (!x.is_square())
90  throw std::runtime_error("'x' must be a square matrix");
91 
92  const len_t n = x.nrows();
93 
94  int info;
95  char uplo = (upper ? 'U' : 'L');
96  char diag = (unit_diag ? 'U' : 'N');
97  lapack::trtri(uplo, diag, x.nrows(), x.data_ptr(), n, &info);
98  linalgutils::check_info(info, "trtri");
99 
100  uplo = (uplo == 'U' ? 'L' : 'U');
101  cpu_utils::tri2zero(uplo, false, n, n, x.data_ptr(), n);
102  }
103 }
104 }
105 
106 
107 #endif
fml::cpumat
Matrix class for data held on a single CPU.
Definition: cpumat.hh:36
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: linalg_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: linalg_invert.hh:87
fml::linalg::invert
void invert(cpumat< REAL > &x)
Compute the matrix inverse.
Definition: linalg_invert.hh:46