upgpkg: ufw 0.36.2-1
[ArchLinux/community.git] / rocsparse / repos / community-x86_64 / test.cpp
blobd7bba2070259a43c809b037dc923c7652e49081f
1 #include <rocsparse/rocsparse.h>
2 #include <hip/hip_runtime.h>
3 #include <iostream>
4 #include <vector>
5 #include <random>
6 #include <algorithm>
8 int main()
10 using rint = rocsparse_int;
11 rint n = 1024;
13 std::random_device rd;
14 std::mt19937 gen(rd());
15 std::uniform_real_distribution<float> dist(-1.0, 1.0);
17 auto myrand = [&]() -> float {return dist(gen);};
19 std::vector<float> xin(n);
20 std::generate(xin.begin(), xin.end(), myrand);
22 rocsparse_handle handle;
23 rocsparse_create_handle(&handle);
25 std::vector<rint> row_ptr(n + 1);
26 std::vector<rint> col(3 * n);
27 std::vector<float> data(3 * n);
29 //Second order finite differences matrix in 1D
30 row_ptr[0] = 0;
31 for(size_t i = 0; i < n; i++){
32 rint off = row_ptr[i];
33 if(i > 0){
34 col[off] = i - 1;
35 data[off++] = -1.0f;
37 col[off] = i;
38 data[off++] = 2.0f;
39 if(i < n - 1){
40 col[off] = i + 1;
41 data[off++] = -1.0f;
43 row_ptr[i + 1] = off;
46 rint *rp;
47 rint *c;
48 float *d;
50 float *x;
51 float *y;
52 hipMalloc((void **)&rp, sizeof *rp * (n + 1));
53 hipMalloc((void **)&c, sizeof *c * 3 * n);
54 hipMalloc((void **)&d, sizeof *d * 3 * n);
56 hipMalloc((void **)&x, sizeof *x * n);
57 hipMalloc((void **)&y, sizeof *y * n);
59 hipMemcpy(rp, row_ptr.data(), sizeof *rp * (n + 1), hipMemcpyHostToDevice);
60 hipMemcpy(c, col.data(), sizeof *c * 3 * n, hipMemcpyHostToDevice);
61 hipMemcpy(d, data.data(), sizeof *d * 3 * n, hipMemcpyHostToDevice);
63 hipMemcpy(x, xin.data(), sizeof *x * n, hipMemcpyHostToDevice);
65 float alpha = 14.124f;
66 float beta = 0.0f;
68 rocsparse_mat_descr descr;
69 rocsparse_create_mat_descr(&descr);
71 rocsparse_scsrmv(handle, rocsparse_operation_none,
72 n, n, 3 * n - 2, &alpha, descr, d, rp, c, nullptr,
73 x, &beta, y);
75 std::vector<float> yout(n);
76 hipMemcpy(yout.data(), y, sizeof *y * n, hipMemcpyDeviceToHost);
78 float tol = 0.0001f;
79 for(rint i = 0; i < n; i++){
80 for(rint jj = row_ptr[i]; jj < row_ptr[i + 1]; jj++){
81 rint j = col[jj];
82 yout[i] -= alpha * data[jj] * xin[j];
84 if(std::abs(yout[i]) > tol){
85 std::cout << "Entry " << i << " is not computed correctly.\n";
86 std::cout << "Expected 0 but got " << yout[i] << std::endl;
87 return 1;
91 std::cout << "TESTS PASSED!" << std::endl;
93 rocsparse_destroy_handle(handle);
94 rocsparse_destroy_mat_descr(descr);
95 hipFree(rp);
96 hipFree(c);
97 hipFree(d);
98 hipFree(x);
99 hipFree(y);