// @HEADER // ***************************************************************************** // Stokhos Package // // Copyright 2009 NTESS and the Stokhos contributors. // SPDX-License-Identifier: BSD-3-Clause // ***************************************************************************** // @HEADER #ifndef STOKHOS_SDM_UTILS_HPP #define STOKHOS_SDM_UTILS_HPP #include "Teuchos_SerialDenseMatrix.hpp" #include "Teuchos_SerialDenseVector.hpp" #include "Teuchos_SerialDenseHelpers.hpp" #include "Teuchos_Array.hpp" #include "Teuchos_LAPACK.hpp" #include #define DGEQP3_F77 F77_BLAS_MANGLE(dgeqp3,DGEQP3) extern "C" { #if defined(HAVE_STOKHOS_MKL) #include "mkl_version.h" #if __INTEL_MKL__ >= 2021 #define MKL_NO_EXCEPT noexcept #else #define MKL_NO_EXCEPT #endif #else #define MKL_NO_EXCEPT #endif void DGEQP3_F77(const int*, const int*, double*, const int*, int*, double*, double*, const int*, int*) MKL_NO_EXCEPT; } #include "Stokhos_ConfigDefs.h" #ifdef HAVE_STOKHOS_MATLABLIB extern "C" { #include "mat.h" #include "matrix.h" } #endif namespace Stokhos { namespace detail { //! Compute weighted inner product between vectors x and y template scalar_type weighted_inner_product( const Teuchos::SerialDenseVector& x, const Teuchos::SerialDenseVector& y, const Teuchos::Array& w) { ordinal_type n = x.length(); scalar_type t = 0; for (ordinal_type i=0; i void saxpy( const scalar_type& alpha, Teuchos::SerialDenseVector& x, const scalar_type& beta, const Teuchos::SerialDenseVector& y) { ordinal_type n = x.length(); for (ordinal_type i=0; i void print_matlab(std::ostream& os, const Teuchos::SerialDenseMatrix& A) { os << "[ "; for (ordinal_type i=0; i void save_matlab(const std::string& file_name, const std::string& matrix_name, const Teuchos::SerialDenseMatrix& A, bool overwrite = true) { // Open matfile const char *mode; if (overwrite) mode = "w"; else mode = "u"; MATFile *file = matOpen(file_name.c_str(), mode); TEUCHOS_ASSERT(file != NULL); // Convert SDM to Matlab matrix mxArray *mat = mxCreateDoubleMatrix(0, 0, mxREAL); TEUCHOS_ASSERT(mat != NULL); mxSetPr(mat, A.values()); mxSetM(mat, A.numRows()); mxSetN(mat, A.numCols()); // Save matrix to file ordinal_type ret = matPutVariable(file, matrix_name.c_str(), mat); TEUCHOS_ASSERT(ret == 0); // Close file ret = matClose(file); TEUCHOS_ASSERT(ret == 0); // Free matlab matrix mxSetPr(mat, NULL); mxSetM(mat, 0); mxSetN(mat, 0); mxDestroyArray(mat); } #endif //! Vector-infinity norm of a matrix template scalar_type vec_norm_inf( const Teuchos::SerialDenseMatrix& A) { Teuchos::SerialDenseMatrix vec_A( Teuchos::View, A.values(), 1, A.numRows()*A.numCols(), 1); return vec_A.normInf(); } //! Compute thin QR using classical Gram-Schmidt /*! * For A an m-by-n matrix computes A = Q*R with R k-by-k upper triangular, * Q m-by-k with orthogonal columns, k <= min(m,n). */ template void QR_CGS( ordinal_type k, const Teuchos::SerialDenseMatrix& A, const Teuchos::Array& w, Teuchos::SerialDenseMatrix& Q, Teuchos::SerialDenseMatrix& R) { using Teuchos::getCol; typedef Teuchos::SerialDenseVector SDV; typedef Teuchos::SerialDenseMatrix SDM; // getCol() requires non-const SDM SDM& Anc = const_cast(A); // Make sure Q is the right size ordinal_type m = A.numRows(); if (Q.numRows() != m || Q.numCols() != k) Q.shape(m,k); if (R.numRows() != k || R.numCols() != k) R.shape(k,k); for (ordinal_type j=0; j void QR_MGS( ordinal_type k, const Teuchos::SerialDenseMatrix& A, const Teuchos::Array& w, Teuchos::SerialDenseMatrix& Q, Teuchos::SerialDenseMatrix& R) { using Teuchos::getCol; typedef Teuchos::SerialDenseVector SDV; typedef Teuchos::SerialDenseMatrix SDM; // getCol() requires non-const SDM SDM& Anc = const_cast(A); // Make sure Q is the right size ordinal_type m = A.numRows(); if (Q.numRows() != m || Q.numCols() != k) Q.shape(m,k); if (R.numRows() != k || R.numCols() != k) R.shape(k,k); for (ordinal_type i=0; i void QR_MGS2( ordinal_type k, const Teuchos::SerialDenseMatrix& A, const Teuchos::Array& w, Teuchos::SerialDenseMatrix& Q, Teuchos::SerialDenseMatrix& R) { using Teuchos::getCol; typedef Teuchos::SerialDenseVector SDV; typedef Teuchos::SerialDenseMatrix SDM; // getCol() requires non-const SDM SDM& Anc = const_cast(A); // Make sure Q is the right size ordinal_type m = A.numRows(); if (Q.numRows() != m || Q.numCols() != k) Q.shape(m,k); if (R.numRows() != k || R.numCols() != k) R.shape(k,k); for (ordinal_type i=0; i=0; j--) { SDV Qj = getCol(Teuchos::View, Q, j); scalar_type v = detail::weighted_inner_product(Qi, Qj, w); detail::saxpy(1.0, Qi, -v, Qj); // Q(:,i) = 1.0*Q(:,i) - v*Q(:,j) R(j,i) += v; } R(i,i) = std::sqrt(detail::weighted_inner_product(Qi, Qi, w)); Qi.scale(1.0/R(i,i)); } } //! Compute thin QR using Householder reflections /*! * For A an m-by-n matrix computes A = Q*R with R k-by-k upper triangular, * Q m-by-k with orthogonal columns, k <= min(m,n). * * The QR factorization is computed by the corresponding LAPACK function. */ template void QR_Householder( ordinal_type k, const Teuchos::SerialDenseMatrix& A, const Teuchos::Array& w, Teuchos::SerialDenseMatrix& Q, Teuchos::SerialDenseMatrix& R) { Teuchos::LAPACK lapack; ordinal_type m = A.numRows(); ordinal_type n = A.numCols(); ordinal_type kk = std::min(m,n); if (k > kk) k = kk; // Check that each component of w is 1 for (ordinal_type i=0; i AA( Teuchos::Copy, A, m, n); // QR ordinal_type lda = AA.stride(); Teuchos::Array tau(k); Teuchos::Array work(1); ordinal_type info; ordinal_type lwork = -1; lapack.GEQRF(m, n, AA.values(), lda, &tau[0], &work[0], lwork, &info); TEUCHOS_TEST_FOR_EXCEPTION( info < 0, std::logic_error, "geqrf returned info = " << info); lwork = work[0]; work.resize(lwork); lapack.GEQRF(m, n, AA.values(), lda, &tau[0], &work[0], lwork, &info); TEUCHOS_TEST_FOR_EXCEPTION( info < 0, std::logic_error, "geqrf returned info = " << info); // Extract R if (R.numRows() != k || R.numCols() != n) R.shape(k,n); R.putScalar(0.0); for (ordinal_type i=0; i r_max) r_max = std::abs(R(rank,rank)); if (std::abs(R(rank,rank)) < r_min) r_min = std::abs(R(rank,rank)); if (r_min / r_max < rank_threshold) break; } // Extract blocks from Q and R R.reshape(rank,rank); Q.reshape(Q.numRows(), rank); return rank; } //! Compute column-pivoted QR using modified Gram-Schmidt /*! * For A an m-by-n matrix, computes A*P = Q*R with R k-by-k upper triangular, * Q m-by-k with orthonormal columns, and P an n-by-k permutation matrix. * Here k <= min(m,n) is determined by a rank threshold tau provided by the * user. The resulting R will have cond(R) <= 1/tau. P is returned in the * pivot array \c piv and the rank k returned by the function. Only the first * k entries of \c piv will be set. As with LAPACK, the user can require * columns of A to be included in P by setting the corresponding entries * of piv to be nonzero on input. The orthogonality of Q is determined by * the weight vector w, defining a weighted inner-product. */ template ordinal_type CPQR_MGS_threshold( const scalar_type& rank_threshold, const Teuchos::SerialDenseMatrix& A, const Teuchos::Array& w, Teuchos::SerialDenseMatrix& Q, Teuchos::SerialDenseMatrix& R, Teuchos::Array& piv) { using Teuchos::getCol; typedef Teuchos::SerialDenseVector SDV; ordinal_type m = A.numRows(); ordinal_type n = A.numCols(); ordinal_type k = std::min(m,n); // Make sure Q is the right size if (Q.numRows() != m || Q.numCols() != n) Q.shape(m,n); if (R.numRows() != m || R.numCols() != n) R.shape(m,n); if (piv.size() != n) piv.resize(n); Q.assign(A); // Compute column norms SDV nrm(n); for (ordinal_type j=0; j piv_orig(piv); for (ordinal_type i=0; i= rank_threshold) { SDV Qj = getCol(Teuchos::View, Q, j); // Find pivot column if we are passed the pre-pivot stage if (j >= nfixed) { ordinal_type pvt = j; for (ordinal_type l=j+1; l nrm(pvt)) pvt = l; // Interchange column j and pvt if (pvt != j) { SDV Qpvt = getCol(Teuchos::View, Q, pvt); Qtmp.assign(Qpvt); Qpvt.assign(Qj); Qj.assign(Qtmp); SDV Rpvt = getCol(Teuchos::View, R, pvt); SDV Rj = getCol(Teuchos::View, R, j); Rtmp.assign(Rpvt); Rpvt.assign(Rj); Rj.assign(Rtmp); ordinal_type t = piv[pvt]; piv[pvt] = piv[j]; piv[j] = t; } } R(j,j) = std::sqrt(detail::weighted_inner_product(Qj, Qj, w)); Qj.scale(1.0/R(j,j)); for (ordinal_type l=j+1; l r_max) r_max = R(j,j); sigma = std::abs(R(j,j)/r_max); j++; } ordinal_type rank = j; if (sigma < rank_threshold) rank--; Q.reshape(m, rank); R.reshape(rank, rank); return rank; } //! Compute column-pivoted QR using modified Gram-Schmidt and reorthogonalization /*! * For A an m-by-n matrix, computes A*P = Q*R with R k-by-k upper triangular, * Q m-by-k with orthonormal columns, and P an n-by-k permutation matrix. * Here k <= min(m,n) is determined by a rank threshold tau provided by the * user. The resulting R will have cond(R) <= 1/tau. P is returned in the * pivot array \c piv and the rank k returned by the function. Only the first * k entries of \c piv will be set. As with LAPACK, the user can require * columns of A to be included in P by setting the corresponding entries * of piv to be nonzero on input. The orthogonality of Q is determined by * the weight vector w, defining a weighted inner-product. */ template ordinal_type CPQR_MGS_reorthog_threshold( const scalar_type& rank_threshold, const Teuchos::SerialDenseMatrix& A, const Teuchos::Array& w, Teuchos::SerialDenseMatrix& Q, Teuchos::SerialDenseMatrix& R, Teuchos::Array& piv) { // First do standard column-pivoted QR ordinal_type rank = CPQR_MGS_threshold(rank_threshold, A, w, Q, R, piv); // Now apply standard MGS to Q Teuchos::SerialDenseMatrix A2(Q), R2; QR_MGS(rank, A2, w, Q, R2); return rank; } //! Compute condition number of upper-triangular R template scalar_type cond_R(const Teuchos::SerialDenseMatrix& R) { ordinal_type k = R.numRows(); if (R.numCols() < k) k = R.numCols(); scalar_type r_max = std::abs(R(0,0)); scalar_type r_min = std::abs(R(0,0)); for (ordinal_type i=1; i r_max) r_max = R(i,i); if (std::abs(R(i,i)) < r_min) r_min = R(i,i); } scalar_type cond_r = r_max / r_min; return cond_r; } //! Compute weighted QR orthogonalization error /*! * Computes ||Q^T*W*Q-I||_infinity for Q coming from a weighted QR * factorization. */ template scalar_type weightedQROrthogonalizationError( const Teuchos::SerialDenseMatrix& Q, const Teuchos::Array& w) { ordinal_type m = Q.numRows(); ordinal_type n = Q.numCols(); Teuchos::SerialDenseMatrix Qt(m,n); for (ordinal_type i=0; i err(n,n); err.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0, Q, Qt, 0.0); for (ordinal_type i=0; i scalar_type QROrthogonalizationError( const Teuchos::SerialDenseMatrix& Q) { ordinal_type n = Q.numCols(); Teuchos::SerialDenseMatrix err(n,n); err.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0, Q, Q, 0.0); for (ordinal_type i=0; i scalar_type residualQRError( const Teuchos::SerialDenseMatrix& A, const Teuchos::SerialDenseMatrix& Q, const Teuchos::SerialDenseMatrix& R) { ordinal_type k = Q.numCols(); ordinal_type m = Q.numRows(); Teuchos::SerialDenseMatrix AA( Teuchos::View, A, m, k, 0, 0); Teuchos::SerialDenseMatrix err(m,k); ordinal_type ret = err.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1.0, Q, R, 0.0); TEUCHOS_ASSERT(ret == 0); err -= AA; return err.normInf(); } //! Compute column-pivoted QR residual error /*! * Computes ||Q*R-A*P||_infinity for Q,R coming from a column-pivoted * QR factorization. * * Works with thin or full QR, weighted or not. */ template scalar_type residualCPQRError( const Teuchos::SerialDenseMatrix& A, const Teuchos::SerialDenseMatrix& Q, const Teuchos::SerialDenseMatrix& R, const Teuchos::Array& piv) { ordinal_type k = Q.numCols(); ordinal_type m = Q.numRows(); Teuchos::SerialDenseMatrix AP(m, k); for (ordinal_type j=0; j err(m,k); ordinal_type ret = err.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1.0, Q, R, 0.0); TEUCHOS_ASSERT(ret == 0); err -= AP; return err.normInf(); } //! Compute SVD of matrix /*! * The SVD is computed by the corresponding LAPACK function. */ template void svd(const Teuchos::SerialDenseMatrix& A, Teuchos::Array& s, Teuchos::SerialDenseMatrix& U, Teuchos::SerialDenseMatrix& Vt) { Teuchos::LAPACK lapack; ordinal_type m = A.numRows(); ordinal_type n = A.numCols(); ordinal_type k = std::min(m,n); ordinal_type lda = A.stride(); // Copy A since GESVD overwrites it (always) Teuchos::SerialDenseMatrix AA( Teuchos::Copy, A, m, n); // Resize appropriately if (U.numRows() != m || U.numCols() != m) U.shape(m,m); if (Vt.numRows() != n || Vt.numCols() != n) Vt.shape(n,n); if (s.size() != k) s.resize(k); ordinal_type ldu = U.stride(); ordinal_type ldv = Vt.stride(); // Workspace query Teuchos::Array work(1); ordinal_type lwork = -1; ordinal_type info; lapack.GESVD('A', 'A', m, n, AA.values(), lda, &s[0], U.values(), ldu, Vt.values(), ldv, &work[0], lwork, NULL, &info); TEUCHOS_TEST_FOR_EXCEPTION( info < 0, std::logic_error, "dgesvd returned info = " << info); // Do SVD lwork = work[0]; work.resize(lwork); lapack.GESVD('A', 'A', m, n, AA.values(), lda, &s[0], U.values(), ldu, Vt.values(), ldv, &work[0], lwork, NULL, &info); TEUCHOS_TEST_FOR_EXCEPTION( info < 0, std::logic_error, "dgesvd returned info = " << info); } template ordinal_type svd_threshold( const scalar_type& rank_threshold, const Teuchos::SerialDenseMatrix& A, Teuchos::Array& s, Teuchos::SerialDenseMatrix& U, Teuchos::SerialDenseMatrix& Vt) { // Compute full SVD svd(A, s, U, Vt); // Find leading block of S such that cond(S) <= 1/tau ordinal_type rank = 0; ordinal_type m = s.size(); while (rank < m && s[rank]/s[0] > rank_threshold) rank++; // Extract blocks from s, U and Vt s.resize(rank); U.reshape(U.numRows(),rank); Vt.reshape(rank, Vt.numCols()); return rank; } } #endif