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/// @todo Add transpose, symmetry diagnostics, and efficient diagonal extraction
4/// utilities for sparse solvers and preconditioners.
5#pragma once
6#include "core/types.hpp"
7#include "core/vector.hpp"
8#include <stdexcept>
9#include <vector>
10
11namespace num {
12
13/// @brief Sparse matrix in Compressed Sparse Row (CSR) format
14///
15/// Non-zero values for row i are stored in vals_[row_ptr_[i] .. row_ptr_[i+1]).
16/// Corresponding column indices are in col_idx_[row_ptr_[i] .. row_ptr_[i+1]).
18public:
19 /// @brief Construct from raw CSR arrays (takes ownership)
21 idx n_cols,
22 std::vector<real> vals,
23 std::vector<idx> col_idx,
24 std::vector<idx> row_ptr);
25
26 /// @brief Build from coordinate (COO / triplet) lists
27 ///
28 /// Duplicate (row, col) entries are summed. Entries need not be sorted.
30 idx n_cols,
31 const std::vector<idx>& rows,
32 const std::vector<idx>& cols,
33 const std::vector<real>& vals);
34
35 idx n_rows() const { return n_rows_; }
36 idx n_cols() const { return n_cols_; }
37 idx nnz() const { return vals_.size(); }
38
39 /// @brief Element access A(i,j); returns 0 if outside stored pattern --
40 /// O(nnz/n)
41 real operator()(idx i, idx j) const;
42
43 [[nodiscard]] const real* values() const { return vals_.data(); }
44 [[nodiscard]] const idx* col_idx() const { return col_idx_.data(); }
45 [[nodiscard]] const idx* row_ptr() const { return row_ptr_.data(); }
46
47private:
48 idx n_rows_ = 0, n_cols_ = 0;
49 std::vector<real> vals_;
50 std::vector<idx> col_idx_;
51 std::vector<idx> row_ptr_; // size n_rows_ + 1
52};
53
54/// @brief y = A * x
55void sparse_matvec(const SparseMatrix& A, const Vector& x, Vector& y);
56
57} // namespace num
Sparse matrix in Compressed Sparse Row (CSR) format.
Definition sparse.hpp:17
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:37
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:36
const idx * row_ptr() const
Definition sparse.hpp:45
idx n_rows() const
Definition sparse.hpp:35
const idx * col_idx() const
Definition sparse.hpp:44
const real * values() const
Definition sparse.hpp:43
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.