|
11 | 11 |
|
12 | 12 | namespace binsparse { |
13 | 13 |
|
| 14 | +// CSR Format |
| 15 | + |
| 16 | +template <typename T, typename I> |
| 17 | +void write_csr_matrix(std::string fname, |
| 18 | + csr_matrix<T, I> m) { |
| 19 | + |
| 20 | + H5::H5File f(fname.c_str(), H5F_ACC_TRUNC); |
| 21 | + |
| 22 | + std::span<T> values(m.values, m.nnz); |
| 23 | + std::span<I> colind(m.colind, m.nnz); |
| 24 | + std::span<I> row_ptr(m.row_ptr, m.m+1); |
| 25 | + |
| 26 | + hdf5_tools::write_dataset(f, "values", values); |
| 27 | + hdf5_tools::write_dataset(f, "indices_1", colind); |
| 28 | + hdf5_tools::write_dataset(f, "pointers_to_1", row_ptr); |
| 29 | + |
| 30 | + std::string json_string = |
| 31 | + "{\n" |
| 32 | + " \"format\": \"CSR\",\n" |
| 33 | + " \"shape\": ["; |
| 34 | + json_string += std::to_string(m.m) + ", " + std::to_string(m.n) + |
| 35 | + "],\n" + |
| 36 | + " \"nnz\": " + std::to_string(m.nnz) + "\n" + |
| 37 | + "}\n"; |
| 38 | + |
| 39 | + hdf5_tools::write_dataset(f, "metadata", json_string); |
| 40 | + |
| 41 | + f.close(); |
| 42 | +} |
| 43 | + |
| 44 | +template <typename T, typename I, typename Allocator> |
| 45 | +csr_matrix<T, I> read_csr_matrix(std::string fname, Allocator&& alloc) { |
| 46 | + H5::H5File f(fname.c_str(), H5F_ACC_RDWR); |
| 47 | + |
| 48 | + auto metadata = hdf5_tools::read_dataset<char>(f, "metadata"); |
| 49 | + |
| 50 | + using json = nlohmann::json; |
| 51 | + auto data = json::parse(metadata); |
| 52 | + |
| 53 | + if (data["format"] == "CSR") { |
| 54 | + auto nrows = data["shape"][0]; |
| 55 | + auto ncols = data["shape"][1]; |
| 56 | + auto nnz = data["nnz"]; |
| 57 | + |
| 58 | + typename std::allocator_traits<std::remove_cvref_t<Allocator>> |
| 59 | + :: template rebind_alloc<I> i_alloc(alloc); |
| 60 | + |
| 61 | + auto values = hdf5_tools::read_dataset<T>(f, "values", alloc); |
| 62 | + auto colind = hdf5_tools::read_dataset<I>(f, "indices_1", i_alloc); |
| 63 | + auto row_ptr = hdf5_tools::read_dataset<I>(f, "pointers_to_1", i_alloc); |
| 64 | + |
| 65 | + return csr_matrix<T, I>{values.data(), colind.data(), row_ptr.data(), nrows, ncols, nnz}; |
| 66 | + } else { |
| 67 | + assert(false); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +template <typename T, typename I> |
| 72 | +csr_matrix<T, I> read_csr_matrix(std::string fname) { |
| 73 | + return read_csr_matrix<T, I>(fname, std::allocator<T>{}); |
| 74 | +} |
| 75 | + |
| 76 | +// COO Format |
| 77 | + |
14 | 78 | template <typename T, typename I> |
15 | 79 | void write_coo_matrix(std::string fname, |
16 | 80 | coo_matrix<T, I> m) { |
|
0 commit comments