CSRMatrix#

class numpy::CSRMatrix#

numpy C++ class.

Example#

#include <numpy/np_ndarray.h>
using namespace numpy;

// Use CSRMatrix
CSRMatrix obj;
// ... operations ...

Constructors#

Signature

Location

Example

CSRMatrix(size_trows, size_tcols)

NP_SPARSE_CSR.H:58

CSRMatrix(size_trows, size_tcols, std::vector<T>&&values, std::vector<sparse_index_t>&&col_indices, std::vector<sparse_index_t>&&row_ptr)

NP_SPARSE_CSR.H:66

Operators#

Signature

Return Type

Location

Example

T operator()(size_ti, size_tj)

T

NP_SPARSE_CSR.H:196

Construction#

Signature

Return Type

Location

Example

CSRMatrix from_dense(const NDArray<T>&dense, Ttol = T{1e-10})

CSRMatrix

NP_SPARSE_CSR.H:91

View

Array Creation#

Signature

Return Type

Location

Example

CSRMatrix diagonal(const std::vector<T>&diag)

CSRMatrix

NP_SPARSE_CSR.H:147

View

CSRMatrix identity(size_tn)

CSRMatrix

NP_SPARSE_CSR.H:127

View

Indexing / Selection#

Signature

Return Type

Location

Example

T get(size_ti, size_tj)

T

NP_SPARSE_CSR.H:221

View

std::vector<std::pair<sparse_index_t,T>> get_col(size_tj)

std::vector<std::pair<sparse_index_t,T>>

NP_SPARSE_CSR.H:280

std::vector<std::pair<sparse_index_t,T>> get_row(size_ti)

std::vector<std::pair<sparse_index_t,T>>

NP_SPARSE_CSR.H:260

Shape Manipulation#

Signature

Return Type

Location

Example

CSRMatrix<T> transpose()

CSRMatrix<T>

NP_SPARSE_CSR.H:381

View

Sorting#

Signature

Return Type

Location

Example

void sort_indices()

void

NP_SPARSE_CSR.H:310

Type Checking#

Signature

Return Type

Location

Example

bool is_square()

bool

NP_SPARSE_CSR.H:238

Other Methods#

Signature

Return Type

Location

Example

bool check_format()

bool

NP_SPARSE_CSR.H:433

View

CSRMatrix<T> clone()

CSRMatrix<T>

NP_SPARSE_CSR.H:419

View

const sparse_index_t \* col_indices()

const sparse_index_t *

NP_SPARSE_CSR.H:247

sparse_index_t \* col_indices()

sparse_index_t *

NP_SPARSE_CSR.H:248

size_t cols()

size_t

NP_SPARSE_CSR.H:230

View

double density()

double

NP_SPARSE_CSR.H:233

size_t nnz()

size_t

NP_SPARSE_CSR.H:231

View

void print(std::ostream &os = std::cout)

void

NP_SPARSE_CSR.H:515

View

void print_structure(std::ostream &os = std::cout)

void

NP_SPARSE_CSR.H:493

void prune(Ttol)

void

NP_SPARSE_CSR.H:374

void remove_zeros(Ttol = T{0})

void

NP_SPARSE_CSR.H:346

const sparse_index_t \* row_ptr()

const sparse_index_t *

NP_SPARSE_CSR.H:250

sparse_index_t \* row_ptr()

sparse_index_t *

NP_SPARSE_CSR.H:251

size_t rows()

size_t

NP_SPARSE_CSR.H:229

View

std::string toString()

std::string

NP_SPARSE_CSR.H:500

View

std::string toString_structure()

std::string

NP_SPARSE_CSR.H:481

View

const T \* values()

const T *

NP_SPARSE_CSR.H:244

View

T \* values()

T *

NP_SPARSE_CSR.H:245

View

Code Examples#

The following examples are extracted from the test suite.

from_dense (np_test_3_all.cpp:19939)
19929      std::cout << "========= CSR Matrix - basic functionality =======================";
19930
19931      numpy::NDArray<double> dense({ 4, 4 });
19932      dense.setElementAt({ 0, 0 }, 1.0);
19933      dense.setElementAt({ 0, 3 }, 2.0);
19934      dense.setElementAt({ 1, 1 }, 3.0);
19935      dense.setElementAt({ 2, 2 }, 4.0);
19936      dense.setElementAt({ 3, 0 }, 5.0);
19937      dense.setElementAt({ 3, 3 }, 6.0);
19938
19939      auto csr = numpy::sparse::CSRMatrix<double>::from_dense(dense);
19940
19941      if (csr.rows() != 4 || csr.cols() != 4 || csr.nnz() != 6) {
19942        std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : Incorrect matrix dimensions";
19943        throw std::runtime_error("np_test_sparse_csr_basic failed: dimension mismatch");
19944      }
19945
19946      if (!csr.check_format()) {
19947        std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : CSR format validation failed";
19948        throw std::runtime_error("np_test_sparse_csr_basic failed: invalid format");
19949      }
diagonal (np_test_2_all.cpp:11408)
11398    void np_test_linalg_missing_diagonal() {
11399      std::cout << "========= diagonal: extract diagonal from matrix =======================";
11400
11401      numpy::NDArray<double> mat({ 3, 4 });
11402      for (size_t i = 0; i < 3; ++i) {
11403        for (size_t j = 0; j < 4; ++j) {
11404          mat.setElementAt({ i, j }, static_cast<double>(i * 4 + j));
11405        }
11406      }
11407
11408      auto diag = numpy::diagonal(mat);
11409      if (diag.getShape()[0] != 3) {
11410        std::cout << "  [FAIL] : diagonal shape incorrect";
11411        throw std::runtime_error("diagonal test failed: wrong shape");
11412      }
11413
11414      // Check diagonal values (0, 5, 10)
11415      if (std::abs(diag.getElementAt({ 0 }) - 0.0) > 1e-10 ||
11416        std::abs(diag.getElementAt({ 1 }) - 5.0) > 1e-10 ||
11417        std::abs(diag.getElementAt({ 2 }) - 10.0) > 1e-10) {
11418        std::cout << "  [FAIL] : diagonal values incorrect";
identity (np_test_1_all.cpp:24002)
23992          throw std::runtime_error(description);
23993      }
23994      if (!((eye_offset.getShape() == std::vector<size_t>{3, 4}))) {
23995          std::string description = std::string("testArrayCreationSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !((eye_offset.getShape() == std::vector<size_t>{3, 4}))";
23996          std::cout << std::string("[FAIL] ") + description << std::endl;
23997          throw std::runtime_error(description);
23998      }
23999      // std::cout << "[OK] eye function with optional parameters works correctly\n";
24000
24001      // Test identity
24002      auto identity_result = identity<int>(4);
24003      if (!((identity_result.getShape() == std::vector<size_t>{4, 4}))) {
24004          std::string description = std::string("testArrayCreationSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !((identity_result.getShape() == std::vector<size_t>{4, 4}))";
24005          std::cout << std::string("[FAIL] ") + description << std::endl;
24006          throw std::runtime_error(description);
24007      }
24008      // std::cout << "[OK] identity function has correct signature\n";
24009
24010      // Test diag with different use cases
24011      auto vector1d = createInt32Array({ 3 }, 5);
24012      auto matrix2d = createInt32Array({ 3, 3 }, 0);
get (np_test_1_all.cpp:28526)
28516      std::cout << " -> tests passed" << std::endl;
28517    }
28518
28519    void np_test_indexing_mask_indices() {
28520      std::cout << "========= mask_indices: triangular mask indices =======================";
28521
28522      // Get upper triangular indices for 3x3 matrix
28523      auto triu_idx = numpy::mask_indices(3, "triu", 0);
28524
28525      // Should return tuple of 2 arrays
28526      bool passed = (std::get<0>(triu_idx).getSize() > 0);
28527      passed = passed && (std::get<1>(triu_idx).getSize() > 0);
28528      passed = passed && (std::get<0>(triu_idx).getSize() == std::get<1>(triu_idx).getSize());
28529
28530      // Get lower triangular indices
28531      auto tril_idx = numpy::mask_indices(3, "tril", 0);
28532      passed = passed && (std::get<0>(tril_idx).getSize() > 0);
28533      passed = passed && (std::get<1>(tril_idx).getSize() > 0);
28534
28535      if (!passed) {
28536        std::cout << "  [FAIL] : in np_test_indexing_mask_indices() : Mask indices incorrect";
transpose (np_test_2_all.cpp:4973)
4963    }
4964
4965    /**
4966     * Test matrix properties and methods
4967     */
4968    void testMatrixProperties() {
4969      std::cout << "========= testMatrixProperties =======================";
4970
4971      // Test transpose
4972      numpy::Matrix<double> m("1 2 3; 4 5 6");
4973      auto mt = m.transpose();
4974      assert_test(mt.rows() == 3, "Transpose rows");
4975      assert_test(mt.cols() == 2, "Transpose cols");
4976      assert_test(std::abs(mt(0, 1) - 4.0) < 1e-10, "Transpose element");
4977      assert_test(std::abs(mt(2, 0) - 3.0) < 1e-10, "Transpose element");
4978
4979      // Test trace for square matrix
4980      numpy::Matrix<double> square("1 2; 3 4");
4981      double tr = square.trace();
4982      assert_test(std::abs(tr - 5.0) < 1e-10, "Matrix trace");
check_format (np_test_3_all.cpp:19946)
19936      dense.setElementAt({ 3, 0 }, 5.0);
19937      dense.setElementAt({ 3, 3 }, 6.0);
19938
19939      auto csr = numpy::sparse::CSRMatrix<double>::from_dense(dense);
19940
19941      if (csr.rows() != 4 || csr.cols() != 4 || csr.nnz() != 6) {
19942        std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : Incorrect matrix dimensions";
19943        throw std::runtime_error("np_test_sparse_csr_basic failed: dimension mismatch");
19944      }
19945
19946      if (!csr.check_format()) {
19947        std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : CSR format validation failed";
19948        throw std::runtime_error("np_test_sparse_csr_basic failed: invalid format");
19949      }
19950
19951      auto reconstructed = csr.to_dense();
19952      for (size_t i = 0; i < 4; ++i) {
19953        for (size_t j = 0; j < 4; ++j) {
19954          if (std::abs(dense.getElementAt({ i, j }) - reconstructed.getElementAt({ i, j })) > 1e-12) {
19955            std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : Roundtrip conversion mismatch";
19956            throw std::runtime_error("np_test_sparse_csr_basic failed");
clone (np_test_1_all.cpp:24942)
24932      }
24933
24934      // Test reproducibility
24935      numpy::random::PCG64DXSM rng2(11111);
24936      if (rng2.next_uint64() != val) {
24937        std::cout << "  [FAIL] : in np_test_bitgen_pcg64dxsm() : not reproducible";
24938        throw std::runtime_error("np_test_bitgen_pcg64dxsm failed");
24939      }
24940
24941      // Test clone
24942      auto cloned = rng.clone();
24943      if (cloned->name() != "PCG64DXSM") {
24944        std::cout << "  [FAIL] : in np_test_bitgen_pcg64dxsm() : clone name incorrect";
24945        throw std::runtime_error("np_test_bitgen_pcg64dxsm failed");
24946      }
24947
24948      std::cout << " -> tests passed" << std::endl;
24949    }
24950
24951    // ============================================================================
24952    // PHILOX TESTS
cols (np_test_2_all.cpp:4911)
4901    /**
4902     * Test basic matrix construction and properties
4903     */
4904    void testMatrixBasics() {
4905      std::cout << "========= testMatrixBasics =======================";
4906
4907      // Test construction from dimensions
4908      numpy::Matrix<double> m1(3, 3);
4909      assert_test(m1.rows() == 3, "Matrix rows");
4910      assert_test(m1.cols() == 3, "Matrix cols");
4911      assert_test(m1.isSquare(), "Matrix is square");
4912
4913      // Test construction from 2D vector
4914      std::vector<std::vector<int>> data = { {1, 2, 3}, {4, 5, 6} };
4915      numpy::Matrix<int> m2(data);
4916      assert_test(m2.rows() == 2, "Matrix from vector rows");
4917      assert_test(m2.cols() == 3, "Matrix from vector cols");
4918      assert_test(m2(0, 0) == 1, "Matrix element access");
4919      assert_test(m2(1, 2) == 6, "Matrix element access");
nnz (np_test_3_all.cpp:19941)
19931      numpy::NDArray<double> dense({ 4, 4 });
19932      dense.setElementAt({ 0, 0 }, 1.0);
19933      dense.setElementAt({ 0, 3 }, 2.0);
19934      dense.setElementAt({ 1, 1 }, 3.0);
19935      dense.setElementAt({ 2, 2 }, 4.0);
19936      dense.setElementAt({ 3, 0 }, 5.0);
19937      dense.setElementAt({ 3, 3 }, 6.0);
19938
19939      auto csr = numpy::sparse::CSRMatrix<double>::from_dense(dense);
19940
19941      if (csr.rows() != 4 || csr.cols() != 4 || csr.nnz() != 6) {
19942        std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : Incorrect matrix dimensions";
19943        throw std::runtime_error("np_test_sparse_csr_basic failed: dimension mismatch");
19944      }
19945
19946      if (!csr.check_format()) {
19947        std::cout << "  [FAIL] : in np_test_sparse_csr_basic() : CSR format validation failed";
19948        throw std::runtime_error("np_test_sparse_csr_basic failed: invalid format");
19949      }
19950
19951      auto reconstructed = csr.to_dense();
print (np_test_1_all.cpp:6395)
6385    std::vector<std::string> strings = {"Alice", "Bob", "Charlie"};
6386    auto arr2 = array<32>(strings);
6387    // std::cout << "Created from strings vector:" << std::endl;
6388    for (size_t i = 0; i < arr2.size(); ++i) {
6389        // std::cout << "arr2[" << i << "] = '" << arr2[i] << "'";
6390    }
6391
6392    // Test 2D array creation
6393    chararray16 arr_2d({2, 3}, "test");
6394    // std::cout << "Created 2D chararray16 with shape {2, 3}:";
6395    // arr_2d.print();
6396
6397    std::cout << " -> tests passed" << std::endl;
6398}
6399
6400void testCharArrayStringOperationsCharArray() {
6401    std::cout << "========= testStringOperations =======================";
6402
6403    // Test string concatenation
6404    std::vector<std::string> words1 = {"Hello", "Good", "Nice"};
6405    std::vector<std::string> words2 = {" World", " Day", " Work"};
rows (np_test_2_all.cpp:4910)
4900  namespace test_matrix {
4901
4902    /**
4903     * Test basic matrix construction and properties
4904     */
4905    void testMatrixBasics() {
4906      std::cout << "========= testMatrixBasics =======================";
4907
4908      // Test construction from dimensions
4909      numpy::Matrix<double> m1(3, 3);
4910      assert_test(m1.rows() == 3, "Matrix rows");
4911      assert_test(m1.cols() == 3, "Matrix cols");
4912      assert_test(m1.isSquare(), "Matrix is square");
4913
4914      // Test construction from 2D vector
4915      std::vector<std::vector<int>> data = { {1, 2, 3}, {4, 5, 6} };
4916      numpy::Matrix<int> m2(data);
4917      assert_test(m2.rows() == 2, "Matrix from vector rows");
4918      assert_test(m2.cols() == 3, "Matrix from vector cols");
4919      assert_test(m2(0, 0) == 1, "Matrix element access");
4920      assert_test(m2(1, 2) == 6, "Matrix element access");
toString (np_test_1_all.cpp:6826)
6816void testDatetime64CreationDateTime() {
6817    std::cout << "========= testDatetime64CreationDateTime =======================";
6818
6819    // Test default constructor
6820    datetime64 default_dt;
6821    if (!(default_dt.isNaT())) {
6822        std::string description = std::string("testDatetime64CreationDateTime():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(default_dt.isNaT())";
6823        std::cout << std::string("[FAIL] ") + description << std::endl;
6824        throw std::runtime_error(description);
6825    }
6826    // std::cout << "Default datetime64 is NaT: " << default_dt.toString() << std::endl;
6827
6828    // Test value constructor
6829    datetime64 epoch_day(0, DateTimeUnit::Day);
6830    // std::cout << "Epoch day: " << epoch_day.toString() << std::endl;
6831
6832    // Test string constructor
6833    datetime64 date_from_string("2024-01-15");
6834    // std::cout << "Date from string '2024-01-15': " << date_from_string.toString() << std::endl;
6835
6836    datetime64 datetime_from_string("2024-01-15T10:30:45");
toString_structure (np_test_5_all.cpp:8652)
8642    }
8643
8644    std::cout << " -> tests passed" << std::endl;
8645  }
8646
8647  // ===========================
8648  // Sparse CSR Tests
8649  // ===========================
8650
8651  void np_test_toString_sparse_structure() {
8652    std::cout << "========= CSRMatrix::toString_structure() =======================";
8653
8654    // Create a sparse matrix using from_dense
8655    numpy::NDArray<double> dense({ 100, 100 });
8656    dense.setElementAt({ 10, 10 }, 3.14);
8657    dense.setElementAt({ 20, 30 }, 2.71);
8658    numpy::sparse::CSRMatrix<double> sparse_matrix = numpy::sparse::CSRMatrix<double>::from_dense(dense);
8659
8660    std::string result = sparse_matrix.toString_structure();
8661
8662    // std::cout << "Result:\n" << result << std::endl;
values (np_test_1_all.cpp:15133)
15123        std::cout << " -> tests passed" << std::endl;
15124      }
15125      else {
15126        std::cout << "[FAIL] Where function failed" << std::endl;
15127        errors++;
15128      }
15129
15130      // Test 8: Clip function
15131      std::cout << "========= test_clip_function =======================" ;
15132
15133      numpy::NDArray<double> values({ 5 });
15134      values.setElementAt({ 0 }, -2.0);
15135      values.setElementAt({ 1 }, -1.0);
15136      values.setElementAt({ 2 }, 0.5);
15137      values.setElementAt({ 3 }, 2.0);
15138      values.setElementAt({ 4 }, 5.0);
15139      double min_val = -1.0;
15140      double max_val = 3.0;
15141
15142      auto clip_result = numpy::clip(values, min_val, max_val);
values (np_test_1_all.cpp:15133)
15123        std::cout << " -> tests passed" << std::endl;
15124      }
15125      else {
15126        std::cout << "[FAIL] Where function failed" << std::endl;
15127        errors++;
15128      }
15129
15130      // Test 8: Clip function
15131      std::cout << "========= test_clip_function =======================" ;
15132
15133      numpy::NDArray<double> values({ 5 });
15134      values.setElementAt({ 0 }, -2.0);
15135      values.setElementAt({ 1 }, -1.0);
15136      values.setElementAt({ 2 }, 0.5);
15137      values.setElementAt({ 3 }, 2.0);
15138      values.setElementAt({ 4 }, 5.0);
15139      double min_val = -1.0;
15140      double max_val = 3.0;
15141
15142      auto clip_result = numpy::clip(values, min_val, max_val);