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
16#include "sleipnir/util/symbol_exports.hpp"
17
18namespace slp {
19
50class SLEIPNIR_DLLEXPORT Spy {
51 public:
62 Spy(std::string_view filename, std::string_view title,
63 std::string_view row_label, std::string_view col_label, int rows,
64 int cols)
65 : m_file{std::string{filename}, std::ios::binary} {
66 // Write title
67 write32le(title.size());
68 m_file.write(title.data(), title.size());
69
70 // Write row label
71 write32le(row_label.size());
72 m_file.write(row_label.data(), row_label.size());
73
74 // Write column label
75 write32le(col_label.size());
76 m_file.write(col_label.data(), col_label.size());
77
78 // Write row and column counts
79 write32le(rows);
80 write32le(cols);
81 }
82
88 void add(const Eigen::SparseMatrix<double>& mat) {
89 // Write number of coordinates
90 write32le(mat.nonZeros());
91
92 // Write coordinates
93 for (int k = 0; k < mat.outerSize(); ++k) {
94 for (Eigen::SparseMatrix<double>::InnerIterator it{mat, k}; it; ++it) {
95 write32le(it.row());
96 write32le(it.col());
97 if (it.value() > 0.0) {
98 m_file << '+';
99 } else if (it.value() < 0.0) {
100 m_file << '-';
101 } else {
102 m_file << '0';
103 }
104 }
105 }
106 }
107
108 private:
109 std::ofstream m_file;
110
116 void write32le(int32_t num) {
117 if constexpr (std::endian::native != std::endian::little) {
118 num = std::byteswap(num);
119 }
120 m_file.write(reinterpret_cast<char*>(&num), sizeof(num));
121 }
122};
123
124} // namespace slp
125
126#endif
Definition spy.hpp:50
void add(const Eigen::SparseMatrix< double > &mat)
Definition spy.hpp:88
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:62