WPILibC++ 2025.1.1
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 <fstream>
6#include <string>
7#include <string_view>
8
9#include <Eigen/SparseCore>
10#include <wpi/SmallVector.h>
11
13
14namespace sleipnir {
15
16/**
17 * Write the sparsity pattern of a sparse matrix to a file.
18 *
19 * Each character represents an element with '.' representing zero, '+'
20 * representing positive, and '-' representing negative. Here's an example for a
21 * 3x3 identity matrix.
22 *
23 * "+.."
24 * ".+."
25 * "..+"
26 *
27 * @param[out] file A file stream.
28 * @param[in] mat The sparse matrix.
29 */
30SLEIPNIR_DLLEXPORT inline void Spy(std::ostream& file,
31 const Eigen::SparseMatrix<double>& mat) {
32 const int cells_width = mat.cols() + 1;
33 const int cells_height = mat.rows();
34
36
37 // Allocate space for matrix of characters plus trailing newlines
38 cells.reserve(cells_width * cells_height);
39
40 // Initialize cell array
41 for (int row = 0; row < mat.rows(); ++row) {
42 for (int col = 0; col < mat.cols(); ++col) {
43 cells.emplace_back('.');
44 }
45 cells.emplace_back('\n');
46 }
47
48 // Fill in non-sparse entries
49 for (int k = 0; k < mat.outerSize(); ++k) {
50 for (Eigen::SparseMatrix<double>::InnerIterator it{mat, k}; it; ++it) {
51 if (it.value() < 0.0) {
52 cells[it.row() * cells_width + it.col()] = '-';
53 } else if (it.value() > 0.0) {
54 cells[it.row() * cells_width + it.col()] = '+';
55 }
56 }
57 }
58
59 // Write cell array to file
60 for (const auto& c : cells) {
61 file << c;
62 }
63}
64
65/**
66 * Write the sparsity pattern of a sparse matrix to a file.
67 *
68 * Each character represents an element with "." representing zero, "+"
69 * representing positive, and "-" representing negative. Here's an example for a
70 * 3x3 identity matrix.
71 *
72 * "+.."
73 * ".+."
74 * "..+"
75 *
76 * @param[in] filename The filename.
77 * @param[in] mat The sparse matrix.
78 */
79SLEIPNIR_DLLEXPORT inline void Spy(std::string_view filename,
80 const Eigen::SparseMatrix<double>& mat) {
81 std::ofstream file{std::string{filename}};
82 if (!file.is_open()) {
83 return;
84 }
85
86 Spy(file, mat);
87}
88
89} // namespace sleipnir
This file defines the SmallVector class.
#define SLEIPNIR_DLLEXPORT
Definition SymbolExports.hpp:34
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition SmallVector.h:1212
reference emplace_back(ArgTypes &&... Args)
Definition SmallVector.h:953
void reserve(size_type N)
Definition SmallVector.h:679
Definition Hessian.hpp:18
SLEIPNIR_DLLEXPORT void Spy(std::ostream &file, const Eigen::SparseMatrix< double > &mat)
Write the sparsity pattern of a sparse matrix to a file.
Definition Spy.hpp:30