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