numerics 0.1.0
Loading...
Searching...
No Matches
sparse.hpp
Go to the documentation of this file.
1/// @file sparse.hpp
2/// @brief Compressed Sparse Row (CSR) matrix and operations
3#pragma once
4#include "core/types.hpp"
5#include "core/vector.hpp"
6#include <stdexcept>
7#include <vector>
8
9namespace num {
10
11/// @brief Sparse matrix in Compressed Sparse Row (CSR) format
12///
13/// Non-zero values for row i are stored in vals_[row_ptr_[i] .. row_ptr_[i+1]).
14/// Corresponding column indices are in col_idx_[row_ptr_[i] .. row_ptr_[i+1]).
16 public:
17 /// @brief Construct from raw CSR arrays (takes ownership)
19 idx n_cols,
20 std::vector<real> vals,
21 std::vector<idx> col_idx,
22 std::vector<idx> row_ptr);
23
24 /// @brief Build from coordinate (COO / triplet) lists
25 ///
26 /// Duplicate (row, col) entries are summed. Entries need not be sorted.
28 idx n_cols,
29 const std::vector<idx>& rows,
30 const std::vector<idx>& cols,
31 const std::vector<real>& vals);
32
33 idx n_rows() const {
34 return n_rows_;
35 }
36 idx n_cols() const {
37 return n_cols_;
38 }
39 idx nnz() const {
40 return vals_.size();
41 }
42
43 /// @brief Element access A(i,j); returns 0 if outside stored pattern --
44 /// O(nnz/n)
45 real operator()(idx i, idx j) const;
46
47 const real* values() const {
48 return vals_.data();
49 }
50 const idx* col_idx() const {
51 return col_idx_.data();
52 }
53 const idx* row_ptr() const {
54 return row_ptr_.data();
55 }
56
57 private:
58 idx n_rows_ = 0, n_cols_ = 0;
59 std::vector<real> vals_;
60 std::vector<idx> col_idx_;
61 std::vector<idx> row_ptr_; // size n_rows_ + 1
62};
63
64/// @brief y = A * x
65void sparse_matvec(const SparseMatrix& A, const Vector& x, Vector& y);
66
67} // namespace num
Sparse matrix in Compressed Sparse Row (CSR) format.
Definition sparse.hpp:15
real operator()(idx i, idx j) const
Element access A(i,j); returns 0 if outside stored pattern – O(nnz/n)
Definition sparse.cpp:117
idx nnz() const
Definition sparse.hpp:39
static SparseMatrix from_triplets(idx n_rows, idx n_cols, const std::vector< idx > &rows, const std::vector< idx > &cols, const std::vector< real > &vals)
Build from coordinate (COO / triplet) lists.
Definition sparse.cpp:26
idx n_cols() const
Definition sparse.hpp:36
const idx * row_ptr() const
Definition sparse.hpp:53
idx n_rows() const
Definition sparse.hpp:33
const idx * col_idx() const
Definition sparse.hpp:50
const real * values() const
Definition sparse.hpp:47
Core type definitions.
double real
Definition types.hpp:10
std::size_t idx
Definition types.hpp:11
void sparse_matvec(const SparseMatrix &A, const Vector &x, Vector &y)
y = A * x
Definition sparse.cpp:124
BasicVector< real > Vector
Real-valued dense vector with full backend dispatch (CPU + GPU)
Definition vector.hpp:130
Vector operations.