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
namespace
slp {
17
47
template
<
typename
Scalar>
48
class
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
slp::IntrusiveSharedPtr
Definition
intrusive_shared_ptr.hpp:29
slp::Spy
Definition
spy.hpp:48
slp::Spy::Spy
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
slp::Spy::add
void add(const Eigen::SparseMatrix< Scalar > &mat)
Definition
spy.hpp:86
include
sleipnir
util
spy.hpp
Generated on Wed Oct 29 2025 07:00:11 for Sleipnir C++ API by
1.9.8