forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Matrix.cpp
1708 lines (1571 loc) · 49.4 KB
/
Matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidKernel/Matrix.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/MersenneTwister.h"
#include "MantidKernel/TimeSeriesProperty.h"
#include "MantidKernel/V3D.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <memory>
#include <sstream>
namespace Mantid::Kernel {
//
#define fabs(x) std::fabs((x)*1.0)
namespace {
//-------------------------------------------------------------------------
// Utility methods and function objects in anonymous namespace
//-------------------------------------------------------------------------
/**
\class PIndex
\author S. Ansell
\date Aug 2005
\version 1.0
\brief Class to fill an index with a progressive count
*/
template <typename T> struct PIndex {
private:
int count; ///< counter
public:
/// Constructor
PIndex() : count(0) {}
/// functional
std::pair<T, int> operator()(const T &A) { return std::pair<T, int>(A, count++); }
};
/**
\class PSep
\author S. Ansell
\date Aug 2005
\version 1.0
\brief Class to access the second object in index pair.
*/
template <typename T> struct PSep {
/// Functional to the second object
int operator()(const std::pair<T, int> &A) { return A.second; }
};
/**
* Function to take a vector and sort the vector
* so as to produce an index. Leaves the vector unchanged.
* @param pVec :: Input vector
* @param Index :: Output vector
*/
template <typename T> void indexSort(const std::vector<T> &pVec, std::vector<int> &Index) {
Index.resize(pVec.size());
std::vector<typename std::pair<T, int>> PartList;
PartList.resize(pVec.size());
transform(pVec.begin(), pVec.end(), PartList.begin(), PIndex<T>());
sort(PartList.begin(), PartList.end());
transform(PartList.begin(), PartList.end(), Index.begin(), PSep<T>());
}
template void indexSort(const std::vector<double> &, std::vector<int> &);
template void indexSort(const std::vector<float> &, std::vector<int> &);
template void indexSort(const std::vector<int> &, std::vector<int> &);
} // namespace
template <typename T> std::vector<T> Matrix<T>::getVector() const {
std::vector<T> rez(m_numRows * m_numColumns);
size_t ic(0);
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
rez[ic] = m_rawData[i][j];
ic++;
}
}
return rez;
}
//
template <typename T>
Matrix<T>::Matrix(const size_t nrow, const size_t ncol, const bool makeIdentity)
: m_numRows(0), m_numColumns(0)
/**
Constructor with pre-set sizes. Matrix is zeroed
@param nrow :: number of rows
@param ncol :: number of columns
@param makeIdentity :: flag for the constructor to return an identity matrix
*/
{
// Note:: m_numRows, m_numColumns zeroed so setMem always works
setMem(nrow, ncol);
zeroMatrix();
if (makeIdentity)
identityMatrix();
}
template <typename T>
Matrix<T>::Matrix(const std::vector<T> &A, const std::vector<T> &B)
: m_numRows(0), m_numColumns(0)
/**
Constructor to take two vectors and multiply them to
construct a matrix. (assuming that we have columns x row
vector.
@param A :: Column vector to multiply
@param B :: Row vector to multiply
*/
{
// Note:: m_numRows,m_numColumns zeroed so setMem always works
setMem(A.size(), B.size());
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = A[i] * B[j];
}
}
}
//
template <typename T> Matrix<T>::Matrix(const std::vector<T> &data) : m_numRows(0), m_numColumns(0) {
size_t numElements = data.size();
auto numRows = static_cast<size_t>(sqrt(double(numElements)));
size_t numRowsSquare = numRows * numRows;
if (numElements != numRowsSquare) {
throw(std::invalid_argument("number of elements in input vector have to be square of some value"));
}
setMem(numRows, numRows);
size_t ic(0);
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = data[ic];
ic++;
}
}
}
template <typename T>
Matrix<T>::Matrix(const std::vector<T> &data, const size_t nrow, const size_t ncol) : m_numRows(0), m_numColumns(0) {
size_t numel = data.size();
size_t test = nrow * ncol;
if (test != numel) {
throw(std::invalid_argument("number of elements in input vector have is "
"incompatible with the number of rows and "
"columns"));
}
setMem(nrow, ncol);
size_t ic(0);
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = data[ic];
ic++;
}
}
}
template <typename T>
Matrix<T>::Matrix(const Matrix<T> &A, const size_t nrow, const size_t ncol)
: m_numRows(A.m_numRows - 1), m_numColumns(A.m_numColumns - 1)
/**
Constructor with for a missing row/column.
@param A :: The input matrix
@param nrow :: number of row to miss
@param ncol :: number of column to miss
*/
{
if (nrow > m_numRows)
throw Kernel::Exception::IndexError(nrow, A.m_numRows, "Matrix::Constructor without row");
if (ncol > m_numColumns)
throw Kernel::Exception::IndexError(ncol, A.m_numColumns, "Matrix::Constructor without col");
setMem(m_numRows, m_numColumns);
size_t iR(0);
for (size_t i = 0; i <= m_numRows; i++) {
if (i != nrow) {
size_t jR(0);
for (size_t j = 0; j <= m_numColumns; j++) {
if (j != ncol) {
m_rawData[iR][jR] = A.m_rawData[i][j];
jR++;
}
}
iR++;
}
}
}
template <typename T>
Matrix<T>::Matrix(const Matrix<T> &A)
: m_numRows(0), m_numColumns(0)
/**
Simple copy constructor
@param A :: Object to copy
*/
{
// Note:: m_numRows,m_numColumns zeroed so setMem always works
setMem(A.m_numRows, A.m_numColumns);
if ((m_numRows * m_numColumns) > 0) {
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = A.m_rawData[i][j];
}
}
}
}
template <typename T>
Matrix<T> &Matrix<T>::operator=(const Matrix<T> &A)
/**
Simple assignment operator
@param A :: Object to copy
@return the copied object
*/
{
if (&A != this) {
setMem(A.m_numRows, A.m_numColumns);
if ((m_numRows * m_numColumns) > 0) {
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = A.m_rawData[i][j];
}
}
}
}
return *this;
}
template <typename T>
Matrix<T>::Matrix(Matrix<T> &&other) noexcept
: m_numRows(other.m_numRows), m_numColumns(other.m_numColumns), m_rawDataAlloc(std::move(other.m_rawDataAlloc)),
m_rawData(std::move(other.m_rawData)) {
other.m_numRows = 0;
other.m_numColumns = 0;
}
template <typename T> Matrix<T> &Matrix<T>::operator=(Matrix<T> &&other) noexcept {
m_numRows = other.m_numRows;
m_numColumns = other.m_numColumns;
m_rawData = std::move(other.m_rawData);
m_rawDataAlloc = std::move(other.m_rawDataAlloc);
other.m_numRows = 0;
other.m_numColumns = 0;
return *this;
}
template <typename T>
Matrix<T> &Matrix<T>::operator+=(const Matrix<T> &A)
/**
Matrix addition THIS + A
If the size is different then 0 is added where appropiate
Matrix A is not expanded.
@param A :: Matrix to add
@return Matrix(this + A)
*/
{
const size_t Xpt((m_numRows > A.m_numRows) ? A.m_numRows : m_numRows);
const size_t Ypt((m_numColumns > A.m_numColumns) ? A.m_numColumns : m_numColumns);
for (size_t i = 0; i < Xpt; i++) {
for (size_t j = 0; j < Ypt; j++) {
m_rawData[i][j] += A.m_rawData[i][j];
}
}
return *this;
}
template <typename T>
Matrix<T> &Matrix<T>::operator-=(const Matrix<T> &A)
/**
Matrix subtractoin THIS - A
If the size is different then 0 is added where appropiate
Matrix A is not expanded.
@param A :: Matrix to add
@return Ma
*/
{
const size_t Xpt((m_numRows > A.m_numRows) ? A.m_numRows : m_numRows);
const size_t Ypt((m_numColumns > A.m_numColumns) ? A.m_numColumns : m_numColumns);
for (size_t i = 0; i < Xpt; i++) {
for (size_t j = 0; j < Ypt; j++) {
m_rawData[i][j] -= A.m_rawData[i][j];
}
}
return *this;
}
template <typename T>
Matrix<T> Matrix<T>::operator+(const Matrix<T> &A) const
/**
Matrix addition THIS + A
If the size is different then 0 is added where appropiate
Matrix A is not expanded.
@param A :: Matrix to add
@return Matrix(this + A)
*/
{
Matrix<T> X(*this);
return X += A;
}
template <typename T>
Matrix<T> Matrix<T>::operator-(const Matrix<T> &A) const
/**
Matrix subtraction THIS - A
If the size is different then 0 is subtracted where
appropiate. This matrix determines the size
@param A :: Matrix to add
@return Matrix(this + A)
*/
{
Matrix<T> X(*this);
return X -= A;
}
template <typename T>
Matrix<T> Matrix<T>::operator*(const Matrix<T> &A) const
/**
Matrix multiplication THIS * A
@param A :: Matrix to multiply by (this->row must == A->columns)
@throw MisMatch<size_t> if there is a size mismatch.
@return Matrix(This * A)
*/
{
if (m_numColumns != A.m_numRows)
throw Kernel::Exception::MisMatch<size_t>(m_numColumns, A.m_numRows, "Matrix::operator*(Matrix)");
Matrix<T> X(m_numRows, A.m_numColumns);
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < A.m_numColumns; j++) {
for (size_t kk = 0; kk < m_numColumns; kk++) {
X.m_rawData[i][j] += m_rawData[i][kk] * A.m_rawData[kk][j];
}
}
}
return X;
}
template <typename T>
std::vector<T> Matrix<T>::operator*(const std::vector<T> &Vec) const
/**
Matrix multiplication THIS * Vec to produce a vec
@param Vec :: size of vector > this->nrows
@throw MisMatch<size_t> if there is a size mismatch.
@return Matrix(This * Vec)
*/
{
if (m_numColumns > Vec.size())
throw Kernel::Exception::MisMatch<size_t>(m_numColumns, Vec.size(), "Matrix::operator*(m_rawDataec)");
std::vector<T> Out(m_numRows);
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
Out[i] += m_rawData[i][j] * Vec[j];
}
}
return Out;
}
/**
Matrix multiplication THIS * Vec to produce a vec
@param in :: size of vector > this->nrows
@param out :: result of Matrix(This * Vec)
@throw MisMatch<size_t> if there is a size mismatch.
*/
template <typename T> void Matrix<T>::multiplyPoint(const std::vector<T> &in, std::vector<T> &out) const {
out.resize(m_numRows);
std::fill(std::begin(out), std::end(out), static_cast<T>(0.0));
if (m_numColumns > in.size())
throw Kernel::Exception::MisMatch<size_t>(m_numColumns, in.size(), "Matrix::multiplyPoint(in,out)");
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
out[i] += m_rawData[i][j] * in[j];
}
}
}
template <typename T>
V3D Matrix<T>::operator*(const V3D &Vx) const
/**
Matrix multiplication THIS * V
@param Vx :: Colunm vector to multiply by
@throw MisMatch<size_t> if there is a size mismatch.
@return Matrix(This * A)
*/
{
if (m_numColumns != 3 || m_numRows > 3)
throw Kernel::Exception::MisMatch<size_t>(m_numColumns, 3, "Matrix::operator*(m_rawData3D)");
V3D v;
for (size_t i = 0; i < m_numRows; ++i) {
v[i] = m_rawData[i][0] * Vx.X() + m_rawData[i][1] * Vx.Y() + m_rawData[i][2] * Vx.Z();
}
return v;
}
template <typename T>
Matrix<T> Matrix<T>::operator*(const T &Value) const
/**
Matrix multiplication THIS * Value
@param Value :: Scalar to multiply by
@return V * (this)
*/
{
Matrix<T> X(*this);
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
X.m_rawData[i][j] *= Value;
}
}
return X;
}
/**
Matrix multiplication THIS *= A
Note that we call operator* to avoid the problem
of changing matrix size.
@param A :: Matrix to multiply by (this->row must == A->columns)
@return This *= A
*/
template <typename T> Matrix<T> &Matrix<T>::operator*=(const Matrix<T> &A) {
if (m_numColumns != A.m_numRows)
throw Kernel::Exception::MisMatch<size_t>(m_numColumns, A.m_numRows, "Matrix*=(Matrix<T>)");
// This construct to avoid the problem of changing size
*this = this->operator*(A);
return *this;
}
template <typename T>
Matrix<T> &Matrix<T>::operator*=(const T &Value)
/**
Matrix multiplication THIS * Value
@param Value :: Scalar to multiply matrix by
@return *this
*/
{
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] *= Value;
}
}
return *this;
}
template <typename T>
Matrix<T> &Matrix<T>::operator/=(const T &Value)
/**
Matrix divishio THIS / Value
@param Value :: Scalar to multiply matrix by
@return *this
*/
{
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] /= Value;
}
}
return *this;
}
template <typename T>
bool Matrix<T>::operator!=(const Matrix<T> &A) const
/**
Element by Element comparison
@param A :: Matrix to check
@return true :: on succees
@return false :: failure
*/
{
return !(this->operator==(A));
}
template <typename T>
bool Matrix<T>::operator==(const Matrix<T> &A) const
/**
Element by element comparison within tolerance.
Tolerance means that the value must be > tolerance
and less than (diff/max)>tolerance
Always returns 0 if the Matrix have different sizes
@param A :: matrix to check.
@return true on success
*/
{
return this->equals(A, 1e-8);
}
//---------------------------------------------------------------------------------------
template <typename T>
bool Matrix<T>::equals(const Matrix<T> &A, const double Tolerance) const
/**
Element by element comparison within tolerance.
Tolerance means that the value must be > tolerance
and less than (diff/max)>tolerance
Always returns 0 if the Matrix have different sizes
@param A :: matrix to check.
@param Tolerance :: tolerance in comparing elements
@return true on success
*/
{
if (&A != this) // this == A == always true
{
if (A.m_numRows != m_numRows || A.m_numColumns != m_numColumns)
return false;
double maxS(0.0);
double maxDiff(0.0); // max di
for (size_t i = 0; i < m_numRows; i++)
for (size_t j = 0; j < m_numColumns; j++) {
const T diff = (m_rawData[i][j] - A.m_rawData[i][j]);
if (std::isnan(static_cast<double>(diff))) {
maxDiff = std::numeric_limits<T>::max();
} else {
if (fabs(diff) > maxDiff)
maxDiff = fabs(diff);
}
if (fabs(m_rawData[i][j]) > maxS)
maxS = fabs(m_rawData[i][j]);
}
if (maxDiff < Tolerance)
return true;
if (maxS > 1.0 && (maxDiff / maxS) < Tolerance)
return true;
return false;
}
// this == this is true
return true;
}
//---------------------------------------------------------------------------------------
/** Element by element comparison of <
Always returns false if the Matrix have different sizes
@param A :: matrix to check.
@return true if this < A
*/
template <typename T> bool Matrix<T>::operator<(const Matrix<T> &A) const {
if (&A == this) // this < A == always false
return false;
if (A.m_numRows != m_numRows || A.m_numColumns != m_numColumns)
return false;
for (size_t i = 0; i < m_numRows; i++)
for (size_t j = 0; j < m_numColumns; j++) {
if (m_rawData[i][j] >= A.m_rawData[i][j])
return false;
}
return true;
}
//---------------------------------------------------------------------------------------
/** Element by element comparison of >=
Always returns false if the Matrix have different sizes
@param A :: matrix to check.
@return true if this >= A
*/
template <typename T> bool Matrix<T>::operator>=(const Matrix<T> &A) const {
if (&A == this)
return true;
if (A.m_numRows != m_numRows || A.m_numColumns != m_numColumns)
return false;
for (size_t i = 0; i < m_numRows; i++)
for (size_t j = 0; j < m_numColumns; j++) {
if (m_rawData[i][j] < A.m_rawData[i][j])
return false;
}
return true;
}
/**
Sets the memory held in matrix
@param a :: number of rows
@param b :: number of columns
*/
template <typename T> void Matrix<T>::setMem(const size_t a, const size_t b) {
if (a == m_numRows && b == m_numColumns && m_rawData != nullptr)
return;
if (a == 0 || b == 0)
return;
m_numRows = a;
m_numColumns = b;
// Allocate memory first - this has to be a flat 1d array masquerading as a 2d
// array so we can expose the memory to Python APIs via numpy which expects
// this
// style of memory layout.
auto allocatedMemory = std::make_unique<T[]>((m_numRows * m_numColumns));
// Next allocate an array of pointers for the rows (X). This partitions
// the 1D array into a 2D array for callers.
auto rowPtrs = std::make_unique<T *[]>(m_numRows);
for (size_t i = 0; i < m_numRows; i++) {
// Calculate offsets into the allocated memory array (Y)
rowPtrs[i] = &allocatedMemory[i * m_numColumns];
}
m_rawDataAlloc = std::move(allocatedMemory);
m_rawData = std::move(rowPtrs);
}
/**
Swap rows I and J
@param RowI :: row I to swap
@param RowJ :: row J to swap
*/
template <typename T> void Matrix<T>::swapRows(const size_t RowI, const size_t RowJ) {
if ((m_numRows * m_numColumns > 0) && RowI < m_numRows && RowJ < m_numRows && RowI != RowJ) {
for (size_t k = 0; k < m_numColumns; k++) {
T tmp = m_rawData[RowI][k];
m_rawData[RowI][k] = m_rawData[RowJ][k];
m_rawData[RowJ][k] = tmp;
}
}
}
/**
Swap columns I and J
@param colI :: col I to swap
@param colJ :: col J to swap
*/
template <typename T> void Matrix<T>::swapCols(const size_t colI, const size_t colJ) {
if ((m_numRows * m_numColumns) > 0 && colI < m_numColumns && colJ < m_numColumns && colI != colJ) {
for (size_t k = 0; k < m_numRows; k++) {
T tmp = m_rawData[k][colI];
m_rawData[k][colI] = m_rawData[k][colJ];
m_rawData[k][colJ] = tmp;
}
}
}
template <typename T>
void Matrix<T>::zeroMatrix()
/**
Zeros all elements of the matrix
*/
{
if ((m_numRows * m_numColumns) > 0) {
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = static_cast<T>(0);
}
}
}
}
template <typename T>
void Matrix<T>::identityMatrix()
/**
Makes the matrix an idenity matrix.
Zeros all the terms outside of the square
*/
{
if ((m_numRows * m_numColumns) > 0) {
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
m_rawData[i][j] = static_cast<T>(j == i);
}
}
}
}
template <typename T> void Matrix<T>::setColumn(const size_t nCol, const std::vector<T> &newCol) {
if (nCol >= this->m_numColumns) {
throw(std::invalid_argument("nCol requested> nCol availible"));
}
size_t m_numRowsM = newCol.size();
if (m_numRows < m_numRowsM)
m_numRowsM = m_numRows;
for (size_t i = 0; i < m_numRowsM; i++) {
m_rawData[i][nCol] = newCol[i];
}
}
template <typename T> void Matrix<T>::setRow(const size_t nRow, const std::vector<T> &newRow) {
if (nRow >= this->m_numRows) {
throw(std::invalid_argument("nRow requested> nRow availible"));
}
size_t m_numColumnsM = newRow.size();
if (m_numColumns < m_numColumnsM)
m_numColumnsM = m_numColumns;
for (size_t j = 0; j < m_numColumnsM; j++) {
m_rawData[nRow][j] = newRow[j];
}
}
template <typename T>
void Matrix<T>::rotate(const double tau, const double s, const int i, const int j, const int k, const int m)
/**
Applies a rotation to a particular point of tan(theta)=tau.
Note that you need both sin(theta) and tan(theta) because of
sign preservation.
@param tau :: tan(theta)
@param s :: sin(theta)
@param i :: first index (xpos)
@param j :: first index (ypos)
@param k :: second index (xpos)
@param m :: second index (ypos)
*/
{
const T gg = m_rawData[i][j];
const T hh = m_rawData[k][m];
m_rawData[i][j] = static_cast<T>(gg - s * (hh + gg * tau));
m_rawData[k][m] = static_cast<T>(hh + s * (gg - hh * tau));
}
template <typename T>
Matrix<T> Matrix<T>::preMultiplyByDiagonal(const std::vector<T> &Dvec) const
/**
Creates a diagonal matrix D from the given vector Dvec and
PRE-multiplies the matrix by it (i.e. D * M).
@param Dvec :: diagonal matrix (just centre points)
@return D*this
*/
{
if (Dvec.size() != m_numRows) {
std::ostringstream cx;
cx << "Matrix::preMultiplyByDiagonal Size: " << Dvec.size() << " " << m_numRows << " " << m_numColumns;
throw std::runtime_error(cx.str());
}
Matrix<T> X(Dvec.size(), m_numColumns);
for (size_t i = 0; i < Dvec.size(); i++) {
for (size_t j = 0; j < m_numColumns; j++) {
X.m_rawData[i][j] = Dvec[i] * m_rawData[i][j];
}
}
return X;
}
template <typename T>
Matrix<T> Matrix<T>::postMultiplyByDiagonal(const std::vector<T> &Dvec) const
/**
Creates a diagonal matrix D from the given vector Dvec and
POST-multiplies the matrix by it (i.e. M * D).
@param Dvec :: diagonal matrix (just centre points)
@return this*D
*/
{
if (Dvec.size() != m_numColumns) {
std::ostringstream cx;
cx << "Error Matrix::bDiaognal size:: " << Dvec.size() << " " << m_numRows << " " << m_numColumns;
throw std::runtime_error(cx.str());
}
Matrix<T> X(m_numRows, Dvec.size());
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < Dvec.size(); j++) {
X.m_rawData[i][j] = Dvec[j] * m_rawData[i][j];
}
}
return X;
}
template <typename T>
Matrix<T> Matrix<T>::Tprime() const
/**
Transpose the matrix :
Has transpose for a square matrix case.
@return M^T
*/
{
if ((m_numRows * m_numColumns) == 0)
return *this;
if (m_numRows == m_numColumns) // inplace transpose
{
Matrix<T> MT(*this);
MT.Transpose();
return MT;
}
// irregular matrix
Matrix<T> MT(m_numColumns, m_numRows);
for (size_t i = 0; i < m_numRows; i++)
for (size_t j = 0; j < m_numColumns; j++)
MT.m_rawData[j][i] = m_rawData[i][j];
return MT;
}
template <typename T>
Matrix<T> &Matrix<T>::Transpose()
/**
Transpose the matrix :
Has a in place transpose for a square matrix case.
@return this^T
*/
{
if ((m_numRows * m_numColumns) == 0)
return *this;
if (m_numRows == m_numColumns) // in place transpose
{
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = i + 1; j < m_numColumns; j++) {
std::swap(m_rawData[i][j], m_rawData[j][i]);
}
}
return *this;
}
// irregular matrix
// get some memory
auto allocatedMemory = std::make_unique<T[]>((m_numRows * m_numColumns));
auto transposePtrs = std::make_unique<T *[]>(m_numRows);
for (size_t i = 0; i < m_numColumns; i++) {
// Notice how this partitions using Rows (X) instead of Cols(Y)
transposePtrs[i] = &allocatedMemory[i * m_numRows];
}
for (size_t i = 0; i < m_numRows; i++) {
for (size_t j = 0; j < m_numColumns; j++) {
transposePtrs[j][i] = m_rawData[i][j];
}
}
// remove old memory
std::swap(m_numRows, m_numColumns);
m_rawDataAlloc = std::move(allocatedMemory);
m_rawData = std::move(transposePtrs);
return *this;
}
template <typename T>
void Matrix<T>::GaussJordan(Matrix<T> &B)
/**
Invert this matrix in place using Gauss-Jordan elimination.
Matrix will be replaced by its inverse.
@param B :: [input, output] Must have same dimensions as A. Returned as
identity matrix. (?)
@throw std::invalid_argument on input error
@throw std::runtime_error if singular
*/
{
// check for input errors
if (m_numRows != m_numColumns || B.m_numRows != m_numRows) {
throw std::invalid_argument("Matrix not square, or sizes do not match");
}
// pivoted rows
std::vector<int> pivoted(m_numRows);
fill(pivoted.begin(), pivoted.end(), 0);
std::vector<int> indxcol(m_numRows); // Column index
std::vector<int> indxrow(m_numRows); // row index
size_t irow(0), icol(0);
for (size_t i = 0; i < m_numRows; i++) {
// Get Biggest non-pivoted item
double bigItem = 0.0; // get point to pivot over
for (size_t j = 0; j < m_numRows; j++) {
if (pivoted[j] != 1) // check only non-pivots
{
for (size_t k = 0; k < m_numRows; k++) {
if (!pivoted[k]) {
if (fabs(m_rawData[j][k]) >= bigItem) {
bigItem = fabs(m_rawData[j][k]);
irow = j;
icol = k;
}
}
}
}
}
pivoted[icol]++;
// Swap in row/col to make a diagonal item
if (irow != icol) {
swapRows(irow, icol);
B.swapRows(irow, icol);
}
indxrow[i] = static_cast<int>(irow);
indxcol[i] = static_cast<int>(icol);
if (m_rawData[icol][icol] == 0.0) {
throw std::runtime_error("Error doing G-J elem on a singular matrix");
}
const T pivDiv = T(1.0) / m_rawData[icol][icol];
m_rawData[icol][icol] = 1;
for (size_t l = 0; l < m_numRows; l++) {
m_rawData[icol][l] *= pivDiv;
}
for (size_t l = 0; l < B.m_numColumns; l++) {
B.m_rawData[icol][l] *= pivDiv;
}
for (size_t ll = 0; ll < m_numRows; ll++) {
if (ll != icol) {
const T div_num = m_rawData[ll][icol];
m_rawData[ll][icol] = 0.0;
for (size_t l = 0; l < m_numRows; l++) {
m_rawData[ll][l] -= m_rawData[icol][l] * div_num;
}
for (size_t l = 0; l < B.m_numColumns; l++) {
B.m_rawData[ll][l] -= B.m_rawData[icol][l] * div_num;
}
}
}
}
// Un-roll interchanges
if (m_numRows > 0) {
for (int l = static_cast<int>(m_numRows) - 1; l >= 0; l--) {
if (indxrow[l] != indxcol[l]) {
swapCols(indxrow[l], indxcol[l]);
}
}
}
}
template <typename T>
T Matrix<T>::Invert()
/**
If the Matrix is square then invert the matrix
using LU decomposition
@return Determinant (0 if the matrix is singular)
*/
{
if (m_numRows != m_numColumns && m_numRows < 1)
return 0;
if (m_numRows == 1) {
T det = m_rawData[0][0];
if (m_rawData[0][0] != static_cast<T>(0.))
m_rawData[0][0] = static_cast<T>(1.) / m_rawData[0][0];
return det;
}
std::vector<int> indx(m_numRows); // Set in lubcmp
std::vector<double> col(m_numRows);
int determinant = 0;
Matrix<T> Lcomp(*this);
Lcomp.lubcmp(indx.data(), determinant);
auto det = static_cast<double>(determinant);
for (size_t j = 0; j < m_numRows; j++)
det *= Lcomp.m_rawData[j][j];
for (size_t j = 0; j < m_numRows; j++) {
for (size_t i = 0; i < m_numRows; i++)
col[i] = 0.0;
col[j] = 1.0;
Lcomp.lubksb(indx.data(), col.data());
for (size_t i = 0; i < m_numRows; i++)
m_rawData[i][j] = static_cast<T>(col[i]);
}
return static_cast<T>(det);
}
template <typename T>
void Matrix<T>::invertTridiagonal()
/**
Check it's a square tridiagonal matrix with all diagonal elements equal and if
yes invert the matrix using analytic formula. If not then use standard Invert
*/
{
bool regular = true;
if ((numRows() > 1) && (numCols() > 1)) {
if (numRows() == numCols()) {
std::vector<T> diagonal = {m_rawData[0][0], m_rawData[1][0]};
for (size_t i = 1; i < numRows() && regular; i++) {
for (size_t j = 1; i < numCols() && regular; i++) {
size_t diff = std::abs(static_cast<int>(i - j));
if (diff < 2) {
if (std::abs(diagonal[diff] - m_rawData[i][j]) > std::numeric_limits<double>::epsilon()) {
regular = false;
}
} else if (m_rawData[i][j] != 0) {
throw std::runtime_error("Matrix is not tridiagonal");
}
}
}
} else {
regular = false;
}
}
if (regular) {
// use analytic expression as described in G Y Hu and R F O'Connell (1996)
T scalefactor = numRows() > 1 ? m_rawData[1][0] : 1;
*this /= scalefactor;
long double D = m_rawData[0][0];
long double k = static_cast<long double>(numRows());
if ((std::abs(D) >= 2.0) && ((k * std::acosh(D / 2.0)) > std::acosh(std::numeric_limits<long double>::max()))) {
*this *= scalefactor;
Invert();
return;
}