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 { return n_rows_; }
34 idx n_cols() const { return n_cols_; }
35 idx nnz() const { return vals_.size(); }
36
37 /// @brief Element access A(i,j); returns 0 if outside stored pattern --
38 /// O(nnz/n)
39 real operator()(idx i, idx j) const;
40
41 [[nodiscard]] const real* values() const { return vals_.data(); }
42 [[nodiscard]] const idx* col_idx() const { return col_idx_.data(); }
43 [[nodiscard]] const idx* row_ptr() const { return row_ptr_.data(); }
44
45 private:
46 idx n_rows_ = 0, n_cols_ = 0;
47 std::vector<real> vals_;
48 std::vector<idx> col_idx_;
49 std::vector<idx> row_ptr_; // size n_rows_ + 1
50};
51
52/// @brief y = A * x
53void sparse_matvec(const SparseMatrix& A, const Vector& x, Vector& y);
54
55} // 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:115
idx nnz() const
Definition sparse.hpp:35
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:25
idx n_cols() const
Definition sparse.hpp:34
const idx * row_ptr() const
Definition sparse.hpp:43
idx n_rows() const
Definition sparse.hpp:33
const idx * col_idx() const
Definition sparse.hpp:42
const real * values() const
Definition sparse.hpp:41
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:122
BasicVector< real > Vector
Real-valued dense vector with full backend dispatch (CPU + GPU)
Definition vector.hpp:129
Dense vector storage and operations.