/
matrix_impl.hpp
2911 lines (2418 loc) · 90.9 KB
/
matrix_impl.hpp
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
/*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CASADI_MATRIX_IMPL_HPP
#define CASADI_MATRIX_IMPL_HPP
// The declaration of the class is in a separate file
#include "matrix.hpp"
#include "matrix_tools.hpp"
/// \cond INTERNAL
namespace casadi {
// Implementations
template<typename DataType>
const DataType& Matrix<DataType>::elem(int rr, int cc) const {
int ind = sparsity().getNZ(rr, cc);
if (ind==-1)
return casadi_limits<DataType>::zero;
else
return at(ind);
}
template<typename DataType>
int Matrix<DataType>::stream_precision_ = 6;
template<typename DataType>
int Matrix<DataType>::stream_width_ = 0;
template<typename DataType>
bool Matrix<DataType>::stream_scientific_ = false;
template<typename DataType>
DataType& Matrix<DataType>::elem(int rr, int cc) {
int oldsize = sparsity().nnz();
int ind = sparsityRef().addNZ(rr, cc);
if (oldsize != sparsity().nnz())
data().insert(begin()+ind, DataType(0));
return at(ind);
}
template<typename DataType>
bool Matrix<DataType>::__nonzero__() const {
if (numel()!=1) {casadi_error("Only scalar Matrix could have a truth value, but you "
"provided a shape" << dimString());}
return at(0)!=0;
}
template<typename DataType>
bool Matrix<DataType>::isSlice(bool ind1) const {
throw CasadiException("\"isSlice\" not defined for instantiation");
return false;
}
template<typename DataType>
Slice Matrix<DataType>::toSlice(bool ind1) const {
throw CasadiException("\"toSlice\" not defined for instantiation");
return Slice();
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1,
const Slice& rr, const Slice& cc) const {
// Both are scalar
if (rr.isscalar(size1()) && cc.isscalar(size2())) {
int k = sparsity().getNZ(rr.toScalar(size1()), cc.toScalar(size2()));
if (k>=0) {
m = at(k);
} else {
m = Matrix<DataType>(1, 1);
}
return;
}
// Fall back on IMatrix-IMatrix
get(m, ind1, rr.getAll(size1(), ind1), cc.getAll(size2(), ind1));
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1,
const Slice& rr, const Matrix<int>& cc) const {
// Fall back on IMatrix-IMatrix
get(m, ind1, rr.getAll(size1(), ind1), cc);
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1,
const Matrix<int>& rr, const Slice& cc) const {
// Fall back on IMatrix-IMatrix
get(m, ind1, rr, cc.getAll(size2(), ind1));
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1,
const Matrix<int>& rr, const Matrix<int>& cc) const {
// Scalar
if (rr.isscalar(true) && cc.isscalar(true)) {
return get(m, ind1, rr.toSlice(ind1), cc.toSlice(ind1));
}
// Row vector rr (e.g. in MATLAB) is transposed to column vector
if (rr.size1()==1 && rr.size2()>1) {
return get(m, ind1, rr.T(), cc);
}
// Row vector cc (e.g. in MATLAB) is transposed to column vector
if (cc.size1()==1 && cc.size2()>1) {
return get(m, ind1, rr, cc.T());
}
casadi_assert_message(rr.isDense() && rr.isVector(),
"Marix::get: First index must be a dense vector");
casadi_assert_message(cc.isDense() && cc.isVector(),
"Marix::get: Second index must be a dense vector");
// Get the sparsity pattern - does bounds checking
std::vector<int> mapping;
Sparsity sp = sparsity().sub(rr.data(), cc.data(), mapping, ind1);
// Copy nonzeros
m = Matrix<DataType>::zeros(sp);
for (int k=0; k<mapping.size(); ++k) m.at(k) = at(mapping[k]);
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1, const Slice& rr) const {
// Scalar
if (rr.isscalar(numel())) {
int r = rr.toScalar(numel());
int k = sparsity().getNZ(r % size1(), r / size1());
if (k>=0) {
m = at(k);
} else {
m = Matrix<DataType>(1, 1);
}
return;
}
// Fall back on IMatrix
get(m, ind1, rr.getAll(numel(), ind1));
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1, const Matrix<int>& rr) const {
// Scalar
if (rr.isscalar(true)) {
return get(m, ind1, rr.toSlice(ind1));
}
// If the indexed matrix is dense, use nonzero indexing
if (isDense()) {
return getNZ(m, ind1, rr);
}
// Get the sparsity pattern - does bounds checking
std::vector<int> mapping;
Sparsity sp = sparsity().sub(rr.data(), rr.sparsity(), mapping, ind1);
// Copy nonzeros
m = Matrix<DataType>::zeros(sp);
for (int k=0; k<mapping.size(); ++k) m.at(k) = at(mapping[k]);
}
template<typename DataType>
void Matrix<DataType>::get(Matrix<DataType>& m, bool ind1, const Sparsity& sp) const {
casadi_assert_message(shape()==sp.shape(),
"get(Sparsity sp): shape mismatch. This matrix has shape "
<< shape() << ", but supplied sparsity index has shape "
<< sp.shape() << ".");
m = project(*this, sp);
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1,
const Slice& rr, const Slice& cc) {
// Both are scalar
if (rr.isscalar(size1()) && cc.isscalar(size2()) && m.isDense()) {
elem(rr.toScalar(size1()), cc.toScalar(size2())) = m.toScalar();
return;
}
// Fall back on (IMatrix, IMatrix)
set(m, ind1, rr.getAll(size1(), ind1), cc.getAll(size2(), ind1));
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1,
const Slice& rr, const Matrix<int>& cc) {
// Fall back on (IMatrix, IMatrix)
set(m, ind1, rr.getAll(size1(), ind1), cc);
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1,
const Matrix<int>& rr, const Slice& cc) {
// Fall back on (IMatrix, IMatrix)
set(m, ind1, rr, cc.getAll(size2(), ind1));
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1,
const Matrix<int>& rr, const Matrix<int>& cc) {
// Scalar
if (rr.isscalar(true) && cc.isscalar(true) && m.isDense()) {
return set(m, ind1, rr.toSlice(ind1), cc.toSlice(ind1));
}
// Row vector rr (e.g. in MATLAB) is transposed to column vector
if (rr.size1()==1 && rr.size2()>1) {
return set(m, ind1, rr.T(), cc);
}
// Row vector cc (e.g. in MATLAB) is transposed to column vector
if (cc.size1()==1 && cc.size2()>1) {
return set(m, ind1, rr, cc.T());
}
// Make sure rr and cc are dense vectors
casadi_assert_message(rr.isDense() && rr.isVector(),
"Matrix::set: First index not dense vector");
casadi_assert_message(cc.isDense() && cc.isVector(),
"Matrix::set: Second index not dense vector");
// Assert dimensions of assigning matrix
if (rr.size1() != m.size1() || cc.size1() != m.size2()) {
if (m.isscalar()) {
// m scalar means "set all"
return set(repmat(m, rr.size1(), cc.size1()), ind1, rr, cc);
} else if (rr.size1() == m.size2() && cc.size1() == m.size1()
&& std::min(m.size1(), m.size2()) == 1) {
// m is transposed if necessary
return set(m.T(), ind1, rr, cc);
} else {
// Error otherwise
casadi_error("Dimension mismatch." << "lhs is " << rr.size1() << "-by-"
<< cc.size1() << ", while rhs is " << m.shape());
}
}
// Dimensions
int sz1 = size1(), sz2 = size2();
// Report out-of-bounds
if (!inBounds(rr.data(), -sz1+ind1, sz1+ind1)) {
casadi_error("set[., r, c] out of bounds. Your rr contains "
<< *std::min_element(rr.begin(), rr.end()) << " up to "
<< *std::max_element(rr.begin(), rr.end())
<< ", which is outside the range [" << -sz1+ind1 << ","<< sz1+ind1 << ").");
}
if (!inBounds(cc.data(), -sz2+ind1, sz2+ind1)) {
casadi_error("set [., r, c] out of bounds. Your cc contains "
<< *std::min_element(cc.begin(), cc.end()) << " up to "
<< *std::max_element(cc.begin(), cc.end())
<< ", which is outside the range [" << -sz2+ind1 << ","<< sz2+ind1 << ").");
}
// If we are assigning with something sparse, first remove existing entries
if (!m.isDense()) {
erase(rr.data(), cc.data(), ind1);
}
// Collect all assignments
IMatrix el = IMatrix::zeros(m.sparsity());
for (int j=0; j<el.size2(); ++j) { // Loop over columns of m
int this_j = cc.at(j) - ind1; // Corresponding column in this
if (this_j<0) this_j += sz2;
for (int k=el.colind(j); k<el.colind(j+1); ++k) { // Loop over rows of m
int i = m.row(k);
int this_i = rr.at(i) - ind1; // Corresponding row in this
if (this_i<0) this_i += sz1;
el.at(k) = this_i + this_j*sz1;
}
}
return set(m, false, el);
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1, const Slice& rr) {
// Scalar
if (rr.isscalar(numel()) && m.isDense()) {
int r = rr.toScalar(numel());
elem(r % size1(), r / size1()) = m.toScalar();
return;
}
// Fall back on IMatrix
set(m, ind1, rr.getAll(numel(), ind1));
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1, const Matrix<int>& rr) {
// Scalar
if (rr.isscalar(true) && m.isDense()) {
return set(m, ind1, rr.toSlice(ind1));
}
// Assert dimensions of assigning matrix
if (rr.sparsity() != m.sparsity()) {
if (rr.shape() == m.shape()) {
// Remove submatrix to be replaced
erase(rr.data(), ind1);
// Find the intersection between rr's and m's sparsity patterns
Sparsity sp = rr.sparsity() * m.sparsity();
// Project both matrices to this sparsity
return set(project(m, sp), ind1, project(rr, sp));
} else if (m.isscalar()) {
// m scalar means "set all"
if (m.isDense()) {
return set(Matrix<DataType>(rr.sparsity(), m), ind1, rr);
} else {
return set(Matrix<DataType>(rr.shape()), ind1, rr);
}
} else if (rr.size1() == m.size2() && rr.size2() == m.size1()
&& std::min(m.size1(), m.size2()) == 1) {
// m is transposed if necessary
return set(m.T(), ind1, rr);
} else {
// Error otherwise
casadi_error("Dimension mismatch." << "lhs is " << rr.shape()
<< ", while rhs is " << m.shape());
}
}
// Dimensions of this
int sz1 = size1(), sz2 = size2(), sz = nnz(), nel = numel(), rrsz = rr.nnz();
// Quick return if nothing to set
if (rrsz==0) return;
// Check bounds
if (!inBounds(rr.data(), -nel+ind1, nel+ind1)) {
casadi_error("set[rr] out of bounds. Your rr contains "
<< *std::min_element(rr.begin(), rr.end()) << " up to "
<< *std::max_element(rr.begin(), rr.end())
<< ", which is outside the range [" << -nel+ind1 << ","<< nel+ind1 << ").");
}
// Dense mode
if (isDense() && m.isDense()) {
return setNZ(m, ind1, rr);
}
// Construct new sparsity pattern
std::vector<int> new_row=sparsity().getRow(), new_col=sparsity().getCol(), nz(rr.data());
new_row.reserve(sz+rrsz);
new_col.reserve(sz+rrsz);
nz.reserve(rrsz);
for (std::vector<int>::iterator i=nz.begin(); i!=nz.end(); ++i) {
if (ind1) (*i)--;
if (*i<0) *i += nel;
new_row.push_back(*i % sz1);
new_col.push_back(*i / sz1);
}
Sparsity sp = Sparsity::triplet(sz1, sz2, new_row, new_col);
// If needed, update pattern
if (sp != sparsity()) *this = project(*this, sp);
// Find the nonzeros corresponding to rr
sparsity().getNZ(nz);
// Carry out the assignments
for (int i=0; i<nz.size(); ++i) {
at(nz[i]) = m.at(i);
}
}
template<typename DataType>
void Matrix<DataType>::set(const Matrix<DataType>& m, bool ind1, const Sparsity& sp) {
casadi_assert_message(shape()==sp.shape(),
"set(Sparsity sp): shape mismatch. This matrix has shape "
<< shape() << ", but supplied sparsity index has shape "
<< sp.shape() << ".");
std::vector<int> ii = sp.find();
if (m.isscalar()) {
(*this)(ii) = densify(m);
} else {
(*this)(ii) = densify(m(ii));
}
}
template<typename DataType>
void Matrix<DataType>::getNZ(Matrix<DataType>& m, bool ind1, const Slice& kk) const {
// Scalar
if (kk.isscalar(nnz())) {
m = at(kk.toScalar(nnz()));
return;
}
// Fall back on IMatrix
getNZ(m, ind1, kk.getAll(nnz(), ind1));
}
template<typename DataType>
void Matrix<DataType>::getNZ(Matrix<DataType>& m, bool ind1, const Matrix<int>& kk) const {
// Scalar
if (kk.isscalar(true)) {
return getNZ(m, ind1, kk.toSlice(ind1));
}
// Get nonzeros of kk
const std::vector<int>& k = kk.data();
int sz = nnz();
// Check bounds
if (!inBounds(k, -sz+ind1, sz+ind1)) {
casadi_error("getNZ[kk] out of bounds. Your kk contains "
<< *std::min_element(k.begin(), k.end()) << " up to "
<< *std::max_element(k.begin(), k.end())
<< ", which is outside the range [" << -sz+ind1 << ","<< sz+ind1 << ").");
}
// Copy nonzeros
m = zeros(kk.sparsity());
for (int el=0; el<k.size(); ++el) {
casadi_assert_message(!(ind1 && k[el]<=0), "Matlab is 1-based, but requested index " <<
k[el] << ". Note that negative slices are" <<
" disabled in the Matlab interface. " <<
"Possibly you may want to use 'end'.");
int k_el = k[el]-ind1;
m.at(el) = at(k_el>=0 ? k_el : k_el+sz);
}
}
template<typename DataType>
void Matrix<DataType>::setNZ(const Matrix<DataType>& m, bool ind1, const Slice& kk) {
// Scalar
if (kk.isscalar(nnz())) {
at(kk.toScalar(nnz())) = m.toScalar();
return;
}
// Fallback on IMatrix
setNZ(m, ind1, kk.getAll(nnz(), ind1));
}
template<typename DataType>
void Matrix<DataType>::setNZ(const Matrix<DataType>& m, bool ind1, const Matrix<int>& kk) {
// Scalar
if (kk.isscalar(true)) {
return setNZ(m, ind1, kk.toSlice(ind1));
}
// Assert dimensions of assigning matrix
if (kk.sparsity() != m.sparsity()) {
if (m.isscalar()) {
// m scalar means "set all"
if (!m.isDense()) return; // Nothing to set
return setNZ(Matrix<DataType>(kk.sparsity(), m), ind1, kk);
} else if (kk.shape() == m.shape()) {
// Project sparsity if needed
return setNZ(project(m, kk.sparsity()), ind1, kk);
} else if (kk.size1() == m.size2() && kk.size2() == m.size1()
&& std::min(m.size1(), m.size2()) == 1) {
// m is transposed if necessary
return setNZ(m.T(), ind1, kk);
} else {
// Error otherwise
casadi_error("Dimension mismatch." << "lhs is " << kk.shape()
<< ", while rhs is " << m.shape());
}
}
// Get nonzeros
const std::vector<int>& k = kk.data();
int sz = nnz();
// Check bounds
if (!inBounds(k, -sz+ind1, sz+ind1)) {
casadi_error("setNZ[kk] out of bounds. Your kk contains "
<< *std::min_element(k.begin(), k.end()) << " up to "
<< *std::max_element(k.begin(), k.end())
<< ", which is outside the range [" << -sz+ind1 << ","<< sz+ind1 << ").");
}
// Set nonzeros, ignoring negative indices
for (int el=0; el<k.size(); ++el) {
casadi_assert_message(!(ind1 && k[el]<=0), "Matlab is 1-based, but requested index " <<
k[el] << ". Note that negative slices are" <<
" disabled in the Matlab interface. " <<
"Possibly you may want to use 'end'.");
int k_el = k[el]-ind1;
at(k_el>=0 ? k_el : k_el+sz) = m.at(el);
}
}
template<typename DataType>
void Matrix<DataType>::makeDense(const DataType& val) {
// Quick return if possible
if (isDense()) return;
// Get sparsity pattern
int nrow = size1();
int ncol = size2();
const int* colind = this->colind();
const int* row = this->row();
// Resize data and copy
data_.resize(nrow*ncol, val);
// Loop over the columns in reverse order
for (int cc=ncol-1; cc>=0; --cc) {
// Loop over nonzero elements of the column in reverse order
for (int el=colind[cc+1]-1; el>=colind[cc]; --el) {
int rr = row[el];
int new_el = cc*nrow + rr;
if (el==new_el) break; // Already done, the rest of the elements must be in the same place
std::swap(data_[new_el], data_[el]);
}
}
// Update the sparsity pattern
sparsity_ = Sparsity::dense(shape());
}
template<typename DataType>
void Matrix<DataType>::makeSparse(double tol) {
// Quick return if there are no entries to be removed
bool remove_nothing = true;
for (typename std::vector<DataType>::iterator it=begin(); it!=end() && remove_nothing; ++it) {
remove_nothing = !casadi_limits<DataType>::isAlmostZero(*it, tol);
}
if (remove_nothing) return;
// Get the current sparsity pattern
int size1 = this->size1();
int size2 = this->size2();
const int* colind = this->colind();
const int* row = this->row();
// Construct the new sparsity pattern
std::vector<int> new_colind(1, 0), new_row;
// Loop over the columns
for (int cc=0; cc<size2; ++cc) {
// Loop over existing nonzeros
for (int el=colind[cc]; el<colind[cc+1]; ++el) {
// If it is not known to be a zero
if (!casadi_limits<DataType>::isAlmostZero(data_[el], tol)) {
// Save the nonzero in its new location
data_[new_row.size()] = data_[el];
// Add to pattern
new_row.push_back(row[el]);
}
}
// Save the new column offset
new_colind.push_back(new_row.size());
}
// Trim the data vector
data_.resize(new_row.size());
// Update the sparsity pattern
sparsity_ = Sparsity(size1, size2, new_colind, new_row);
}
template<typename DataType>
Matrix<DataType>::Matrix() : sparsity_(Sparsity(0, 0)) {
}
template<typename DataType>
Matrix<DataType>::Matrix(const Matrix<DataType>& m) : sparsity_(m.sparsity_), data_(m.data_) {
}
template<typename DataType>
Matrix<DataType>::Matrix(const std::vector<DataType>& x) :
sparsity_(Sparsity::dense(x.size(), 1)), data_(x) {
}
template<typename DataType>
Matrix<DataType>& Matrix<DataType>::operator=(const Matrix<DataType>& m) {
sparsity_ = m.sparsity_;
data_ = m.data_;
return *this;
}
template<typename DataType>
std::string Matrix<DataType>::className() { return matrixName<DataType>(); }
template<typename DataType>
void Matrix<DataType>::printScalar(std::ostream &stream, bool trailing_newline) const {
casadi_assert_message(numel()==1, "Not a scalar");
std::streamsize precision = stream.precision();
std::streamsize width = stream.width();
std::ios_base::fmtflags flags = stream.flags();
stream.precision(stream_precision_);
stream.width(stream_width_);
if (stream_scientific_) {
stream.setf(std::ios::scientific);
} else {
stream.unsetf(std::ios::scientific);
}
if (nnz()==0) {
stream << "00";
} else {
stream << toScalar();
}
if (trailing_newline) stream << std::endl;
stream << std::flush;
stream.precision(precision);
stream.width(width);
stream.flags(flags);
}
template<typename DataType>
void Matrix<DataType>::printVector(std::ostream &stream, bool trailing_newline) const {
casadi_assert_message(isVector(), "Not a vector");
// Get components
std::vector<std::string> nz, inter;
printSplit(nz, inter);
// Print intermediate expressions
for (int i=0; i<inter.size(); ++i)
stream << "@" << (i+1) << "=" << inter[i] << ", ";
inter.clear();
// Access data structures
const int* r = row();
int sz = nnz();
// Nonzero
int el=0;
// Loop over rows
stream << "[";
for (int rr=0; rr<size1(); ++rr) {
// Add delimiter
if (rr!=0) stream << ", ";
// Check if nonzero
if (el<sz && rr==r[el]) {
stream << nz.at(el++);
} else {
stream << "00";
}
}
stream << "]";
if (trailing_newline) stream << std::endl;
stream << std::flush;
}
template<typename DataType>
void Matrix<DataType>::printDense(std::ostream &stream, bool trailing_newline) const {
// Print as a single line
bool oneliner=this->size1()<=1;
// Get components
std::vector<std::string> nz, inter;
printSplit(nz, inter);
// Print intermediate expressions
for (int i=0; i<inter.size(); ++i)
stream << "@" << (i+1) << "=" << inter[i] << ", ";
inter.clear();
// Index counter for each column
const int* cptr = this->colind();
int ncol = size2();
std::vector<int> cind(cptr, cptr+ncol+1);
// Loop over rows
for (int rr=0; rr<size1(); ++rr) {
// Beginning of row
if (rr==0) {
if (!oneliner) stream << std::endl;
stream << "[[";
} else {
stream << " [";
}
// Loop over columns
for (int cc=0; cc<ncol; ++cc) {
// Separating comma
if (cc>0) stream << ", ";
// Check if nonzero
if (cind[cc]<colind(cc+1) && row(cind[cc])==rr) {
stream << nz.at(cind[cc]++);
} else {
stream << "00";
}
}
// End of row
if (rr<size1()-1) {
stream << "], ";
if (!oneliner) stream << std::endl;
} else {
stream << "]]";
}
}
if (trailing_newline) stream << std::endl;
stream << std::flush;
}
template<typename DataType>
void Matrix<DataType>::printSparse(std::ostream &stream, bool trailing_newline) const {
if (nnz()==0) {
stream << "all zero sparse: " << size1() << "-by-" << size2();
} else {
// Print header
stream << "sparse: " << size1() << "-by-" << size2() << ", " << nnz() << " nnz";
// Get components
std::vector<std::string> nz, inter;
printSplit(nz, inter);
// Print intermediate expressions
for (int i=0; i<inter.size(); ++i)
stream << std::endl << " @" << (i+1) << "=" << inter[i] << ",";
inter.clear();
// Print nonzeros
for (int cc=0; cc<size2(); ++cc) {
for (int el=colind(cc); el<colind(cc+1); ++el) {
int rr=row(el);
stream << std::endl << " (" << rr << ", " << cc << ") -> " << nz.at(el);
}
}
}
if (trailing_newline) stream << std::endl;
stream << std::flush;
}
template<typename DataType>
void Matrix<DataType>::printSplit(std::vector<std::string>& nz,
std::vector<std::string>& inter) const {
nz.resize(nnz());
inter.resize(0);
// Temporary
std::stringstream ss;
ss.precision(stream_precision_);
ss.width(stream_width_);
if (stream_scientific_) {
ss.setf(std::ios::scientific);
} else {
ss.unsetf(std::ios::scientific);
}
// Print nonzeros
for (int i=0; i<nz.size(); ++i) {
ss.str(std::string());
ss << data().at(i);
nz[i] = ss.str();
}
}
template<typename DataType>
void Matrix<DataType>::print(std::ostream &stream, bool trailing_newline) const {
if (isEmpty()) {
stream << "[]";
} else if (numel()==1) {
printScalar(stream, false);
} else if (isVector()) {
printVector(stream, false);
} else if (std::max(size1(), size2())<=10 || static_cast<double>(nnz())/numel()>=0.5) {
// if "small" or "dense"
printDense(stream, false);
} else {
printSparse(stream, false);
}
if (trailing_newline) stream << std::endl;
}
template<typename DataType>
void Matrix<DataType>::repr(std::ostream &stream, bool trailing_newline) const {
stream << className() << "(";
print(stream, false);
stream << ")";
if (trailing_newline) stream << std::endl;
stream << std::flush;
}
template<typename DataType>
void Matrix<DataType>::reserve(int nnz) {
reserve(nnz, size2());
}
template<typename DataType>
void Matrix<DataType>::reserve(int nnz, int ncol) {
data().reserve(nnz);
}
template<typename DataType>
void Matrix<DataType>::resize(int nrow, int ncol) {
sparsity_.resize(nrow, ncol);
}
template<typename DataType>
void Matrix<DataType>::clear() {
sparsity_ = Sparsity(0, 0);
data().clear();
}
template<typename DataType>
Matrix<DataType>::Matrix(double val) :
sparsity_(Sparsity::dense(1, 1)), data_(std::vector<DataType>(1, val)) {
}
template<typename DataType>
Matrix<DataType>::Matrix(const std::vector< std::vector<double> >& d) {
// Get dimensions
int nrow=d.size();
int ncol=d.empty() ? 1 : d.front().size();
// Assert consistency
for (int rr=0; rr<nrow; ++rr) {
casadi_assert_message(ncol==d[rr].size(),
"Matrix<DataType>::Matrix(const std::vector< std::vector<DataType> >& d): "
"shape mismatch" << std::endl
<< "Attempting to construct a matrix from a nested list." << std::endl
<< "I got convinced that the desired size is ("<< nrow << " x " << ncol
<< " ), but now I encounter a vector of size ("
<< d[rr].size() << " )" << std::endl);
}
// Form matrix
sparsity_ = Sparsity::dense(nrow, ncol);
data().resize(nrow*ncol);
typename std::vector<DataType>::iterator it=begin();
for (int cc=0; cc<ncol; ++cc) {
for (int rr=0; rr<nrow; ++rr) {
*it++ = d[rr][cc];
}
}
}
template<typename DataType>
Matrix<DataType>::Matrix(const Sparsity& sp, int dummy1, int dummy2, int dummy3) :
sparsity_(sp), data_(sp.nnz(), 1) {
}
template<typename DataType>
Matrix<DataType>::Matrix(int nrow, int ncol) : sparsity_(nrow, ncol) {
}
template<typename DataType>
Matrix<DataType>::Matrix(const std::pair<int, int>& rc) : sparsity_(rc) {
}
template<typename DataType>
Matrix<DataType>::Matrix(const Sparsity& sp, const DataType& val, bool dummy) :
sparsity_(sp), data_(sp.nnz(), val) {
}
template<typename DataType>
Matrix<DataType>::Matrix(const Sparsity& sp, const std::vector<DataType>& d, bool dummy) :
sparsity_(sp), data_(d) {
casadi_assert_message(sp.nnz()==d.size(), "Size mismatch." << std::endl
<< "You supplied a sparsity of " << sp.dimString()
<< ", but the supplied vector is of length " << d.size());
}
template<typename DataType>
Matrix<DataType>::Matrix(const Sparsity& sp, const Matrix<DataType>& d) {
if (d.isscalar()) {
*this = Matrix<DataType>(sp, d.toScalar(), false);
} else if (d.isVector() || d.size1()==1) {
casadi_assert(sp.nnz()==d.numel());
if (d.isDense()) {
*this = Matrix<DataType>(sp, d.data(), false);
} else {
*this = Matrix<DataType>(sp, densify(d).data(), false);
}
} else {
casadi_error("Matrix(Sparsisty, Matrix): Only allowed for scalars and vectors");
}
}
template<typename DataType>
void Matrix<DataType>::setZero() {
setAll(0);
}
template<typename DataType>
void Matrix<DataType>::setAll(const DataType& val) {
std::fill(begin(), end(), val);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::unary(int op, const Matrix<DataType> &x) {
// Return value
Matrix<DataType> ret = Matrix<DataType>::zeros(x.sparsity());
// Nonzeros
std::vector<DataType>& ret_data = ret.data();
const std::vector<DataType>& x_data = x.data();
// Do the operation on all non-zero elements
for (int el=0; el<x.nnz(); ++el) {
casadi_math<DataType>::fun(op, x_data[el], x_data[el], ret_data[el]);
}
// Check the value of the structural zero-entries, if there are any
if (!x.isDense() && !operation_checker<F0XChecker>(op)) {
// Get the value for the structural zeros
DataType fcn_0;
casadi_math<DataType>::fun(op, 0, 0, fcn_0);
if (!casadi_limits<DataType>::isZero(fcn_0)) { // Remove this if?
ret.makeDense(fcn_0);
}
}
return ret;
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::operator-() const {
return unary(OP_NEG, *this);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::operator+() const {
return *this;
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_plus(const Matrix<DataType> &y) const {
return binary(OP_ADD, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_minus(const Matrix<DataType> &y) const {
return binary(OP_SUB, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_times(const Matrix<DataType> &y) const {
return binary(OP_MUL, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_rdivide(const Matrix<DataType> &y) const {
return binary(OP_DIV, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_lt(const Matrix<DataType> &y) const {
return binary(OP_LT, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_le(const Matrix<DataType> &y) const {
return binary(OP_LE, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_eq(const Matrix<DataType> &y) const {
return binary(OP_EQ, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_ne(const Matrix<DataType> &y) const {
return binary(OP_NE, *this, y);
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::__mrdivide__(const Matrix<DataType>& b) const {
if (b.numel()==1) return *this/b;
throw CasadiException("mrdivide: Not implemented");
}
template<typename DataType>
Matrix<DataType> Matrix<DataType>::zz_mpower(const Matrix<DataType>& b) const {
if (b.numel()==1) return pow(*this, b);
throw CasadiException("mpower: Not implemented");
}