-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsparseEigen.cpp
More file actions
2196 lines (1806 loc) · 91.5 KB
/
sparseEigen.cpp
File metadata and controls
2196 lines (1806 loc) · 91.5 KB
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
// Check if TBB is available
#ifdef __TBB_parallel_for_H
#define EXECUTION_AVAILABLE 1
#else
#define EXECUTION_AVAILABLE 0
#endif
#if EXECUTION_AVAILABLE
#include <execution>
#else
#include <algorithm>
#endif
#include <chrono>
#include <array>
#include <numeric>
#include "class_handle.hpp"
#include "sparseEigen.hpp"
//// Construct & Delete ////
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen()
{
this->eigSpMatrix = std::make_shared<spMat_t>();
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(const sparseEigen& copy) :
eigSpMatrix(std::make_shared<spMat_t>(*copy.eigSpMatrix)),
transposed(copy.transposed)
{}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(sparseEigen& copy)
{
this->eigSpMatrix = copy.eigSpMatrix;
this->transposed = copy.transposed;
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(std::shared_ptr<spMat_t> eigSpMatrix_)
{
this->eigSpMatrix = eigSpMatrix_;
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(const mxArray *inputMatrix)
{
if (!inputMatrix)
{
throw(MexException("sparseEigen:invalidInputType","Matrix to construct from invalid!"));
}
if (mxIsSparse(inputMatrix) && mxIsDouble(inputMatrix)) //I think there's also sparse logicals
{
mwIndex *ir, *jc; // ir: row indec, jc: encode row index and values in pr per coloumn
mxDouble *pr; //value pointer
// Get the starting pointer of all three data arrays.
pr = mxGetPr(inputMatrix); // row index array
ir = mxGetIr(inputMatrix); // row index array
jc = mxGetJc(inputMatrix); // column encrypt array
mwSize nCols = mxGetN(inputMatrix); // number of columns
mwSize nRows = mxGetM(inputMatrix); // number of rows
// nnz = mxGetNzmax(prhs[0]); // number of possible non zero elements
mwSize nnz = jc[nCols]; // number of non zero elements currently stored inside the sparse matrix
//Create the Eigen Sparse Matrix
try {
/*
//For some reason manual copying creates issues with m_size in CompressedStorage
//Maybe this would work with calling conservativeResize afterwards
//this->eigSpMatrix = std::shared_ptr<spMat_t>(new spMat_t(nRows,nCols));
this->eigSpMatrix = std::make_shared<spMat_t>(nRows,nCols);
//this->eigSpMatrix->makeCompressed();
this->eigSpMatrix->reserve(nnz);
std::transform(std::execution::par_unseq, pr, pr+nnz, this->eigSpMatrix->valuePtr(), [](double d) -> value_t { return static_cast<value_t>(d);});
std::transform(std::execution::par_unseq, ir, ir+nnz, this->eigSpMatrix->innerIndexPtr(), [](mwIndex i) -> index_t { return static_cast<index_t>(i);});
std::transform(std::execution::par_unseq, jc, jc+(nCols+1), this->eigSpMatrix->outerIndexPtr(), [](mwIndex i) -> index_t { return static_cast<index_t>(i);});
this->eigSpMatrix->makeCompressed();
*/
Eigen::Map<Eigen::SparseMatrix<mxDouble,Eigen::ColMajor,mwIndex>> matlabSparse(nRows,nCols,nnz,jc,ir,pr);
this->eigSpMatrix = std::make_shared<spMat_t>(matlabSparse.cast<value_t>());
}
catch (const std::exception& e) {
std::string msg = std::string("Eigen Map could not be constructed from sparse matrix! Caught exception ") + e.what();
throw(MexException("sparseEigen:errorOnConstruct",msg));
}
catch (...)
{
throw(MexException("sparseEigen:errorOnConstruct","Eigen Map could not be constructed from sparse matrix!"));
}
}
else if (mxIsSingle(inputMatrix)) // full matrix
{
mwSize nCols = mxGetN(inputMatrix); // number of columns
mwSize nRows = mxGetM(inputMatrix); // number of rows
mxSingle *singleData = mxGetSingles(inputMatrix);
Eigen::Map<mxSingleAsMatrix_t> singleDataMap(singleData,nRows,nCols);
this->eigSpMatrix = std::make_shared<spMat_t>(singleDataMap.cast<value_t>().sparseView());
}
else if (mxIsDouble(inputMatrix))
{
mwSize nCols = mxGetN(inputMatrix); // number of columns
mwSize nRows = mxGetM(inputMatrix); // number of rows
mxDouble *doubleData = mxGetDoubles(inputMatrix);
Eigen::Map<mxDoubleAsMatrix_t> doubleDataMap(doubleData,nRows,nCols);
this->eigSpMatrix = std::make_shared<spMat_t>(doubleDataMap.cast<value_t>().sparseView());
}
else
{
throw(MexException("sparseEigen:invalidInputType","Invalid Input Argument!"));
}
this->eigSpMatrix->makeCompressed(); // Not sure if necessary
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(const mxArray *m_, const mxArray *n_)
{
//Argument checks
if (!mxIsScalar(m_) || !mxIsScalar(n_))
throw(MexException("sparseEigen:invalidInputType","Row and Column Number must both be scalars!"));
if ((!mxIsNumeric(m_) && !mxIsChar(m_) ) || !mxIsNumeric(n_) && !mxIsChar(n_))
throw(MexException("sparseEigen:invalidInputType","Row and/or Column Number input is invalid!"));
//Note that this implicitly casts to double and thus also allows other data types from matlab
mwIndex m = (mwIndex) mxGetScalar(m_);
mwIndex n = (mwIndex) mxGetScalar(n_);
this->eigSpMatrix = std::make_shared<spMat_t>(m,n);
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(const mxArray* i_, const mxArray* j_, const mxArray* v_)
{
//We only obtain the size here before calling the construction with given sizes
mwIndex maxI = 0;
mwIndex maxJ = 0;
UntypedMxDataAccessor<mwIndex> i(i_);
UntypedMxDataAccessor<mwIndex> j(j_);
#pragma omp parallel sections
{
#pragma omp section
{
for (size_t n=0; n < i.size(); n++)
maxI = std::max<mwIndex>(maxI,i[n]);
}
#pragma omp section
{
for (size_t n=0; n < j.size(); n++)
maxJ = std::max<mwIndex>(maxJ,j[n]);
}
}
mxArray* m = mxCreateDoubleScalar((mxDouble) maxI);
mxArray* n = mxCreateDoubleScalar((mxDouble) maxJ);
this->constructFromMatlabTriplets(i_,j_,v_,m,n);
mxDestroyArray(m);
mxDestroyArray(n);
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::sparseEigen(const mxArray* i, const mxArray* j, const mxArray* v, const mxArray* m, const mxArray* n, const mxArray* nz)
{
this->constructFromMatlabTriplets(i,j,v,m,n,nz);
}
template <typename index_t, typename value_t>
void sparseEigen<index_t,value_t>::constructFromMatlabTriplets(const mxArray* i_, const mxArray* j_, const mxArray* v_, const mxArray* m_, const mxArray* n_, const mxArray* nz_)
{
//We fill triplets manually because Eigen would expect them as a Triplet construct, but we have independent mxArrays and would need to copy everything together
UntypedMxDataAccessor<index_t> i(i_);
UntypedMxDataAccessor<index_t> j(j_);
//For now we mimic the SparseDouble behavior of only allowing values of similar type. We could cast, if we want to, as well
if (v_ == nullptr || !mxIsValueType<value_t>(v_))
throw(MexException("sparseEigen:invalidInputType","Values must be of matching data type"));
mwSize numValues = mxGetNumberOfElements(v_); //We can even have matrices as input, so we only care for the number of elements
value_t* v = static_cast<value_t*>(mxGetData(v_));
if ((i.size() != j.size()) || j.size() != numValues)
throw(MexException("sparseEigen:invalidInputType","Different number of elements in input triplet vectors!"));
std::vector<index_t> sortPattern(numValues);
#pragma omp parallel for schedule(static)
for (index_t r = 0; r < numValues; r++)
sortPattern[r] = r;
if (!mxIsScalar(m_) || !mxIsScalar(n_) || !mxIsNumeric(m_) || !mxIsNumeric(n_))
throw(MexException("sparseEigen:invalidInputType","Row and Column numbers must be numeric scalars!"));
index_t m = mxGetScalar(m_);
index_t n = mxGetScalar(n_);
if (m < 0 || n < 0)
throw(MexException("sparseEigen:invalidInputType","Row and Column numbers must be greater or equal to zero!"));
index_t nnz_reserve = numValues;
if (nz_ != nullptr)
{
if(!mxIsScalar(nz_) || !mxIsNumeric(nz_))
throw(MexException("sparseEigen:invalidInputType","Invalid number of nonzeros to reserve"));
nnz_reserve = (index_t) mxGetScalar(nz_);
//Should we throw an error here or just silently adapt?
if (nnz_reserve < numValues)
nnz_reserve = numValues;
}
if (m < 0 || n < 0)
throw(MexException("sparseEigen:invalidInputType","Row and Column numbers must be greater or equal to zero!"));
//Now we obtain the sort pattern of the triplets
//The data accessor is not yet in index base 0!!
//We could use a linear index comparison or we define a double comparison
//We sort by linear index
#if EXECUTION_AVAILABLE
std::stable_sort(std::execution::par,sortPattern.begin(),sortPattern.end(),
#else
std::stable_sort(sortPattern.begin(),sortPattern.end(),
#endif
[&i,&j,&m](index_t i1, index_t i2) {
return ((j[i1]-1)*m + i[i1] - 1) < ((j[i2]-1)*m + i[i2] - 1);
});
this->eigSpMatrix = std::make_shared<spMat_t>(m,n);
this->eigSpMatrix->reserve(nnz_reserve);
//We could also use insertBack here from the low-level Eigen API but since we have our weird ordering, I'll do it manually for now.
this->eigSpMatrix->outerIndexPtr()[0] = 0;
//Can this be parallelized if the indices are sorted as in our case?
//#pragma omp parallel for schedule(static)
for (index_t r = 0; r < numValues; r++)
{
//This is the index to be written
index_t getIx = sortPattern[r];
//Convert to base 0
index_t row = i[getIx] - 1;
index_t col = j[getIx] - 1;
value_t value = v[getIx];
//mexPrintf("Inserting triplet %d at (%d,%d) with value %f;.\n",r,row,col,value);
this->eigSpMatrix->innerIndexPtr()[r] = row;
this->eigSpMatrix->valuePtr()[r] = value;
this->eigSpMatrix->outerIndexPtr()[col+1]++;
}
std::partial_sum(this->eigSpMatrix->outerIndexPtr(),this->eigSpMatrix->outerIndexPtr()+n+1,this->eigSpMatrix->outerIndexPtr());
this->eigSpMatrix->makeCompressed();
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>::~sparseEigen()
{
#ifndef NDEBUG
mexPrintf("Calling destructor - %d Eigen sparse matrix instances still exist!\n",this->eigSpMatrix.use_count() - 1);
#endif
}
//// Getters & Setters ////
template <typename index_t, typename value_t>
mwSize sparseEigen<index_t,value_t>::getNnz() const {
return this->eigSpMatrix->nonZeros();
}
template <typename index_t, typename value_t>
mwSize sparseEigen<index_t,value_t>::getCols() const {
if (this->transposed)
return this->eigSpMatrix->rows();
else
return this->eigSpMatrix->cols();
}
template <typename index_t, typename value_t>
mwSize sparseEigen<index_t,value_t>::getRows() const {
if (this->transposed)
return this->eigSpMatrix->cols();
else
return this->eigSpMatrix->rows();
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::size() const {
mxArray* szArray = mxCreateDoubleMatrix(1,2,mxREAL);
double* pr = mxGetDoubles(szArray);
pr[0] = static_cast<double>(this->getRows());
pr[1] = static_cast<double>(this->getCols());
return szArray;
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::nnz() const {
return mxCreateDoubleScalar((double) this->getNnz());
}
template <typename index_t, typename value_t>
bool sparseEigen<index_t,value_t>::isScalar() const {
return (this->getCols() == 1) && (this->getRows() == 1);
}
template <typename index_t, typename value_t>
bool sparseEigen<index_t,value_t>::isSquare() const {
return this->getCols() == this->getRows();
}
//// Private Helpers ////
template <typename index_t, typename value_t>
void sparseEigen<index_t,value_t>::reportSolverInfo(Eigen::ComputationInfo& info) const
{
//if (info == Eigen::ComputationInfo::Success)
// mexWarnMsgTxt("Solved!!!");
if (info == Eigen::ComputationInfo::NumericalIssue)
mexWarnMsgIdAndTxt("sparseEigen:solver:numericalIssue","Matrix is close to singular or badly scaled. Results may be inaccurate.");
if (info == Eigen::ComputationInfo::InvalidInput)
throw(MexException("sparseEigen:solver:wrongInput","Sparse solver could not interpret input!"));
if (info == Eigen::ComputationInfo::NoConvergence)
mexWarnMsgIdAndTxt("sparseEigen:solver:numericalIssue","Sparse solver could not interpret input!");
}
//// Indexing ////
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::rowColIndexing(const mxArray * const rowIndex, const mxArray * const colIndex) const
{
//TODO: Transpose Implementation
sparseEigen* indexedSubMatrix = nullptr;
//Check if we are indexing a block
bool consecutiveRows = false;
bool consecutiveCols = false;
sparseEigen<index_t,value_t>::Matlab2EigenIndexListConverter rowIndices4Eigen(rowIndex);
sparseEigen<index_t,value_t>::Matlab2EigenIndexListConverter colIndices4Eigen(colIndex);
const mxDouble * const rowIndexData = rowIndices4Eigen.data();
const mxDouble * const colIndexData = colIndices4Eigen.data();
const index_t nRowIndices = rowIndices4Eigen.size();
const index_t nColIndices = colIndices4Eigen.size();
#pragma omp parallel sections
{
#pragma omp section
consecutiveRows = this->isConsecutiveArray(rowIndexData,nRowIndices);
#pragma omp section
consecutiveCols = this->isConsecutiveArray(colIndexData,nColIndices);
}
bool blockIndexing = consecutiveRows & consecutiveCols;
//Debug output
#ifndef NDEBUG
mexPrintf("Block indexing detected? %s\n",blockIndexing ? "true" : "false");
#endif
if (blockIndexing)
{
if(this->transposed)
{
//mexErrMsgTxt("Transpose not implemented!");
throw(MexException("sparseEigen:implementationMissing","Transpose not implemented!"));
}
else{
index_t startRow = rowIndices4Eigen[0];
index_t rows = nRowIndices;
index_t startCol = colIndices4Eigen[0];
index_t cols = nColIndices;
auto block = this->eigSpMatrix->block(startRow,startCol,rows,cols);
std::shared_ptr<spMat_t> blockSpMat = std::make_shared<spMat_t>(block);
indexedSubMatrix = new sparseEigen(blockSpMat);
}
}
else
{
//Eigen Supports slicing for Dense Matrices Only, so we need to manually slice the matrix
//Indexing by Matrix Multiplication as found here: https://people.eecs.berkeley.edu/~aydin/spgemm_sisc12.pdf
// Matlab equivalent
// [m,n] = size(A);
// R = sparse(1:len(I),I,1,len(I),m);
// Q = sparse(J,1:len(J),1,n,len(J));
// B=R*A*Q;
if(this->transposed)
{
throw(MexException("sparseEigen:implementationMissing","Transpose not implemented!"));
}
else
{
typedef Eigen::Triplet<value_t,index_t> T;
spMat_t R(nRowIndices,this->getRows());
spMat_t Q(this->getCols(),nColIndices);
//Build the R matrix
std::vector<T> tripletListR(nRowIndices);
//tripletListR.reserve(nRowIndices);
#pragma omp parallel for schedule(static)
for (index_t i = 0; i < nRowIndices; i++)
tripletListR[i] = T(i,rowIndices4Eigen[i],1);
R.setFromTriplets(tripletListR.begin(),tripletListR.end()) ;
//Build the Q matrix
std::vector<T> tripletListQ(nColIndices);
//tripletListQ.reserve(nColIndices);
#pragma omp parallel for schedule(static)
for (index_t j = 0; j < nColIndices; j++)
tripletListQ[j] = T(colIndices4Eigen[j],j,1);
Q.setFromTriplets(tripletListQ.begin(),tripletListQ.end());
//Now perform the slicing product
std::shared_ptr<spMat_t> subSpMat = std::make_shared<spMat_t>(nRowIndices,nColIndices);
//subSpMat->makeCompressed();
(*subSpMat) = R*(*this->eigSpMatrix)*Q;
indexedSubMatrix = new sparseEigen(subSpMat);
}
}
return convertPtr2Mat<sparseEigen>(indexedSubMatrix);
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::rowColAssignment(const mxArray * const rowIndex, const mxArray * const colIndex, const mxArray* assignedValues)
{
mwSize nRowIx = mxGetNumberOfElements(rowIndex);
mwSize nColIx = mxGetNumberOfElements(colIndex);
mwSize nValues = mxGetNumberOfElements(assignedValues);
mxClassID mxTypeRowIx = mxGetClassID(rowIndex);
mxClassID mxTypeColIx = mxGetClassID(colIndex);
mxClassID mxTypeValues = mxGetClassID(assignedValues);
bool isScalar = nRowIx == 1 && nColIx == 1 && nValues == 1;
mxArray* returnedSparse = nullptr;
//This might be a sparseEigen matrix, try it out
if (mxTypeValues == mxUINT64_CLASS && isScalar)
{
sparseEigen* newValues = nullptr;
try
{
newValues = convertMat2Ptr<sparseEigen>(assignedValues);
}
catch (MexException& e)
{
std::string id(e.id());
if (id.compare("classHandle:invalidHandle")) //Later we could allow uint64 operations as well, but I advise against this
throw(MexException("sparseEigen:wrongDataType","Assigning uint64 is not supported!"));
else
throw;
}
catch (...)
{
throw;
}
throw(MexException("sparseEigen<index_t,value_t>::implementationMissing","Sparse assignment not yet implemented!"));
return nullptr;
}
if (isScalar)
{
mwSize rowIx = mwSize(mxGetScalar(rowIndex)) - 1;
mwSize colIx = mwSize(mxGetScalar(colIndex)) - 1;
value_t value = value_t(mxGetScalar(assignedValues));
sparseEigen* newMatrixPtr;
//We are assigning into the only instance of the matrix, so lets modify directly
if (this->eigSpMatrix.use_count() == 1)
newMatrixPtr = new sparseEigen(this->eigSpMatrix); //We use the shared_ptr
else
newMatrixPtr = new sparseEigen(std::as_const(*this)); //We create a full copy such that other instance are unaffected
if (newMatrixPtr->transposed)
newMatrixPtr->eigSpMatrix->coeffRef(colIx,rowIx) = value;
else
newMatrixPtr->eigSpMatrix->coeffRef(rowIx,colIx) = value;
newMatrixPtr->eigSpMatrix->makeCompressed();
return convertPtr2Mat<sparseEigen>(newMatrixPtr);
}
//I am not sure about this, because we could also assign the same value to multiple locations?
//if (nRowIx != nColIx || nColIx != nValues)
//throw(MexException("sparseEigen<index_t,value_t>::rowColAssignment:wrongInputSize","Index and value dimension needs to agree!"));
//Check if we are indexing a block
bool consecutiveRows = false;
bool consecutiveCols = false;
sparseEigen<index_t,value_t>::Matlab2EigenIndexListConverter rowIndices4Eigen(rowIndex);
sparseEigen<index_t,value_t>::Matlab2EigenIndexListConverter colIndices4Eigen(colIndex);
const double * const rowIndexData = rowIndices4Eigen.data();
const double * const colIndexData = colIndices4Eigen.data();
const index_t nRowIndices = rowIndices4Eigen.size();
const index_t nColIndices = colIndices4Eigen.size();
#pragma omp parallel sections
{
#pragma omp section
consecutiveRows = this->isConsecutiveArray(rowIndexData,nRowIndices);
#pragma omp section
consecutiveCols = this->isConsecutiveArray(colIndexData,nColIndices);
}
bool blockAssignment = consecutiveRows & consecutiveCols;
//Debug output
#ifndef NDEBUG
mexPrintf("Block assignment detected? %s\n",blockAssignment ? "true" : "false");
#endif
throw(MexException("sparseEigen:implementationMissing","Subscripted assignment has not been implemented yet!"));
}
template <typename index_t, typename value_t>
sparseEigen<index_t,value_t>* sparseEigen<index_t,value_t>::allValues() const
{
index_t numValues = this->getRows()*this->getCols();
index_t nnz = this->getNnz();
std::shared_ptr<spMat_t> subSpMat = std::make_shared<spMat_t>(numValues,1);
subSpMat->reserve(nnz);
//Sanity Check
if (!(this->eigSpMatrix->isCompressed()))
throw(MexException("sparseEigen:invalidMatrixState","The matrix is not compressed! This is unexpected behavior!"));
#if EXECUTION_AVAILABLE
std::copy(std::execution::par_unseq,this->eigSpMatrix->valuePtr(),this->eigSpMatrix->valuePtr() + nnz, subSpMat->valuePtr());
#else
std::copy(this->eigSpMatrix->valuePtr(),this->eigSpMatrix->valuePtr() + nnz, subSpMat->valuePtr());
#endif
subSpMat->outerIndexPtr()[0] = index_t(0);
subSpMat->outerIndexPtr()[1] = nnz;
if (this->transposed)
{
Eigen::Map<spMatTransposed_t> crs_transposed(this->getRows(),this->getCols(),this->getNnz(),this->eigSpMatrix->outerIndexPtr(),this->eigSpMatrix->innerIndexPtr(),this->eigSpMatrix->valuePtr());
index_t count = 0;
//#pragma omp parallel for schedule(dynamic)
for (index_t k = 0; k < crs_transposed.outerSize(); ++k)
for (typename Eigen::Map<spMatTransposed_t>::InnerIterator it(crs_transposed,k); it; ++it)
{
index_t linearIndex = this->toLinearIndex(it.row(),it.col());
subSpMat->innerIndexPtr()[count] = linearIndex;
count++;
}
}
else{
#pragma omp parallel for schedule(dynamic)
for (index_t k = 0; k < this->eigSpMatrix->outerSize(); ++k)
{
index_t nnzInCol = this->eigSpMatrix->outerIndexPtr()[k+1] - this->eigSpMatrix->outerIndexPtr()[k];
index_t offset = this->eigSpMatrix->outerIndexPtr()[k];
index_t count = 0;
for (typename spMat_t::InnerIterator it(*this->eigSpMatrix,k); it; ++it)
{
index_t linearIndex = this->toLinearIndex(it.row(),it.col());
subSpMat->innerIndexPtr()[offset + count] = linearIndex;
count++;
}
}
}
sparseEigen* indexedMatrix = new sparseEigen(subSpMat);
return indexedMatrix;
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::find() const
{
mxArray* findLin = mxCreateDoubleMatrix(this->getNnz(),1,mxREAL);
double* findLinData = mxGetDoubles(findLin);
index_t count = 0;
if (this->transposed)
{
Eigen::Map<spMatTransposed_t> crs_transposed(this->getRows(),this->getCols(),this->getNnz(),this->eigSpMatrix->outerIndexPtr(),this->eigSpMatrix->innerIndexPtr(),this->eigSpMatrix->valuePtr());
for (index_t k = 0; k < crs_transposed.outerSize(); ++k)
for (typename Eigen::Map<spMatTransposed_t>::InnerIterator it(crs_transposed,k); it; ++it)
{
index_t currLinIx = this->toLinearIndex(it.row(),it.col());
findLinData[count] = double(currLinIx) + 1;
count++;
}
if (count != this->getNnz())
throw(MexException("sparseEigen:find:invalidDataStructure","For some reason, we found more or less nonzeros than expected!"));
#if EXECUTION_AVAILABLE
std::sort(std::execution::par_unseq,findLinData,findLinData + count);
#else
std::sort(findLinData,findLinData + count);
#endif
}
else
{
for (index_t k = 0; k < this->eigSpMatrix->outerSize(); ++k)
for (typename spMat_t::InnerIterator it(*this->eigSpMatrix,k); it; ++it)
{
index_t currLinIx = this->toLinearIndex(it.row(),it.col());
findLinData[count] = double(currLinIx) + 1;
count++;
}
if (count != this->getNnz())
throw(MexException("sparseEigen:find:invalidDataStructure","For some reason, we found more or less nonzeros than expected!"));
}
return findLin;
}
template <typename index_t, typename value_t>
void sparseEigen<index_t,value_t>::disp() const
{
if (this->getNnz() == 0)
{
mexPrintf(" All zero sparse: %dx%d\n",this->getRows(),this->getCols());
}
if (this->transposed)
{
Eigen::Map<spMatTransposed_t> crs_transposed(this->getRows(),this->getCols(),this->getNnz(),this->eigSpMatrix->outerIndexPtr(),this->eigSpMatrix->innerIndexPtr(),this->eigSpMatrix->valuePtr());
for (index_t k = 0; k < crs_transposed.outerSize(); ++k)
for (typename Eigen::Map<spMatTransposed_t>::InnerIterator it(crs_transposed,k); it; ++it)
{
mexPrintf("\t(%d,%d)\t\t%g\n",it.row()+1,it.col()+1,it.value());
}
}
else
{
for (index_t k = 0; k < this->eigSpMatrix->outerSize(); ++k)
for (typename spMat_t::InnerIterator it(*this->eigSpMatrix,k); it; ++it)
{
mexPrintf("\t(%d,%d)\t\t%g\n",it.row()+1,it.col()+1,it.value());
}
}
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::linearIndexing(const mxArray* indexList) const
{
//First check if it is indeed an index list or a colon operator
mxClassID ixType = mxGetClassID(indexList);
sparseEigen* result = nullptr;
if (ixType == mxCHAR_CLASS) // We have a colon operator
result = this->allValues();
else if (ixType == mxDOUBLE_CLASS)
{
//mexErrMsgTxt("Only colon indexing supported at the moment!");
//Normal double indexing list
mwSize nDim = mxGetNumberOfDimensions(indexList);
if (nDim > 2)
throw(MexException("sparseEigen:invalidIndex","Indexing list has dimensionality bigger than 2!"));
const mwSize* ixDim = mxGetDimensions(indexList);
index_t numValues;
bool isColumnVector;
if (ixDim[0] == 1)
{
numValues = mxGetN(indexList);
isColumnVector = false;
}
else if (ixDim[1] == 1)
{
numValues = mxGetM(indexList);
isColumnVector = true;
}
else
throw(MexException("sparseEigen:implementationMissing","Only vector index lists are implemented for now!"));
index_t nnz = this->getNnz();
std::shared_ptr<spMat_t> subSpMat;
Matlab2EigenIndexListConverter indexList4Eigen(indexList);
//check first if we have a scalar to avoid expensive copies
if (numValues == 1)
{
index_t linearIndex = indexList4Eigen[0];
index_t rowIx = this->linearIndexToRowIndex(linearIndex);
index_t colIx = this->linearIndexToColIndex(linearIndex);
value_t value;
if (!this->transposed)
value = this->eigSpMatrix->coeff(rowIx,colIx);
else
value = this->eigSpMatrix->coeff(colIx,rowIx);
subSpMat = std::make_shared<spMat_t>(1,1);
if (value > 0.0)
subSpMat->coeffRef(0,0) = value;
isColumnVector = true; //We do not want to set the transpose flag in this case at any times
}
else{
std::vector<index_t> tmpInnerIndex(nnz);
std::array<index_t,2> tmpOuterIndex;
tmpOuterIndex[0] = 0;
tmpOuterIndex[1] = nnz;
if (this->transposed)
{
Eigen::Map<spMatTransposed_t> crs_transposed(this->getRows(),this->getCols(),nnz,this->eigSpMatrix->outerIndexPtr(),this->eigSpMatrix->innerIndexPtr(),this->eigSpMatrix->valuePtr());
index_t count = 0;
//#pragma omp parallel for schedule(dynamic)
for (index_t k = 0; k < crs_transposed.outerSize(); ++k)
for (typename Eigen::Map<spMatTransposed_t>::InnerIterator it(crs_transposed,k); it; ++it)
{
index_t linearIndex = this->toLinearIndex(it.row(),it.col());
tmpInnerIndex[count] = linearIndex;
count++;
}
}
else{
//#pragma omp parallel for schedule(dynamic)
for (index_t k = 0; k < this->eigSpMatrix->outerSize(); ++k)
{
index_t nnzInCol = this->eigSpMatrix->outerIndexPtr()[k+1] - this->eigSpMatrix->outerIndexPtr()[k];
index_t offset = this->eigSpMatrix->outerIndexPtr()[k];
index_t count = 0;
for (typename spMat_t::InnerIterator it(*this->eigSpMatrix,k); it; ++it)
{
index_t linearIndex = this->toLinearIndex(it.row(),it.col());
tmpInnerIndex[offset + count] = linearIndex;
count++;
}
}
}
//typedef Eigen::SparseVector<value_t,Eigen::ColMajor,index_t> spColVec_t;
Eigen::Map<spMat_t> spMatAsVector(this->getRows()*this->getCols(),1,nnz,tmpOuterIndex.data(),tmpInnerIndex.data(),this->eigSpMatrix->valuePtr());
//Check if we have a range
bool isRange = this->isConsecutiveArray(indexList4Eigen.data(),numValues);
if (isRange)
{ //mexPrintf("We have a block!\n");
index_t start = indexList4Eigen[0];
auto block = spMatAsVector.block(start,0,numValues,1);
subSpMat = std::make_shared<spMat_t>(block);
}
else
{
typedef Eigen::Triplet<value_t,index_t> T;
std::vector<T> triplets;
std::vector<index_t> sortPattern(numValues);
#pragma omp parallel for schedule(static)
for (index_t i = 0; i < numValues; i++)
sortPattern[i] = i;
#if EXECUTION_AVAILABLE
std::stable_sort(std::execution::par,sortPattern.begin(),sortPattern.end(),[&indexList4Eigen](index_t i1, index_t i2) {return indexList4Eigen[i1] < indexList4Eigen[i2];});
#else
std::stable_sort(sortPattern.begin(),sortPattern.end(),[&indexList4Eigen](index_t i1, index_t i2) {return indexList4Eigen[i1] < indexList4Eigen[i2];});
#endif
index_t searchIxSpVec = 0;
index_t searchInnerIndex;
//Now perform the search and exploit the sorting of the index string
//We accumulate triplets since it is difficult to know beforehand how much storage we need.
//Alternatively, we could directly fill the column vector sparse storage and then perform a
//sort on the vector afterwards (reusing the sortPattern storage to keep track of the index permutation)
for (index_t i = 0; i < numValues; i++)
{
//There is no more values in the matrix
if (searchIxSpVec >= nnz)
break;
index_t currIx = indexList4Eigen[sortPattern[i]];
searchInnerIndex = spMatAsVector.innerIndexPtr()[searchIxSpVec];
while (searchInnerIndex < currIx)
{
searchIxSpVec++;
searchInnerIndex = spMatAsVector.innerIndexPtr()[searchIxSpVec];
}
if (searchInnerIndex == currIx)
triplets.emplace_back(sortPattern[i],0,spMatAsVector.valuePtr()[searchIxSpVec]);
}
subSpMat = std::make_shared<spMat_t>(numValues,1);
subSpMat->setFromTriplets(triplets.begin(),triplets.end());
//There's two other ways I consider doing this elegantly
//1) Map a Sparse Vector a' over the existing values, create a slicing matrix R (similar to row/colon indexing, we don't need Q) and perform R*a';
// Indexing by Matrix Multiplication as found here: https://people.eecs.berkeley.edu/~aydin/spgemm_sisc12.pdf
//2) Convert the linear index list into subscripts, perform row colon indexing, and then reshape the matrix to a vector (should be less efficient?)
//I tried implementing 1), but it throughs bad_alloc in the matrix product
//Variant 1) - gives bad_alloc in some cases for now
//Note that index lists are actually doubles in matlab, so we cast to actuall indices
//Temporary Sparse Vector
//mexPrintf("We have arbitrary indices!\n");
//Build the R matrix
//spMat_t R(numValues,this->getRows()*this->getCols()); //outerIndexVector may become to large in csc storage
//We explicitly create a csr_matrix here to avoid overflowing the outerIndexVector
/*
Eigen::SparseMatrix<value_t,Eigen::RowMajor,index_t> R(numValues,this->getRows()*this->getCols());
//mexPrintf("%dx%d Matrix initialized!",R.rows(),R.cols());
R.reserve(numValues);
//mexPrintf("Reserved Storage!");
#pragma omp parallel for schedule(static)
for (index_t i = 0; i < numValues; i++)
{
R.valuePtr()[i] = 1;
R.innerIndexPtr()[i] = indexList4Eigen[i];
R.outerIndexPtr()[i] = i;
}
R.outerIndexPtr()[numValues] = numValues;
//mexPrintf("Matrix created!");
//We don't need Q as it would be a scalar 1
subSpMat = std::make_shared<spMat_t>(numValues,1);
//Perform the slicing product
//This product may throw bad alloc when we have very large matrices. I don't know why.
(*subSpMat) = R*spMatAsVector;
*/
}
}
result = new sparseEigen(subSpMat);
if (!isColumnVector)
result->transposed = true;
}
else{
throw(MexException("sparseEigen:invalidIndex","Unsupported index type!"));
}
return convertPtr2Mat<sparseEigen>(result);
}
template <typename index_t, typename value_t>
index_t sparseEigen<index_t,value_t>::toLinearIndex(const index_t row, const index_t col) const
{
return this->getRows()*col + row;
}
template <typename index_t, typename value_t>
index_t sparseEigen<index_t,value_t>::linearIndexToColIndex(const index_t linIx) const
{
return linIx / this->getRows();
}
template <typename index_t, typename value_t>
index_t sparseEigen<index_t,value_t>::linearIndexToRowIndex(const index_t linIx) const
{
return linIx % this->getRows();
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::full() const
{
mxArray* fullMatrix = mxCreateNumericMatrix(this->getRows(),this->getCols(),valueMxClassID,mxREAL);
value_t* fullMatrix_data = static_cast<value_t*>(mxGetData(fullMatrix));
Eigen::Map<mxValueAsMatrix_t> fullMatrixMap(fullMatrix_data,this->getRows(),this->getCols());
if (this->transposed)
fullMatrixMap = this->eigSpMatrix->transpose().toDense();
else
fullMatrixMap = this->eigSpMatrix->toDense();
return fullMatrix;
}
template <typename index_t, typename value_t>
mxArray* sparseEigen<index_t,value_t>::elementWiseBinaryOperation(const mxArray* operand, const ElementWiseOperation& op) const
{
mxClassID mxType = mxGetClassID(operand);
//Check if it is a sparse eigen through first checking a scalar
mwSize m = mxGetM(operand);
mwSize n = mxGetN(operand);
bool isScalar = (m == 1) & (n == 1);
std::string opName = "Matrix ";
switch (op)
{
case ELEMENTWISE_PLUS:
opName += "addition";
break;
case ELEMENTWISE_MINUS_L:
case ELEMENTWISE_MINUS_R:
opName += "subtraction";
break;
case ELEMENTWISE_DIVIDE_L:
case ELEMENTWISE_DIVIDE_R:
opName += "elementwise division";
break;
case ELEMENTWISE_TIMES:
opName += "hadamard product";
break;
default:
throw(MexException("sparseEigen:unkownOperation","Binary elementwise matrix operation not known!"));
}
mxArray* resultMatrix;
//First, check for an uint64 scalar, as it might reference another instance of a sparseEigen matrix
if (mxType == mxUINT64_CLASS && isScalar)
{
sparseEigen* operandSpS = nullptr;
try
{
operandSpS = convertMat2Ptr<sparseEigen>(operand);
}
catch (MexException& e)
{
std::string id(e.id());
if (id.compare("classHandle:invalidHandle")) //Later we could allow uint64 operations as well, but I advise against this
throw(MexException("sparseEigen:wrongDataType",opName + " only implemented for single/double!"));
else
throw;
}
catch (...)
{
throw;
}
m = operandSpS->getRows();
n = operandSpS->getCols();
bool sizeMatch = (m == this->getRows()) & (n == this->getCols());
isScalar = (m == n) & (n == 1);
if (isScalar)
{
throw(MexException("sparseEigen:missingImplementation",opName + " not implemented for scalar sparse matrix!"));
}
else if (sizeMatch)
{
std::shared_ptr<spMat_t> resultSparse = std::make_shared<spMat_t>(m,n);
switch (op)
{
case ELEMENTWISE_PLUS:
if (!this->transposed && !operandSpS->transposed)
*resultSparse = (*this->eigSpMatrix + *operandSpS->eigSpMatrix).pruned();