TRIQS/nda 1.3.0
Multi-dimensional array library for C++
Loading...
Searching...
No Matches
gelss_worker.hpp
1// Copyright (c) 2020--present, The Simons Foundation
2// This file is part of TRIQS/nda and is licensed under the Apache License, Version 2.0.
3// SPDX-License-Identifier: Apache-2.0
4// See LICENSE in the root of this distribution for details.
5
6#pragma once
7
8#include "./gesvd.hpp"
9#include "../algorithms.hpp"
10#include "../basic_array.hpp"
11#include "../declarations.hpp"
12#include "../exceptions.hpp"
15#include "../linalg.hpp"
18
19#include <itertools/itertools.hpp>
20
21#include <algorithm>
22#include <array>
23#include <cmath>
24#include <complex>
25#include <optional>
26#include <utility>
27#include <vector>
28
29namespace nda::lapack {
30
35
76 template <typename T>
78 // Number of rows (M) and columns (N) of the Matrix A.
79 long M_, N_;
80
81 // Pseudo inverse of A, i.e. A^{+} = V * \Sigma^{+} * U^H.
82 matrix<T> A_plus_;
83
84 // U_N^H defining the error of the least squares problem.
85 matrix<T> U_N_H_;
86
87 // Array containing the singular values.
89
90 public:
95 int n_var() const { return N_; }
96
101 [[nodiscard]] array<double, 1> const &S_vec() const { return s_; }
102
112 gelss_worker(matrix_const_view<T> A) : M_(A.extent(0)), N_(A.extent(1)), s_(std::min(M_, N_)) {
113 if (N_ > M_) NDA_RUNTIME_ERROR << "Error in nda::lapack::gelss_worker: Matrix A cannot have more columns than rows";
114
115 // initialize matrices
116 matrix<T, F_layout> A_work{A};
117 matrix<T, F_layout> U(M_, M_);
118 matrix<T, F_layout> V_H(N_, N_);
119
120 // calculate the SVD: A = U * \Sigma * V^H
121 gesvd(A_work, s_, U, V_H);
122
123 // calculate the pseudo inverse A^{+} = V * \Sigma^{+} * U^H
124 matrix<double, F_layout> S_plus(N_, M_);
125 S_plus = 0.;
126 for (long i : range(s_.size())) S_plus(i, i) = 1.0 / s_(i);
127 A_plus_ = dagger(V_H) * S_plus * dagger(U);
128
129 // set U_N^H
130 if (N_ < M_) U_N_H_ = dagger(U)(range(N_, M_), range(M_));
131 }
132
147 auto operator()(matrix_const_view<T> B, std::optional<long> /* inner_matrix_dim */ = {}) const {
148 using std::sqrt;
149 double err = 0.0;
150 if (M_ != N_) {
151 std::vector<double> err_vec;
152 for (long i : range(B.shape()[1])) err_vec.push_back(frobenius_norm(U_N_H_ * B(range::all, range(i, i + 1))) / sqrt(B.shape()[0]));
153 err = *std::ranges::max_element(err_vec);
154 }
155 return std::pair<matrix<T>, double>{A_plus_ * B, err};
156 }
157
168 auto operator()(vector_const_view<T> b, std::optional<long> /*inner_matrix_dim*/ = {}) const {
169 using std::sqrt;
170 double err = 0.0;
171 if (M_ != N_) { err = norm(U_N_H_ * b) / sqrt(b.size()); }
172 return std::pair<vector<T>, double>{A_plus_ * b, err};
173 }
174 };
175
198 private:
199 // Complex double type.
200 using dcomplex = std::complex<double>;
201
202 // Worker for the original least squares problem.
204
205 // Worker for the extended least squares problem.
206 gelss_worker<dcomplex> lss_herm_;
207
208 public:
213 int n_var() const { return lss_herm_.n_var(); }
214
219 [[nodiscard]] array<double, 1> const &S_vec() const { return lss_.S_vec(); }
220
226
238 auto operator()(matrix_const_view<dcomplex> B, std::optional<long> inner_matrix_dim = {}) const {
239 if (not inner_matrix_dim.has_value())
240 NDA_RUNTIME_ERROR << "Error in nda::lapack::gelss_worker_hermitian: Inner matrix dimension required for hermitian least square fitting";
241 long d = *inner_matrix_dim;
242
243 // take the inner 'adjoint' of a matrix C:
244 // * reshape C -> C': (M, N) -> (M, N', d, d)
245 // * for each m and n: C'(m, n, :, :) -> C'(m, n, :, :)^/dagger
246 // * reshape C' -> C: (M, N', d, d) -> (M, N)
247 auto inner_adjoint = [d](auto &C) {
248 NDA_ASSERT2(C.shape()[1] % (d * d) == 0, "Error in nda::lapack::gelss_worker_hermitian: Data shape incompatible with inner matrix dimension");
249 auto shape = C.shape();
250
251 // get extent N' of second dimension
252 long N = shape[1] / (d * d);
253
254 // reshape, transpose and take the complex conjugate
255 array<dcomplex, 4> arr_dag = conj(permuted_indices_view<encode(std::array{0, 1, 3, 2})>(reshape(C, std::array{shape[0], N, d, d})));
256
257 // return the result in a new matrix
258 return matrix<dcomplex>{reshape(std::move(arr_dag), shape)};
259 };
260
261 // solve the extended system vstack(A, A*) * X = vstack(B, B_dag)
262 auto B_dag = inner_adjoint(B);
263 auto [x, err] = lss_herm_(vstack(B, B_dag));
264
265 // resymmetrize the results to cure small hermiticity violations
266 return std::pair<matrix<dcomplex>, double>{0.5 * (x + inner_adjoint(x)), err};
267 }
268 };
269
271
272} // namespace nda::lapack
Provides various algorithms to be used with nda::Array objects.
Provides the generic class for arrays.
auto const & shape() const noexcept
Get the shape of the view/array.
long size() const noexcept
Get the total size of the view/array.
Worker class for solving linear least squares problems.
auto operator()(vector_const_view< T > b, std::optional< long >={}) const
Solve the least squares problem for a given right hand side vector .
array< double, 1 > const & S_vec() const
Get the singular values, i.e. the diagonal elements of the matrix .
gelss_worker(matrix_const_view< T > A)
Construct a new worker object for a given matrix .
auto operator()(matrix_const_view< T > B, std::optional< long >={}) const
Solve the least squares problem for a given right hand side matrix .
int n_var() const
Get the number of variables of the given problem, i.e. the size of the vector .
Provides various convenient aliases and helper functions for nda::basic_array and nda::basic_array_vi...
Provides a custom runtime error class and macros to assert conditions and throw exceptions.
Provides a generic interface to the LAPACK gesvd routine.
auto permuted_indices_view(A &&a)
Permute the indices/dimensions of an nda::basic_array or nda::basic_array_view.
auto reshape(A &&a, std::array< Int, R > const &new_shape)
Reshape an nda::basic_array or nda::basic_array_view.
matrix< get_value_t< A > > vstack(A const &a, B const &b)
Stack two 2-dimensional arrays/views vertically.
auto sqrt(A &&a)
Function sqrt for non-matrix nda::ArrayOrScalar types (lazy and coefficient-wise for nda::Array types...
ArrayOfRank< 2 > auto dagger(M const &m)
Get the conjugate transpose of 2-dimensional array/view.
double frobenius_norm(A const &a)
Calculate the Frobenius norm of a 2-dimensional array.
decltype(auto) conj(A &&a)
Function conj for nda::ArrayOrScalar types (lazy and coefficient-wise for nda::Array types with a com...
basic_array< ValueType, Rank, Layout, 'A', ContainerPolicy > array
Alias template of an nda::basic_array with an 'A' algebra.
basic_array_view< ValueType const, 1, Layout, 'V', default_accessor, borrowed<> > vector_const_view
Same as nda::vector_view except for const value types.
basic_array_view< ValueType const, 2, Layout, 'M', default_accessor, borrowed<> > matrix_const_view
Same as nda::matrix_view except for const value types.
basic_array< ValueType, 2, Layout, 'M', ContainerPolicy > matrix
Alias template of an nda::basic_array with rank 2 and an 'M' algebra.
int gesvd(A &&a, S &&s, U &&u, VT &&vt)
Interface to the LAPACK gesvd routine.
Definition gesvd.hpp:64
constexpr uint64_t encode(std::array< int, N > const &a)
Encode a std::array<int, N> in a uint64_t.
Provides definitions of various layout policies.
Provides functions to transform the memory layout of an nda::basic_array or nda::basic_array_view.
Includes all relevant headers for the linear algebra functionality.
Provides some custom implementations of standard mathematical functions used for lazy,...
Provides functions to create and manipulate matrices, i.e. arrays/view with 'M' algebra.
int n_var() const
Get the number of variables of the given problem.
gelss_worker_hermitian(matrix_const_view< dcomplex > A)
Construct a new worker object for a given matrix .
array< double, 1 > const & S_vec() const
Get the singular values of the original matrix .
auto operator()(matrix_const_view< dcomplex > B, std::optional< long > inner_matrix_dim={}) const
Solve the least squares problem for a given right hand side matrix .