Sleipnir C++ API
Loading...
Searching...
No Matches
Spy.hpp
Go to the documentation of this file.
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
15
16namespace sleipnir {
17
49 public:
60 Spy(std::string_view filename, std::string_view title,
61 std::string_view rowLabel, std::string_view colLabel, int rows, int cols)
62 : m_file{std::string{filename}, std::ios::binary} {
63 // Write title
64 Write32le(title.size());
65 m_file.write(title.data(), title.size());
66
67 // Write row label
68 Write32le(rowLabel.size());
69 m_file.write(rowLabel.data(), rowLabel.size());
70
71 // Write column label
72 Write32le(colLabel.size());
73 m_file.write(colLabel.data(), colLabel.size());
74
75 // Write row and column counts
76 Write32le(rows);
77 Write32le(cols);
78 }
79
85 void Add(const Eigen::SparseMatrix<double>& mat) {
86 // Write number of coordinates
87 Write32le(mat.nonZeros());
88
89 // Write coordinates
90 for (int k = 0; k < mat.outerSize(); ++k) {
91 for (Eigen::SparseMatrix<double>::InnerIterator it{mat, k}; it; ++it) {
92 Write32le(it.row());
93 Write32le(it.col());
94 if (it.value() > 0.0) {
95 m_file << '+';
96 } else if (it.value() < 0.0) {
97 m_file << '-';
98 } else {
99 m_file << '0';
100 }
101 }
102 }
103 }
104
105 private:
106 std::ofstream m_file;
107
113 void Write32le(int32_t num) {
114 if constexpr (std::endian::native != std::endian::little) {
115 num = std::byteswap(num);
116 }
117 m_file.write(reinterpret_cast<char*>(&num), sizeof(num));
118 }
119};
120
121} // namespace sleipnir
#define SLEIPNIR_DLLEXPORT
Definition SymbolExports.hpp:34
Definition Spy.hpp:48
Spy(std::string_view filename, std::string_view title, std::string_view rowLabel, std::string_view colLabel, int rows, int cols)
Definition Spy.hpp:60
void Add(const Eigen::SparseMatrix< double > &mat)
Definition Spy.hpp:85
Definition Expression.hpp:18