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
45template <typename Scalar>
46class Spy {
47 public:
56 Spy(std::string_view filename, std::string_view title,
57 std::string_view row_label, std::string_view col_label, int rows,
58 int cols)
59 : m_file{std::string{filename}, std::ios::binary} {
60 // Write title
61 write32le(title.size());
62 m_file.write(title.data(), title.size());
63
64 // Write row label
65 write32le(row_label.size());
66 m_file.write(row_label.data(), row_label.size());
67
68 // Write column label
69 write32le(col_label.size());
70 m_file.write(col_label.data(), col_label.size());
71
72 // Write row and column counts
73 write32le(rows);
74 write32le(cols);
75 }
76
80 void add(const Eigen::SparseMatrix<Scalar>& mat) {
81 // Write number of coordinates
82 write32le(mat.nonZeros());
83
84 // Write coordinates
85 for (int k = 0; k < mat.outerSize(); ++k) {
86 for (typename Eigen::SparseMatrix<Scalar>::InnerIterator it{mat, k}; it;
87 ++it) {
88 write32le(it.row());
89 write32le(it.col());
90 if (it.value() > Scalar(0)) {
91 m_file << '+';
92 } else if (it.value() < Scalar(0)) {
93 m_file << '-';
94 } else {
95 m_file << '0';
96 }
97 }
98 }
99 }
100
101 private:
102 std::ofstream m_file;
103
107 void write32le(int32_t num) {
108 if constexpr (std::endian::native != std::endian::little) {
109 num = std::byteswap(num);
110 }
111 m_file.write(reinterpret_cast<char*>(&num), sizeof(num));
112 }
113};
114
115} // namespace slp
116
117#endif
Definition intrusive_shared_ptr.hpp:27
Definition spy.hpp:46
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:56
void add(const Eigen::SparseMatrix< Scalar > &mat)
Definition spy.hpp:80