Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
al-matrix.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
43# ifndef AH_MATRIX_H
44# define AH_MATRIX_H
45
46# include <memory>
47# include <type_traits>
48# include <utility>
49# include <al-vector.H>
50# include <ah-errors.H>
51
52namespace Aleph
53{
67 template <typename Trow = int, typename Tcol = int, typename NumType = double>
68 requires AlDomainKey<Trow> and AlDomainKey<Tcol> and AlNumber<NumType>
69 class Matrix
70 {
71 public:
74 using RDomainPtr = std::shared_ptr<RDomain>;
75 using CDomainPtr = std::shared_ptr<CDomain>;
76
77 using RCPair = std::pair<Trow, Tcol>;
78
80
82
84
85 private:
86 static const NumType default_epsilon;
87
91 NumType epsilon;
92
93 bool is_zero(const NumType & val) const noexcept
94 {
95 assert(epsilon >= 0);
96 return val >= -epsilon and val <= epsilon;
97 }
98
99 // A pointer to a domain that the matrix does not own: the caller keeps
100 // it alive
101 template <class D>
102 static std::shared_ptr<D> borrow(const D & d)
103 {
104 return std::shared_ptr<D>(&const_cast<D &>(d), [](D *) {});
105 }
106
107 // A pointer to a copy of a temporary domain, which the matrix owns
108 template <class D>
109 static std::shared_ptr<D> own(D && d)
110 {
111 return std::make_shared<D>(std::move(d));
112 }
113
114 public:
116 const NumType &get_epsilon() const noexcept { return epsilon; }
117
122 void set_epsilon(const NumType & e)
123 {
124 ah_domain_error_if(e < 0)
125 << "epsilon must be greater or equal to zero";
126 epsilon = e;
127 }
128
130 typedef std::pair<RCPair, NumType> Pair;
131
133 const RDomain &get_row_domain() const noexcept { return *rdomain_ptr; }
134
136 const CDomain &get_col_domain() const noexcept { return *cdomain_ptr; }
137
139 const RDomainPtr &get_row_domain_ptr() const noexcept { return rdomain_ptr; }
140
142 const CDomainPtr &get_col_domain_ptr() const noexcept { return cdomain_ptr; }
143
149 Matrix(RDomainPtr rdomain, CDomainPtr cdomain,
150 const NumType & e = default_epsilon)
151 : rdomain_ptr(std::move(rdomain)),
152 cdomain_ptr(std::move(cdomain)),
153 entries(10, Aleph::pair_dft_hash_ptr_fct<Trow, Tcol>,
154 Aleph::pair_snd_hash_ptr_fct<Trow, Tcol>)
155 {
156 set_epsilon(e);
157 }
158
165 Matrix(const RDomain & rdomain, const CDomain & cdomain,
166 const NumType & e = default_epsilon)
167 : Matrix(borrow(rdomain), borrow(cdomain), e)
168 {
169 // empty
170 }
171
180 Matrix(RDomain && rdomain, CDomain && cdomain,
181 const NumType & e = default_epsilon)
182 : Matrix(own(std::move(rdomain)), own(std::move(cdomain)), e)
183 {
184 // empty
185 }
186
188 Matrix(RDomain && rdomain, const CDomain & cdomain,
189 const NumType & e = default_epsilon)
190 : Matrix(own(std::move(rdomain)), borrow(cdomain), e)
191 {
192 // empty
193 }
194
196 Matrix(const RDomain & rdomain, CDomain && cdomain,
197 const NumType & e = default_epsilon)
198 : Matrix(borrow(rdomain), own(std::move(cdomain)), e)
199 {
200 // empty
201 }
202
206 template <typename R, typename C, typename... Rest>
207 requires (std::is_integral_v<std::remove_cvref_t<R>> or
208 std::is_integral_v<std::remove_cvref_t<C>>)
209 Matrix(R &&, C &&, Rest &&...) = delete;
210
218 Matrix(RDomainPtr rdomain, CDomainPtr cdomain,
219 std::initializer_list<std::initializer_list<NumType>> l,
220 const NumType & e = default_epsilon)
222 : Matrix(std::move(rdomain), std::move(cdomain), e)
223 {
224 ah_range_error_if(l.size() != rdomain_ptr->size()) << "mismatch with number of rows";
225
226 auto itr = l.begin();
227 const DynList<Tcol> & clist = cdomain_ptr->keys();
228 rdomain_ptr->keys().
229 for_each([this, &itr, &clist](const Trow & row)
230 {
231 ah_range_error_if(itr->size() != cdomain_ptr->size())
232 << "mismatch with number of columns";
233 auto itc = itr->begin();
234 clist.for_each([this, &itc, &row](const Tcol & col)
235 {
236 const NumType & val = *itc++;
237 if (is_zero(val))
238 return;
239
240 entries.insert(RCPair(row, col), val);
241 });
242 ++itr;
243 });
244 }
245
253 Matrix(const RDomain & rdomain, const CDomain & cdomain,
254 std::initializer_list<std::initializer_list<NumType>> l,
255 const NumType & e = default_epsilon)
257 : Matrix(borrow(rdomain), borrow(cdomain), l, e)
258 {}
259
269 Matrix(RDomain && rdomain, CDomain && cdomain,
270 std::initializer_list<std::initializer_list<NumType>> l,
271 const NumType & e = default_epsilon)
273 : Matrix(own(std::move(rdomain)), own(std::move(cdomain)), l, e)
274 {}
275
277 Matrix(RDomain && rdomain, const CDomain & cdomain,
278 std::initializer_list<std::initializer_list<NumType>> l,
279 const NumType & e = default_epsilon)
281 : Matrix(own(std::move(rdomain)), borrow(cdomain), l, e)
282 {}
283
285 Matrix(const RDomain & rdomain, CDomain && cdomain,
286 std::initializer_list<std::initializer_list<NumType>> l,
287 const NumType & e = default_epsilon)
289 : Matrix(borrow(rdomain), own(std::move(cdomain)), l, e)
290 {}
291
299 Matrix(RDomainPtr rdomain, CDomainPtr cdomain,
300 const DynList<DynList<NumType>> & l,
301 const NumType & e = default_epsilon)
303 : Matrix(std::move(rdomain), std::move(cdomain), e)
304 {
305 ah_range_error_if(l.size() != rdomain_ptr->size()) << "mismatch with number of rows";
306
307 for (auto it = zip_it(rdomain_ptr->keys(), l); it.has_curr(); it.next())
308 {
309 auto t = it.get_curr();
310 const Trow & row_idx = get<0>(t);
311 const DynList<NumType> & row = get<1>(t);
312 ah_range_error_if(row.size() != cdomain_ptr->size())
313 << "mismatch with number of columns";
314 for (auto it = zip_it(cdomain_ptr->keys(), row); it.has_curr(); it.next())
315 {
316 auto t = it.get_curr();
317 const NumType & val = get<1>(t);
318 if (is_zero(val))
319 continue;
320 const Tcol & col_idx = get<0>(t);
321 entries.insert(RCPair(row_idx, col_idx), val);
322 }
323 }
324 }
325
333 Matrix(const RDomain & rdomain, const CDomain & cdomain,
334 const DynList<DynList<NumType>> & l,
335 const NumType & e = default_epsilon)
337 : Matrix(borrow(rdomain), borrow(cdomain), l, e)
338 {}
339
349 Matrix(RDomain && rdomain, CDomain && cdomain,
350 const DynList<DynList<NumType>> & l,
351 const NumType & e = default_epsilon)
353 : Matrix(own(std::move(rdomain)), own(std::move(cdomain)), l, e)
354 {}
355
357 Matrix(RDomain && rdomain, const CDomain & cdomain,
358 const DynList<DynList<NumType>> & l,
359 const NumType & e = default_epsilon)
361 : Matrix(own(std::move(rdomain)), borrow(cdomain), l, e)
362 {}
363
365 Matrix(const RDomain & rdomain, CDomain && cdomain,
366 const DynList<DynList<NumType>> & l,
367 const NumType & e = default_epsilon)
369 : Matrix(borrow(rdomain), own(std::move(cdomain)), l, e)
370 {}
371
373 Matrix(const Matrix & other)
374 : rdomain_ptr(other.rdomain_ptr),
376 entries(other.entries),
377 epsilon(other.epsilon)
378 {
379 // empty
380 }
381
383 Matrix(Matrix && other) noexcept
384 : rdomain_ptr(other.rdomain_ptr),
385 cdomain_ptr(other.cdomain_ptr),
386 entries(std::move(other.entries)),
387 epsilon(other.epsilon)
388 {
389 // empty
390 }
391
393 Matrix &operator =(const Matrix & other)
394 {
395 if (this != &other)
396 {
397 rdomain_ptr = other.rdomain_ptr;
398 cdomain_ptr = other.cdomain_ptr;
399 entries = other.entries;
400 epsilon = other.epsilon;
401 }
402 return *this;
403 }
404
406 Matrix &operator =(Matrix && other) noexcept
407 {
408 if (this != &other)
409 {
410 rdomain_ptr = other.rdomain_ptr;
411 cdomain_ptr = other.cdomain_ptr;
412 entries = std::move(other.entries);
413 epsilon = other.epsilon;
414 }
415 return *this;
416 }
417
418 private:
419 // The vectors of a matrix built by rows or by columns: one per element
420 // of the domain, all over the same domain, which the matrix shares
421 template <class Vec, class D>
422 static void check_vectors(const D & domain, const DynList<Vec> & vectors,
423 const char * name)
424 {
425 ah_range_error_if(vectors.size() != domain.size())
426 << name << "(): " << vectors.size() << " vectors for "
427 << domain.size() << " elements of the domain";
428 const auto & first = vectors.get_first().get_domain_ptr();
429 ah_domain_error_if(not vectors.all([&first] (const Vec & v)
430 {
431 return v.get_domain_ptr() == first;
432 }))
433 << name << "(): the vectors have different domains";
434 }
435
438 const NumType & e)
440 {
441 check_vectors(*rdomain, rows, "create_by_rows");
442 Matrix ret(rdomain, rows.get_first().get_domain_ptr(), e);
443
444 for (auto it = zip_it(rdomain->keys(), rows); it.has_curr(); it.next())
445 {
446 auto t = it.get_curr();
447 const Trow & row_idx = get<0>(t);
448 const Vector<Tcol, NumType> & row = get<1>(t);
449 for (auto it_col = row.get_it(); it_col.has_curr(); it_col.next())
450 {
451 auto & p = it_col.get_curr();
452 const NumType & val = p.second;
453 if (ret.is_zero(val))
454 continue;
455 const Tcol & col_idx = p.first;
456 ret.entries.insert(RCPair(row_idx, col_idx), val);
457 }
458 }
459
460 return ret;
461 }
462
465 const NumType & e)
467 {
468 check_vectors(*cdomain, cols, "create_by_columns");
469 Matrix ret(cols.get_first().get_domain_ptr(), cdomain, e);
470
471 for (auto it = zip_it(cdomain->keys(), cols); it.has_curr(); it.next())
472 {
473 auto t = it.get_curr();
474 const Tcol & col_idx = get<0>(t);
475 const Vector<Trow, NumType> & col = get<1>(t);
476 for (auto it_col = col.get_it(); it_col.has_curr(); it_col.next())
477 {
478 auto & p = it_col.get_curr();
479 const NumType & val = p.second;
480 if (ret.is_zero(val))
481 continue;
482 const Trow & row_idx = p.first;
483 ret.entries.insert(RCPair(row_idx, col_idx), val);
484 }
485 }
486
487 return ret;
488 }
489
490 public:
504 static Matrix create_by_rows(const RDomain & rdomain,
506 const NumType & e = default_epsilon)
508 {
509 return create_by_rows_impl(borrow(rdomain), rows, e);
510 }
511
514 static Matrix create_by_rows(RDomain && rdomain,
516 const NumType & e = default_epsilon)
518 {
519 return create_by_rows_impl(own(std::move(rdomain)), rows, e);
520 }
521
535 static Matrix create_by_columns(const CDomain & cdomain,
537 const NumType & e = default_epsilon)
539 {
540 return create_by_columns_impl(borrow(cdomain), cols, e);
541 }
542
547 const NumType & e = default_epsilon)
549 {
550 return create_by_columns_impl(own(std::move(cdomain)), cols, e);
551 }
552
562 NumType get_entry(const Trow & row, const Tcol & col)
563 {
564 assert(rdomain_ptr->has(row) and cdomain_ptr->has(col));
565 auto *ptr = entries.search(RCPair(row, col));
566 if (ptr == nullptr)
567 return 0;
568 if (is_zero(ptr->second))
569 {
570 entries.remove_ptr(ptr);
571 return 0;
572 }
573 return ptr->second;
574 }
575
581 NumType get_entry(const Trow & row, const Tcol & col) const noexcept
582 {
583 assert(rdomain_ptr->has(row) and cdomain_ptr->has(col));
584 auto *ptr = entries.search(RCPair(row, col));
585 if (ptr == nullptr)
586 return 0;
587 return ptr->second;
588 }
589
599 void set_entry(const Trow & row, const Tcol & col, const NumType & val)
600 {
601 assert(rdomain_ptr->has(row) and cdomain_ptr->has(col));
602 auto *ptr = entries.search(RCPair(row, col));
603 if (is_zero(val))
604 {
605 if (ptr != nullptr)
606 entries.remove_ptr(ptr);
607 return;
608 }
609 if (ptr == nullptr)
610 entries.insert(RCPair(row, col), val);
611 else
612 ptr->second = val;
613 }
614
620 {
622 entries.for_each([&ret_val](const Pair & p)
623 {
624 const RCPair & rc = p.first;
625 const NumType & val = p.second;
626 ret_val.set_entry(rc.second, rc.first, val);
627 });
628 return ret_val;
629 }
630
633 requires AlOrderedDomainKey<Trow>
634 {
635 return rdomain_ptr->keys();
636 }
637
640 requires AlOrderedDomainKey<Tcol>
641 {
642 return cdomain_ptr->keys();
643 }
644
652 {
653 ah_domain_error_if(not rdomain_ptr->has(row)) << "row is not inside the row domain";
654 return col_domain_list().
655 template maps<NumType>([this, &row](const Tcol & col)
656 {
657 return get_entry(row, col);
658 });
659 }
660
668 {
669 ah_domain_error_if(not cdomain_ptr->has(col)) << "col is not inside the column domain";
670 return row_domain_list().template maps<NumType>
671 ([this, &col](const Trow & row) { return get_entry(row, col); });
672 }
673
676 requires AlOrderedDomainKey<Trow> and AlOrderedDomainKey<Tcol>
677 {
681 for_each([this, &ret_val, cols](const Trow & row)
682 {
684 cols.for_each([this, &vec, &row](const Tcol & col)
685 {
686 auto *val_ptr =
687 entries.search(RCPair(row, col));
688 if (val_ptr != nullptr)
689 vec.set_entry(col, val_ptr->second);
690 });
691 ret_val.append(vec);
692 });
693 return ret_val;
694 }
695
698 requires AlOrderedDomainKey<Trow> and AlOrderedDomainKey<Tcol>
699 {
700 DynList<ColVector> ret_val;
703 for_each([this, &ret_val, &rows](const Tcol & col)
704 {
706 rows.for_each([this, &vec, &col](const Trow & row)
707 {
708 auto *ptr = entries.search(RCPair(row, col));
709 if (ptr != nullptr)
710 vec.set_entry(row, ptr->second);
711 });
712 ret_val.append(vec);
713 });
714 return ret_val;
715 }
716
719 {
721 << "get_row_vector(): invalid row";
723 cdomain_ptr->for_each([&](const Tcol & col)
724 {
725 auto *ptr = entries.search(RCPair(row, col));
726 if (ptr != nullptr)
727 ret_val.set_entry(col, ptr->second);
728 });
729 return ret_val;
730 }
731
734 {
736 << "get_col_vector(): invalid col";
738 rdomain_ptr->for_each([&](const Trow & row)
739 {
740 auto *ptr = entries.search(RCPair(row, col));
741 if (ptr != nullptr)
742 ret_val.set_entry(row, ptr->second);
743 });
744 return ret_val;
745 }
746
758 {
759 ah_domain_error_if(&vec.get_domain() != &get_col_domain())
760 << "mult_matrix_vector_linear_comb: domain mismatch";
762 vec.for_each([this, &ret_val](const std::pair<Tcol, NumType> & p)
763 {
764 const Tcol & col = p.first;
765 const NumType & val = p.second;
766 ret_val += val * get_col_vector(col);
767 });
768 return ret_val;
769 }
770
782 {
783 ah_domain_error_if(&vec.get_domain() != &get_col_domain())
784 << "mult_matrix_vector_sparse: domain mismatch";
786 entries.for_each([&ret_val, &vec](const Pair & p)
787 {
788 const Trow & row = p.first.first;
789 const Tcol & col = p.first.second;
790 const NumType & entry_val = p.second;
791 const NumType *vec_entry = vec.search_entry(col);
792 if (vec_entry != nullptr)
793 ret_val.set_entry(row, ret_val.get_entry(row) +
794 entry_val * *vec_entry);
795 });
796 return ret_val;
797 }
798
811 {
812 ah_domain_error_if(&vec.get_domain() != &get_row_domain())
813 << "mult_vector_matrix_linear_comb: domain mismatch";
815 vec.for_each([this, &ret_val](const std::pair<Trow, NumType> & p)
816 {
817 const Trow & row = p.first;
818 const NumType & val = p.second;
819 ret_val += val * get_row_vector(row);
820 });
821 return ret_val;
822 }
823
835 {
836 ah_domain_error_if(&vec.get_domain() != &get_col_domain())
837 << "mult_matrix_vector_dot_product: domain mismatch";
839 rdomain_ptr->for_each([&](const Trow & row)
840 {
841 ret_val.set_entry(row, vec * get_row_vector(row));
842 });
843 return ret_val;
844 }
845
857 {
858 ah_domain_error_if(&vec.get_domain() != &get_row_domain())
859 << "mult_vector_matrix_dot_product: domain mismatch";
861 cdomain_ptr->for_each([&](const Tcol & col)
862 {
863 ret_val.set_entry(col, vec * get_col_vector(col));
864 });
865 return ret_val;
866 }
867
875
876 private:
885 template <typename T2row, typename T2col>
887 const
888 {
889 static_assert(std::is_same_v<T2row, Tcol>,
890 "AxB: the rows of B must be of the type of the columns of A");
891 ah_domain_error_if(cdomain_ptr != m.get_row_domain_ptr())
892 << "AxB: Column domain of A must be identical to row domain of B";
893 }
894
895 public:
903 {
905 << "set_vector_as_row: domain vec mismatch";
906 vec.for_each([this, &row](const std::pair<Tcol, NumType> & p)
907 {
908 const Tcol & col = p.first;
909 const NumType & val = p.second;
910 set_entry(row, col, val);
911 });
912 return *this;
913 }
914
922 {
924 << "set_vector_as_col: domain vec mismatch";
925 vec.for_each([this, &col](const std::pair<Trow, NumType> & p)
926 {
927 const Trow & row = p.first;
928 const NumType & val = p.second;
929 set_entry(row, col, val);
930 });
931 return *this;
932 }
933
941 {
942 static_assert(std::is_same_v<Trow, Tcol>,
943 "Row domain is not equal to column domain");
944
946 rdomain_ptr->for_each([&i](const Trow & row)
947 {
948 i.set_entry(row, row, 1);
949 });
950 return i;
951 }
952
960 {
961 ah_domain_error_if(rdomain_ptr != m.rdomain_ptr or cdomain_ptr != m.cdomain_ptr)
962 << "Matrix addition domain mismatch";
963 m.entries.for_each([this](const Pair & p)
964 {
965 const Trow & row = p.first.first;
966 const Tcol & col = p.first.second;
967 const RCPair rcp = RCPair(row, col);
968 auto *ptr = entries.search(rcp);
969 if (ptr == nullptr)
970 entries.insert(rcp, p.second);
971 else
972 ptr->second += p.second;
973 });
974 return *this;
975 }
976
978 Matrix operator +(const Matrix & m) const
980 {
981 Matrix ret_val = *this;
982 ret_val += m;
983 return ret_val;
984 }
985
993 {
994 ah_domain_error_if(rdomain_ptr != m.rdomain_ptr or cdomain_ptr != m.cdomain_ptr)
995 << "Matrix subtraction domain mismatch";
996 m.entries.for_each([this](const Pair & p)
997 {
998 const Trow & row = p.first.first;
999 const Tcol & col = p.first.second;
1000 const RCPair rcp = RCPair(row, col);
1001 auto *ptr = entries.search(rcp);
1002 if (ptr == nullptr)
1003 entries.insert(rcp, -p.second);
1004 else
1005 ptr->second -= p.second;
1006 });
1007 return *this;
1008 }
1009
1011 Matrix operator -(const Matrix & m) const
1013 {
1014 Matrix ret_val = *this;
1015 ret_val -= m;
1016 return ret_val;
1017 }
1018
1023 Matrix &mult_by_scalar(const NumType & scalar)
1025 {
1026 entries.for_each([&scalar](const Pair & p)
1027 {
1028 NumType & val = const_cast<Pair &>(p).second;
1029 val *= scalar;
1030 });
1031 return *this;
1032 }
1033
1041 template <typename T2row, typename T2col>
1045 {
1047 Matrix<Trow, T2col, NumType> ret_val(rdomain_ptr, m.get_col_domain_ptr());
1048 rdomain_ptr->
1049 for_each([this, &m, &ret_val](const Trow & row)
1050 {
1052 });
1053 return ret_val;
1054 }
1055
1063 template <typename T2row, typename T2col>
1067 {
1069 Matrix<Trow, T2col, NumType> ret_val(rdomain_ptr, m.get_col_domain_ptr());
1070 m.get_col_domain().
1071 for_each([this, &m, &ret_val](const T2col & col)
1072 {
1073 ret_val.set_vector_as_col(col,
1074 *this * m.get_col_vector(col));
1075 });
1076 return ret_val;
1077 }
1078
1080 void print() const
1081 requires AlStreamable<Trow> and AlStreamable<Tcol> and AlStreamable<NumType>
1082 {
1083 std::cout << "Non zero entries = " << '\n';
1084 entries.for_each([](const Pair & p)
1085 {
1086 std::cout << "(" << Aleph::to_str(p.first.first) << ","
1087 << Aleph::to_str(p.first.second) << ") : "
1088 << Aleph::to_str(p.second) << '\n';
1089 });
1090 std::cout << '\n';
1091 }
1092
1094 [[nodiscard]] std::string to_str() const
1095 requires AlOrderedDomainKey<Trow> and AlOrderedDomainKey<Tcol> and
1096 AlStreamable<Trow> and AlStreamable<Tcol> and AlStreamable<NumType>
1097 {
1098 typedef std::pair<std::string, std::string> StrPair;
1100 // list of longest strings for each column
1101 const DynList<std::string> collens = cols.
1102 template maps<std::string>([](const ColVector & vec)
1103 {
1104 return vec.to_list().
1105 template foldl<std::string>
1106 ("", [](const std::string & s, const NumType & val)
1107 {
1108 std::string val_str = Aleph::to_str(val);
1109 return val_str.size() > s.size() ? val_str : s;
1110 });
1111 });
1112
1113 // The labels in the order of the keys, which is that of the values
1114 const DynList<std::string> col_labels =
1115 cdomain_ptr->keys().template maps<std::string>([](const Tcol & col)
1116 {
1117 return Aleph::to_str(col);
1118 });
1119
1120 DynList<std::string> longers = zip(collens, col_labels).
1121 template maps<std::string>([](const StrPair & p)
1122 {
1123 return p.first.size() > p.second.size() ?
1124 p.first :
1125 p.second;
1126 });
1127
1128 DynList<std::string> row_labels =
1129 rdomain_ptr->keys().template maps<std::string>([](const Trow & row)
1130 {
1131 return Aleph::to_str(row);
1132 });
1133
1134 const std::string longer_row_label = row_labels.template foldl<std::string>
1135 (std::string(), [](const std::string & s,
1136 const std::string & row_label)
1137 {
1138 return row_label.size() > s.size() ? row_label : s;
1139 });
1140
1141 size_t longer_row_label_sz = longer_row_label.size();
1142
1143 std::string ret_val = std::string(longer_row_label_sz, ' ') + " |";
1144 ret_val = zip(col_labels, longers).template foldl<std::string>
1145 (ret_val, [](const std::string & s, const StrPair & p)
1146 {
1147 const size_t fsz = p.first.size();
1148 const size_t ssz = p.second.size();
1149 return s + std::string((fsz > ssz ? fsz - ssz : ssz - fsz) + 1, ' ') + p.first;
1150 });
1151
1152 ret_val += "\n" + std::string(ret_val.size(), '-');
1153
1154 zip(row_labels, row_domain_list()).for_each
1155 ([this, &ret_val, &longers, &longer_row_label_sz]
1156 (const std::pair<std::string, Trow> & p)
1157 {
1158 const std::string & label = p.first;
1159 const Trow & row = p.second;
1160
1161 ret_val += "\n" +
1162 std::string(longer_row_label_sz - label.size(), ' ') + label + " |";
1163 ret_val =
1164 zip(get_row_as_list(row), longers).template foldl<std::string>
1165 (ret_val, [](const std::string & s,
1166 const std::pair<NumType, std::string> & q)
1167 {
1168 const std::string val = Aleph::to_str(q.first);
1169 const std::string & len_str = q.second;
1170 assert(len_str.size() - val.size() + 1);
1171 return s + std::string(len_str.size() - val.size() + 1, ' ') + val;
1172 });
1173 });
1174
1175 return ret_val;
1176 }
1177
1179 bool are_equal(const NumType & n1, const NumType & n2) const
1181 {
1182 return is_zero(n1 - n2);
1183 }
1184
1190 bool equal_to(const Matrix & m) const
1192 {
1193 ah_domain_error_if(not (rdomain_ptr == m.rdomain_ptr and cdomain_ptr == m.cdomain_ptr))
1194 << "invalid matrix's domains";
1195 return entries.all([&m, this](const Pair & p)
1196 {
1197 const Trow & row = p.first.first;
1198 const Tcol & col = p.first.second;
1199 return are_equal(m.get_entry(row, col), p.second);
1200 }) and
1201 m.entries.all([this](const Pair & p)
1202 {
1203 const Trow & row = p.first.first;
1204 const Tcol & col = p.first.second;
1205 return are_equal(get_entry(row, col), p.second);
1206 });
1207 }
1208
1210 bool operator ==(const Matrix & m) const
1212 {
1213 return equal_to(m);
1214 }
1215
1217 bool operator !=(const Matrix & m) const
1219 {
1220 return not equal_to(m);
1221 }
1222 };
1223
1225 template <typename Trow, typename Tcol, typename NumType>
1226 requires AlMultiplicativeNumber<NumType>
1227 inline
1230 {
1232 return ret_val.mult_by_scalar(scalar);
1233 }
1234
1236 template <typename Trow, typename Tcol, typename NumType>
1237 requires AlAdditiveNumber<NumType> and AlMultiplicativeNumber<NumType>
1238 inline
1241 {
1242 return m.mult_vector_matrix_linear_comb(vec);
1243 }
1244
1245 template <typename Trow, typename Tcol, typename NumType>
1246 requires AlDomainKey<Trow> and AlDomainKey<Tcol> and AlNumber<NumType>
1248
1250 template <typename Trow, typename Tcol, typename NumType>
1251 requires AlOrderedDomainKey<Trow> and AlOrderedDomainKey<Tcol> and
1252 AlStreamable<Trow> and AlStreamable<Tcol> and AlStreamable<NumType>
1253 inline
1254 std::ostream &operator <<(std::ostream & s, const Matrix<Trow, Tcol, NumType> & m)
1255 {
1256 return s << m.to_str();
1257 }
1258
1267 template <typename Trow, typename Tcol, typename NumType = double>
1268 requires AlMultiplicativeNumber<NumType>
1269 inline
1271 const Vector<Tcol, NumType> & v2)
1272 {
1274
1275 v1.for_each([&ret_val, &v2](const std::pair<Trow, NumType> & p1)
1276 {
1277 v2.for_each([&ret_val, &p1](const std::pair<Tcol, NumType> & p2)
1278 {
1279 ret_val.set_entry(p1.first, p2.first,
1280 p1.second * p2.second);
1281 });
1282 });
1283 return ret_val;
1284 }
1285} // end namespace Aleph
1286
1287# endif // AH_MATRIX_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_range_error_if(C)
Throws std::range_error if condition holds.
Definition ah-errors.H:356
Sparse vector with named elements.
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t size_t col
Definition ca-c-api.h:116
size_t cols
Definition ca-c-api.h:105
Generic domain class based on hash set.
Definition al-domain.H:132
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
auto for_each(Operation &operation) const -> decltype(self())
Apply an operation to each element (read-only).
Sparse matrix with generic row and column domains.
Definition al-matrix.H:70
const NumType & get_epsilon() const noexcept
Return the epsilon value used for zero comparisons.
Definition al-matrix.H:116
const CDomainPtr & get_col_domain_ptr() const noexcept
Return the shared pointer to the column domain.
Definition al-matrix.H:142
CDomainPtr cdomain_ptr
Definition al-matrix.H:89
Matrix(RDomainPtr rdomain, CDomainPtr cdomain, const NumType &e=default_epsilon)
Construct an empty sparse matrix over the given domains (shared_ptr version).
Definition al-matrix.H:149
DynList< ColVector > to_collist() const and AlOrderedDomainKey< Tcol >
Return a list of vectors corresponding to the columns.
Definition al-matrix.H:697
Vector< Trow, NumType > mult_matrix_vector_sparse(const Vector< Tcol, NumType > &vec) const and AlMultiplicativeNumber< NumType >
Matrix-vector multiplication using sparse iteration.
Definition al-matrix.H:780
Matrix(const Matrix &other)
Copy constructor.
Definition al-matrix.H:373
Matrix & operator+=(const Matrix &m)
Add another matrix to this one.
Definition al-matrix.H:958
void validate_domains_for_mult(const Matrix< T2row, T2col, NumType > &m) const
Validate domain compatibility for matrix multiplication.
Definition al-matrix.H:886
Matrix(RDomain &&rdomain, const CDomain &cdomain, std::initializer_list< std::initializer_list< NumType > > l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:277
static Matrix create_by_columns_impl(CDomainPtr cdomain, const DynList< Vector< Trow, NumType > > &cols, const NumType &e)
Definition al-matrix.H:463
Matrix(const RDomain &rdomain, const CDomain &cdomain, const NumType &e=default_epsilon)
Construct an empty sparse matrix over the given domains (reference version).
Definition al-matrix.H:165
Matrix operator-(const Matrix &m) const
Matrix subtraction operator.
Definition al-matrix.H:1011
static Matrix create_by_rows(RDomain &&rdomain, const DynList< Vector< Tcol, NumType > > &rows, const NumType &e=default_epsilon)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:514
const CDomain & get_col_domain() const noexcept
Return the column domain.
Definition al-matrix.H:136
std::string to_str() const and AlOrderedDomainKey< Tcol > and AlStreamable< Trow > and AlStreamable< Tcol > and AlStreamable< NumType >
Convert matrix to a formatted string representation.
Definition al-matrix.H:1094
std::shared_ptr< RDomain > RDomainPtr
Definition al-matrix.H:74
NumType epsilon
Definition al-matrix.H:91
std::shared_ptr< CDomain > CDomainPtr
Definition al-matrix.H:75
Vector< Tcol, NumType > get_row_vector(const Trow &row) const
Given a row, build a vector corresponding to the row.
Definition al-matrix.H:718
bool are_equal(const NumType &n1, const NumType &n2) const
Check if two values are equal within epsilon tolerance.
Definition al-matrix.H:1179
Matrix< Trow, T2col, NumType > matrix_vector_mult(const Matrix< T2row, T2col, NumType > &m) const and AlMultiplicativeNumber< NumType >
Matrix multiplication using matrix times column-vector approach.
Definition al-matrix.H:1065
static std::shared_ptr< D > own(D &&d)
Definition al-matrix.H:109
DynList< Tcol > col_domain_list() const
Return a sorted list of column domain keys.
Definition al-matrix.H:639
Matrix & mult_by_scalar(const NumType &scalar)
Multiply all entries by a scalar (in-place).
Definition al-matrix.H:1023
static Matrix create_by_rows(const RDomain &rdomain, const DynList< Vector< Tcol, NumType > > &rows, const NumType &e=default_epsilon)
Create a matrix from a list of row vectors.
Definition al-matrix.H:504
Matrix(Matrix &&other) noexcept
Move constructor.
Definition al-matrix.H:383
Matrix< Trow, T2col, NumType > vector_matrix_mult(const Matrix< T2row, T2col, NumType > &m) const and AlMultiplicativeNumber< NumType >
Matrix multiplication using row-vector times matrix approach.
Definition al-matrix.H:1043
static Matrix create_by_columns(const CDomain &cdomain, const DynList< Vector< Trow, NumType > > &cols, const NumType &e=default_epsilon)
Create a matrix from a list of column vectors.
Definition al-matrix.H:535
Matrix(const RDomain &rdomain, CDomain &&cdomain, std::initializer_list< std::initializer_list< NumType > > l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:285
static const NumType default_epsilon
Definition al-matrix.H:86
std::pair< RCPair, NumType > Pair
Type alias for entries stored in the hash table: ((row,col), value).
Definition al-matrix.H:130
Vector< Tcol, NumType > mult_vector_matrix_dot_product(const Vector< Trow, NumType > &vec) const and AlMultiplicativeNumber< NumType >
Vector-matrix multiplication using dot products.
Definition al-matrix.H:855
Matrix operator+(const Matrix &m) const
Matrix addition operator.
Definition al-matrix.H:978
Vector< Trow, NumType > operator*(const Vector< Tcol, NumType > &vec) const and AlMultiplicativeNumber< NumType >
Matrix-vector multiplication operator (uses linear combination method).
Definition al-matrix.H:870
bool operator!=(const Matrix &m) const
Inequality operator.
Definition al-matrix.H:1217
NumType get_entry(const Trow &row, const Tcol &col)
Get an entry value (non-const version with lazy cleanup).
Definition al-matrix.H:562
bool equal_to(const Matrix &m) const
Check if this matrix equals another (within epsilon).
Definition al-matrix.H:1190
Matrix(RDomain &&rdomain, CDomain &&cdomain, const DynList< DynList< NumType > > &l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
Construct a matrix from a list of lists over domains of which one, or both, are temporary: the matrix...
Definition al-matrix.H:349
Matrix(const RDomain &rdomain, CDomain &&cdomain, const DynList< DynList< NumType > > &l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:365
Matrix(RDomainPtr rdomain, CDomainPtr cdomain, std::initializer_list< std::initializer_list< NumType > > l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
Construct a matrix from a 2D initializer list (shared_ptr version).
Definition al-matrix.H:218
static std::shared_ptr< D > borrow(const D &d)
Definition al-matrix.H:102
static Matrix create_by_rows_impl(RDomainPtr rdomain, const DynList< Vector< Tcol, NumType > > &rows, const NumType &e)
Definition al-matrix.H:436
DynList< Trow > row_domain_list() const
Return a sorted list of row domain keys.
Definition al-matrix.H:632
Vector< Trow, NumType > mult_matrix_vector_dot_product(const Vector< Tcol, NumType > &vec) const and AlMultiplicativeNumber< NumType >
Matrix-vector multiplication using dot products.
Definition al-matrix.H:833
Matrix(RDomain &&rdomain, const CDomain &cdomain, const DynList< DynList< NumType > > &l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:357
DynList< NumType > get_row_as_list(const Trow &row) const
Get a row as a list of values (in column order).
Definition al-matrix.H:650
Matrix & operator=(const Matrix &other)
Copy assignment operator.
Definition al-matrix.H:393
Vector< Trow, NumType > get_col_vector(const Tcol &col) const
Given a column, build a vector corresponding to the column.
Definition al-matrix.H:733
bool operator==(const Matrix &m) const
Equality operator (uses equal_to).
Definition al-matrix.H:1210
NumType get_entry(const Trow &row, const Tcol &col) const noexcept
Get an entry value (const version, no cleanup).
Definition al-matrix.H:581
void set_entry(const Trow &row, const Tcol &col, const NumType &val)
Set an entry value.
Definition al-matrix.H:599
Matrix(const RDomain &rdomain, CDomain &&cdomain, const NumType &e=default_epsilon)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:196
Matrix & operator-=(const Matrix &m)
Subtract another matrix from this one.
Definition al-matrix.H:991
Vector< Trow, NumType > mult_matrix_vector_linear_comb(const Vector< Tcol, NumType > &vec) const and AlMultiplicativeNumber< NumType >
return this*vec in terms of linear combinations
Definition al-matrix.H:756
void set_epsilon(const NumType &e)
Set the epsilon value for zero comparisons.
Definition al-matrix.H:122
const RDomain & get_row_domain() const noexcept
Return the row domain.
Definition al-matrix.H:133
Matrix(RDomainPtr rdomain, CDomainPtr cdomain, const DynList< DynList< NumType > > &l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
Construct a matrix from a list of lists (shared_ptr version).
Definition al-matrix.H:299
Matrix identity() const
Create an identity matrix (only for square matrices).
Definition al-matrix.H:940
DynList< NumType > get_col_as_list(const Tcol &col) const
Get a column as a list of values (in row order).
Definition al-matrix.H:666
bool is_zero(const NumType &val) const noexcept
Definition al-matrix.H:93
Matrix< Tcol, Trow, NumType > transpose() const
Compute the transpose of this matrix.
Definition al-matrix.H:619
Matrix & set_vector_as_col(const Tcol &col, const Vector< Trow, NumType > &vec)
Set a column from a vector.
Definition al-matrix.H:921
Matrix(RDomain &&rdomain, CDomain &&cdomain, std::initializer_list< std::initializer_list< NumType > > l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
Construct a matrix from a 2D initializer list over domains of which one, or both, are temporary: the ...
Definition al-matrix.H:269
Matrix(R &&, C &&, Rest &&...)=delete
A matrix needs domains: Matrix(IntRange(n), IntRange(m)), not Matrix(n, m), which would turn the numb...
Matrix(RDomain &&rdomain, const CDomain &cdomain, const NumType &e=default_epsilon)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:188
Matrix(RDomain &&rdomain, CDomain &&cdomain, const NumType &e=default_epsilon)
Construct an empty sparse matrix over domains of which one, or both, are temporary: the matrix keeps ...
Definition al-matrix.H:180
Matrix(const RDomain &rdomain, const CDomain &cdomain, const DynList< DynList< NumType > > &l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
Construct a matrix from a list of lists (reference version).
Definition al-matrix.H:333
void print() const and AlStreamable< Tcol > and AlStreamable< NumType >
Print non-zero entries to stdout.
Definition al-matrix.H:1080
std::pair< Trow, Tcol > RCPair
Definition al-matrix.H:77
RDomainPtr rdomain_ptr
Definition al-matrix.H:88
Matrix(const RDomain &rdomain, const CDomain &cdomain, std::initializer_list< std::initializer_list< NumType > > l, const NumType &e=default_epsilon) and AlOrderedDomainKey< Tcol >
Construct a matrix from a 2D initializer list (reference version).
Definition al-matrix.H:253
Vector< Tcol, NumType > mult_vector_matrix_linear_comb(const Vector< Trow, NumType > &vec) const and AlMultiplicativeNumber< NumType >
return vec*this in terms of linear combinations
Definition al-matrix.H:809
Matrix & set_vector_as_row(const Trow &row, const Vector< Tcol, NumType > &vec)
Set a row from a vector.
Definition al-matrix.H:902
static Matrix create_by_columns(CDomain &&cdomain, const DynList< Vector< Trow, NumType > > &cols, const NumType &e=default_epsilon)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition al-matrix.H:545
static void check_vectors(const D &domain, const DynList< Vec > &vectors, const char *name)
Definition al-matrix.H:422
DynList< Vector< Tcol, NumType > > to_rowlist() const and AlOrderedDomainKey< Tcol >
Return a list of vectors corresponding to the rows.
Definition al-matrix.H:675
const RDomainPtr & get_row_domain_ptr() const noexcept
Return the shared pointer to the row domain.
Definition al-matrix.H:139
Sparse vector implementation with domain-based indexing.
Definition al-vector.H:155
const Domain & get_domain() const noexcept
Get the domain over which this vector is defined.
Definition al-vector.H:205
void set_entry(const T &i, const NumType &value)
Set a vector entry at given index.
Definition al-vector.H:381
DynList< NumType > to_list() const
The values of the vector, in the order of the sorted keys of its domain.
Definition al-vector.H:719
NumType get_entry(const T &i)
Get vector entry at given index (non-const version)
Definition al-vector.H:474
const DomainPtr & get_domain_ptr() const noexcept
Return the shared pointer to the domain.
Definition al-vector.H:208
bool all(Operation &operation) const
Check if all the elements of the container satisfy a condition.
Definition ah-dry.H:1666
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
iterator begin() noexcept
Return an STL-compatible iterator to the first element.
A number that adds and subtracts: what the sums, the differences and the comparisons of vectors and m...
Definition al-vector.H:94
A number that multiplies: what the products by a scalar, and the products of vectors and matrices,...
Definition al-vector.H:108
A key of a domain that < orders: what AlDomain::keys(), and the members that take the keys in their o...
Definition al-domain.H:98
A value that << writes to a stream: what the members that print keys or numbers need.
Definition al-domain.H:109
Main namespace for Aleph-w library functions.
ZipIterator< Cs... > zip_it(const Cs &...cs)
Alias for get_zip_it.
Definition ah-zip.H:359
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zip(const Container1 &a, const Container2 &b)
Zip two containers into a list of pairs.
size_t pair_snd_hash_ptr_fct(const std::pair< K1, K2 > &p) noexcept
Definition hash-fct.H:1203
and
Check uniqueness with explicit hash + equality functors.
Matrix< Trow, Tcol, NumType > outer_product(const Vector< Trow, NumType > &v1, const Vector< Tcol, NumType > &v2)
Compute the outer product of two vectors.
Definition al-matrix.H:1270
Matrix< Trow, Tcol, NumType > operator*(const NumType &scalar, const Matrix< Trow, Tcol, NumType > &m)
Scalar-matrix multiplication (scalar * matrix).
Definition al-matrix.H:1228
Operation for_each(Itor beg, const Itor &end, Operation op)
Apply an operation to each element in a range.
Definition ahAlgo.H:76
std::string to_str(const double d)
Convert double to a std::string with maximum round-trip precision.
size_t pair_dft_hash_ptr_fct(const std::pair< K1, K2 > &p) noexcept
Definition hash-fct.H:1197
std::ostream & operator<<(std::ostream &osObject, const Field< T > &rightOp)
Definition ahField.H:121
STL namespace.
Aleph::DynList< T > keys() const
See items().
Definition ah-dry.H:2916
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
DynList< int > l