Storm 2.0.0.3
A Modern Probabilistic Model Checker
Loading...
Searching...
No Matches
SparseMatrix.cpp
Go to the documentation of this file.
2
3#include <algorithm>
4#include <iterator>
5
24
25namespace storm {
26namespace storage {
27
28template<typename IndexType, typename ValueType>
29MatrixEntry<IndexType, ValueType>::MatrixEntry(IndexType column, ValueType value) : entry(column, value) {
30 // Intentionally left empty.
31}
32
33template<typename IndexType, typename ValueType>
34MatrixEntry<IndexType, ValueType>::MatrixEntry(std::pair<IndexType, ValueType>&& pair) : entry(std::move(pair)) {
35 // Intentionally left empty.
36}
37
38template<typename IndexType, typename ValueType>
40 return this->entry.first;
41}
42
43template<typename IndexType, typename ValueType>
44void MatrixEntry<IndexType, ValueType>::setColumn(IndexType const& column) {
45 this->entry.first = column;
46}
47
48template<typename IndexType, typename ValueType>
50 return this->entry.second;
51}
52
53template<typename IndexType, typename ValueType>
54void MatrixEntry<IndexType, ValueType>::setValue(ValueType const& value) {
55 this->entry.second = value;
56}
57
58template<typename IndexType, typename ValueType>
59std::pair<IndexType, ValueType> const& MatrixEntry<IndexType, ValueType>::getColumnValuePair() const {
60 return this->entry;
61}
62
63template<typename IndexType, typename ValueType>
67
68template<typename IndexType, typename ValueType>
70 return this->entry.first == other.entry.first && this->entry.second == other.entry.second;
71}
72
73template<typename IndexType, typename ValueType>
75 return !(*this == other);
76}
77
78template<typename IndexTypePrime, typename ValueTypePrime>
79std::ostream& operator<<(std::ostream& out, MatrixEntry<IndexTypePrime, ValueTypePrime> const& entry) {
80 out << "(" << entry.getColumn() << ", " << entry.getValue() << ")";
81 return out;
82}
83
84template<typename ValueType>
85SparseMatrixBuilder<ValueType>::SparseMatrixBuilder(index_type rows, index_type columns, index_type entries, bool forceDimensions, bool hasCustomRowGrouping,
86 index_type rowGroups)
87 : initialRowCountSet(rows != 0),
88 initialRowCount(rows),
89 initialColumnCountSet(columns != 0),
90 initialColumnCount(columns),
91 initialEntryCountSet(entries != 0),
92 initialEntryCount(entries),
93 forceInitialDimensions(forceDimensions),
94 hasCustomRowGrouping(hasCustomRowGrouping),
95 initialRowGroupCountSet(rowGroups != 0),
96 initialRowGroupCount(rowGroups),
97 rowGroupIndices(),
98 columnsAndValues(),
99 rowIndications(),
100 currentEntryCount(0),
101 lastRow(0),
102 lastColumn(0),
103 highestColumn(0),
104 currentRowGroupCount(0) {
105 // Prepare the internal storage.
106 if (initialRowCountSet) {
107 rowIndications.reserve(initialRowCount + 1);
108 }
109 if (initialEntryCountSet) {
110 columnsAndValues.reserve(initialEntryCount);
111 }
112 if (hasCustomRowGrouping) {
113 rowGroupIndices = std::vector<index_type>();
114 }
115 if (initialRowGroupCountSet && hasCustomRowGrouping) {
116 rowGroupIndices.get().reserve(initialRowGroupCount + 1);
117 }
118 rowIndications.push_back(0);
119}
120
121template<typename ValueType>
123 : initialRowCountSet(false),
124 initialRowCount(0),
125 initialColumnCountSet(false),
126 initialColumnCount(0),
127 initialEntryCountSet(false),
128 initialEntryCount(0),
129 forceInitialDimensions(false),
130 hasCustomRowGrouping(!matrix.trivialRowGrouping),
131 initialRowGroupCountSet(false),
132 initialRowGroupCount(0),
133 rowGroupIndices(),
134 columnsAndValues(std::move(matrix.columnsAndValues)),
135 rowIndications(std::move(matrix.rowIndications)),
136 currentEntryCount(matrix.entryCount),
137 currentRowGroupCount() {
138 lastRow = matrix.rowCount == 0 ? 0 : matrix.rowCount - 1;
139 lastColumn = columnsAndValues.empty() ? 0 : columnsAndValues.back().getColumn();
140 highestColumn = matrix.getColumnCount() == 0 ? 0 : matrix.getColumnCount() - 1;
141
142 // If the matrix has a custom row grouping, we move it and remove the last element to make it 'open' again.
143 if (hasCustomRowGrouping) {
144 rowGroupIndices = std::move(matrix.rowGroupIndices);
145 if (!rowGroupIndices->empty()) {
146 rowGroupIndices.get().pop_back();
147 }
148 currentRowGroupCount = rowGroupIndices->empty() ? 0 : rowGroupIndices.get().size() - 1;
149 }
150
151 // Likewise, we need to 'open' the row indications again.
152 if (!rowIndications.empty()) {
153 rowIndications.pop_back();
154 }
155 // The (open) row indications always contain the start of the current row, which is the case also if the matrix did not have any rows.
156 if (rowIndications.empty()) {
157 rowIndications.push_back(0);
158 }
159}
160
161namespace {
167template<typename ValueType>
169 typename SparseMatrixBuilder<ValueType>::index_type column, ValueType const& existingValue, ValueType const& newValue) {
170 using AccumulationMode = typename SparseMatrixBuilder<ValueType>::AccumulationMode;
171 switch (mode) {
172 case AccumulationMode::Sum:
173 return existingValue + newValue;
174 case AccumulationMode::ExpectSame:
175 STORM_LOG_THROW(existingValue == newValue, storm::exceptions::InvalidArgumentException,
176 "Multiple different values (" << existingValue << " and " << newValue << ") added to matrix entry in row " << row << " and column "
177 << column << ", but all values for the same entry are expected to be equal.");
178 return existingValue;
179 case AccumulationMode::ExpectNone:
180 STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException,
181 "Multiple values added to matrix entry in row " << row << " and column " << column << ", but no duplicate entries are expected.");
182 }
183 STORM_LOG_ASSERT(false, "Unhandled accumulation mode.");
184 return existingValue;
185}
186} // namespace
187
188template<typename ValueType>
190 accumulationMode = mode;
191}
192
193template<typename ValueType>
197
198template<typename ValueType>
199void SparseMatrixBuilder<ValueType>::addNextValue(index_type row, index_type column, ValueType const& value) {
200 // Check that we did not move backwards wrt. the row.
201 STORM_LOG_THROW(row >= lastRow, storm::exceptions::InvalidArgumentException,
202 "Adding an element in row " << row << ", but an element in row " << lastRow << " has already been added.");
203 STORM_LOG_ASSERT(columnsAndValues.size() == currentEntryCount, "Unexpected size of columnsAndValues vector.");
204
205 // Check if a diagonal entry shall be inserted before
206 if (pendingDiagonalEntry) {
207 index_type diagColumn = hasCustomRowGrouping ? currentRowGroupCount - 1 : lastRow;
208 if (row > lastRow || column >= diagColumn) {
209 ValueType diagValue = std::move(pendingDiagonalEntry.get());
210 pendingDiagonalEntry = boost::none; // clear now, so addNextValue works properly
211 // Add the pending diagonal value now. If the currently added value coincides with the diagonal entry,
212 // the two values are combined when the current value is added below.
213 addNextValue(lastRow, diagColumn, diagValue);
214 }
215 }
216
217 // In case we did not expect this value, we throw an exception.
218 if (forceInitialDimensions) {
219 STORM_LOG_THROW(!initialRowCountSet || row < initialRowCount, storm::exceptions::OutOfRangeException,
220 "Cannot insert value at illegal row " << row << ".");
221 STORM_LOG_THROW(!initialColumnCountSet || column < initialColumnCount, storm::exceptions::OutOfRangeException,
222 "Cannot insert value at illegal column " << column << ".");
223 }
224
225 // If we switched to another row, we have to adjust the missing entries in the row indices vector.
226 if (row != lastRow) {
227 STORM_LOG_ASSERT(rowIndications.size() == lastRow + 1, "Row indications size mismatch.");
228 rowIndications.resize(row + 1, currentEntryCount);
229 lastRow = row;
230 }
231
232 // The current row starts at rowIndications.back() and is kept sorted (without duplicates) at all times.
233 bool const rowHasEntries = rowIndications.back() < currentEntryCount;
234 if (!rowHasEntries || columnsAndValues.back().getColumn() < column) {
235 // The common case: The row is still empty or the column is larger than all columns in the row so far.
236 columnsAndValues.emplace_back(column, value);
237 ++currentEntryCount;
238 } else if (columnsAndValues.back().getColumn() == column) {
239 // The element is in the same column as the previous entry.
240 columnsAndValues.back().setValue(accumulate(accumulationMode, row, column, columnsAndValues.back().getValue(), value));
241 } else {
242 // The element was not inserted in the correct order. As the row is sorted, we find the correct position via binary search.
243 auto const rowBegin = columnsAndValues.begin() + rowIndications.back();
244 auto position =
245 std::lower_bound(rowBegin, columnsAndValues.end(), column,
246 [](storm::storage::MatrixEntry<index_type, ValueType> const& entry, index_type col) { return entry.getColumn() < col; });
247 if (position != columnsAndValues.end() && position->getColumn() == column) {
248 position->setValue(accumulate(accumulationMode, row, column, position->getValue(), value));
249 } else {
250 STORM_LOG_TRACE("Column " << column << " is added out-of-order to row " << row << ".");
251 columnsAndValues.emplace(position, column, value);
252 ++currentEntryCount;
253 }
254 }
255 // Because the row is sorted, the last entry has the highest column.
256 lastColumn = columnsAndValues.back().getColumn();
257 highestColumn = std::max(highestColumn, column);
258
259 if (forceInitialDimensions) {
260 STORM_LOG_THROW(!initialEntryCountSet || currentEntryCount <= initialEntryCount, storm::exceptions::OutOfRangeException,
261 "Too many entries in matrix, expected only " << initialEntryCount << ".");
262 }
263}
264
265template<typename ValueType>
267 STORM_LOG_THROW(hasCustomRowGrouping, storm::exceptions::InvalidStateException, "Matrix was not created to have a custom row grouping.");
268 STORM_LOG_THROW(startingRow >= lastRow, storm::exceptions::InvalidStateException, "Illegal row group with negative size.");
269
270 // If there still is a pending diagonal entry, we need to add it now (otherwise, the correct diagonal column will be unclear)
271 if (pendingDiagonalEntry) {
272 STORM_LOG_ASSERT(currentRowGroupCount > 0, "Diagonal entry was set before opening the first row group.");
273 index_type diagColumn = currentRowGroupCount - 1;
274 ValueType diagValue = std::move(pendingDiagonalEntry.get());
275 pendingDiagonalEntry = boost::none; // clear now, so addNextValue works properly
276 addNextValue(lastRow, diagColumn, diagValue);
277 }
278
279 rowGroupIndices.get().push_back(startingRow);
280 ++currentRowGroupCount;
281
282 // Handle the case where the previous row group ends with one or more empty rows
283 if (lastRow + 1 < startingRow) {
284 // Close all rows from the most recent one to the starting row.
285 STORM_LOG_ASSERT(rowIndications.size() == lastRow + 1, "Row indications size mismatch.");
286 rowIndications.resize(startingRow, currentEntryCount);
287 // Reset the most recently seen row/column to allow for proper insertion of the following elements.
288 lastRow = startingRow - 1;
289 lastColumn = 0;
290 }
291}
292
293template<typename ValueType>
295 index_type overriddenRowGroupCount) {
296 // If there still is a pending diagonal entry, we need to add it now
297 if (pendingDiagonalEntry) {
298 index_type diagColumn = hasCustomRowGrouping ? currentRowGroupCount - 1 : lastRow;
299 ValueType diagValue = std::move(pendingDiagonalEntry.get());
300 pendingDiagonalEntry = boost::none; // clear now, so addNextValue works properly
301 addNextValue(lastRow, diagColumn, diagValue);
302 }
303
304 bool hasEntries = currentEntryCount != 0;
305
306 uint_fast64_t rowCount = hasEntries ? lastRow + 1 : 0;
307
308 // If the last row group was empty, we need to add one more to the row count, because otherwise this empty row is not counted.
309 if (hasCustomRowGrouping) {
310 if (lastRow < rowGroupIndices->back()) {
311 ++rowCount;
312 }
313 }
314
315 if (overriddenRowCount != 0) {
316 STORM_LOG_THROW(rowCount <= overriddenRowCount, storm::exceptions::InvalidStateException,
317 "Expected not more than " << overriddenRowCount << " rows, but got " << rowCount << ".");
318 }
319 if (initialRowCountSet && forceInitialDimensions) {
320 STORM_LOG_THROW(rowCount <= initialRowCount, storm::exceptions::InvalidStateException,
321 "Expected not more than " << initialRowCount << " rows, but got " << rowCount << ".");
322 rowCount = std::max(rowCount, initialRowCount);
323 }
324 rowCount = std::max(rowCount, overriddenRowCount);
325
326 // If the current row count was overridden, we may need to add empty rows.
327 for (index_type i = lastRow + 1; i < rowCount; ++i) {
328 rowIndications.push_back(currentEntryCount);
329 }
330
331 // We put a sentinel element at the last position of the row indices array. This eases iteration work,
332 // as now the indices of row i are always between rowIndications[i] and rowIndications[i + 1], also for
333 // the first and last row.
334 if (rowCount > 0) {
335 rowIndications.push_back(currentEntryCount);
336 }
337 STORM_LOG_ASSERT(rowCount == rowIndications.size() - 1,
338 "Wrong sizes of row indications vector: (Rowcount) " << rowCount << " != " << (rowIndications.size() - 1) << " (Vector).");
339 uint_fast64_t columnCount = hasEntries ? highestColumn + 1 : 0;
340 if (overriddenColumnCount != 0) {
341 STORM_LOG_THROW(columnCount <= overriddenColumnCount, storm::exceptions::InvalidStateException,
342 "Expected not more than " << overriddenColumnCount << " columns, but got " << columnCount << ".");
343 }
344 if (initialColumnCountSet && forceInitialDimensions) {
345 STORM_LOG_THROW(columnCount <= initialColumnCount, storm::exceptions::InvalidStateException,
346 "Expected not more than " << initialColumnCount << " columns, but got " << columnCount << ".");
347 columnCount = std::max(columnCount, initialColumnCount);
348 }
349 columnCount = std::max(columnCount, overriddenColumnCount);
350
351 uint_fast64_t entryCount = currentEntryCount;
352 if (initialEntryCountSet && forceInitialDimensions) {
353 STORM_LOG_THROW(entryCount == initialEntryCount, storm::exceptions::InvalidStateException,
354 "Expected " << initialEntryCount << " entries, but got " << entryCount << ".");
355 }
356
357 // Check whether row groups are missing some entries.
358 if (hasCustomRowGrouping) {
359 uint_fast64_t rowGroupCount = currentRowGroupCount;
360 if (overriddenRowGroupCount != 0) {
361 STORM_LOG_THROW(rowGroupCount <= overriddenRowGroupCount, storm::exceptions::InvalidStateException,
362 "Expected not more than " << overriddenRowGroupCount << " row groups, but got " << rowGroupCount << ".");
363 }
364 if (initialRowGroupCountSet && forceInitialDimensions) {
365 STORM_LOG_THROW(rowGroupCount <= initialRowGroupCount, storm::exceptions::InvalidStateException,
366 "Expected not more than " << initialRowGroupCount << " row groups, but got " << rowGroupCount << ".");
367 rowGroupCount = std::max(rowGroupCount, initialRowGroupCount);
368 }
369 rowGroupCount = std::max(rowGroupCount, overriddenRowGroupCount);
370
371 for (index_type i = currentRowGroupCount; i <= rowGroupCount; ++i) {
372 rowGroupIndices.get().push_back(rowCount);
373 }
374 }
375
376 return SparseMatrix<ValueType>(columnCount, std::move(rowIndications), std::move(columnsAndValues), std::move(rowGroupIndices));
377}
378
379template<typename ValueType>
383
384template<typename ValueType>
386 if (this->hasCustomRowGrouping) {
387 return currentRowGroupCount;
388 } else {
389 return getLastRow() + 1;
390 }
391}
392
393template<typename ValueType>
397
398// Debug method for printing the current matrix
399template<typename ValueType>
400void print(std::vector<typename SparseMatrix<ValueType>::index_type> const& rowGroupIndices,
401 std::vector<MatrixEntry<typename SparseMatrix<ValueType>::index_type, typename SparseMatrix<ValueType>::value_type>> const& columnsAndValues,
402 std::vector<typename SparseMatrix<ValueType>::index_type> const& rowIndications) {
403 typename SparseMatrix<ValueType>::index_type endGroups;
405 // Iterate over all row groups.
406 for (typename SparseMatrix<ValueType>::index_type group = 0; group < rowGroupIndices.size(); ++group) {
407 std::cout << "\t---- group " << group << "/" << (rowGroupIndices.size() - 1) << " ---- \n";
408 endGroups = group < rowGroupIndices.size() - 1 ? rowGroupIndices[group + 1] : rowIndications.size();
409 // Iterate over all rows in a row group
410 for (typename SparseMatrix<ValueType>::index_type i = rowGroupIndices[group]; i < endGroups; ++i) {
411 endRows = i < rowIndications.size() - 1 ? rowIndications[i + 1] : columnsAndValues.size();
412 // Print the actual row.
413 std::cout << "Row " << i << " (" << rowIndications[i] << " - " << endRows << ")"
414 << ": ";
415 for (typename SparseMatrix<ValueType>::index_type pos = rowIndications[i]; pos < endRows; ++pos) {
416 std::cout << "(" << columnsAndValues[pos].getColumn() << ": " << columnsAndValues[pos].getValue() << ") ";
417 }
418 std::cout << '\n';
419 }
420 }
421}
422
423template<typename ValueType>
424void SparseMatrixBuilder<ValueType>::replaceColumns(std::vector<index_type> const& replacements, index_type offset) {
425 index_type maxColumn = 0;
426
427 for (index_type row = 0; row < rowIndications.size(); ++row) {
428 bool changed = false;
429 auto startRow = std::next(columnsAndValues.begin(), rowIndications[row]);
430 auto endRow = row < rowIndications.size() - 1 ? std::next(columnsAndValues.begin(), rowIndications[row + 1]) : columnsAndValues.end();
431 for (auto entry = startRow; entry != endRow; ++entry) {
432 if (entry->getColumn() >= offset) {
433 // Change column
434 entry->setColumn(replacements[entry->getColumn() - offset]);
435 changed = true;
437 maxColumn = std::max(maxColumn, entry->getColumn());
438 }
439 if (changed) {
440 // Sort columns in row
441 std::sort(startRow, endRow,
443 // Assert no equal elements
444 STORM_LOG_ASSERT(std::is_sorted(startRow, endRow,
446 return a.getColumn() < b.getColumn();
447 }),
448 "Columns not sorted.");
449 }
451
452 highestColumn = maxColumn;
453 lastColumn = columnsAndValues.empty() ? 0 : columnsAndValues.back().getColumn();
454}
455
456template<typename ValueType>
458 STORM_LOG_THROW(row >= lastRow, storm::exceptions::InvalidArgumentException,
459 "Adding a diagonal element in row " << row << ", but an element in row " << lastRow << " has already been added.");
460 if (pendingDiagonalEntry) {
461 if (row == lastRow) {
462 // Combine the two diagonal entries, nothing else to be done.
463 index_type column = hasCustomRowGrouping ? currentRowGroupCount - 1 : lastRow;
464 pendingDiagonalEntry = accumulate(accumulationMode, row, column, pendingDiagonalEntry.get(), value);
465 return;
466 } else {
467 // add the pending entry
468 index_type column = hasCustomRowGrouping ? currentRowGroupCount - 1 : lastRow;
469 ValueType diagValue = std::move(pendingDiagonalEntry.get());
470 pendingDiagonalEntry = boost::none; // clear now, so addNextValue works properly
471 addNextValue(lastRow, column, diagValue);
472 }
473 }
474 pendingDiagonalEntry = value;
475 if (lastRow != row) {
476 STORM_LOG_ASSERT(rowIndications.size() == lastRow + 1, "Row indications size mismatch.");
477 rowIndications.resize(row + 1, currentEntryCount);
478 lastRow = row;
479 lastColumn = 0;
480 }
481}
482
483template<typename ValueType>
484SparseMatrix<ValueType>::rows::rows(iterator begin, index_type entryCount) : beginIterator(begin), entryCount(entryCount) {
485 // Intentionally left empty.
486}
487
488template<typename ValueType>
492
493template<typename ValueType>
495 return beginIterator + entryCount;
496}
497
498template<typename ValueType>
502
503template<typename ValueType>
504SparseMatrix<ValueType>::const_rows::const_rows(const_iterator begin, index_type entryCount) : beginIterator(begin), entryCount(entryCount) {
505 // Intentionally left empty.
506}
507
508template<typename ValueType>
512
513template<typename ValueType>
515 return beginIterator + entryCount;
516}
517
518template<typename ValueType>
522
523template<typename ValueType>
525 : rowCount(0), columnCount(0), entryCount(0), nonzeroEntryCount(0), columnsAndValues(), rowIndications(), rowGroupIndices() {
526 // Intentionally left empty.
527}
528
529template<typename ValueType>
531 : rowCount(other.rowCount),
532 columnCount(other.columnCount),
533 entryCount(other.entryCount),
534 nonzeroEntryCount(other.nonzeroEntryCount),
535 columnsAndValues(other.columnsAndValues),
536 rowIndications(other.rowIndications),
537 trivialRowGrouping(other.trivialRowGrouping),
538 rowGroupIndices(other.rowGroupIndices) {
539 // Intentionally left empty.
540}
541
542template<typename ValueType>
543SparseMatrix<ValueType>::SparseMatrix(SparseMatrix<value_type> const& other, bool insertDiagonalElements) {
544 storm::storage::BitVector rowConstraint(other.getRowCount(), true);
545 storm::storage::BitVector columnConstraint(other.getColumnCount(), true);
546 *this = other.getSubmatrix(false, rowConstraint, columnConstraint, insertDiagonalElements);
547}
548
549template<typename ValueType>
551 : rowCount(other.rowCount),
552 columnCount(other.columnCount),
553 entryCount(other.entryCount),
554 nonzeroEntryCount(other.nonzeroEntryCount),
555 columnsAndValues(std::move(other.columnsAndValues)),
556 rowIndications(std::move(other.rowIndications)),
557 trivialRowGrouping(other.trivialRowGrouping),
558 rowGroupIndices(std::move(other.rowGroupIndices)) {
559 // Now update the source matrix
560 other.rowCount = 0;
561 other.columnCount = 0;
562 other.entryCount = 0;
563}
564
565template<typename ValueType>
566SparseMatrix<ValueType>::SparseMatrix(index_type columnCount, std::vector<index_type> const& rowIndications,
567 std::vector<MatrixEntry<index_type, ValueType>> const& columnsAndValues,
568 boost::optional<std::vector<index_type>> const& rowGroupIndices)
569 : rowCount(rowIndications.size() - 1),
570 columnCount(columnCount),
571 entryCount(columnsAndValues.size()),
572 nonzeroEntryCount(0),
573 columnsAndValues(columnsAndValues),
574 rowIndications(rowIndications),
575 trivialRowGrouping(!rowGroupIndices),
576 rowGroupIndices(rowGroupIndices) {
578}
580template<typename ValueType>
581SparseMatrix<ValueType>::SparseMatrix(index_type columnCount, std::vector<index_type>&& rowIndications,
582 std::vector<MatrixEntry<index_type, ValueType>>&& columnsAndValues,
583 boost::optional<std::vector<index_type>>&& rowGroupIndices)
584 : columnCount(columnCount),
585 nonzeroEntryCount(0),
586 columnsAndValues(std::move(columnsAndValues)),
587 rowIndications(std::move(rowIndications)),
588 rowGroupIndices(std::move(rowGroupIndices)) {
589 // Initialize some variables here which depend on other variables
590 // This way we are more robust against different initialization orders
591 this->rowCount = this->rowIndications.size() - 1;
592 this->entryCount = this->columnsAndValues.size();
593 this->trivialRowGrouping = !this->rowGroupIndices;
595}
596
597template<typename ValueType>
599 // Only perform assignment if source and target are not the same.
600 if (this != &other) {
601 rowCount = other.rowCount;
602 columnCount = other.columnCount;
603 entryCount = other.entryCount;
604 nonzeroEntryCount = other.nonzeroEntryCount;
605
606 columnsAndValues = other.columnsAndValues;
607 rowIndications = other.rowIndications;
608 rowGroupIndices = other.rowGroupIndices;
609 trivialRowGrouping = other.trivialRowGrouping;
610 }
611 return *this;
613
614template<typename ValueType>
616 // Only perform assignment if source and target are not the same.
617 if (this != &other) {
618 rowCount = other.rowCount;
619 columnCount = other.columnCount;
620 entryCount = other.entryCount;
621 nonzeroEntryCount = other.nonzeroEntryCount;
622
623 columnsAndValues = std::move(other.columnsAndValues);
624 rowIndications = std::move(other.rowIndications);
625 rowGroupIndices = std::move(other.rowGroupIndices);
626 trivialRowGrouping = other.trivialRowGrouping;
627 }
628 return *this;
629}
631template<typename ValueType>
633 if (this == &other) {
634 return true;
635 }
636
637 bool equalityResult = true;
638
639 equalityResult &= this->getRowCount() == other.getRowCount();
640 if (!equalityResult) {
641 return false;
642 }
643 equalityResult &= this->getColumnCount() == other.getColumnCount();
644 if (!equalityResult) {
645 return false;
646 }
648 equalityResult &= this->getRowGroupIndices() == other.getRowGroupIndices();
649 } else {
650 equalityResult &= this->hasTrivialRowGrouping() && other.hasTrivialRowGrouping();
651 }
652 if (!equalityResult) {
653 return false;
655
656 // For the actual contents, we need to do a little bit more work, because we want to ignore elements that
657 // are set to zero, as they may be represented implicitly in the other matrix.
658 for (index_type row = 0; row < this->getRowCount(); ++row) {
659 const_iterator it1 = this->begin(row), ite1 = this->end(row), it2 = other.begin(row), ite2 = other.end(row);
660 while (true) {
661 // Skip over all zero entries in both rows.
662 while (it1 != ite1 && storm::utility::isZero(it1->getValue())) {
663 ++it1;
664 }
665 while (it2 != ite2 && storm::utility::isZero(it2->getValue())) {
666 ++it2;
667 }
668 if (it1 == ite1 || it2 == ite2) {
669 // The rows are equal iff both have no further non-zero entries.
670 if (it1 != ite1 || it2 != ite2) {
671 return false;
672 }
673 break;
674 }
675 if (it1->getColumn() != it2->getColumn() || it1->getValue() != it2->getValue()) {
676 return false;
677 }
678 ++it1;
679 ++it2;
680 }
681 }
682
683 return equalityResult;
685
686template<typename ValueType>
690
691template<typename ValueType>
695
696template<typename ValueType>
700
701template<typename ValueType>
703 if (!this->hasTrivialRowGrouping()) {
704 index_type result = 0;
705 for (auto row : this->getRowGroupIndices(group)) {
706 result += getRowEntryCount(row);
707 }
708 return result;
709 } else {
710 return getRowEntryCount(group);
711 }
712}
713
714template<typename ValueType>
716 return (this->rowIndications[row + 1] - this->rowIndications[row]);
717}
718
719template<typename ValueType>
721 return nonzeroEntryCount;
722}
724template<typename ValueType>
726 this->nonzeroEntryCount = 0;
727 for (auto const& element : *this) {
728 if (element.getValue() != storm::utility::zero<ValueType>()) {
729 ++this->nonzeroEntryCount;
730 }
731 }
732}
733
734template<typename ValueType>
735void SparseMatrix<ValueType>::updateNonzeroEntryCount(std::make_signed<index_type>::type difference) {
736 this->nonzeroEntryCount += difference;
737}
738
739template<typename ValueType>
741 this->nonzeroEntryCount = 0;
742 this->columnCount = 0;
743 for (auto const& element : *this) {
744 if (element.getValue() != storm::utility::zero<ValueType>()) {
745 ++this->nonzeroEntryCount;
746 this->columnCount = std::max(element.getColumn() + 1, this->columnCount);
747 }
748 }
749}
751template<typename ValueType>
753 if (!this->hasTrivialRowGrouping()) {
754 return rowGroupIndices.get().size() - 1;
755 } else {
756 return rowCount;
757 }
758}
759
760template<typename ValueType>
762 return this->getRowGroupIndices()[group + 1] - this->getRowGroupIndices()[group];
763}
764
765template<typename ValueType>
767 if (this->hasTrivialRowGrouping()) {
768 return 1;
769 }
770 index_type res = 0;
771 index_type previousGroupStart = 0;
772 for (auto const& i : rowGroupIndices.get()) {
773 res = std::max(res, i - previousGroupStart);
774 previousGroupStart = i;
775 }
776 return res;
777}
778
779template<typename ValueType>
781 if (this->hasTrivialRowGrouping()) {
782 return groupConstraint.getNumberOfSetBits();
783 }
784 index_type numRows = 0;
785 index_type rowGroupIndex = groupConstraint.getNextSetIndex(0);
786 while (rowGroupIndex < this->getRowGroupCount()) {
787 index_type start = this->getRowGroupIndices()[rowGroupIndex];
788 rowGroupIndex = groupConstraint.getNextUnsetIndex(rowGroupIndex + 1);
789 index_type end = this->getRowGroupIndices()[rowGroupIndex];
790 // All rows with index in [start,end) are selected.
791 numRows += end - start;
792 rowGroupIndex = groupConstraint.getNextSetIndex(rowGroupIndex + 1);
793 }
794 return numRows;
795}
796
797template<typename ValueType>
798std::vector<typename SparseMatrix<ValueType>::index_type> const& SparseMatrix<ValueType>::getRowGroupIndices() const {
799 // If there is no current row grouping, we need to create it.
800 if (!this->rowGroupIndices) {
801 STORM_LOG_ASSERT(trivialRowGrouping, "Only trivial row-groupings can be constructed on-the-fly.");
802 this->rowGroupIndices = storm::utility::vector::buildVectorForRange(static_cast<index_type>(0), this->getRowGroupCount() + 1);
804 return rowGroupIndices.get();
805}
806
807template<typename ValueType>
808std::vector<typename SparseMatrix<ValueType>::index_type> const& SparseMatrix<ValueType>::getRowIndices() const {
809 return rowIndications;
810}
812template<typename ValueType>
813boost::integer_range<typename SparseMatrix<ValueType>::index_type> SparseMatrix<ValueType>::getRowGroupIndices(index_type group) const {
814 STORM_LOG_ASSERT(group < this->getRowGroupCount(),
815 "Invalid row group index:" << group << ". Only " << this->getRowGroupCount() << " row groups available.");
816 if (this->rowGroupIndices) {
817 return boost::irange(rowGroupIndices.get()[group], rowGroupIndices.get()[group + 1]);
818 } else {
819 return boost::irange(group, group + 1);
821}
822
823template<typename ValueType>
824std::vector<typename SparseMatrix<ValueType>::index_type> SparseMatrix<ValueType>::swapRowGroupIndices(std::vector<index_type>&& newRowGrouping) {
825 std::vector<index_type> result;
826 if (this->rowGroupIndices) {
827 result = std::move(rowGroupIndices.get());
828 rowGroupIndices = std::move(newRowGrouping);
830 return result;
831}
832
833template<typename ValueType>
834void SparseMatrix<ValueType>::setRowGroupIndices(std::vector<index_type> const& newRowGroupIndices) {
835 trivialRowGrouping = false;
836 rowGroupIndices = newRowGroupIndices;
837}
838
839template<typename ValueType>
841 return trivialRowGrouping;
843
844template<typename ValueType>
846 if (trivialRowGrouping) {
848 !rowGroupIndices || rowGroupIndices.get() == storm::utility::vector::buildVectorForRange(static_cast<index_type>(0), this->getRowGroupCount() + 1),
849 "Row grouping is supposed to be trivial but actually it is not.");
850 } else {
851 trivialRowGrouping = true;
852 rowGroupIndices = boost::none;
853 }
855
856template<typename ValueType>
858 storm::storage::BitVector res(this->getRowCount(), false);
859 for (uint64_t group : groupConstraint) {
860 res.setMultiple(getRowGroupIndices()[group], getRowGroupSize(group));
861 }
862 return res;
864
865template<typename ValueType>
867 storm::storage::BitVector const& columnConstraint) const {
868 storm::storage::BitVector result(this->getRowCount(), false);
869 for (uint64_t group : groupConstraint) {
870 for (auto row : this->getRowGroupIndices(group)) {
871 bool choiceSatisfiesColumnConstraint = true;
872 for (auto const& entry : this->getRow(row)) {
873 if (!columnConstraint.get(entry.getColumn())) {
874 choiceSatisfiesColumnConstraint = false;
875 break;
876 }
877 }
878 if (choiceSatisfiesColumnConstraint) {
879 result.set(row, true);
880 }
881 }
882 }
883 return result;
885
886template<typename ValueType>
888 STORM_LOG_ASSERT(!this->hasTrivialRowGrouping(), "Tried to get a row group filter but this matrix does not have row groups.");
889 storm::storage::BitVector result(this->getRowGroupCount(), false);
890 auto const& groupIndices = this->getRowGroupIndices();
891 if (setIfForAllRowsInGroup) {
892 for (uint64_t group = 0; group < this->getRowGroupCount(); ++group) {
893 if (rowConstraint.getNextUnsetIndex(groupIndices[group]) >= groupIndices[group + 1]) {
894 // All rows within this group are set
895 result.set(group, true);
896 }
897 }
898 } else {
899 for (uint64_t group = 0; group < this->getRowGroupCount(); ++group) {
900 if (rowConstraint.getNextSetIndex(groupIndices[group]) < groupIndices[group + 1]) {
901 // Some row is set
902 result.set(group, true);
903 }
904 }
906 return result;
907}
908
909template<typename ValueType>
911 // First transform ALL rows without dropping zero entries, then drop zero entries once
912 // This prevents iteration over the whole matrix every time an entry is set to zero.
913 for (uint64_t row : rows) {
914 makeRowDirac(row, row, false);
915 }
916 if (dropZeroEntries) {
917 this->dropZeroEntries();
918 }
919}
920
921template<typename ValueType>
923 // First transform ALL rows without dropping zero entries, then drop zero entries once.
924 // This prevents iteration over the whole matrix every time an entry is set to zero.
925 if (!this->hasTrivialRowGrouping()) {
926 for (uint64_t rowGroup : rowGroupConstraint) {
927 for (index_type row = this->getRowGroupIndices()[rowGroup]; row < this->getRowGroupIndices()[rowGroup + 1]; ++row) {
928 makeRowDirac(row, rowGroup, false);
929 }
930 }
931 } else {
932 for (uint64_t rowGroup : rowGroupConstraint) {
933 makeRowDirac(rowGroup, rowGroup, false);
934 }
935 }
937 this->dropZeroEntries();
938 }
939}
940
941template<typename ValueType>
943 iterator columnValuePtr = this->begin(row);
944 iterator columnValuePtrEnd = this->end(row);
945
946 // If the row has no elements in it, we cannot make it absorbing, because we would need to move all elements
947 // in the vector of nonzeros otherwise.
948 STORM_LOG_THROW(columnValuePtr < columnValuePtrEnd, storm::exceptions::InvalidStateException,
949 "Illegal call to SparseMatrix::makeRowDirac: cannot make row " << row << " absorbing, because there is no entry in this row.");
950 iterator lastColumnValuePtr = this->end(row) - 1;
951
952 // If there is at least one entry in this row, we can set it to one, modify its column value to the
953 // one given by the parameter and set all subsequent elements of this row to zero.
954 // However, we want to preserve that column indices within a row are ascending, so we pick an entry that is close to the desired column index
955 while (columnValuePtr->getColumn() < column && columnValuePtr != lastColumnValuePtr) {
956 if (!storm::utility::isZero(columnValuePtr->getValue())) {
957 --this->nonzeroEntryCount;
958 }
959 columnValuePtr->setValue(storm::utility::zero<ValueType>());
960 ++columnValuePtr;
962 // At this point, we have found the first entry whose column is >= the desired column (or the last entry of the row, if no such column exist)
963 if (storm::utility::isZero(columnValuePtr->getValue())) {
964 ++this->nonzeroEntryCount;
965 }
966 columnValuePtr->setValue(storm::utility::one<ValueType>());
967 columnValuePtr->setColumn(column);
968 for (++columnValuePtr; columnValuePtr != columnValuePtrEnd; ++columnValuePtr) {
969 if (!storm::utility::isZero(columnValuePtr->getValue())) {
970 --this->nonzeroEntryCount;
971 }
972 columnValuePtr->setValue(storm::utility::zero<ValueType>());
973 }
974 if (dropZeroEntries) {
975 this->dropZeroEntries();
976 }
977}
978
979template<typename ValueType>
981 const_iterator end1 = this->end(i1);
982 const_iterator end2 = this->end(i2);
983 const_iterator it1 = this->begin(i1);
984 const_iterator it2 = this->begin(i2);
985 for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
986 if (*it1 != *it2) {
987 return false;
988 }
989 }
990 if (it1 == end1 && it2 == end2) {
991 return true;
992 }
993 return false;
994}
995
996template<typename ValueType>
998 BitVector bv(this->getRowCount());
999 for (size_t rowgroup = 0; rowgroup < this->getRowGroupCount(); ++rowgroup) {
1000 for (size_t row1 = this->getRowGroupIndices().at(rowgroup); row1 < this->getRowGroupIndices().at(rowgroup + 1); ++row1) {
1001 for (size_t row2 = row1; row2 < this->getRowGroupIndices().at(rowgroup + 1); ++row2) {
1002 if (compareRows(row1, row2)) {
1003 bv.set(row2);
1004 }
1005 }
1007 }
1008 return bv;
1009}
1010
1011template<typename ValueType>
1013 if (row1 == row2) {
1014 return;
1015 }
1016
1017 // Get the index of the row that has more / less entries than the other.
1018 index_type largerRow = getRow(row1).getNumberOfEntries() > getRow(row2).getNumberOfEntries() ? row1 : row2;
1019 index_type smallerRow = largerRow == row1 ? row2 : row1;
1020 index_type rowSizeDifference = getRow(largerRow).getNumberOfEntries() - getRow(smallerRow).getNumberOfEntries();
1021
1022 // Save contents of larger row.
1023 auto copyRow = getRow(largerRow);
1024 std::vector<MatrixEntry<index_type, value_type>> largerRowContents(copyRow.begin(), copyRow.end());
1026 if (largerRow < smallerRow) {
1027 auto writeIt = getRows(largerRow, smallerRow + 1).begin();
1028
1029 // Write smaller row to its new position.
1030 for (auto& smallerRowEntry : getRow(smallerRow)) {
1031 *writeIt = std::move(smallerRowEntry);
1032 ++writeIt;
1033 }
1034
1035 // Write the intermediate rows into their correct position.
1036 if (!storm::utility::isZero(rowSizeDifference)) {
1037 for (auto& intermediateRowEntry : getRows(largerRow + 1, smallerRow)) {
1038 *writeIt = std::move(intermediateRowEntry);
1039 ++writeIt;
1040 }
1041 } else {
1042 // skip the intermediate rows
1043 writeIt = getRow(smallerRow).begin();
1044 }
1045
1046 // Write the larger row to its new position.
1047 for (auto& largerRowEntry : largerRowContents) {
1048 *writeIt = std::move(largerRowEntry);
1049 ++writeIt;
1050 }
1051
1052 STORM_LOG_ASSERT(writeIt == getRow(smallerRow).end(), "Unexpected position of write iterator.");
1053
1054 // Update the row indications to account for the shift of indices at where the rows now start.
1055 if (!storm::utility::isZero(rowSizeDifference)) {
1056 for (index_type row = largerRow + 1; row <= smallerRow; ++row) {
1057 rowIndications[row] -= rowSizeDifference;
1058 }
1059 }
1060 } else {
1061 auto writeIt = getRows(smallerRow, largerRow + 1).end() - 1;
1062
1063 // Write smaller row to its new position
1064 auto copyRow = getRow(smallerRow);
1065 for (auto smallerRowEntryIt = copyRow.end() - 1; smallerRowEntryIt != copyRow.begin() - 1; --smallerRowEntryIt) {
1066 *writeIt = std::move(*smallerRowEntryIt);
1067 --writeIt;
1069
1070 // Write the intermediate rows into their correct position.
1071 if (!storm::utility::isZero(rowSizeDifference)) {
1072 for (auto intermediateRowEntryIt = getRows(smallerRow + 1, largerRow).end() - 1;
1073 intermediateRowEntryIt != getRows(smallerRow + 1, largerRow).begin() - 1; --intermediateRowEntryIt) {
1074 *writeIt = std::move(*intermediateRowEntryIt);
1075 --writeIt;
1076 }
1077 } else {
1078 // skip the intermediate rows
1079 writeIt = getRow(smallerRow).end() - 1;
1080 }
1081
1082 // Write the larger row to its new position.
1083 for (auto largerRowEntryIt = largerRowContents.rbegin(); largerRowEntryIt != largerRowContents.rend(); ++largerRowEntryIt) {
1084 *writeIt = std::move(*largerRowEntryIt);
1085 --writeIt;
1086 }
1088 STORM_LOG_ASSERT(writeIt == getRow(smallerRow).begin() - 1, "Unexpected position of write iterator.");
1089
1090 // Update row indications.
1091 // Update the row indications to account for the shift of indices at where the rows now start.
1092 if (!storm::utility::isZero(rowSizeDifference)) {
1093 for (index_type row = smallerRow + 1; row <= largerRow; ++row) {
1094 rowIndications[row] += rowSizeDifference;
1095 }
1096 }
1097 }
1098}
1099
1100template<typename ValueType>
1101std::vector<ValueType> SparseMatrix<ValueType>::getRowSumVector() const {
1102 std::vector<ValueType> result(this->getRowCount());
1104 index_type row = 0;
1105 for (auto resultIt = result.begin(), resultIte = result.end(); resultIt != resultIte; ++resultIt, ++row) {
1106 *resultIt = getRowSum(row);
1107 }
1108
1109 return result;
1110}
1111
1112template<typename ValueType>
1114 ValueType result = storm::utility::zero<ValueType>();
1115 for (const_iterator it = this->begin(row), ite = this->end(row); it != ite; ++it) {
1116 if (constraint.get(it->getColumn())) {
1117 result += it->getValue();
1118 }
1119 }
1120 return result;
1121}
1122
1123template<typename ValueType>
1125 storm::storage::BitVector const& columnConstraint) const {
1126 std::vector<ValueType> result(rowConstraint.getNumberOfSetBits());
1127 index_type currentRowCount = 0;
1128 for (uint64_t row : rowConstraint) {
1129 result[currentRowCount++] = getConstrainedRowSum(row, columnConstraint);
1130 }
1131 return result;
1133
1134template<typename ValueType>
1136 storm::storage::BitVector const& columnConstraint) const {
1137 std::vector<ValueType> result;
1138 result.reserve(this->getNumRowsInRowGroups(rowGroupConstraint));
1140 for (uint64_t rowGroup : rowGroupConstraint) {
1141 for (index_type row = this->getRowGroupIndices()[rowGroup]; row < this->getRowGroupIndices()[rowGroup + 1]; ++row) {
1142 result.push_back(getConstrainedRowSum(row, columnConstraint));
1143 }
1144 }
1145 } else {
1146 for (uint64_t rowGroup : rowGroupConstraint) {
1147 result.push_back(getConstrainedRowSum(rowGroup, columnConstraint));
1149 }
1150 return result;
1151}
1152
1153template<typename ValueType>
1155 storm::storage::BitVector const& columnConstraint, bool insertDiagonalElements,
1156 storm::storage::BitVector const& makeZeroColumns) const {
1157 SubmatrixBuilder<ValueType> submatrixBuilder(*this);
1159 if (makeZeroColumns.size() > 0) {
1160 makeZeroColumnsRef.reset(makeZeroColumns);
1161 }
1162 if (useGroups) {
1163 return submatrixBuilder.getByRowGroupConstraint(rowConstraint, columnConstraint, insertDiagonalElements, makeZeroColumnsRef);
1164 } else {
1165 return submatrixBuilder.getByRowConstraint(rowConstraint, columnConstraint, insertDiagonalElements, makeZeroColumnsRef);
1166 }
1167}
1168
1169template<typename ValueType>
1171 STORM_LOG_ASSERT(rowsToKeep.size() == this->getRowCount(), "Dimensions mismatch.");
1172
1173 // Count the number of entries of the resulting matrix
1174 index_type entryCount = 0;
1175 for (uint64_t row : rowsToKeep) {
1176 entryCount += this->getRow(row).getNumberOfEntries();
1177 }
1178
1179 // Get the smallest row group index such that all row groups with at least this index are empty.
1180 index_type firstTrailingEmptyRowGroup = this->getRowGroupCount();
1181 for (auto groupIndexIt = this->getRowGroupIndices().rbegin() + 1; groupIndexIt != this->getRowGroupIndices().rend(); ++groupIndexIt) {
1182 if (rowsToKeep.getNextSetIndex(*groupIndexIt) != rowsToKeep.size()) {
1183 break;
1184 }
1185 --firstTrailingEmptyRowGroup;
1186 }
1187 STORM_LOG_THROW(allowEmptyRowGroups || firstTrailingEmptyRowGroup == this->getRowGroupCount(), storm::exceptions::InvalidArgumentException,
1188 "Empty rows are not allowed, but row group " << firstTrailingEmptyRowGroup << " is empty.");
1189
1190 // build the matrix. The row grouping will always be considered as nontrivial.
1191 SparseMatrixBuilder<ValueType> builder(rowsToKeep.getNumberOfSetBits(), this->getColumnCount(), entryCount, true, true, this->getRowGroupCount());
1192 index_type newRow = 0;
1193 for (index_type rowGroup = 0; rowGroup < firstTrailingEmptyRowGroup; ++rowGroup) {
1194 // Add a new row group
1195 builder.newRowGroup(newRow);
1196 bool rowGroupEmpty = true;
1197 for (index_type row = rowsToKeep.getNextSetIndex(this->getRowGroupIndices()[rowGroup]); row < this->getRowGroupIndices()[rowGroup + 1];
1198 row = rowsToKeep.getNextSetIndex(row + 1)) {
1199 rowGroupEmpty = false;
1200 for (auto const& entry : this->getRow(row)) {
1201 builder.addNextValue(newRow, entry.getColumn(), entry.getValue());
1202 }
1203 ++newRow;
1204 }
1205 STORM_LOG_THROW(allowEmptyRowGroups || !rowGroupEmpty, storm::exceptions::InvalidArgumentException,
1206 "Empty rows are not allowed, but row group " << rowGroup << " is empty.");
1207 }
1208
1209 // The all remaining row groups will be empty. Note that it is not allowed to call builder.addNewGroup(...) if there are no more rows afterwards.
1210 SparseMatrix<ValueType> res = builder.build();
1211 return res;
1212}
1214template<typename ValueType>
1216 // Count the number of entries in the resulting matrix.
1217 index_type entryCount = 0;
1218 for (uint64_t row : rowFilter) {
1219 entryCount += getRow(row).getNumberOfEntries();
1220 }
1221
1222 // Build the resulting matrix.
1224 for (uint64_t row : rowFilter) {
1225 for (auto const& entry : getRow(row)) {
1226 builder.addNextValue(row, entry.getColumn(), entry.getValue());
1227 }
1228 }
1229 SparseMatrix<ValueType> result = builder.build();
1230
1231 // Add a row grouping if necessary.
1232 if (!hasTrivialRowGrouping()) {
1234 }
1235 return result;
1236}
1237
1238template<typename ValueType>
1243 for (index_type row = 0; row < getRowCount(); ++row) {
1244 for (auto const& entry : getRow(row)) {
1245 if (!storm::utility::isZero(entry.getValue())) {
1246 builder.addNextValue(row, entry.getColumn(), entry.getValue());
1247 }
1248 }
1249 }
1250 SparseMatrix<ValueType> result = builder.build();
1251 // Add a row grouping if necessary.
1252 if (!hasTrivialRowGrouping()) {
1253 result.setRowGroupIndices(getRowGroupIndices());
1254 }
1255 *this = std::move(result);
1256 }
1257}
1258
1259template<typename ValueType>
1260SparseMatrix<ValueType> SparseMatrix<ValueType>::selectRowsFromRowGroups(std::vector<index_type> const& rowGroupToRowIndexMapping,
1261 bool insertDiagonalEntries) const {
1262 // First, we need to count how many non-zero entries the resulting matrix will have and reserve space for
1263 // diagonal entries if requested.
1264 index_type subEntries = 0;
1265 for (index_type rowGroupIndex = 0, rowGroupIndexEnd = rowGroupToRowIndexMapping.size(); rowGroupIndex < rowGroupIndexEnd; ++rowGroupIndex) {
1266 // Determine which row we need to select from the current row group.
1267 STORM_LOG_ASSERT(rowGroupToRowIndexMapping[rowGroupIndex] < this->getRowGroupSize(rowGroupIndex),
1268 "Cannot point to row offset " << rowGroupToRowIndexMapping[rowGroupIndex] << " for rowGroup " << rowGroupIndex << " which starts at "
1269 << this->getRowGroupIndices()[rowGroupIndex] << " and ends at "
1270 << this->getRowGroupIndices()[rowGroupIndex + 1] << ".");
1271 index_type rowToCopy = this->getRowGroupIndices()[rowGroupIndex] + rowGroupToRowIndexMapping[rowGroupIndex];
1272
1273 // Iterate through that row and count the number of slots we have to reserve for copying.
1274 bool foundDiagonalElement = false;
1275 for (const_iterator it = this->begin(rowToCopy), ite = this->end(rowToCopy); it != ite; ++it) {
1276 if (it->getColumn() == rowGroupIndex) {
1277 foundDiagonalElement = true;
1278 }
1279 ++subEntries;
1280 }
1281 if (insertDiagonalEntries && !foundDiagonalElement) {
1282 ++subEntries;
1283 }
1284 }
1285
1286 // Now create the matrix to be returned with the appropriate size.
1287 SparseMatrixBuilder<ValueType> matrixBuilder(rowGroupIndices.get().size() - 1, columnCount, subEntries);
1288
1289 // Copy over the selected lines from the source matrix.
1290 for (index_type rowGroupIndex = 0, rowGroupIndexEnd = rowGroupToRowIndexMapping.size(); rowGroupIndex < rowGroupIndexEnd; ++rowGroupIndex) {
1291 // Determine which row we need to select from the current row group.
1292 index_type rowToCopy = this->getRowGroupIndices()[rowGroupIndex] + rowGroupToRowIndexMapping[rowGroupIndex];
1293
1294 // Iterate through that row and copy the entries. This also inserts a zero element on the diagonal if
1295 // there is no entry yet.
1296 bool insertedDiagonalElement = false;
1297 for (const_iterator it = this->begin(rowToCopy), ite = this->end(rowToCopy); it != ite; ++it) {
1298 if (it->getColumn() == rowGroupIndex) {
1299 insertedDiagonalElement = true;
1300 } else if (insertDiagonalEntries && !insertedDiagonalElement && it->getColumn() > rowGroupIndex) {
1301 matrixBuilder.addNextValue(rowGroupIndex, rowGroupIndex, storm::utility::zero<ValueType>());
1302 insertedDiagonalElement = true;
1303 }
1304 matrixBuilder.addNextValue(rowGroupIndex, it->getColumn(), it->getValue());
1305 }
1306 if (insertDiagonalEntries && !insertedDiagonalElement) {
1307 matrixBuilder.addNextValue(rowGroupIndex, rowGroupIndex, storm::utility::zero<ValueType>());
1308 }
1309 }
1310
1311 // Finalize created matrix and return result.
1312 return matrixBuilder.build();
1313}
1314
1315template<typename ValueType>
1317 bool insertDiagonalEntries) const {
1318 // First, we need to count how many non-zero entries the resulting matrix will have and reserve space for
1319 // diagonal entries if requested.
1320 index_type newEntries = 0;
1321 for (index_type row = 0, rowEnd = rowIndexSequence.size(); row < rowEnd; ++row) {
1322 bool foundDiagonalElement = false;
1323 for (const_iterator it = this->begin(rowIndexSequence[row]), ite = this->end(rowIndexSequence[row]); it != ite; ++it) {
1324 if (it->getColumn() == row) {
1325 foundDiagonalElement = true;
1326 }
1327 ++newEntries;
1328 }
1329 if (insertDiagonalEntries && !foundDiagonalElement) {
1330 ++newEntries;
1331 }
1332 }
1333
1334 // Now create the matrix to be returned with the appropriate size.
1335 SparseMatrixBuilder<ValueType> matrixBuilder(rowIndexSequence.size(), columnCount, newEntries);
1336
1337 // Copy over the selected rows from the source matrix.
1338 for (index_type row = 0, rowEnd = rowIndexSequence.size(); row < rowEnd; ++row) {
1339 bool insertedDiagonalElement = false;
1340 for (const_iterator it = this->begin(rowIndexSequence[row]), ite = this->end(rowIndexSequence[row]); it != ite; ++it) {
1341 if (it->getColumn() == row) {
1342 insertedDiagonalElement = true;
1343 } else if (insertDiagonalEntries && !insertedDiagonalElement && it->getColumn() > row) {
1344 matrixBuilder.addNextValue(row, row, storm::utility::zero<ValueType>());
1345 insertedDiagonalElement = true;
1346 }
1347 matrixBuilder.addNextValue(row, it->getColumn(), it->getValue());
1348 }
1349 if (insertDiagonalEntries && !insertedDiagonalElement) {
1350 matrixBuilder.addNextValue(row, row, storm::utility::zero<ValueType>());
1351 }
1352 }
1353
1354 // Finally create matrix and return result.
1355 return matrixBuilder.build();
1356}
1357
1358template<typename ValueType>
1359SparseMatrix<ValueType> SparseMatrix<ValueType>::permuteRows(std::vector<index_type> const& inversePermutation) const {
1360 // Now create the matrix to be returned with the appropriate size.
1361 // The entry size is only adequate if this is indeed a permutation.
1362 SparseMatrixBuilder<ValueType> matrixBuilder(inversePermutation.size(), columnCount, entryCount);
1363
1364 // Copy over the selected rows from the source matrix.
1365
1366 for (index_type writeTo = 0; writeTo < inversePermutation.size(); ++writeTo) {
1367 index_type const& readFrom = inversePermutation[writeTo];
1368 auto row = this->getRow(readFrom);
1369 for (auto const& entry : row) {
1370 matrixBuilder.addNextValue(writeTo, entry.getColumn(), entry.getValue());
1371 }
1372 }
1373 // Finally create matrix and return result.
1374 auto result = matrixBuilder.build();
1375 if (this->rowGroupIndices) {
1376 result.setRowGroupIndices(this->rowGroupIndices.get());
1377 }
1378 return result;
1379}
1380
1381template<typename ValueType>
1382SparseMatrix<ValueType> SparseMatrix<ValueType>::permuteRowGroupsAndColumns(std::vector<index_type> const& inverseRowGroupPermutation,
1383 std::vector<index_type> const& columnPermutation) const {
1384 STORM_LOG_ASSERT(storm::utility::permutation::isValidPermutation(inverseRowGroupPermutation), "Row group permutation is not a permutation.");
1385 STORM_LOG_ASSERT(storm::utility::permutation::isValidPermutation(columnPermutation), "Column permutation is not a permutation.");
1386 index_type const rowCount = getRowCount();
1388 auto oldGroupIt = inverseRowGroupPermutation.cbegin();
1389 index_type newRowIndex = 0;
1390 while (newRowIndex < rowCount) {
1391 if (!hasTrivialRowGrouping()) {
1392 matrixBuilder.newRowGroup(newRowIndex);
1393 }
1394 for (auto oldRowIndex : getRowGroupIndices(*oldGroupIt)) {
1395 for (auto const& oldEntry : getRow(oldRowIndex)) {
1396 matrixBuilder.addNextValue(newRowIndex, columnPermutation[oldEntry.getColumn()], oldEntry.getValue());
1397 }
1398 ++newRowIndex;
1399 }
1400 ++oldGroupIt;
1401 }
1402 return matrixBuilder.build();
1403}
1404
1405template<typename ValueType>
1406SparseMatrix<ValueType> SparseMatrix<ValueType>::transpose(bool joinGroups, bool keepZeros) const {
1407 index_type rowCount = this->getColumnCount();
1408 index_type columnCount = joinGroups ? this->getRowGroupCount() : this->getRowCount();
1409 index_type entryCount;
1410 if (keepZeros) {
1411 entryCount = this->getEntryCount();
1412 } else {
1414 entryCount = this->getNonzeroEntryCount();
1415 }
1416
1417 std::vector<index_type> rowIndications(rowCount + 1);
1418 std::vector<MatrixEntry<index_type, ValueType>> columnsAndValues(entryCount);
1419
1420 // First, we need to count how many entries each column has.
1421 for (index_type group = 0; group < columnCount; ++group) {
1422 for (auto const& transition : joinGroups ? this->getRowGroup(group) : this->getRow(group)) {
1423 if (transition.getValue() != storm::utility::zero<ValueType>() || keepZeros) {
1424 ++rowIndications[transition.getColumn() + 1];
1425 }
1426 }
1427 }
1428
1429 // Now compute the accumulated offsets.
1430 for (index_type i = 1; i < rowCount + 1; ++i) {
1431 rowIndications[i] = rowIndications[i - 1] + rowIndications[i];
1432 }
1433
1434 // Create an array that stores the index for the next value to be added for
1435 // each row in the transposed matrix. Initially this corresponds to the previously
1436 // computed accumulated offsets.
1437 std::vector<index_type> nextIndices = rowIndications;
1438
1439 // Now we are ready to actually fill in the values of the transposed matrix.
1440 for (index_type group = 0; group < columnCount; ++group) {
1441 for (auto const& transition : joinGroups ? this->getRowGroup(group) : this->getRow(group)) {
1442 if (transition.getValue() != storm::utility::zero<ValueType>() || keepZeros) {
1443 columnsAndValues[nextIndices[transition.getColumn()]] = std::make_pair(group, transition.getValue());
1444 nextIndices[transition.getColumn()]++;
1445 }
1446 }
1447 }
1448
1449 storm::storage::SparseMatrix<ValueType> transposedMatrix(columnCount, std::move(rowIndications), std::move(columnsAndValues), boost::none);
1450
1451 return transposedMatrix;
1452}
1453
1454template<typename ValueType>
1455SparseMatrix<ValueType> SparseMatrix<ValueType>::transposeSelectedRowsFromRowGroups(std::vector<uint64_t> const& rowGroupChoices, bool keepZeros) const {
1456 index_type rowCount = this->getColumnCount();
1457 index_type columnCount = this->getRowGroupCount();
1458
1459 // Get the overall entry count as well as the number of entries of each column
1460 index_type entryCount = 0;
1461 std::vector<index_type> rowIndications(columnCount + 1);
1462 auto rowGroupChoiceIt = rowGroupChoices.begin();
1463 for (index_type rowGroup = 0; rowGroup < columnCount; ++rowGroup, ++rowGroupChoiceIt) {
1464 for (auto const& entry : this->getRow(rowGroup, *rowGroupChoiceIt)) {
1465 if (keepZeros || !storm::utility::isZero(entry.getValue())) {
1466 ++entryCount;
1467 ++rowIndications[entry.getColumn() + 1];
1468 }
1469 }
1470 }
1471
1472 // Now compute the accumulated offsets.
1473 for (index_type i = 1; i < rowCount + 1; ++i) {
1474 rowIndications[i] = rowIndications[i - 1] + rowIndications[i];
1475 }
1476
1477 std::vector<MatrixEntry<index_type, ValueType>> columnsAndValues(entryCount);
1478
1479 // Create an array that stores the index for the next value to be added for
1480 // each row in the transposed matrix. Initially this corresponds to the previously
1481 // computed accumulated offsets.
1482 std::vector<index_type> nextIndices = rowIndications;
1483
1484 // Now we are ready to actually fill in the values of the transposed matrix.
1485 rowGroupChoiceIt = rowGroupChoices.begin();
1486 for (index_type rowGroup = 0; rowGroup < columnCount; ++rowGroup, ++rowGroupChoiceIt) {
1487 for (auto const& entry : this->getRow(rowGroup, *rowGroupChoiceIt)) {
1488 if (keepZeros || !storm::utility::isZero(entry.getValue())) {
1489 columnsAndValues[nextIndices[entry.getColumn()]] = std::make_pair(rowGroup, entry.getValue());
1490 ++nextIndices[entry.getColumn()];
1491 }
1492 }
1493 }
1494
1495 return storm::storage::SparseMatrix<ValueType>(std::move(columnCount), std::move(rowIndications), std::move(columnsAndValues), boost::none);
1496}
1497
1498template<typename ValueType>
1503
1504template<typename ValueType>
1506 // Now iterate over all row groups and set the diagonal elements to the inverted value.
1507 // If there is a row without the diagonal element, an exception is thrown.
1508 ValueType one = storm::utility::one<ValueType>();
1509 ValueType zero = storm::utility::zero<ValueType>();
1510 bool foundDiagonalElement = false;
1511 for (index_type group = 0; group < this->getRowGroupCount(); ++group) {
1512 for (auto& entry : this->getRowGroup(group)) {
1513 if (entry.getColumn() == group) {
1514 if (entry.getValue() == one) {
1515 --this->nonzeroEntryCount;
1516 entry.setValue(zero);
1517 } else if (entry.getValue() == zero) {
1518 ++this->nonzeroEntryCount;
1519 entry.setValue(one);
1520 } else {
1521 entry.setValue(one - entry.getValue());
1522 }
1523 foundDiagonalElement = true;
1524 }
1525 }
1526
1527 // Throw an exception if a row did not have an element on the diagonal.
1528 STORM_LOG_THROW(foundDiagonalElement, storm::exceptions::InvalidArgumentException,
1529 "Illegal call to SparseMatrix::invertDiagonal: matrix is missing diagonal entries.");
1530 }
1531}
1532
1533template<typename ValueType>
1535 // Iterate over all row groups and negate all the elements that are not on the diagonal.
1536 for (index_type group = 0; group < this->getRowGroupCount(); ++group) {
1537 for (auto& entry : this->getRowGroup(group)) {
1538 if (entry.getColumn() != group) {
1539 entry.setValue(-entry.getValue());
1540 }
1541 }
1542 }
1543}
1544
1545template<typename ValueType>
1547 // Iterate over all rows and negate all the elements that are not on the diagonal.
1548 for (index_type group = 0; group < this->getRowGroupCount(); ++group) {
1549 for (auto& entry : this->getRowGroup(group)) {
1550 if (entry.getColumn() == group) {
1551 --this->nonzeroEntryCount;
1552 entry.setValue(storm::utility::zero<ValueType>());
1553 }
1554 }
1555 }
1556 if (dropZeroEntries) {
1557 this->dropZeroEntries();
1558 }
1559}
1560
1561template<typename ValueType>
1562typename std::pair<storm::storage::SparseMatrix<ValueType>, std::vector<ValueType>> SparseMatrix<ValueType>::getJacobiDecomposition() const {
1563 STORM_LOG_THROW(this->getRowCount() == this->getColumnCount(), storm::exceptions::InvalidArgumentException,
1564 "Canno compute Jacobi decomposition of non-square matrix.");
1565
1566 // Prepare the resulting data structures.
1567 SparseMatrixBuilder<ValueType> luBuilder(this->getRowCount(), this->getColumnCount());
1568 std::vector<ValueType> invertedDiagonal(rowCount);
1569
1570 // Copy entries to the appropriate matrices.
1571 for (index_type rowNumber = 0; rowNumber < rowCount; ++rowNumber) {
1572 for (const_iterator it = this->begin(rowNumber), ite = this->end(rowNumber); it != ite; ++it) {
1573 if (it->getColumn() == rowNumber) {
1574 invertedDiagonal[rowNumber] = storm::utility::one<ValueType>() / it->getValue();
1575 } else {
1576 luBuilder.addNextValue(rowNumber, it->getColumn(), it->getValue());
1577 }
1578 }
1579 }
1580
1581 return std::make_pair(luBuilder.build(), std::move(invertedDiagonal));
1582}
1583
1584template<>
1585typename std::pair<storm::storage::SparseMatrix<Interval>, std::vector<Interval>> SparseMatrix<Interval>::getJacobiDecomposition() const {
1586 STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This operation is not supported.");
1587}
1588
1589template<>
1590typename std::pair<storm::storage::SparseMatrix<RationalFunction>, std::vector<RationalFunction>> SparseMatrix<RationalFunction>::getJacobiDecomposition()
1591 const {
1592 STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This operation is not supported.");
1593}
1594
1595template<typename ValueType>
1596template<typename OtherValueType, typename ResultValueType>
1598 index_type const& row) const {
1603
1604 ResultValueType result = storm::utility::zero<ResultValueType>();
1605 for (; it1 != ite1 && it2 != ite2; ++it1) {
1606 if (it1->getColumn() < it2->getColumn()) {
1607 continue;
1608 } else {
1609 // If the precondition of this method (i.e. that the given matrix is a submatrix
1610 // of the current one) was fulfilled, we know now that the two elements are in
1611 // the same column, so we can multiply and add them to the row sum vector.
1612 STORM_LOG_ASSERT(it1->getColumn() == it2->getColumn(), "The given matrix is not a submatrix of this one.");
1613 result += it2->getValue() * OtherValueType(it1->getValue());
1614 ++it2;
1615 }
1616 }
1617 return result;
1618}
1619
1620template<typename ValueType>
1621template<typename OtherValueType, typename ResultValueType>
1623 std::vector<ResultValueType> result;
1624 result.reserve(rowCount);
1625 for (index_type row = 0; row < rowCount && row < otherMatrix.getRowCount(); ++row) {
1626 result.push_back(getPointwiseProductRowSum<OtherValueType, ResultValueType>(otherMatrix, row));
1627 }
1628 return result;
1629}
1630
1631template<typename ValueType>
1632void SparseMatrix<ValueType>::multiplyWithVector(std::vector<ValueType> const& vector, std::vector<ValueType>& result,
1633 std::vector<value_type> const* summand) const {
1634 // If the vector and the result are aliases and this is not set to be allowed, we need and temporary vector.
1635 std::vector<ValueType>* target;
1636 std::vector<ValueType> temporary;
1637 if (&vector == &result) {
1638 STORM_LOG_WARN("Vectors are aliased. Using temporary, which is potentially slow.");
1639 temporary = std::vector<ValueType>(vector.size());
1640 target = &temporary;
1641 } else {
1642 target = &result;
1643 }
1644
1645 this->multiplyWithVectorForward(vector, *target, summand);
1646
1647 if (target == &temporary) {
1648 std::swap(result, *target);
1649 }
1650}
1651
1652template<typename ValueType>
1653void SparseMatrix<ValueType>::multiplyWithVectorForward(std::vector<ValueType> const& vector, std::vector<ValueType>& result,
1654 std::vector<value_type> const* summand) const {
1655 const_iterator it = this->begin();
1656 const_iterator ite;
1657 std::vector<index_type>::const_iterator rowIterator = rowIndications.begin();
1658 typename std::vector<ValueType>::iterator resultIterator = result.begin();
1659 typename std::vector<ValueType>::iterator resultIteratorEnd = result.end();
1660 typename std::vector<ValueType>::const_iterator summandIterator;
1661 if (summand) {
1662 summandIterator = summand->begin();
1663 }
1664
1665 for (; resultIterator != resultIteratorEnd; ++rowIterator, ++resultIterator, ++summandIterator) {
1666 ValueType newValue;
1667 if (summand) {
1668 newValue = *summandIterator;
1669 } else {
1671 }
1672
1673 for (ite = this->begin() + *(rowIterator + 1); it != ite; ++it) {
1674 newValue += it->getValue() * vector[it->getColumn()];
1675 }
1676
1677 *resultIterator = newValue;
1678 }
1679}
1680
1681template<typename ValueType>
1682void SparseMatrix<ValueType>::multiplyWithVectorBackward(std::vector<ValueType> const& vector, std::vector<ValueType>& result,
1683 std::vector<value_type> const* summand) const {
1684 const_iterator it = this->end() - 1;
1685 const_iterator ite;
1686 std::vector<index_type>::const_iterator rowIterator = rowIndications.end() - 2;
1687 typename std::vector<ValueType>::iterator resultIterator = result.end() - 1;
1688 typename std::vector<ValueType>::iterator resultIteratorEnd = result.begin() - 1;
1689 typename std::vector<ValueType>::const_iterator summandIterator;
1690 if (summand) {
1691 summandIterator = summand->end() - 1;
1692 }
1693
1694 for (; resultIterator != resultIteratorEnd; --rowIterator, --resultIterator, --summandIterator) {
1695 ValueType newValue;
1696 if (summand) {
1697 newValue = *summandIterator;
1698 } else {
1700 }
1701
1702 for (ite = this->begin() + *rowIterator - 1; it != ite; --it) {
1703 newValue += (it->getValue() * vector[it->getColumn()]);
1704 }
1705
1706 *resultIterator = newValue;
1707 }
1708}
1709
1710template<typename ValueType>
1711ValueType SparseMatrix<ValueType>::multiplyRowWithVector(index_type row, std::vector<ValueType> const& vector, ValueType offset) const {
1712 ValueType result = std::move(offset);
1713 for (auto const& entry : this->getRow(row)) {
1714 if (storm::utility::isZero(entry.getValue())) {
1715 continue; // Ignore zero entries, even if the corresponding vector value is infinite.
1716 }
1717 result += entry.getValue() * vector[entry.getColumn()];
1718 }
1719 return result;
1720}
1721
1722template<typename ValueType>
1724 std::vector<storm::utility::ExtendedNumber<ValueType>> const& vector,
1726 storm::utility::ExtendedNumber<ValueType> result = std::move(offset);
1727 for (auto const& entry : this->getRow(row)) {
1728 if (storm::utility::isZero(entry.getValue())) {
1729 continue; // Ignore zero entries, even if the corresponding vector value is infinite.
1730 }
1731 auto const& vectorValue = vector[entry.getColumn()];
1732 // Avoid copies into ExtendedNumber wrapper
1733 if (result.isFinite() && vectorValue.isFinite()) {
1734 result.getFinite() += entry.getValue() * vectorValue.getFinite();
1735 } else {
1736 result += entry.getValue() * vectorValue;
1737 }
1738 }
1739 return result;
1740}
1741
1742template<typename ValueType>
1743void SparseMatrix<ValueType>::performSuccessiveOverRelaxationStep(ValueType omega, std::vector<ValueType>& x, std::vector<ValueType> const& b) const {
1744 const_iterator it = this->end() - 1;
1745 const_iterator ite;
1746 std::vector<index_type>::const_iterator rowIterator = rowIndications.end() - 2;
1747 typename std::vector<ValueType>::const_iterator bIt = b.end() - 1;
1748 typename std::vector<ValueType>::iterator resultIterator = x.end() - 1;
1749 typename std::vector<ValueType>::iterator resultIteratorEnd = x.begin() - 1;
1750
1751 index_type currentRow = getRowCount();
1752 for (; resultIterator != resultIteratorEnd; --rowIterator, --resultIterator, --bIt) {
1753 --currentRow;
1754 ValueType tmpValue = storm::utility::zero<ValueType>();
1755 ValueType diagonalElement = storm::utility::zero<ValueType>();
1756
1757 for (ite = this->begin() + *rowIterator - 1; it != ite; --it) {
1758 if (it->getColumn() != currentRow) {
1759 tmpValue += it->getValue() * x[it->getColumn()];
1760 } else {
1761 diagonalElement += it->getValue();
1762 }
1763 }
1764 STORM_LOG_ASSERT(!storm::utility::isZero(diagonalElement), "Diagonal element is zero.");
1765 *resultIterator = ((storm::utility::one<ValueType>() - omega) * *resultIterator) + (omega / diagonalElement) * (*bIt - tmpValue);
1766 }
1767}
1768
1769template<>
1770void SparseMatrix<Interval>::performSuccessiveOverRelaxationStep(Interval, std::vector<Interval>&, std::vector<Interval> const&) const {
1771 STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "This operation is not supported.");
1772}
1773
1774template<typename ValueType>
1775void SparseMatrix<ValueType>::performWalkerChaeStep(std::vector<ValueType> const& x, std::vector<ValueType> const& columnSums, std::vector<ValueType> const& b,
1776 std::vector<ValueType> const& ax, std::vector<ValueType>& result) const {
1777 const_iterator it = this->begin();
1778 const_iterator ite;
1779 std::vector<index_type>::const_iterator rowIterator = rowIndications.begin();
1780
1781 // Clear all previous entries.
1782 ValueType zero = storm::utility::zero<ValueType>();
1783 for (auto& entry : result) {
1784 entry = zero;
1785 }
1786
1787 for (index_type row = 0; row < rowCount; ++row, ++rowIterator) {
1788 for (ite = this->begin() + *(rowIterator + 1); it != ite; ++it) {
1789 result[it->getColumn()] += it->getValue() * (b[row] / ax[row]);
1790 }
1791 }
1792
1793 auto xIterator = x.begin();
1794 auto sumsIterator = columnSums.begin();
1795 for (auto& entry : result) {
1796 entry *= *xIterator / *sumsIterator;
1797 ++xIterator;
1798 ++sumsIterator;
1799 }
1800}
1801
1802template<>
1803void SparseMatrix<Interval>::performWalkerChaeStep(std::vector<Interval> const& x, std::vector<Interval> const& rowSums, std::vector<Interval> const& b,
1804 std::vector<Interval> const& ax, std::vector<Interval>& result) const {
1805 STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "This operation is not supported.");
1806}
1807
1808template<typename ValueType>
1809void SparseMatrix<ValueType>::multiplyAndReduceForward(OptimizationDirection const& dir, std::vector<uint64_t> const& rowGroupIndices,
1810 std::vector<ValueType> const& vector, std::vector<ValueType> const* summand,
1811 std::vector<ValueType>& result, std::vector<uint64_t>* choices) const {
1812 if (dir == OptimizationDirection::Minimize) {
1813 multiplyAndReduceForward<storm::utility::ElementLess<ValueType>>(rowGroupIndices, vector, summand, result, choices);
1814 } else {
1815 multiplyAndReduceForward<storm::utility::ElementGreater<ValueType>>(rowGroupIndices, vector, summand, result, choices);
1816 }
1817}
1818
1819template<typename ValueType>
1820template<typename Compare>
1821void SparseMatrix<ValueType>::multiplyAndReduceForward(std::vector<uint64_t> const& rowGroupIndices, std::vector<ValueType> const& vector,
1822 std::vector<ValueType> const* summand, std::vector<ValueType>& result,
1823 std::vector<uint64_t>* choices) const {
1824 Compare compare;
1825 auto elementIt = this->begin();
1826 auto rowGroupIt = rowGroupIndices.begin();
1827 auto rowIt = rowIndications.begin();
1828 typename std::vector<ValueType>::const_iterator summandIt;
1829 if (summand) {
1830 summandIt = summand->begin();
1831 }
1832 typename std::vector<uint64_t>::iterator choiceIt;
1833 if (choices) {
1834 choiceIt = choices->begin();
1835 }
1836
1837 // Variables for correctly tracking choices (only update if new choice is strictly better).
1838 ValueType oldSelectedChoiceValue;
1839 uint64_t selectedChoice;
1840
1841 uint64_t currentRow = 0;
1842 for (auto resultIt = result.begin(), resultIte = result.end(); resultIt != resultIte; ++resultIt, ++choiceIt, ++rowGroupIt) {
1843 ValueType currentValue = storm::utility::zero<ValueType>();
1844
1845 // Only multiply and reduce if there is at least one row in the group.
1846 if (*rowGroupIt < *(rowGroupIt + 1)) {
1847 if (summand) {
1848 currentValue = *summandIt;
1849 ++summandIt;
1850 }
1851
1852 for (auto elementIte = this->begin() + *(rowIt + 1); elementIt != elementIte; ++elementIt) {
1853 currentValue += elementIt->getValue() * vector[elementIt->getColumn()];
1854 }
1855
1856 if (choices) {
1857 selectedChoice = 0;
1858 if (*choiceIt == 0) {
1859 oldSelectedChoiceValue = currentValue;
1860 }
1861 }
1862
1863 ++rowIt;
1864 ++currentRow;
1865
1866 for (; currentRow < *(rowGroupIt + 1); ++rowIt, ++currentRow) {
1867 ValueType newValue = summand ? *summandIt : storm::utility::zero<ValueType>();
1868 for (auto elementIte = this->begin() + *(rowIt + 1); elementIt != elementIte; ++elementIt) {
1869 newValue += elementIt->getValue() * vector[elementIt->getColumn()];
1870 }
1871
1872 if (choices && currentRow == *choiceIt + *rowGroupIt) {
1873 oldSelectedChoiceValue = newValue;
1874 }
1875
1876 if (compare(newValue, currentValue)) {
1877 currentValue = newValue;
1878 if (choices) {
1879 selectedChoice = currentRow - *rowGroupIt;
1880 }
1881 }
1882 if (summand) {
1883 ++summandIt;
1884 }
1885 }
1886
1887 // Finally write value to target vector.
1888 *resultIt = currentValue;
1889 if (choices && compare(currentValue, oldSelectedChoiceValue)) {
1890 *choiceIt = selectedChoice;
1891 }
1892 }
1893 }
1894}
1895
1896template<>
1897void SparseMatrix<storm::RationalFunction>::multiplyAndReduceForward(OptimizationDirection const& dir, std::vector<uint64_t> const& rowGroupIndices,
1898 std::vector<storm::RationalFunction> const& vector,
1899 std::vector<storm::RationalFunction> const* b,
1900 std::vector<storm::RationalFunction>& result, std::vector<uint64_t>* choices) const {
1901 STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "This operation is not supported.");
1902}
1903
1904template<typename ValueType>
1905void SparseMatrix<ValueType>::multiplyAndReduceBackward(OptimizationDirection const& dir, std::vector<uint64_t> const& rowGroupIndices,
1906 std::vector<ValueType> const& vector, std::vector<ValueType> const* summand,
1907 std::vector<ValueType>& result, std::vector<uint64_t>* choices) const {
1908 if (dir == storm::OptimizationDirection::Minimize) {
1909 multiplyAndReduceBackward<storm::utility::ElementLess<ValueType>>(rowGroupIndices, vector, summand, result, choices);
1910 } else {
1911 multiplyAndReduceBackward<storm::utility::ElementGreater<ValueType>>(rowGroupIndices, vector, summand, result, choices);
1912 }
1913}
1914
1915template<typename ValueType>
1916template<typename Compare>
1917void SparseMatrix<ValueType>::multiplyAndReduceBackward(std::vector<uint64_t> const& rowGroupIndices, std::vector<ValueType> const& vector,
1918 std::vector<ValueType> const* summand, std::vector<ValueType>& result,
1919 std::vector<uint64_t>* choices) const {
1920 Compare compare;
1921 auto elementIt = this->end() - 1;
1922 auto rowGroupIt = rowGroupIndices.end() - 2;
1923 auto rowIt = rowIndications.end() - 2;
1924 typename std::vector<ValueType>::const_iterator summandIt;
1925 if (summand) {
1926 summandIt = summand->end() - 1;
1927 }
1928 typename std::vector<uint64_t>::iterator choiceIt;
1929 if (choices) {
1930 choiceIt = choices->end() - 1;
1931 }
1932
1933 // Variables for correctly tracking choices (only update if new choice is strictly better).
1934 ValueType oldSelectedChoiceValue;
1935 uint64_t selectedChoice;
1936
1937 uint64_t currentRow = this->getRowCount() - 1;
1938 for (auto resultIt = result.end() - 1, resultIte = result.begin() - 1; resultIt != resultIte; --resultIt, --choiceIt, --rowGroupIt) {
1939 ValueType currentValue = storm::utility::zero<ValueType>();
1940
1941 // Only multiply and reduce if there is at least one row in the group.
1942 if (*rowGroupIt < *(rowGroupIt + 1)) {
1943 if (summand) {
1944 currentValue = *summandIt;
1945 --summandIt;
1946 }
1947
1948 for (auto elementIte = this->begin() + *rowIt - 1; elementIt != elementIte; --elementIt) {
1949 currentValue += elementIt->getValue() * vector[elementIt->getColumn()];
1950 }
1951 if (choices) {
1952 selectedChoice = currentRow - *rowGroupIt;
1953 if (*choiceIt == selectedChoice) {
1954 oldSelectedChoiceValue = currentValue;
1955 }
1956 }
1957 --rowIt;
1958 --currentRow;
1959
1960 for (uint64_t i = *rowGroupIt + 1, end = *(rowGroupIt + 1); i < end; --rowIt, --currentRow, ++i, --summandIt) {
1961 ValueType newValue = summand ? *summandIt : storm::utility::zero<ValueType>();
1962 for (auto elementIte = this->begin() + *rowIt - 1; elementIt != elementIte; --elementIt) {
1963 newValue += elementIt->getValue() * vector[elementIt->getColumn()];
1964 }
1965
1966 if (choices && currentRow == *choiceIt + *rowGroupIt) {
1967 oldSelectedChoiceValue = newValue;
1968 }
1969
1970 if (compare(newValue, currentValue)) {
1971 currentValue = newValue;
1972 if (choices) {
1973 selectedChoice = currentRow - *rowGroupIt;
1974 }
1975 }
1976 }
1977
1978 // Finally write value to target vector.
1979 *resultIt = currentValue;
1980 if (choices && compare(currentValue, oldSelectedChoiceValue)) {
1981 *choiceIt = selectedChoice;
1982 }
1983 }
1984 }
1985}
1986
1987template<>
1988void SparseMatrix<storm::RationalFunction>::multiplyAndReduceBackward(OptimizationDirection const& dir, std::vector<uint64_t> const& rowGroupIndices,
1989 std::vector<storm::RationalFunction> const& vector,
1990 std::vector<storm::RationalFunction> const* b,
1991 std::vector<storm::RationalFunction>& result, std::vector<uint64_t>* choices) const {
1992 STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "This operation is not supported.");
1993}
1994
1995template<typename ValueType>
1996void SparseMatrix<ValueType>::multiplyAndReduce(OptimizationDirection const& dir, std::vector<uint64_t> const& rowGroupIndices,
1997 std::vector<ValueType> const& vector, std::vector<ValueType> const* summand, std::vector<ValueType>& result,
1998 std::vector<uint64_t>* choices) const {
1999 // If the vector and the result are aliases, we need and temporary vector.
2000 std::vector<ValueType>* target;
2001 std::vector<ValueType> temporary;
2002 if (&vector == &result) {
2003 STORM_LOG_WARN("Vectors are aliased but are not allowed to be. Using temporary, which is potentially slow.");
2004 temporary = std::vector<ValueType>(vector.size());
2005 target = &temporary;
2006 } else {
2007 target = &result;
2008 }
2009
2010 this->multiplyAndReduceForward(dir, rowGroupIndices, vector, summand, *target, choices);
2011
2012 if (target == &temporary) {
2013 std::swap(temporary, result);
2014 }
2015}
2016
2017template<typename ValueType>
2018void SparseMatrix<ValueType>::multiplyVectorWithMatrix(std::vector<value_type> const& vector, std::vector<value_type>& result) const {
2019 const_iterator it = this->begin();
2020 const_iterator ite;
2021 std::vector<index_type>::const_iterator rowIterator = rowIndications.begin();
2022 std::vector<index_type>::const_iterator rowIteratorEnd = rowIndications.end();
2023
2024 index_type currentRow = 0;
2025 for (; rowIterator != rowIteratorEnd - 1; ++rowIterator) {
2026 for (ite = this->begin() + *(rowIterator + 1); it != ite; ++it) {
2027 result[it->getColumn()] += it->getValue() * vector[currentRow];
2028 }
2029 ++currentRow;
2030 }
2031}
2032
2033template<typename ValueType>
2034void SparseMatrix<ValueType>::scaleRowsInPlace(std::vector<ValueType> const& factors) {
2035 STORM_LOG_ASSERT(factors.size() == this->getRowCount(), "Can not scale rows: Number of rows and number of scaling factors do not match.");
2036 index_type row = 0;
2037 for (auto const& factor : factors) {
2038 for (auto& entry : getRow(row)) {
2039 entry.setValue(entry.getValue() * factor);
2040 }
2041 ++row;
2042 }
2043}
2044
2045template<typename ValueType>
2046void SparseMatrix<ValueType>::divideRowsInPlace(std::vector<ValueType> const& divisors) {
2047 STORM_LOG_ASSERT(divisors.size() == this->getRowCount(), "Can not divide rows: Number of rows and number of divisors do not match.");
2048 index_type row = 0;
2049 for (auto const& divisor : divisors) {
2050 STORM_LOG_ASSERT(!storm::utility::isZero(divisor), "Can not divide row " << row << " by 0.");
2051 for (auto& entry : getRow(row)) {
2052 entry.setValue(entry.getValue() / divisor);
2053 }
2054 ++row;
2055 }
2056}
2057
2058template<>
2059void SparseMatrix<Interval>::divideRowsInPlace(std::vector<Interval> const&) {
2060 STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This operation is not supported.");
2061}
2062
2063template<typename ValueType>
2065 return const_rows(this->columnsAndValues.begin() + this->rowIndications[startRow], this->rowIndications[endRow] - this->rowIndications[startRow]);
2066}
2067
2068template<typename ValueType>
2070 return rows(this->columnsAndValues.begin() + this->rowIndications[startRow], this->rowIndications[endRow] - this->rowIndications[startRow]);
2071}
2072
2073template<typename ValueType>
2075 return getRows(row, row + 1);
2076}
2077
2078template<typename ValueType>
2082
2083template<typename ValueType>
2085 STORM_LOG_ASSERT(rowGroup < this->getRowGroupCount(), "Row group is out-of-bounds.");
2086 STORM_LOG_ASSERT(offset < this->getRowGroupSize(rowGroup), "Row offset in row-group is out-of-bounds.");
2087 if (!this->hasTrivialRowGrouping()) {
2088 return getRow(this->getRowGroupIndices()[rowGroup] + offset);
2089 } else {
2090 STORM_LOG_ASSERT(offset == 0, "Invalid offset.");
2091 return getRow(rowGroup + offset);
2092 }
2093}
2094
2095template<typename ValueType>
2097 STORM_LOG_ASSERT(rowGroup < this->getRowGroupCount(), "Row group is out-of-bounds.");
2098 STORM_LOG_ASSERT(offset < this->getRowGroupSize(rowGroup), "Row offset in row-group is out-of-bounds.");
2099 if (!this->hasTrivialRowGrouping()) {
2100 return getRow(this->getRowGroupIndices()[rowGroup] + offset);
2101 } else {
2102 STORM_LOG_ASSERT(offset == 0, "Invalid offset.");
2103 return getRow(rowGroup + offset);
2104 }
2105}
2106
2107template<typename ValueType>
2109 STORM_LOG_ASSERT(rowGroup < this->getRowGroupCount(), "Row group is out-of-bounds.");
2110 if (!this->hasTrivialRowGrouping()) {
2111 return getRows(this->getRowGroupIndices()[rowGroup], this->getRowGroupIndices()[rowGroup + 1]);
2112 } else {
2113 return getRows(rowGroup, rowGroup + 1);
2114 }
2115}
2116
2117template<typename ValueType>
2119 STORM_LOG_ASSERT(rowGroup < this->getRowGroupCount(), "Row group is out-of-bounds.");
2120 if (!this->hasTrivialRowGrouping()) {
2121 return getRows(this->getRowGroupIndices()[rowGroup], this->getRowGroupIndices()[rowGroup + 1]);
2122 } else {
2123 return getRows(rowGroup, rowGroup + 1);
2124 }
2125}
2126
2127template<typename ValueType>
2129 STORM_LOG_ASSERT(row < this->getRowCount(), "Row " << row << " exceeds row count " << this->getRowCount() << ".");
2130 return this->columnsAndValues.begin() + this->rowIndications[row];
2131}
2132
2133template<typename ValueType>
2135 STORM_LOG_ASSERT(row < this->getRowCount(), "Row " << row << " exceeds row count " << this->getRowCount() << ".");
2136 return this->columnsAndValues.begin() + this->rowIndications[row];
2137}
2138
2139template<typename ValueType>
2141 return this->columnsAndValues.begin();
2142}
2143
2144template<typename ValueType>
2146 return this->columnsAndValues.begin();
2147}
2148
2149template<typename ValueType>
2151 STORM_LOG_ASSERT(row < this->getRowCount(), "Row " << row << " exceeds row count " << this->getRowCount() << ".");
2152 return this->columnsAndValues.begin() + this->rowIndications[row + 1];
2153}
2154
2155template<typename ValueType>
2157 STORM_LOG_ASSERT(row < this->getRowCount(), "Row " << row << " exceeds row count " << this->getRowCount() << ".");
2158 return this->columnsAndValues.begin() + this->rowIndications[row + 1];
2159}
2160
2161template<typename ValueType>
2163 return this->columnsAndValues.begin() + this->rowIndications[rowCount];
2164}
2165
2166template<typename ValueType>
2168 return this->columnsAndValues.begin() + this->rowIndications[rowCount];
2169}
2170
2171template<typename ValueType>
2173 ValueType sum = storm::utility::zero<ValueType>();
2174 for (const_iterator it = this->begin(row), ite = this->end(row); it != ite; ++it) {
2175 sum += it->getValue();
2176 }
2177 return sum;
2178}
2179
2180template<typename ValueType>
2182 index_type nonConstEntries = 0;
2183 for (auto const& entry : *this) {
2184 if (!storm::utility::isConstant(entry.getValue())) {
2185 ++nonConstEntries;
2186 }
2187 }
2188 return nonConstEntries;
2189}
2190
2191template<typename ValueType>
2193 index_type nonConstRowGroups = 0;
2194 for (index_type rowGroup = 0; rowGroup < this->getRowGroupCount(); ++rowGroup) {
2195 for (auto const& entry : this->getRowGroup(rowGroup)) {
2196 if (!storm::utility::isConstant(entry.getValue())) {
2197 ++nonConstRowGroups;
2198 break;
2199 }
2200 }
2201 }
2202 return nonConstRowGroups;
2203}
2204
2205template<typename ValueType>
2207 using BaseType =
2208 std::conditional_t<std::is_same_v<ValueType, storm::RationalFunction>, storm::RationalFunctionCoefficient, storm::IntervalBaseType<ValueType>>;
2210 STORM_LOG_ASSERT(tolerance == storm::utility::zero<ValueType>(), "Exact value type requires zero tolerance for isProbabilistic.");
2211 }
2212 auto toBaseType = [](ValueType const& value) {
2213 if constexpr (std::is_same_v<ValueType, BaseType>) {
2214 return value;
2215 } else {
2217 }
2218 };
2219 STORM_LOG_ASSERT(storm::utility::isConstant(tolerance), "Expected constant tolerance. Got " << tolerance);
2220 BaseType const zeroMinusTolerance = storm::utility::zero<BaseType>() - toBaseType(tolerance);
2221 BaseType const onePlusTolerance = storm::utility::one<BaseType>() + toBaseType(tolerance);
2222 BaseType const oneMinusTolerance = storm::utility::one<BaseType>() - toBaseType(tolerance);
2223
2224 auto isContained = [&toBaseType](ValueType const& value, BaseType const& lower, BaseType const& upper) {
2225 // surpress unused lambda capture warning for toBaseType in case it is not needed for the given ValueType.
2226 (void)toBaseType;
2227 if constexpr (storm::IsIntervalType<ValueType>) {
2228 // check if the interval contains some value in [lower,upper]
2229 return value.lower() <= upper && value.upper() >= lower;
2230 } else if constexpr (std::is_same_v<ValueType, storm::RationalFunction>) {
2231 // for rational functions, we only perform a check if the value is constant.
2232 if (storm::utility::isConstant(value)) {
2233 auto const constValue = toBaseType(value);
2234 return constValue <= upper && constValue >= lower;
2235 }
2236 return true;
2237 } else {
2238 // in all other cases, we expect the value to be constant
2239 STORM_LOG_ASSERT(storm::utility::isConstant(value), "Expected constant value. Got " << value);
2240 return value <= upper && value >= lower;
2241 }
2242 };
2243
2244 auto toString = [](ValueType const& value) {
2245 std::stringstream s;
2246 s << value;
2247 return s.str();
2248 };
2249
2250 for (index_type row = 0; row < this->rowCount; ++row) {
2251 auto rowSum = storm::utility::zero<ValueType>();
2252 for (auto const& entry : getRow(row)) {
2253 if (!isContained(entry.getValue(), zeroMinusTolerance, onePlusTolerance)) {
2254 if (reason) {
2255 *reason = "Entry in row " + std::to_string(row) + " is not a probability: " + toString(entry.getValue());
2256 }
2257 return false;
2258 }
2259 rowSum += entry.getValue();
2260 }
2261 if (!isContained(rowSum, oneMinusTolerance, onePlusTolerance)) {
2262 if (reason) {
2263 // print sum-1 to ensure that the reason is informative even if the sum is very close to one.
2264 *reason = "Sum of entries in row " + std::to_string(row) + " is not one: sum-1=" + toString(rowSum - storm::utility::one<ValueType>());
2265 }
2266 return false;
2267 }
2268 }
2269 return true;
2270}
2271
2272template<typename ValueType>
2274 for (auto const& entry : *this) {
2275 if (!storm::utility::isPositive(entry.getValue())) {
2276 return false;
2277 }
2278 }
2279 return true;
2280}
2281
2282template<typename ValueType>
2284 if constexpr (storm::IsIntervalType<ValueType>) {
2285 using BaseType = storm::IntervalBaseType<ValueType>;
2286 for (index_type row = 0; row < this->getRowCount(); ++row) {
2287 BaseType sumOfUpperBounds = storm::utility::zero<BaseType>();
2288 for (auto const& entry : this->getRow(row)) {
2289 sumOfUpperBounds += entry.getValue().upper();
2290 }
2291 for (auto const& entry : this->getRow(row)) {
2292 // The lower bound after tightening is the maximum of the given lower bound and what is left if all other entries take their upper bound.
2293 BaseType const tightenedLower =
2294 std::max<BaseType>(entry.getValue().lower(), storm::utility::one<BaseType>() - (sumOfUpperBounds - entry.getValue().upper()));
2295 if (!storm::utility::isPositive(tightenedLower)) {
2296 return false;
2297 }
2298 }
2299 }
2300 return true;
2301 } else {
2302 return hasOnlyPositiveEntries();
2303 }
2304}
2305
2306template<typename ValueType>
2307template<typename OtherValueType>
2309 // Check for matching sizes.
2310 if (this->getRowCount() != matrix.getRowCount() || this->getColumnCount() != matrix.getColumnCount() ||
2311 this->hasTrivialRowGrouping() != matrix.hasTrivialRowGrouping() ||
2312 (!this->hasTrivialRowGrouping() && this->getRowGroupIndices() != matrix.getRowGroupIndices())) {
2313 return false;
2314 }
2315
2316 // Check the subset property for all rows individually.
2317 for (index_type row = 0; row < this->getRowCount(); ++row) {
2318 auto it2 = matrix.begin(row);
2319 auto ite2 = matrix.end(row);
2320 for (const_iterator it1 = this->begin(row), ite1 = this->end(row); it1 != ite1; ++it1) {
2321 // Skip over all entries of the other matrix that are before the current entry in the current matrix.
2322 while (it2 != ite2 && it2->getColumn() < it1->getColumn()) {
2323 ++it2;
2324 }
2325 if (it2 == ite2 || it1->getColumn() != it2->getColumn()) {
2326 return false;
2327 }
2328 }
2329 }
2330 return true;
2331}
2332
2333template<typename ValueType>
2335 if (this->getRowCount() != this->getColumnCount()) {
2336 return false;
2337 }
2338 if (this->getNonzeroEntryCount() != this->getRowCount()) {
2339 return false;
2340 }
2341 for (uint64_t row = 0; row < this->getRowCount(); ++row) {
2342 bool rowHasEntry = false;
2343 for (auto const& entry : this->getRow(row)) {
2344 if (entry.getColumn() == row) {
2345 if (!storm::utility::isOne(entry.getValue())) {
2346 return false;
2347 }
2348 rowHasEntry = true;
2349 } else {
2350 if (!storm::utility::isZero(entry.getValue())) {
2351 return false;
2352 }
2353 }
2354 }
2355 if (!rowHasEntry) {
2356 return false;
2357 }
2358 }
2359 return true;
2360}
2361
2362template<typename ValueType>
2364 std::string result =
2365 std::to_string(getRowCount()) + "x" + std::to_string(getColumnCount()) + " matrix (" + std::to_string(getNonzeroEntryCount()) + " non-zeroes";
2366 if (!hasTrivialRowGrouping()) {
2367 result += ", " + std::to_string(getRowGroupCount()) + " groups";
2368 }
2369 result += ")";
2370 return result;
2371}
2372
2373template<typename ValueType>
2374std::ostream& operator<<(std::ostream& out, SparseMatrix<ValueType> const& matrix) {
2375 // Print column numbers in header.
2376 out << "\t\t";
2377 for (typename SparseMatrix<ValueType>::index_type i = 0; i < matrix.getColumnCount(); ++i) {
2378 out << i << "\t";
2379 }
2380 out << '\n';
2381
2382 // Iterate over all row groups.
2383 for (typename SparseMatrix<ValueType>::index_type group = 0; group < matrix.getRowGroupCount(); ++group) {
2384 out << "\t---- group " << group << "/" << (matrix.getRowGroupCount() - 1) << " ---- \n";
2385 typename SparseMatrix<ValueType>::index_type start = matrix.hasTrivialRowGrouping() ? group : matrix.getRowGroupIndices()[group];
2386 typename SparseMatrix<ValueType>::index_type end = matrix.hasTrivialRowGrouping() ? group + 1 : matrix.getRowGroupIndices()[group + 1];
2387
2388 for (typename SparseMatrix<ValueType>::index_type i = start; i < end; ++i) {
2389 typename SparseMatrix<ValueType>::index_type nextIndex = matrix.rowIndications[i];
2390
2391 // Print the actual row.
2392 out << i << "\t(\t";
2393 typename SparseMatrix<ValueType>::index_type currentRealIndex = 0;
2394 while (currentRealIndex < matrix.columnCount) {
2395 if (nextIndex < matrix.rowIndications[i + 1] && currentRealIndex == matrix.columnsAndValues[nextIndex].getColumn()) {
2396 out << matrix.columnsAndValues[nextIndex].getValue() << "\t";
2397 ++nextIndex;
2398 } else {
2399 out << "0\t";
2400 }
2401 ++currentRealIndex;
2402 }
2403 out << "\t)\t" << i << '\n';
2404 }
2405 }
2406
2407 // Print column numbers in footer.
2408 out << "\t\t";
2409 for (typename SparseMatrix<ValueType>::index_type i = 0; i < matrix.getColumnCount(); ++i) {
2410 out << i << "\t";
2411 }
2412 out << '\n';
2413
2414 return out;
2415}
2416
2417template<typename ValueType>
2419 // Iterate over all row groups.
2420 for (typename SparseMatrix<ValueType>::index_type group = 0; group < this->getRowGroupCount(); ++group) {
2421 STORM_LOG_ASSERT(this->getRowGroupSize(group) == 1, "Incorrect row group size.");
2422 for (typename SparseMatrix<ValueType>::index_type i = this->getRowGroupIndices()[group]; i < this->getRowGroupIndices()[group + 1]; ++i) {
2423 typename SparseMatrix<ValueType>::index_type nextIndex = this->rowIndications[i];
2424
2425 // Print the actual row.
2426 out << i << "\t(";
2427 typename SparseMatrix<ValueType>::index_type currentRealIndex = 0;
2428 while (currentRealIndex < this->columnCount) {
2429 if (nextIndex < this->rowIndications[i + 1] && currentRealIndex == this->columnsAndValues[nextIndex].getColumn()) {
2430 out << this->columnsAndValues[nextIndex].getValue() << " ";
2431 ++nextIndex;
2432 } else {
2433 out << "0 ";
2434 }
2435 ++currentRealIndex;
2436 }
2437 out << ";\n";
2438 }
2439 }
2440}
2441
2442template<typename ValueType>
2444 std::size_t result = 0;
2445
2446 boost::hash_combine(result, this->getRowCount());
2447 boost::hash_combine(result, this->getColumnCount());
2448 boost::hash_combine(result, this->getEntryCount());
2449 boost::hash_combine(result, boost::hash_range(columnsAndValues.begin(), columnsAndValues.end()));
2450 boost::hash_combine(result, boost::hash_range(rowIndications.begin(), rowIndications.end()));
2451 if (!this->hasTrivialRowGrouping()) {
2452 boost::hash_combine(result, boost::hash_range(rowGroupIndices.get().begin(), rowGroupIndices.get().end()));
2453 }
2454
2455 return result;
2456}
2457
2458// Explicitly instantiate the entry, builder and the matrix.
2459// double
2461template std::ostream& operator<<(std::ostream& out, MatrixEntry<typename SparseMatrix<double>::index_type, double> const& entry);
2462template class SparseMatrixBuilder<double>;
2463template class SparseMatrix<double>;
2464template std::ostream& operator<<(std::ostream& out, SparseMatrix<double> const& matrix);
2465template bool SparseMatrix<double>::isSubmatrixOf(SparseMatrix<double> const& matrix) const;
2467 typename SparseMatrix<double>::index_type const& row) const;
2468template std::vector<double> SparseMatrix<double>::getPointwiseProductRowSumVector(storm::storage::SparseMatrix<double> const& otherMatrix) const;
2469
2470template class MatrixEntry<uint32_t, double>;
2471template std::ostream& operator<<(std::ostream& out, MatrixEntry<uint32_t, double> const& entry);
2472
2473// int
2475template std::ostream& operator<<(std::ostream& out, MatrixEntry<typename SparseMatrix<int>::index_type, int> const& entry);
2476template class SparseMatrixBuilder<int>;
2477template class SparseMatrix<int>;
2478template std::ostream& operator<<(std::ostream& out, SparseMatrix<int> const& matrix);
2479template bool SparseMatrix<int>::isSubmatrixOf(SparseMatrix<int> const& matrix) const;
2480
2481// state_type
2483template std::ostream& operator<<(
2487template std::ostream& operator<<(std::ostream& out, SparseMatrix<storm::storage::sparse::state_type> const& matrix);
2489
2490// Rational Numbers
2492template std::ostream& operator<<(std::ostream& out, MatrixEntry<typename SparseMatrix<storm::RationalNumber>::index_type, storm::RationalNumber> const& entry);
2495template std::ostream& operator<<(std::ostream& out, SparseMatrix<storm::RationalNumber> const& matrix);
2499template std::vector<storm::RationalNumber> SparseMatrix<storm::RationalNumber>::getPointwiseProductRowSumVector(
2501
2502// Rational Function
2504template std::ostream& operator<<(std::ostream& out, MatrixEntry<typename SparseMatrix<RationalFunction>::index_type, RationalFunction> const& entry);
2506template class SparseMatrix<RationalFunction>;
2507template std::ostream& operator<<(std::ostream& out, SparseMatrix<RationalFunction> const& matrix);
2512 typename SparseMatrix<storm::RationalFunction>::index_type const& row) const;
2514 typename SparseMatrix<storm::RationalFunction>::index_type const& row) const;
2515template std::vector<storm::RationalFunction> SparseMatrix<RationalFunction>::getPointwiseProductRowSumVector(
2517template std::vector<storm::RationalFunction> SparseMatrix<double>::getPointwiseProductRowSumVector(
2519template std::vector<storm::RationalFunction> SparseMatrix<int>::getPointwiseProductRowSumVector(
2521
2522// Intervals
2524template std::ostream& operator<<(std::ostream& out, MatrixEntry<typename SparseMatrix<Interval>::index_type, Interval> const& entry);
2525template class SparseMatrixBuilder<Interval>;
2526template class SparseMatrix<Interval>;
2527template std::ostream& operator<<(std::ostream& out, SparseMatrix<Interval> const& matrix);
2530template std::vector<storm::Interval> SparseMatrix<Interval>::getPointwiseProductRowSumVector(
2531 storm::storage::SparseMatrix<storm::Interval> const& otherMatrix) const;
2532template std::vector<storm::Interval> SparseMatrix<double>::getPointwiseProductRowSumVector(
2533 storm::storage::SparseMatrix<storm::Interval> const& otherMatrix) const;
2534
2535// Rational Intervals
2537template std::ostream& operator<<(std::ostream& out, MatrixEntry<typename SparseMatrix<RationalInterval>::index_type, RationalInterval> const& entry);
2539template class SparseMatrix<RationalInterval>;
2540template std::ostream& operator<<(std::ostream& out, SparseMatrix<RationalInterval> const& matrix);
2543template std::vector<storm::RationalInterval> SparseMatrix<RationalInterval>::getPointwiseProductRowSumVector(
2545template std::vector<storm::RationalInterval> SparseMatrix<storm::RationalNumber>::getPointwiseProductRowSumVector(
2547
2548} // namespace storage
2549} // namespace storm
Helper class that optionally holds a reference to an object of type T.
Definition OptionalRef.h:48
void reset()
Unsets the reference.
A bit vector that is internally represented as a vector of 64-bit values.
Definition BitVector.h:16
void setMultiple(uint64_t bitIndex, uint64_t nrOfBits, bool newValue=true)
Sets multiple bits to the given value.
uint64_t getNextSetIndex(uint64_t startingIndex) const
Retrieves the index of the bit that is the next bit set to true in the bit vector.
uint64_t getNumberOfSetBits() const
Returns the number of bits that are set to true in this bit vector.
uint64_t getNextUnsetIndex(uint64_t startingIndex) const
Retrieves the index of the bit that is the next bit set to false in the bit vector.
void set(uint64_t index, bool value=true)
Sets the given truth value at the given index.
size_t size() const
Retrieves the number of bits this bit vector can store.
bool get(uint64_t index) const
Retrieves the truth value of the bit at the given index and performs a bound check.
MatrixEntry(index_type column, value_type value)
Constructs a matrix entry with the given column and value.
MatrixEntry operator*(value_type factor) const
Multiplies the entry with the given factor and returns the result.
value_type const & getValue() const
Retrieves the value of the matrix entry.
std::pair< index_type, value_type > const & getColumnValuePair() const
Retrieves a pair of column and value that characterizes this entry.
void setColumn(index_type const &column)
Sets the column of the current entry.
MatrixEntry()=default
index_type const & getColumn() const
Retrieves the column of the matrix entry.
bool operator!=(MatrixEntry const &other) const
void setValue(value_type const &value)
Sets the value of the entry in the matrix.
ValueType value_type
bool operator==(MatrixEntry const &other) const
This class represents a number of consecutive rows of the matrix.
const_rows(const_iterator begin, index_type entryCount)
Constructs an object that represents the rows defined by the value of the first entry,...
const_iterator end() const
Retrieves an iterator that points past the last entry of the rows.
index_type getNumberOfEntries() const
Retrieves the number of entries in the rows.
const_iterator begin() const
Retrieves an iterator that points to the beginning of the rows.
This class represents a number of consecutive rows of the matrix.
iterator end()
Retrieves an iterator that points past the last entry of the rows.
iterator begin()
Retrieves an iterator that points to the beginning of the rows.
index_type getNumberOfEntries() const
Retrieves the number of entries in the rows.
rows(iterator begin, index_type entryCount)
Constructs an object that represents the rows defined by the value of the first entry,...
A class that can be used to build a sparse matrix by adding value by value.
index_type getCurrentRowGroupCount() const
Retrieves the current row group count.
AccumulationMode
Specifies how values that are added for the same row and column are combined.
index_type getLastRow() const
Retrieves the most recently used row.
void addNextValue(index_type row, index_type column, value_type const &value)
Sets the matrix entry at the given row and column to the given value.
void replaceColumns(std::vector< index_type > const &replacements, index_type offset)
Replaces all columns with id > offset according to replacements.
SparseMatrixBuilder(index_type rows=0, index_type columns=0, index_type entries=0, bool forceDimensions=true, bool hasCustomRowGrouping=false, index_type rowGroups=0)
Constructs a sparse matrix builder producing a matrix with the given number of rows,...
void newRowGroup(index_type startingRow)
Starts a new row group in the matrix.
index_type getLastColumn() const
Retrieves the most recently used row.
void addDiagonalEntry(index_type row, ValueType const &value)
Makes sure that a diagonal entry will be inserted at the given row.
void setAccumulationMode(AccumulationMode mode)
Sets how values that are added for the same row and column are combined.
SparseMatrix< value_type > build(index_type overriddenRowCount=0, index_type overriddenColumnCount=0, index_type overriddenRowGroupCount=0)
AccumulationMode getAccumulationMode() const
Retrieves how values that are added for the same row and column are combined.
A class that holds a possibly non-square matrix in the compressed row storage format.
void divideRowsInPlace(std::vector< value_type > const &divisors)
Divides each row of the matrix, i.e., divides each element in row i with divisors[i].
ResultValueType getPointwiseProductRowSum(storm::storage::SparseMatrix< OtherValueType > const &otherMatrix, index_type const &row) const
Performs a pointwise multiplication of the entries in the given row of this matrix and the entries of...
void convertToEquationSystem()
Transforms the matrix into an equation system.
SparseMatrix()
Constructs an empty sparse matrix.
void swapRows(index_type const &row1, index_type const &row2)
Swaps the two rows.
bool operator==(SparseMatrix< value_type > const &other) const
Determines whether the current and the given matrix are semantically equal.
const_rows getRow(index_type row) const
Returns an object representing the given row.
index_type getSizeOfLargestRowGroup() const
Returns the size of the largest row group of the matrix.
SparseMatrix selectRowsFromRowGroups(std::vector< index_type > const &rowGroupToRowIndexMapping, bool insertDiagonalEntries=true) const
Selects exactly one row from each row group of this matrix and returns the resulting matrix.
void multiplyWithVectorForward(std::vector< value_type > const &vector, std::vector< value_type > &result, std::vector< value_type > const *summand=nullptr) const
index_type getEntryCount() const
Returns the number of entries in the matrix.
bool isProbabilistic(ValueType const &tolerance, storm::OptionalRef< std::string > reason={}) const
Checks for each row whether (i) each entry is between zero and one and (ii) all entries sum to one.
const_rows getRows(index_type startRow, index_type endRow) const
index_type getNonconstantEntryCount() const
Returns the number of non-constant entries.
void multiplyVectorWithMatrix(std::vector< value_type > const &vector, std::vector< value_type > &result) const
Multiplies the vector to the matrix from the left and writes the result to the given result vector.
void multiplyAndReduceBackward(storm::solver::OptimizationDirection const &dir, std::vector< uint64_t > const &rowGroupIndices, std::vector< ValueType > const &vector, std::vector< ValueType > const *b, std::vector< ValueType > &result, std::vector< uint64_t > *choices) const
index_type getNumRowsInRowGroups(storm::storage::BitVector const &groupConstraint) const
Returns the total number of rows that are in one of the specified row groups.
void makeRowsAbsorbing(storm::storage::BitVector const &rows, bool dropZeroEntries=false)
This function makes the given rows absorbing.
ValueType multiplyRowWithVector(index_type row, std::vector< ValueType > const &vector, ValueType offset=storm::utility::zero< ValueType >()) const
Multiplies a single row of the matrix with the given vector and adds the given offset to the result.
void multiplyWithVector(std::vector< value_type > const &vector, std::vector< value_type > &result, std::vector< value_type > const *summand=nullptr) const
Multiplies the matrix with the given vector and writes the result to the given result vector.
void multiplyWithVectorBackward(std::vector< value_type > const &vector, std::vector< value_type > &result, std::vector< value_type > const *summand=nullptr) const
SparseMatrix getSubmatrix(bool useGroups, storm::storage::BitVector const &rowConstraint, storm::storage::BitVector const &columnConstraint, bool insertDiagonalEntries=false, storm::storage::BitVector const &makeZeroColumns=storm::storage::BitVector()) const
Creates a submatrix of the current matrix by dropping all rows and columns whose bits are not set to ...
void performWalkerChaeStep(std::vector< ValueType > const &x, std::vector< ValueType > const &columnSums, std::vector< ValueType > const &b, std::vector< ValueType > const &ax, std::vector< ValueType > &result) const
Performs one step of the Walker-Chae technique.
void updateDimensions() const
Recomputes the number of columns and the number of non-zero entries.
const_iterator begin(index_type row) const
Retrieves an iterator that points to the beginning of the given row.
void printAsMatlabMatrix(std::ostream &out) const
Prints the matrix in a dense format, as also used by e.g.
void performSuccessiveOverRelaxationStep(ValueType omega, std::vector< ValueType > &x, std::vector< ValueType > const &b) const
Performs one step of the successive over-relaxation technique.
std::vector< value_type > getConstrainedRowSumVector(storm::storage::BitVector const &rowConstraint, storm::storage::BitVector const &columnConstraint) const
Computes a vector whose i-th entry is the sum of the entries in the i-th selected row where only thos...
BitVector duplicateRowsInRowgroups() const
Finds duplicate rows in a rowgroup.
bool compareRows(index_type i1, index_type i2) const
Compares two rows.
const_rows getRowGroup(index_type rowGroup) const
Returns an object representing the given row group.
SparseMatrix permuteRows(std::vector< index_type > const &inversePermutation) const
Permute rows of the matrix according to the vector.
void setRowGroupIndices(std::vector< index_type > const &newRowGroupIndices)
Sets the row grouping to the given one.
void negateAllNonDiagonalEntries()
Negates (w.r.t.
const_iterator begin() const
Retrieves an iterator that points to the beginning of the first row of the matrix.
std::vector< index_type > swapRowGroupIndices(std::vector< index_type > &&newRowGrouping)
Swaps the grouping of rows of this matrix.
SparseMatrix restrictRows(storm::storage::BitVector const &rowsToKeep, bool allowEmptyRowGroups=false) const
Restrict rows in grouped rows matrix.
std::vector< ValueType > getRowSumVector() const
Sums the entries in all rows.
SparseMatrix< ValueType > transposeSelectedRowsFromRowGroups(std::vector< uint64_t > const &rowGroupChoices, bool keepZeros=false) const
Transposes the matrix w.r.t.
std::vector< index_type > const & getRowIndices() const
Returns the entry indices within the given row.
index_type getRowEntryCount(index_type const row) const
void multiplyAndReduceForward(storm::solver::OptimizationDirection const &dir, std::vector< uint64_t > const &rowGroupIndices, std::vector< ValueType > const &vector, std::vector< ValueType > const *b, std::vector< ValueType > &result, std::vector< uint64_t > *choices) const
value_type getRowSum(index_type row) const
const_iterator end(index_type row) const
Retrieves an iterator that points past the end of the given row.
SparseMatrix permuteRowGroupsAndColumns(std::vector< index_type > const &inverseRowGroupPermutation, std::vector< index_type > const &columnPermutation) const
Permutes row groups and columns of the matrix according to the given permutations.
void multiplyAndReduce(storm::solver::OptimizationDirection const &dir, std::vector< uint64_t > const &rowGroupIndices, std::vector< ValueType > const &vector, std::vector< ValueType > const *summand, std::vector< ValueType > &result, std::vector< uint64_t > *choices) const
Multiplies the matrix with the given vector, reduces it according to the given direction and and writ...
index_type getRowGroupCount() const
Returns the number of row groups in the matrix.
void dropZeroEntries()
Removes all zero entries from this.
bool isSubmatrixOf(SparseMatrix< OtherValueType > const &matrix) const
Checks if the current matrix is a submatrix of the given matrix, where a matrix A is called a submatr...
SparseMatrix< value_type > & operator=(SparseMatrix< value_type > const &other)
Assigns the contents of the given matrix to the current one by deep-copying its contents.
void makeRowGroupsAbsorbing(storm::storage::BitVector const &rowGroupConstraint, bool dropZeroEntries=false)
This function makes the groups of rows given by the bit vector absorbing.
std::string getDimensionsAsString() const
Returns a string describing the dimensions of the matrix.
index_type getColumnCount() const
Returns the number of columns of the matrix.
std::pair< storm::storage::SparseMatrix< value_type >, std::vector< value_type > > getJacobiDecomposition() const
Calculates the Jacobi decomposition of this sparse matrix.
void makeRowDirac(index_type row, index_type column, bool dropZeroEntries=false)
This function makes the given row Dirac.
std::vector< MatrixEntry< index_type, value_type > >::const_iterator const_iterator
value_type getConstrainedRowSum(index_type row, storm::storage::BitVector const &columns) const
Sums the entries in the given row and columns.
std::vector< ResultValueType > getPointwiseProductRowSumVector(storm::storage::SparseMatrix< OtherValueType > const &otherMatrix) const
Performs a pointwise matrix multiplication of the matrix with the given matrix and returns a vector c...
void deleteDiagonalEntries(bool dropZeroEntries=false)
Sets all diagonal elements to zero.
void invertDiagonal()
Inverts all entries on the diagonal, i.e.
storm::storage::BitVector getRowGroupFilter(storm::storage::BitVector const &rowConstraint, bool setIfForAllRowsInGroup) const
Returns the indices of all row groups selected by the row constraints.
void makeRowGroupingTrivial()
Makes the row grouping of this matrix trivial.
SparseMatrix selectRowsFromRowIndexSequence(std::vector< index_type > const &rowIndexSequence, bool insertDiagonalEntries=true) const
Selects the rows that are given by the sequence of row indices, allowing to select rows arbitrarily o...
bool isProbabilisticGraphPreserving() const
Checks whether the support graph of the matrix is preserved by every way of resolving the uncertainty...
std::size_t hash() const
Calculates a hash value over all values contained in the matrix.
std::vector< index_type > const & getRowGroupIndices() const
std::vector< MatrixEntry< index_type, value_type > >::iterator iterator
index_type getRowGroupSize(index_type group) const
Returns the size of the given row group.
std::vector< value_type > getConstrainedRowGroupSumVector(storm::storage::BitVector const &rowGroupConstraint, storm::storage::BitVector const &columnConstraint) const
Computes a vector whose entries represent the sums of selected columns for all rows in selected row g...
storm::storage::SparseMatrix< value_type > transpose(bool joinGroups=false, bool keepZeros=false) const
Transposes the matrix.
bool hasOnlyPositiveEntries() const
Checks whether each present entry is strictly positive (omitted entries are not considered).
index_type getRowCount() const
Returns the number of rows of the matrix.
SparseMatrixIndexType index_type
index_type getNonzeroEntryCount() const
Returns the cached number of nonzero entries in the matrix.
const_iterator end() const
Retrieves an iterator that points past the end of the last row of the matrix.
index_type getNonconstantRowGroupCount() const
Returns the number of rowGroups that contain a non-constant value.
void scaleRowsInPlace(std::vector< value_type > const &factors)
Scales each row of the matrix, i.e., multiplies each element in row i with factors[i].
index_type getRowGroupEntryCount(index_type const group) const
Returns the number of entries in the given row group of the matrix.
storm::storage::BitVector getRowFilter(storm::storage::BitVector const &groupConstraint) const
Returns a bitvector representing the set of rows, with all indices set that correspond to one of the ...
SparseMatrix filterEntries(storm::storage::BitVector const &rowFilter) const
Returns a copy of this matrix that only considers entries in the selected rows.
Helper class to extract submatrices of a fixed sparse matrix.
SparseMatrix< ValueType > getByRowGroupConstraint(RowConstraintType const &rowGroupConstraint, ColumnConstraintType const &columnConstraint, bool const insertDiagonalElement, storm::OptionalRef< storm::storage::BitVector const > makeZeroColumns=storm::NullRef) const
Creates the submatrix that keeps only the given row groups and columns The row group structure of the...
SparseMatrix< ValueType > getByRowConstraint(RowConstraintType const &rowConstraint, ColumnConstraintType const &columnConstraint, bool const insertDiagonalElement, storm::OptionalRef< storm::storage::BitVector const > makeZeroColumns=storm::NullRef) const
Creates the submatrix that keeps only the given rows and columns If the matrix has a non-trivial row ...
A value of ValueType extended with the two infinities -infinity and +infinity.
ValueType const & getFinite() const
#define STORM_LOG_WARN(message)
Definition logging.h:35
#define STORM_LOG_TRACE(message)
Definition logging.h:22
#define STORM_LOG_ASSERT(cond, message)
Definition macros.h:9
#define STORM_LOG_THROW(cond, exception, message)
Definition macros.h:39
std::string toString(PomdpMemoryPattern const &pattern)
void print(std::vector< typename SparseMatrix< ValueType >::index_type > const &rowGroupIndices, std::vector< MatrixEntry< typename SparseMatrix< ValueType >::index_type, typename SparseMatrix< ValueType >::value_type > > const &columnsAndValues, std::vector< typename SparseMatrix< ValueType >::index_type > const &rowIndications)
std::ostream & operator<<(std::ostream &out, ParameterRegion< ParametricType > const &region)
bool isValidPermutation(std::vector< index_type > const &permutation)
Returns true if the given vector is a permutation of the numbers 0, 1, ..., n-1 for n = permutation....
std::vector< T > buildVectorForRange(T min, T max)
Constructs a vector [min, min+1, ...., max-1].
Definition vector.h:130
bool isPositive(ValueType const &a)
Definition constants.cpp:69
bool isOne(ValueType const &a)
Definition constants.cpp:39
bool isConstant(ValueType const &)
bool isZero(ValueType const &a)
Definition constants.cpp:44
ValueType zero()
Definition constants.cpp:26
ValueType one()
Definition constants.cpp:21
TargetType convertNumber(SourceType const &number)
The contract of a DD backend.
carl::Interval< storm::RationalNumber > RationalInterval
carl::Interval< double > Interval
Interval type.
solver::OptimizationDirection OptimizationDirection
constexpr bool IsIntervalType
Helper to check if a type is an interval.
carl::RationalFunction< Polynomial, true > RationalFunction
typename detail::IntervalMetaProgrammingHelper< ValueType >::BaseType IntervalBaseType
Helper to access the type in which interval boundaries are stored.
static const bool IsExact