Macaulay2 Engine
Loading...
Searching...
No Matches

◆ least_squares() [3/4]

bool Lapack::least_squares ( const DMatRR * A,
const DMatRR * b,
DMatRR * x )
static

Definition at line 707 of file lapack.cpp.

708{
709 bool ret = true;
710 char job = 'N';
711 int info;
712 int rows = static_cast<int>(A->numRows());
713 int cols = static_cast<int>(A->numColumns());
714 int brows = static_cast<int>(b->numRows());
715 int bcols = static_cast<int>(b->numColumns());
716 int min = (rows <= cols) ? rows : cols;
717 int max = (rows >= cols) ? rows : cols;
718 int wsize = min + ((bcols >= max) ? bcols : max);
719
720 if (brows != rows)
721 {
722 ERROR("expected compatible right hand side");
723 return false;
724 }
725
726 if (min == 0 || bcols == 0)
727 {
728 x->resize(cols, bcols);
729 return true;
730 }
731
732 std::vector<double> copyA = make_lapack_array(*A);
733 std::vector<double> copyb = make_lapack_array(*b);
734 double* workspace = new double[wsize];
735
736 if (rows < cols)
737 {
738 // Make 'b' (copyb) into a cols x bcols matrix, by adding a zero block at
739 // the bottom
740 std::vector<double> copyb2(cols * bcols);
741 for (auto&a : copyb2) a = 0;
742 int bloc = 0;
743 int copyloc = 0;
744 for (int j = 0; j < bcols; j++)
745 {
746 copyloc = j * cols;
747 for (int i = 0; i < brows; i++)
748 {
749 copyb2[copyloc++] = copyb[bloc++];
750 }
751 }
752 std::swap(copyb2, copyb);
753 }
754
755 dgels_(&job,
756 &rows,
757 &cols,
758 &bcols,
759 copyA.data(),
760 &rows,
761 copyb.data(),
762 &max,
763 workspace,
764 &wsize,
765 &info);
766
767 if (info != 0)
768 {
769 ERROR("argument passed to dgels had an illegal value");
770 ret = false;
771 }
772 else
773 {
774 x->resize(cols, bcols);
775 if (rows > cols)
776 {
777 // We only need the first 'cols' rows of copyb
778 int copyloc = 0;
779 for (int j = 0; j < bcols; j++)
780 {
781 copyloc = j * rows;
782 for (int i = 0; i < cols; i++)
783 {
784 x->entry(i,j) = copyb[copyloc++];
785 }
786 }
787 }
788 else
789 {
790 fill_from_lapack_array(copyb, *x);
791 }
792 }
793
794 delete [] workspace;
795
796 return ret;
797}
size_t numRows() const
Definition dmat.hpp:144
size_t numColumns() const
Definition dmat.hpp:145
std::vector< double > make_lapack_array(const DMatRR &mat)
Definition lapack.cpp:20
void fill_from_lapack_array(const std::vector< double > &doubles, DMatRR &mat)
Definition lapack.cpp:45
int dgels_(char *job, int *rows, int *cols, int *nhrs, double *A, int *ldA, double *b, int *ldb, double *work, int *lwork, int *info)
const int ERROR
Definition m2-mem.cpp:55
const mpreal min(const mpreal &x, const mpreal &y)
Definition mpreal.h:2792
void swap(mpfr::mpreal &x, mpfr::mpreal &y)
Definition mpreal.h:3244
volatile int x
#define max(a, b)
Definition polyroots.cpp:52

References dgels_(), ERROR, fill_from_lapack_array(), make_lapack_array(), max, DMat< ACoeffRing >::numColumns(), DMat< ACoeffRing >::numRows(), std::swap(), and x.