Sleipnir C++ API
Loading...
Searching...
No Matches
spy.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
6
7#include <stdint.h>
8
9#include <bit>
10#include <fstream>
11#include <string>
12#include <string_view>
13
14#include <Eigen/SparseCore>
15
16namespace slp {
17
47template <typename Scalar>
48class 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<Scalar>& 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 (typename Eigen::SparseMatrix<Scalar>::InnerIterator it{mat, k}; it;
93 ++it) {
94 write32le(it.row());
95 write32le(it.col());
96 if (it.value() > Scalar(0)) {
97 m_file << '+';
98 } else if (it.value() < Scalar(0)) {
99 m_file << '-';
100 } else {
101 m_file << '0';
102 }
103 }
104 }
105 }
106
107 private:
108 std::ofstream m_file;
109
115 void write32le(int32_t num) {
116 if constexpr (std::endian::native != std::endian::little) {
117 num = std::byteswap(num);
118 }
119 m_file.write(reinterpret_cast<char*>(&num), sizeof(num));
120 }
121};
122
123} // namespace slp
124
125#endif
Definition intrusive_shared_ptr.hpp:29
Definition spy.hpp:48
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
void add(const Eigen::SparseMatrix< Scalar > &mat)
Definition spy.hpp:86