12#include <cuda_runtime.h>
13#include <cusparse_v2.h>
16#define CUDA_ENABLE_ERROR_CHECK
18#ifdef CUDA_ENABLE_ERROR_CHECK
19#define CUDA_CHECK_ERROR(CUDA_CALL) \
21 cudaError_t code = (cudaError_t)CUDA_CALL; \
22 if (code != cudaSuccess) { \
23 printf("CUDA Error: %s\n", cudaGetErrorString(code)); \
27#define CUDA_CHECK_ERROR(CUDA_CALL) CUDA_CALL
44 std::vector<T> buffer(n);
46 cudaMemcpy(buffer.data(), ptr, n *
sizeof(T), cudaMemcpyDeviceToHost));
49 std::cout << d <<
' ';
56 Vector(
size_t preAlloc) : buf(nullptr), n(preAlloc) {
64 std::swap(buf, other.buf);
65 std::swap(n, other.n);
76 std::swap(buf, other.buf);
77 std::swap(n, other.n);
84 cudaMemcpy(&element, &buf[pos],
sizeof(T), cudaMemcpyDeviceToHost));
88 T *
data()
const {
return buf; }
90 class iterator :
public std::iterator<std::random_access_iterator_tag, T> {
92 iterator(T *buf,
long num) : buf(buf), pos(num) {}
112 return buf == other.buf && pos == other.pos;
118 cudaMemcpy(&element, &buf[pos],
sizeof(T), cudaMemcpyDeviceToHost));
136template <
typename ValueType,
typename IndexType>
struct CudaMatrix {
138 CudaMatrix(
const Eigen::SparseMatrix<ValueType, Eigen::RowMajor> &mat,
141 val(mat.nonZeros()) {
145 (
dim + 1) *
sizeof(
int),
146 cudaMemcpyHostToDevice));
149 cudaMemcpyHostToDevice));
152 cudaMemcpyHostToDevice));
162 friend std::ostream &
166 std::vector<double> bufferVal(mat.
non_zero);
167 std::vector<int> bufferCol(mat.
non_zero);
168 std::vector<int> bufferRow(mat.
dim);
171 cudaMemcpyDeviceToHost));
174 cudaMemcpyDeviceToHost));
176 mat.
dim *
sizeof(
int), cudaMemcpyDeviceToHost));
179 os <<
"Nonzero entries:\n";
180 for (
int i = 0; i < mat.
non_zero; i++) {
181 os <<
'(' << bufferVal[i] <<
',' << bufferCol[i] <<
") ";
184 os <<
"Outer pointers:\n";
185 for (
auto i : bufferRow) {
#define CUDA_CHECK_ERROR(CUDA_CALL)
iterator(T *buf, long num)
bool operator!=(iterator other) const
bool operator==(iterator other) const
Vector & operator=(const Vector &)=delete
Vector & operator=(Vector &&other)
void copybackAndPrint(std::ostream &stream, const char *msg, T *ptr, int n)
cuda::Vector< IndexType > row
cuda::Vector< IndexType > col
CudaMatrix(const Eigen::SparseMatrix< ValueType, Eigen::RowMajor > &mat, int dim)
cuda::Vector< ValueType > val
friend std::ostream & operator<<(std::ostream &os, const DPsim::cuda::CudaMatrix< ValueType, IndexType > &mat)