I am trying to solve a simple working example, a linear system $Ax=b$, where $A$ is sparse SPD and $b$ is dense, using CHOLMOD.
#include <cmath>
#include <iostream>
#include <vector>
#include "suitesparse/cholmod.h"
int main()
{
cholmod_sparse *a;
cholmod_dense *x, *b;
cholmod_factor *L;
cholmod_common c;
cholmod_start(&c);
std::vector<double> A = {4.0, 0.0, 1.0,
0.0, 3.0, 1.0,
1.0, 1.0, 2.0};
std::vector<double> B = {1.0, 1.0, 1.0};
size_t n = sqrt(A.size());
// Dense vector B
b = cholmod_allocate_dense(n, 1, n, CHOLMOD_REAL, &c);
b->x = &*B.begin();
cholmod_print_dense(b, "b", &c);
// Sparse matrix A
cholmod_triplet *T;
std::vector<int> Ti, Tj;
std::vector<double> Tx;
size_t index;
double value;
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
index = n * j + i;
value = A.at(index);
if (abs(value) > 0)
{
Ti.push_back(i);
Tj.push_back(j);
Tx.push_back(value);
}
}
}
T = cholmod_allocate_triplet(n, n, Tx.size(), 0, CHOLMOD_REAL, &c);
T->i = &*Ti.begin();
T->j = &*Tj.begin();
T->x = &*Tx.begin();
T->nnz = Tx.size();
cholmod_print_triplet(T, "T", &c);
a = cholmod_triplet_to_sparse(T, Tx.size(), &c);
cholmod_print_sparse(a, "A", &c);
L = cholmod_analyze(a, &c);
cholmod_factorize(a, L, &c);
x = cholmod_solve(CHOLMOD_A, L, b, &c);
cholmod_free_factor(&L, &c);
cholmod_free_sparse(&a, &c);
cholmod_free_dense(&x, &c);
cholmod_free_dense(&r, &c);
cholmod_free_dense(&b, &c);
cholmod_finish(&c);
return 0;
}
Does someone know how to print the values of x = cholmod_solve(CHOLMOD_A, L, b, &c)
and how to assign his values to a std::vector
? As I do not know how to print and assign the values of the solution, I even know whether my code is working properly.
For sake of clarity, cholmod_dense
is a Struct
:
typedef struct cholmod_dense_struct
{
size_t nrow ; /* the matrix is nrow-by-ncol */
size_t ncol ;
size_t nzmax ; /* maximum number of entries in the matrix */
size_t d ; /* leading dimension (d >= nrow must hold) */
void *x ; /* size nzmax or 2*nzmax, if present */
void *z ; /* size nzmax, if present */
int xtype ; /* pattern, real, complex, or zomplex */
int dtype ; /* x and z double or float */
} cholmod_dense ;
I would like to see the values of void *x
of this struct.