numerics
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 <vector>
7#include <stdexcept>
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]).
16public:
17 /// @brief Construct from raw CSR arrays (takes ownership)
19 std::vector<real> vals,
20 std::vector<idx> col_idx,
21 std::vector<idx> row_ptr);
22
23 /// @brief Build from coordinate (COO / triplet) lists
24 ///
25 /// Duplicate (row, col) entries are summed. Entries need not be sorted.
27 const std::vector<idx>& rows,
28 const std::vector<idx>& cols,
29 const std::vector<real>& vals);
30
31 idx n_rows() const { return n_rows_; }
32 idx n_cols() const { return n_cols_; }
33 idx nnz() const { return vals_.size(); }
34
35 /// @brief Element access A(i,j); returns 0 if outside stored pattern -- O(nnz/n)
36 real operator()(idx i, idx j) const;
37
38 const real* values() const { return vals_.data(); }
39 const idx* col_idx() const { return col_idx_.data(); }
40 const idx* row_ptr() const { return row_ptr_.data(); }
41
42private:
43 idx n_rows_, n_cols_;
44 std::vector<real> vals_;
45 std::vector<idx> col_idx_;
46 std::vector<idx> row_ptr_; // size n_rows_ + 1
47};
48
49/// @brief y = A * x
50void sparse_matvec(const SparseMatrix& A, const Vector& x, Vector& y);
51
52} // 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:104
idx nnz() const
Definition sparse.hpp:33
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:23
idx n_cols() const
Definition sparse.hpp:32
const idx * row_ptr() const
Definition sparse.hpp:40
idx n_rows() const
Definition sparse.hpp:31
const idx * col_idx() const
Definition sparse.hpp:39
const real * values() const
Definition sparse.hpp:38
Core type definitions.
double real
Definition types.hpp:10
constexpr T ipow(T x) noexcept
Compute x^N at compile time via repeated squaring.
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:110
BasicVector< real > Vector
Real-valued dense vector with full backend dispatch (CPU + GPU)
Definition vector.hpp:122
Vector operations.