forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sparse.cc
1549 lines (1386 loc) · 53.4 KB
/
sparse.cc
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
// Copyright 2010-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/lp_data/sparse.h"
#include <algorithm>
#include <cstdlib>
#include <initializer_list>
#include <string>
#include <utility>
#include <vector>
#include "absl/log/check.h"
#include "absl/strings/str_format.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/lp_data/permutation.h"
#include "ortools/lp_data/sparse_column.h"
#include "ortools/util/return_macros.h"
namespace operations_research {
namespace glop {
namespace {
using ::util::Reverse;
template <typename Matrix>
EntryIndex ComputeNumEntries(const Matrix& matrix) {
EntryIndex num_entries(0);
const ColIndex num_cols(matrix.num_cols());
for (ColIndex col(0); col < num_cols; ++col) {
num_entries += matrix.column(col).num_entries();
}
return num_entries;
}
// Computes the 1-norm of the matrix.
// The 1-norm |A| is defined as max_j sum_i |a_ij| or
// max_col sum_row |a(row,col)|.
template <typename Matrix>
Fractional ComputeOneNormTemplate(const Matrix& matrix) {
Fractional norm(0.0);
const ColIndex num_cols(matrix.num_cols());
for (ColIndex col(0); col < num_cols; ++col) {
Fractional column_norm(0);
for (const SparseColumn::Entry e : matrix.column(col)) {
// Compute sum_i |a_ij|.
column_norm += fabs(e.coefficient());
}
// Compute max_j sum_i |a_ij|
norm = std::max(norm, column_norm);
}
return norm;
}
// Computes the oo-norm (infinity-norm) of the matrix.
// The oo-norm |A| is defined as max_i sum_j |a_ij| or
// max_row sum_col |a(row,col)|.
template <typename Matrix>
Fractional ComputeInfinityNormTemplate(const Matrix& matrix) {
DenseColumn row_sum(matrix.num_rows(), 0.0);
const ColIndex num_cols(matrix.num_cols());
for (ColIndex col(0); col < num_cols; ++col) {
for (const SparseColumn::Entry e : matrix.column(col)) {
// Compute sum_j |a_ij|.
row_sum[e.row()] += fabs(e.coefficient());
}
}
// Compute max_i sum_j |a_ij|
Fractional norm = 0.0;
const RowIndex num_rows(matrix.num_rows());
for (RowIndex row(0); row < num_rows; ++row) {
norm = std::max(norm, row_sum[row]);
}
return norm;
}
} // namespace
// --------------------------------------------------------
// SparseMatrix
// --------------------------------------------------------
SparseMatrix::SparseMatrix() : columns_(), num_rows_(0) {}
#if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
SparseMatrix::SparseMatrix(
std::initializer_list<std::initializer_list<Fractional>> init_list) {
ColIndex num_cols(0);
num_rows_ = RowIndex(init_list.size());
RowIndex row(0);
for (std::initializer_list<Fractional> init_row : init_list) {
num_cols = std::max(num_cols, ColIndex(init_row.size()));
columns_.resize(num_cols, SparseColumn());
ColIndex col(0);
for (Fractional value : init_row) {
if (value != 0.0) {
columns_[col].SetCoefficient(row, value);
}
++col;
}
++row;
}
}
#endif
void SparseMatrix::Clear() {
columns_.clear();
num_rows_ = RowIndex(0);
}
bool SparseMatrix::IsEmpty() const {
return columns_.empty() || num_rows_ == 0;
}
void SparseMatrix::CleanUp() {
const ColIndex num_cols(columns_.size());
for (ColIndex col(0); col < num_cols; ++col) {
columns_[col].CleanUp();
}
}
bool SparseMatrix::CheckNoDuplicates() const {
DenseBooleanColumn boolean_column;
const ColIndex num_cols(columns_.size());
for (ColIndex col(0); col < num_cols; ++col) {
if (!columns_[col].CheckNoDuplicates(&boolean_column)) return false;
}
return true;
}
bool SparseMatrix::IsCleanedUp() const {
const ColIndex num_cols(columns_.size());
for (ColIndex col(0); col < num_cols; ++col) {
if (!columns_[col].IsCleanedUp()) return false;
}
return true;
}
void SparseMatrix::SetNumRows(RowIndex num_rows) { num_rows_ = num_rows; }
ColIndex SparseMatrix::AppendEmptyColumn() {
const ColIndex result = columns_.size();
columns_.push_back(SparseColumn());
return result;
}
void SparseMatrix::AppendUnitVector(RowIndex row, Fractional value) {
DCHECK_LT(row, num_rows_);
SparseColumn new_col;
new_col.SetCoefficient(row, value);
columns_.push_back(std::move(new_col));
}
void SparseMatrix::Swap(SparseMatrix* matrix) {
// We do not need to swap the different mutable scratchpads we use.
columns_.swap(matrix->columns_);
std::swap(num_rows_, matrix->num_rows_);
}
void SparseMatrix::PopulateFromZero(RowIndex num_rows, ColIndex num_cols) {
columns_.resize(num_cols, SparseColumn());
for (ColIndex col(0); col < num_cols; ++col) {
columns_[col].Clear();
}
num_rows_ = num_rows;
}
void SparseMatrix::PopulateFromIdentity(ColIndex num_cols) {
PopulateFromZero(ColToRowIndex(num_cols), num_cols);
for (ColIndex col(0); col < num_cols; ++col) {
const RowIndex row = ColToRowIndex(col);
columns_[col].SetCoefficient(row, Fractional(1.0));
}
}
template <typename Matrix>
void SparseMatrix::PopulateFromTranspose(const Matrix& input) {
Reset(RowToColIndex(input.num_rows()), ColToRowIndex(input.num_cols()));
// We do a first pass on the input matrix to resize the new columns properly.
StrictITIVector<RowIndex, EntryIndex> row_degree(input.num_rows(),
EntryIndex(0));
for (ColIndex col(0); col < input.num_cols(); ++col) {
for (const SparseColumn::Entry e : input.column(col)) {
++row_degree[e.row()];
}
}
for (RowIndex row(0); row < input.num_rows(); ++row) {
columns_[RowToColIndex(row)].Reserve(row_degree[row]);
}
for (ColIndex col(0); col < input.num_cols(); ++col) {
const RowIndex transposed_row = ColToRowIndex(col);
for (const SparseColumn::Entry e : input.column(col)) {
const ColIndex transposed_col = RowToColIndex(e.row());
columns_[transposed_col].SetCoefficient(transposed_row, e.coefficient());
}
}
DCHECK(IsCleanedUp());
}
void SparseMatrix::PopulateFromSparseMatrix(const SparseMatrix& matrix) {
Reset(ColIndex(0), matrix.num_rows_);
columns_ = matrix.columns_;
}
template <typename Matrix>
void SparseMatrix::PopulateFromPermutedMatrix(
const Matrix& a, const RowPermutation& row_perm,
const ColumnPermutation& inverse_col_perm) {
const ColIndex num_cols = a.num_cols();
Reset(num_cols, a.num_rows());
for (ColIndex col(0); col < num_cols; ++col) {
for (const auto e : a.column(inverse_col_perm[col])) {
columns_[col].SetCoefficient(row_perm[e.row()], e.coefficient());
}
}
DCHECK(CheckNoDuplicates());
}
void SparseMatrix::PopulateFromLinearCombination(Fractional alpha,
const SparseMatrix& a,
Fractional beta,
const SparseMatrix& b) {
DCHECK_EQ(a.num_cols(), b.num_cols());
DCHECK_EQ(a.num_rows(), b.num_rows());
const ColIndex num_cols = a.num_cols();
Reset(num_cols, a.num_rows());
const RowIndex num_rows = a.num_rows();
RandomAccessSparseColumn dense_column(num_rows);
for (ColIndex col(0); col < num_cols; ++col) {
for (const SparseColumn::Entry e : a.columns_[col]) {
dense_column.AddToCoefficient(e.row(), alpha * e.coefficient());
}
for (const SparseColumn::Entry e : b.columns_[col]) {
dense_column.AddToCoefficient(e.row(), beta * e.coefficient());
}
dense_column.PopulateSparseColumn(&columns_[col]);
columns_[col].CleanUp();
dense_column.Clear();
}
}
void SparseMatrix::PopulateFromProduct(const SparseMatrix& a,
const SparseMatrix& b) {
const ColIndex num_cols = b.num_cols();
const RowIndex num_rows = a.num_rows();
Reset(num_cols, num_rows);
RandomAccessSparseColumn tmp_column(num_rows);
for (ColIndex col_b(0); col_b < num_cols; ++col_b) {
for (const SparseColumn::Entry eb : b.columns_[col_b]) {
if (eb.coefficient() == 0.0) {
continue;
}
const ColIndex col_a = RowToColIndex(eb.row());
for (const SparseColumn::Entry ea : a.columns_[col_a]) {
const Fractional value = ea.coefficient() * eb.coefficient();
tmp_column.AddToCoefficient(ea.row(), value);
}
}
// Populate column col_b.
tmp_column.PopulateSparseColumn(&columns_[col_b]);
columns_[col_b].CleanUp();
tmp_column.Clear();
}
}
void SparseMatrix::DeleteColumns(const DenseBooleanRow& columns_to_delete) {
if (columns_to_delete.empty()) return;
ColIndex new_index(0);
const ColIndex num_cols = columns_.size();
for (ColIndex col(0); col < num_cols; ++col) {
if (col >= columns_to_delete.size() || !columns_to_delete[col]) {
columns_[col].Swap(&(columns_[new_index]));
++new_index;
}
}
columns_.resize(new_index);
}
void SparseMatrix::DeleteRows(RowIndex new_num_rows,
const RowPermutation& permutation) {
DCHECK_EQ(num_rows_, permutation.size());
for (RowIndex row(0); row < num_rows_; ++row) {
DCHECK_LT(permutation[row], new_num_rows);
}
const ColIndex end = num_cols();
for (ColIndex col(0); col < end; ++col) {
columns_[col].ApplyPartialRowPermutation(permutation);
}
SetNumRows(new_num_rows);
}
bool SparseMatrix::AppendRowsFromSparseMatrix(const SparseMatrix& matrix) {
const ColIndex end = num_cols();
if (end != matrix.num_cols()) {
return false;
}
const RowIndex offset = num_rows();
for (ColIndex col(0); col < end; ++col) {
const SparseColumn& source_column = matrix.columns_[col];
columns_[col].AppendEntriesWithOffset(source_column, offset);
}
SetNumRows(offset + matrix.num_rows());
return true;
}
void SparseMatrix::ApplyRowPermutation(const RowPermutation& row_perm) {
const ColIndex num_cols(columns_.size());
for (ColIndex col(0); col < num_cols; ++col) {
columns_[col].ApplyRowPermutation(row_perm);
}
}
Fractional SparseMatrix::LookUpValue(RowIndex row, ColIndex col) const {
return columns_[col].LookUpCoefficient(row);
}
bool SparseMatrix::Equals(const SparseMatrix& a, Fractional tolerance) const {
if (num_cols() != a.num_cols() || num_rows() != a.num_rows()) {
return false;
}
RandomAccessSparseColumn dense_column(num_rows());
RandomAccessSparseColumn dense_column_a(num_rows());
const ColIndex num_cols = a.num_cols();
for (ColIndex col(0); col < num_cols; ++col) {
// Store all entries of current matrix in a dense column.
for (const SparseColumn::Entry e : columns_[col]) {
dense_column.AddToCoefficient(e.row(), e.coefficient());
}
// Check all entries of a are those stored in the dense column.
for (const SparseColumn::Entry e : a.columns_[col]) {
if (fabs(e.coefficient() - dense_column.GetCoefficient(e.row())) >
tolerance) {
return false;
}
}
// Store all entries of matrix a in a dense column.
for (const SparseColumn::Entry e : a.columns_[col]) {
dense_column_a.AddToCoefficient(e.row(), e.coefficient());
}
// Check all entries are those stored in the dense column a.
for (const SparseColumn::Entry e : columns_[col]) {
if (fabs(e.coefficient() - dense_column_a.GetCoefficient(e.row())) >
tolerance) {
return false;
}
}
dense_column.Clear();
dense_column_a.Clear();
}
return true;
}
void SparseMatrix::ComputeMinAndMaxMagnitudes(Fractional* min_magnitude,
Fractional* max_magnitude) const {
RETURN_IF_NULL(min_magnitude);
RETURN_IF_NULL(max_magnitude);
*min_magnitude = kInfinity;
*max_magnitude = 0.0;
for (ColIndex col(0); col < num_cols(); ++col) {
for (const SparseColumn::Entry e : columns_[col]) {
const Fractional magnitude = fabs(e.coefficient());
if (magnitude != 0.0) {
*min_magnitude = std::min(*min_magnitude, magnitude);
*max_magnitude = std::max(*max_magnitude, magnitude);
}
}
}
if (*max_magnitude == 0.0) {
*min_magnitude = 0.0;
}
}
EntryIndex SparseMatrix::num_entries() const {
return ComputeNumEntries(*this);
}
Fractional SparseMatrix::ComputeOneNorm() const {
return ComputeOneNormTemplate(*this);
}
Fractional SparseMatrix::ComputeInfinityNorm() const {
return ComputeInfinityNormTemplate(*this);
}
std::string SparseMatrix::Dump() const {
std::string result;
const ColIndex num_cols(columns_.size());
for (RowIndex row(0); row < num_rows_; ++row) {
result.append("{ ");
for (ColIndex col(0); col < num_cols; ++col) {
absl::StrAppendFormat(&result, "%g ", ToDouble(LookUpValue(row, col)));
}
result.append("}\n");
}
return result;
}
void SparseMatrix::Reset(ColIndex num_cols, RowIndex num_rows) {
Clear();
columns_.resize(num_cols, SparseColumn());
num_rows_ = num_rows;
}
EntryIndex MatrixView::num_entries() const { return ComputeNumEntries(*this); }
Fractional MatrixView::ComputeOneNorm() const {
return ComputeOneNormTemplate(*this);
}
Fractional MatrixView::ComputeInfinityNorm() const {
return ComputeInfinityNormTemplate(*this);
}
// Instantiate needed templates.
template void SparseMatrix::PopulateFromTranspose<SparseMatrix>(
const SparseMatrix& input);
template void SparseMatrix::PopulateFromPermutedMatrix<SparseMatrix>(
const SparseMatrix& a, const RowPermutation& row_perm,
const ColumnPermutation& inverse_col_perm);
template void SparseMatrix::PopulateFromPermutedMatrix<CompactSparseMatrixView>(
const CompactSparseMatrixView& a, const RowPermutation& row_perm,
const ColumnPermutation& inverse_col_perm);
void CompactSparseMatrix::PopulateFromMatrixView(const MatrixView& input) {
num_cols_ = input.num_cols();
num_rows_ = input.num_rows();
const EntryIndex num_entries = input.num_entries();
starts_.assign(num_cols_ + 1, EntryIndex(0));
coefficients_.assign(num_entries, 0.0);
rows_.assign(num_entries, RowIndex(0));
EntryIndex index(0);
for (ColIndex col(0); col < input.num_cols(); ++col) {
starts_[col] = index;
for (const SparseColumn::Entry e : input.column(col)) {
coefficients_[index] = e.coefficient();
rows_[index] = e.row();
++index;
}
}
starts_[input.num_cols()] = index;
}
void CompactSparseMatrix::PopulateFromSparseMatrixAndAddSlacks(
const SparseMatrix& input) {
num_cols_ = input.num_cols() + RowToColIndex(input.num_rows());
num_rows_ = input.num_rows();
const EntryIndex num_entries =
input.num_entries() + EntryIndex(num_rows_.value());
starts_.assign(num_cols_ + 1, EntryIndex(0));
coefficients_.assign(num_entries, 0.0);
rows_.assign(num_entries, RowIndex(0));
EntryIndex index(0);
for (ColIndex col(0); col < input.num_cols(); ++col) {
starts_[col] = index;
for (const SparseColumn::Entry e : input.column(col)) {
coefficients_[index] = e.coefficient();
rows_[index] = e.row();
++index;
}
}
for (RowIndex row(0); row < num_rows_; ++row) {
starts_[input.num_cols() + RowToColIndex(row)] = index;
coefficients_[index] = 1.0;
rows_[index] = row;
++index;
}
starts_[num_cols_] = index;
}
void CompactSparseMatrix::PopulateFromTranspose(
const CompactSparseMatrix& input) {
num_cols_ = RowToColIndex(input.num_rows());
num_rows_ = ColToRowIndex(input.num_cols());
// Fill the starts_ vector by computing the number of entries of each rows and
// then doing a cumulative sum. After this step starts_[col + 1] will be the
// actual start of the column col when we are done.
starts_.assign(num_cols_ + 2, EntryIndex(0));
for (const RowIndex row : input.rows_) {
++starts_[RowToColIndex(row) + 2];
}
for (ColIndex col(2); col < starts_.size(); ++col) {
starts_[col] += starts_[col - 1];
}
coefficients_.resize(starts_.back(), 0.0);
rows_.resize(starts_.back(), kInvalidRow);
starts_.pop_back();
// Use starts_ to fill the matrix. Note that starts_ is modified so that at
// the end it has its final values.
const auto entry_rows = rows_.view();
const auto input_entry_rows = input.rows_.view();
const auto entry_coefficients = coefficients_.view();
const auto input_entry_coefficients = input.coefficients_.view();
const auto num_cols = input.num_cols();
const auto starts = starts_.view();
for (ColIndex col(0); col < num_cols; ++col) {
const RowIndex transposed_row = ColToRowIndex(col);
for (const EntryIndex i : input.Column(col)) {
const ColIndex transposed_col = RowToColIndex(input_entry_rows[i]);
const EntryIndex index = starts[transposed_col + 1]++;
entry_coefficients[index] = input_entry_coefficients[i];
entry_rows[index] = transposed_row;
}
}
DCHECK_EQ(starts_.front(), 0);
DCHECK_EQ(starts_.back(), rows_.size());
}
void TriangularMatrix::PopulateFromTranspose(const TriangularMatrix& input) {
CompactSparseMatrix::PopulateFromTranspose(input);
// This takes care of the triangular special case.
diagonal_coefficients_ = input.diagonal_coefficients_;
all_diagonal_coefficients_are_one_ = input.all_diagonal_coefficients_are_one_;
// The elimination structure of the transpose is not the same.
pruned_ends_.resize(num_cols_, EntryIndex(0));
for (ColIndex col(0); col < num_cols_; ++col) {
pruned_ends_[col] = starts_[col + 1];
}
// Compute first_non_identity_column_. Note that this is not necessarily the
// same as input.first_non_identity_column_ for an upper triangular matrix.
first_non_identity_column_ = 0;
const ColIndex end = diagonal_coefficients_.size();
while (first_non_identity_column_ < end &&
ColumnNumEntries(first_non_identity_column_) == 0 &&
diagonal_coefficients_[first_non_identity_column_] == 1.0) {
++first_non_identity_column_;
}
}
void CompactSparseMatrix::Reset(RowIndex num_rows) {
num_rows_ = num_rows;
num_cols_ = 0;
rows_.clear();
coefficients_.clear();
starts_.clear();
starts_.push_back(EntryIndex(0));
}
void TriangularMatrix::Reset(RowIndex num_rows, ColIndex col_capacity) {
CompactSparseMatrix::Reset(num_rows);
first_non_identity_column_ = 0;
all_diagonal_coefficients_are_one_ = true;
pruned_ends_.resize(col_capacity);
diagonal_coefficients_.resize(col_capacity);
starts_.resize(col_capacity + 1);
// Non-zero entries in the first column always have an offset of 0.
starts_[ColIndex(0)] = 0;
}
ColIndex CompactSparseMatrix::AddDenseColumn(const DenseColumn& dense_column) {
return AddDenseColumnPrefix(dense_column.const_view(), RowIndex(0));
}
ColIndex CompactSparseMatrix::AddDenseColumnPrefix(
DenseColumn::ConstView dense_column, RowIndex start) {
const RowIndex num_rows(dense_column.size());
for (RowIndex row(start); row < num_rows; ++row) {
if (dense_column[row] != 0.0) {
rows_.push_back(row);
coefficients_.push_back(dense_column[row]);
}
}
starts_.push_back(rows_.size());
++num_cols_;
return num_cols_ - 1;
}
ColIndex CompactSparseMatrix::AddDenseColumnWithNonZeros(
const DenseColumn& dense_column, const std::vector<RowIndex>& non_zeros) {
if (non_zeros.empty()) return AddDenseColumn(dense_column);
for (const RowIndex row : non_zeros) {
const Fractional value = dense_column[row];
if (value != 0.0) {
rows_.push_back(row);
coefficients_.push_back(value);
}
}
starts_.push_back(rows_.size());
++num_cols_;
return num_cols_ - 1;
}
ColIndex CompactSparseMatrix::AddAndClearColumnWithNonZeros(
DenseColumn* column, std::vector<RowIndex>* non_zeros) {
for (const RowIndex row : *non_zeros) {
const Fractional value = (*column)[row];
if (value != 0.0) {
rows_.push_back(row);
coefficients_.push_back(value);
(*column)[row] = 0.0;
}
}
non_zeros->clear();
starts_.push_back(rows_.size());
++num_cols_;
return num_cols_ - 1;
}
void CompactSparseMatrix::Swap(CompactSparseMatrix* other) {
std::swap(num_rows_, other->num_rows_);
std::swap(num_cols_, other->num_cols_);
coefficients_.swap(other->coefficients_);
rows_.swap(other->rows_);
starts_.swap(other->starts_);
}
void TriangularMatrix::Swap(TriangularMatrix* other) {
CompactSparseMatrix::Swap(other);
diagonal_coefficients_.swap(other->diagonal_coefficients_);
std::swap(first_non_identity_column_, other->first_non_identity_column_);
std::swap(all_diagonal_coefficients_are_one_,
other->all_diagonal_coefficients_are_one_);
}
EntryIndex CompactSparseMatrixView::num_entries() const {
return ComputeNumEntries(*this);
}
Fractional CompactSparseMatrixView::ComputeOneNorm() const {
return ComputeOneNormTemplate(*this);
}
Fractional CompactSparseMatrixView::ComputeInfinityNorm() const {
return ComputeInfinityNormTemplate(*this);
}
// Internal function used to finish adding one column to a triangular matrix.
// This sets the diagonal coefficient to the given value, and prepares the
// matrix for the next column addition.
void TriangularMatrix::CloseCurrentColumn(Fractional diagonal_value) {
DCHECK_NE(diagonal_value, 0.0);
// The vectors diagonal_coefficients, pruned_ends, and starts_ should have all
// been preallocated by a call to SetTotalNumberOfColumns().
DCHECK_LT(num_cols_, diagonal_coefficients_.size());
diagonal_coefficients_[num_cols_] = diagonal_value;
// TODO(user): This is currently not used by all matrices. It will be good
// to fill it only when needed.
DCHECK_LT(num_cols_, pruned_ends_.size());
pruned_ends_[num_cols_] = coefficients_.size();
++num_cols_;
DCHECK_LT(num_cols_, starts_.size());
starts_[num_cols_] = coefficients_.size();
if (first_non_identity_column_ == num_cols_ - 1 && coefficients_.empty() &&
diagonal_value == 1.0) {
first_non_identity_column_ = num_cols_;
}
all_diagonal_coefficients_are_one_ =
all_diagonal_coefficients_are_one_ && (diagonal_value == 1.0);
}
void TriangularMatrix::AddDiagonalOnlyColumn(Fractional diagonal_value) {
CloseCurrentColumn(diagonal_value);
}
void TriangularMatrix::AddTriangularColumn(const ColumnView& column,
RowIndex diagonal_row) {
Fractional diagonal_value = 0.0;
for (const SparseColumn::Entry e : column) {
if (e.row() == diagonal_row) {
diagonal_value = e.coefficient();
} else {
DCHECK_NE(0.0, e.coefficient());
rows_.push_back(e.row());
coefficients_.push_back(e.coefficient());
}
}
CloseCurrentColumn(diagonal_value);
}
void TriangularMatrix::AddAndNormalizeTriangularColumn(
const SparseColumn& column, RowIndex diagonal_row,
Fractional diagonal_coefficient) {
// TODO(user): use division by a constant using multiplication.
for (const SparseColumn::Entry e : column) {
if (e.row() != diagonal_row) {
if (e.coefficient() != 0.0) {
rows_.push_back(e.row());
coefficients_.push_back(e.coefficient() / diagonal_coefficient);
}
} else {
DCHECK_EQ(e.coefficient(), diagonal_coefficient);
}
}
CloseCurrentColumn(1.0);
}
void TriangularMatrix::AddTriangularColumnWithGivenDiagonalEntry(
const SparseColumn& column, RowIndex diagonal_row,
Fractional diagonal_value) {
for (SparseColumn::Entry e : column) {
DCHECK_NE(e.row(), diagonal_row);
rows_.push_back(e.row());
coefficients_.push_back(e.coefficient());
}
CloseCurrentColumn(diagonal_value);
}
void TriangularMatrix::PopulateFromTriangularSparseMatrix(
const SparseMatrix& input) {
Reset(input.num_rows(), input.num_cols());
for (ColIndex col(0); col < input.num_cols(); ++col) {
AddTriangularColumn(ColumnView(input.column(col)), ColToRowIndex(col));
}
DCHECK(IsLowerTriangular() || IsUpperTriangular());
}
bool TriangularMatrix::IsLowerTriangular() const {
for (ColIndex col(0); col < num_cols_; ++col) {
if (diagonal_coefficients_[col] == 0.0) return false;
for (EntryIndex i : Column(col)) {
if (rows_[i] <= ColToRowIndex(col)) return false;
}
}
return true;
}
bool TriangularMatrix::IsUpperTriangular() const {
for (ColIndex col(0); col < num_cols_; ++col) {
if (diagonal_coefficients_[col] == 0.0) return false;
for (EntryIndex i : Column(col)) {
if (rows_[i] >= ColToRowIndex(col)) return false;
}
}
return true;
}
void TriangularMatrix::ApplyRowPermutationToNonDiagonalEntries(
const RowPermutation& row_perm) {
EntryIndex num_entries = rows_.size();
for (EntryIndex i(0); i < num_entries; ++i) {
rows_[i] = row_perm[rows_[i]];
}
}
void TriangularMatrix::CopyColumnToSparseColumn(ColIndex col,
SparseColumn* output) const {
output->Clear();
const auto entry_rows = rows_.view();
const auto entry_coefficients = coefficients_.view();
for (const EntryIndex i : Column(col)) {
output->SetCoefficient(entry_rows[i], entry_coefficients[i]);
}
output->SetCoefficient(ColToRowIndex(col), diagonal_coefficients_[col]);
output->CleanUp();
}
void TriangularMatrix::CopyToSparseMatrix(SparseMatrix* output) const {
output->PopulateFromZero(num_rows_, num_cols_);
for (ColIndex col(0); col < num_cols_; ++col) {
CopyColumnToSparseColumn(col, output->mutable_column(col));
}
}
void TriangularMatrix::LowerSolve(DenseColumn* rhs) const {
LowerSolveStartingAt(ColIndex(0), rhs);
}
void TriangularMatrix::LowerSolveStartingAt(ColIndex start,
DenseColumn* rhs) const {
RETURN_IF_NULL(rhs);
if (all_diagonal_coefficients_are_one_) {
LowerSolveStartingAtInternal<true>(start, rhs->view());
} else {
LowerSolveStartingAtInternal<false>(start, rhs->view());
}
}
template <bool diagonal_of_ones>
void TriangularMatrix::LowerSolveStartingAtInternal(
ColIndex start, DenseColumn::View rhs) const {
const ColIndex begin = std::max(start, first_non_identity_column_);
const auto entry_rows = rows_.view();
const auto entry_coefficients = coefficients_.view();
const auto diagonal_coefficients = diagonal_coefficients_.view();
const ColIndex end = diagonal_coefficients.size();
for (ColIndex col(begin); col < end; ++col) {
const Fractional value = rhs[ColToRowIndex(col)];
if (value == 0.0) continue;
const Fractional coeff =
diagonal_of_ones ? value : value / diagonal_coefficients[col];
if (!diagonal_of_ones) {
rhs[ColToRowIndex(col)] = coeff;
}
for (const EntryIndex i : Column(col)) {
rhs[entry_rows[i]] -= coeff * entry_coefficients[i];
}
}
}
void TriangularMatrix::UpperSolve(DenseColumn* rhs) const {
RETURN_IF_NULL(rhs);
if (all_diagonal_coefficients_are_one_) {
UpperSolveInternal<true>(rhs->view());
} else {
UpperSolveInternal<false>(rhs->view());
}
}
template <bool diagonal_of_ones>
void TriangularMatrix::UpperSolveInternal(DenseColumn::View rhs) const {
const ColIndex end = first_non_identity_column_;
const auto entry_rows = rows_.view();
const auto entry_coefficients = coefficients_.view();
const auto diagonal_coefficients = diagonal_coefficients_.view();
for (ColIndex col(diagonal_coefficients.size() - 1); col >= end; --col) {
const Fractional value = rhs[ColToRowIndex(col)];
if (value == 0.0) continue;
const Fractional coeff =
diagonal_of_ones ? value : value / diagonal_coefficients[col];
if (!diagonal_of_ones) {
rhs[ColToRowIndex(col)] = coeff;
}
// It is faster to iterate this way (instead of i : Column(col)) because of
// cache locality. Note that the floating-point computations are exactly the
// same in both cases.
const EntryIndex i_end = starts_[col];
for (EntryIndex i(starts_[col + 1] - 1); i >= i_end; --i) {
rhs[entry_rows[i]] -= coeff * entry_coefficients[i];
}
}
}
void TriangularMatrix::TransposeUpperSolve(DenseColumn* rhs) const {
RETURN_IF_NULL(rhs);
if (all_diagonal_coefficients_are_one_) {
TransposeUpperSolveInternal<true>(rhs->view());
} else {
TransposeUpperSolveInternal<false>(rhs->view());
}
}
template <bool diagonal_of_ones>
void TriangularMatrix::TransposeUpperSolveInternal(
DenseColumn::View rhs) const {
const ColIndex end = num_cols_;
const auto starts = starts_.view();
const auto entry_rows = rows_.view();
const auto entry_coefficients = coefficients_.view();
const auto diagonal_coefficients = diagonal_coefficients_.view();
EntryIndex i = starts_[first_non_identity_column_];
for (ColIndex col(first_non_identity_column_); col < end; ++col) {
Fractional sum = rhs[ColToRowIndex(col)];
// Note that this is a bit faster than the simpler
// for (const EntryIndex i : Column(col)) {
// EntryIndex i is explicitly not modified in outer iterations, since
// the last entry in column col is stored contiguously just before the
// first entry in column col+1.
const EntryIndex i_end = starts[col + 1];
const EntryIndex shifted_end = i_end - 3;
for (; i < shifted_end; i += 4) {
sum -= entry_coefficients[i] * rhs[entry_rows[i]] +
entry_coefficients[i + 1] * rhs[entry_rows[i + 1]] +
entry_coefficients[i + 2] * rhs[entry_rows[i + 2]] +
entry_coefficients[i + 3] * rhs[entry_rows[i + 3]];
}
if (i < i_end) {
sum -= entry_coefficients[i] * rhs[entry_rows[i]];
if (i + 1 < i_end) {
sum -= entry_coefficients[i + 1] * rhs[entry_rows[i + 1]];
if (i + 2 < i_end) {
sum -= entry_coefficients[i + 2] * rhs[entry_rows[i + 2]];
}
}
i = i_end;
}
rhs[ColToRowIndex(col)] =
diagonal_of_ones ? sum : sum / diagonal_coefficients[col];
}
}
void TriangularMatrix::TransposeLowerSolve(DenseColumn* rhs) const {
RETURN_IF_NULL(rhs);
if (all_diagonal_coefficients_are_one_) {
TransposeLowerSolveInternal<true>(rhs->view());
} else {
TransposeLowerSolveInternal<false>(rhs->view());
}
}
template <bool diagonal_of_ones>
void TriangularMatrix::TransposeLowerSolveInternal(
DenseColumn::View rhs) const {
const ColIndex end = first_non_identity_column_;
// We optimize a bit the solve by skipping the last 0.0 positions.
ColIndex col = num_cols_ - 1;
while (col >= end && rhs[ColToRowIndex(col)] == 0.0) {
--col;
}
const auto starts = starts_.view();
const auto diagonal_coeffs = diagonal_coefficients_.view();
const auto entry_rows = rows_.view();
const auto entry_coefficients = coefficients_.view();
EntryIndex i = starts[col + 1] - 1;
for (; col >= end; --col) {
Fractional sum = rhs[ColToRowIndex(col)];
// Note that this is a bit faster than the simpler
// for (const EntryIndex i : Column(col)) {
// mainly because we iterate in a good direction for the cache.
// EntryIndex i is explicitly not modified in outer iterations, since
// the last entry in column col is stored contiguously just before the
// first entry in column col+1.
const EntryIndex i_end = starts[col];
const EntryIndex shifted_end = i_end + 3;
for (; i >= shifted_end; i -= 4) {
sum -= entry_coefficients[i] * rhs[entry_rows[i]] +
entry_coefficients[i - 1] * rhs[entry_rows[i - 1]] +
entry_coefficients[i - 2] * rhs[entry_rows[i - 2]] +
entry_coefficients[i - 3] * rhs[entry_rows[i - 3]];
}
if (i >= i_end) {
sum -= entry_coefficients[i] * rhs[entry_rows[i]];
if (i >= i_end + 1) {
sum -= entry_coefficients[i - 1] * rhs[entry_rows[i - 1]];
if (i >= i_end + 2) {
sum -= entry_coefficients[i - 2] * rhs[entry_rows[i - 2]];
}
}
i = i_end - 1;
}
rhs[ColToRowIndex(col)] =
diagonal_of_ones ? sum : sum / diagonal_coeffs[col];
}
}
void TriangularMatrix::HyperSparseSolve(DenseColumn* rhs,
RowIndexVector* non_zero_rows) const {
RETURN_IF_NULL(rhs);
if (all_diagonal_coefficients_are_one_) {
HyperSparseSolveInternal<true>(rhs->view(), non_zero_rows);
} else {
HyperSparseSolveInternal<false>(rhs->view(), non_zero_rows);
}
}
template <bool diagonal_of_ones>
void TriangularMatrix::HyperSparseSolveInternal(
DenseColumn::View rhs, RowIndexVector* non_zero_rows) const {
int new_size = 0;
const auto entry_rows = rows_.view();
const auto entry_coefficients = coefficients_.view();
for (const RowIndex row : *non_zero_rows) {
if (rhs[row] == 0.0) continue;
const ColIndex row_as_col = RowToColIndex(row);
const Fractional coeff =
diagonal_of_ones ? rhs[row]
: rhs[row] / diagonal_coefficients_[row_as_col];
rhs[row] = coeff;
for (const EntryIndex i : Column(row_as_col)) {
rhs[entry_rows[i]] -= coeff * entry_coefficients[i];
}
(*non_zero_rows)[new_size] = row;
++new_size;
}
non_zero_rows->resize(new_size);
}
void TriangularMatrix::HyperSparseSolveWithReversedNonZeros(
DenseColumn* rhs, RowIndexVector* non_zero_rows) const {
RETURN_IF_NULL(rhs);
if (all_diagonal_coefficients_are_one_) {
HyperSparseSolveWithReversedNonZerosInternal<true>(rhs->view(),
non_zero_rows);
} else {
HyperSparseSolveWithReversedNonZerosInternal<false>(rhs->view(),
non_zero_rows);
}
}