|
17 | 17 | #include <vector> |
18 | 18 | #include <cmath> |
19 | 19 | #include <format> |
| 20 | +#include <fstream> |
20 | 21 |
|
21 | 22 | #include "../utility/Logger.hpp" |
22 | 23 | #include "../utility/Typedef.hpp" |
@@ -190,6 +191,13 @@ namespace dsm { |
190 | 191 | /// @brief reshape the matrix |
191 | 192 | void reshape(Id dim); |
192 | 193 |
|
| 194 | + /// @brief save the matrix to a binary file (.dsmcache) |
| 195 | + /// @param filename the name of the file |
| 196 | + void cache(std::string const& filename) const; |
| 197 | + /// @brief load the matrix from a binary file (.dsmcache) |
| 198 | + /// @param filename the name of the file |
| 199 | + void load(std::string const& filename); |
| 200 | + |
193 | 201 | /// @brief return the begin iterator of the matrix |
194 | 202 | /// @return the begin iterator |
195 | 203 | typename std::unordered_map<Id, T>::const_iterator begin() const { |
@@ -632,6 +640,43 @@ namespace dsm { |
632 | 640 | } |
633 | 641 | } |
634 | 642 |
|
| 643 | + template <typename T> |
| 644 | + void SparseMatrix<T>::cache(std::string const& filename) const { |
| 645 | + std::ofstream file(filename, std::ios::binary); |
| 646 | + if (!file.is_open()) { |
| 647 | + Logger::error(std::format("Error opening file \"{}\" for writing.", filename)); |
| 648 | + } |
| 649 | + file.write(reinterpret_cast<const char*>(&_rows), sizeof(Id)); |
| 650 | + file.write(reinterpret_cast<const char*>(&_cols), sizeof(Id)); |
| 651 | + size_t size = _matrix.size(); |
| 652 | + file.write(reinterpret_cast<const char*>(&size), sizeof(size_t)); |
| 653 | + for (auto& it : _matrix) { |
| 654 | + file.write(reinterpret_cast<const char*>(&it.first), sizeof(Id)); |
| 655 | + file.write(reinterpret_cast<const char*>(&it.second), sizeof(T)); |
| 656 | + } |
| 657 | + file.close(); |
| 658 | + } |
| 659 | + |
| 660 | + template <typename T> |
| 661 | + void SparseMatrix<T>::load(std::string const& filename) { |
| 662 | + std::ifstream file(filename, std::ios::binary); |
| 663 | + if (!file.is_open()) { |
| 664 | + Logger::error(std::format("Error opening file \"{}\" for reading.", filename)); |
| 665 | + } |
| 666 | + file.read(reinterpret_cast<char*>(&_rows), sizeof(Id)); |
| 667 | + file.read(reinterpret_cast<char*>(&_cols), sizeof(Id)); |
| 668 | + size_t size; |
| 669 | + file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); |
| 670 | + for (size_t i = 0; i < size; ++i) { |
| 671 | + Id index; |
| 672 | + T value; |
| 673 | + file.read(reinterpret_cast<char*>(&index), sizeof(Id)); |
| 674 | + file.read(reinterpret_cast<char*>(&value), sizeof(T)); |
| 675 | + _matrix.insert_or_assign(index, value); |
| 676 | + } |
| 677 | + file.close(); |
| 678 | + } |
| 679 | + |
635 | 680 | template <typename T> |
636 | 681 | const T& SparseMatrix<T>::operator()(Id i, Id j) const { |
637 | 682 | if (i >= _rows || j >= _cols) { |
|
0 commit comments