| 68 | |
| 69 | template<typename T> |
| 70 | void ExportSparseMatrix(py::module m) |
| 71 | { |
| 72 | py::class_<SparseMatrix<T>, shared_ptr<SparseMatrix<T>>, BaseSparseMatrix /*, S_BaseMatrix<typename mat_traits<T>::TSCAL> */ > |
| 73 | (m, (string("SparseMatrix") + typeid(T).name()).c_str(), |
| 74 | "a sparse matrix in CSR storage") |
| 75 | .def("__getitem__", |
| 76 | [](const SparseMatrix<T> & self, py::tuple t) |
| 77 | { |
| 78 | size_t row = t[0].cast<size_t>(); |
| 79 | size_t col = t[1].cast<size_t>(); |
| 80 | if(row >= self.Height() || col >= self.Width()) |
| 81 | throw py::index_error("Access (" + ToString(row) + "," + ToString(col) + ") in " + ToString(self.Height()) + "x" + ToString(self.Width()) + " matrix!"); |
| 82 | return self(row,col); |
| 83 | }, py::arg("pos"), "Return value at given position") |
| 84 | .def("__setitem__", |
| 85 | [](SparseMatrix<T> & self, py::tuple t, T value) |
| 86 | { |
| 87 | size_t row = t[0].cast<size_t>(); |
| 88 | size_t col = t[1].cast<size_t>(); |
| 89 | self(row,col) = value; |
| 90 | }, py::arg("pos"), py::arg("value"), "Set value at given position") |
| 91 | |
| 92 | .def("COO", [] (SparseMatrix<T> * sp) -> py::object |
| 93 | { |
| 94 | size_t nze = sp->NZE(); |
| 95 | Array<int> ri(nze), ci(nze); |
| 96 | Vector<T> vals(nze); |
| 97 | for (size_t i = 0, ii = 0; i < sp->Height(); i++) |
| 98 | { |
| 99 | FlatArray ind = sp->GetRowIndices(i); |
| 100 | FlatVector<T> rv = sp->GetRowValues(i); |
| 101 | for (int j = 0; j < ind.Size(); j++, ii++) |
| 102 | { |
| 103 | ri[ii] = i; |
| 104 | ci[ii] = ind[j]; |
| 105 | vals[ii] = rv[j]; |
| 106 | } |
| 107 | } |
| 108 | /* |
| 109 | t2.Start(); |
| 110 | // still copies, we don't understand why |
| 111 | py::object pyri = py::cast(std::move(ri)); |
| 112 | py::object pyci = py::cast(std::move(ci)); |
| 113 | py::object pyvals = py::cast(std::move(vals)); |
| 114 | t2.Stop(); |
| 115 | return py::make_tuple (pyri, pyci, pyvals); |
| 116 | */ |
| 117 | // moves the arrays |
| 118 | return py::make_tuple (std::move(ri), std::move(ci), std::move(vals)); |
| 119 | }) |
| 120 | |
| 121 | .def("CSR", [] (shared_ptr<SparseMatrix<T>> sp) -> py::object |
| 122 | { |
| 123 | // FlatArray<int> colind(sp->NZE(), sp->GetRowIndices().Addr(0)); |
| 124 | FlatArray colind = sp->GetColIndices(); |
| 125 | // FlatVector<T> values(sp->NZE(), sp->GetRowValues().Addr(0)); |
| 126 | FlatVector<T> values = sp->GetValues(); |
| 127 | typedef typename mat_traits<T>::TSCAL TSCAL; |