Sleipnir C++ API
Loading...
Searching...
No Matches
spy.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <stdint.h>
6
7#include <bit>
8#include <fstream>
9#include <string>
10#include <string_view>
11
12#include <Eigen/SparseCore>
13
14#include "sleipnir/util/symbol_exports.hpp"
15
16namespace slp {
17
48class SLEIPNIR_DLLEXPORT Spy {
49 public:
60 Spy(std::string_view filename, std::string_view title,
61 std::string_view row_label, std::string_view col_label, int rows,
62 int cols)
63 : m_file{std::string{filename}, std::ios::binary} {
64 // Write title
65 write32le(title.size());
66 m_file.write(title.data(), title.size());
67
68 // Write row label
69 write32le(row_label.size());
70 m_file.write(row_label.data(), row_label.size());
71
72 // Write column label
73 write32le(col_label.size());
74 m_file.write(col_label.data(), col_label.size());
75
76 // Write row and column counts
77 write32le(rows);
78 write32le(cols);
79 }
80
86 void add(const Eigen::SparseMatrix<double>& mat) {
87 // Write number of coordinates
88 write32le(mat.nonZeros());
89
90 // Write coordinates
91 for (int k = 0; k < mat.outerSize(); ++k) {
92 for (Eigen::SparseMatrix<double>::InnerIterator it{mat, k}; it; ++it) {
93 write32le(it.row());
94 write32le(it.col());
95 if (it.value() > 0.0) {
96 m_file << '+';
97 } else if (it.value() < 0.0) {
98 m_file << '-';
99 } else {
100 m_file << '0';
101 }
102 }
103 }
104 }
105
106 private:
107 std::ofstream m_file;
108
114 void write32le(int32_t num) {
115 if constexpr (std::endian::native != std::endian::little) {
116 num = std::byteswap(num);
117 }
118 m_file.write(reinterpret_cast<char*>(&num), sizeof(num));
119 }
120};
121
122} // namespace slp
Definition spy.hpp:48
void add(const Eigen::SparseMatrix< double > &mat)
Definition spy.hpp:86
Spy(std::string_view filename, std::string_view title, std::string_view row_label, std::string_view col_label, int rows, int cols)
Definition spy.hpp:60