I am using sparse arrays with LibraryLink. I noticed that when MSparseArray_fromExplicitPositions and MSparseArray_fromMTensor return an all-zero sparse array, the corresponding MSparseArray will have neither an explicit values vector nor a column indices vector. There is a null pointer in place of both.

It is documented that this may be the case for explicit values (pattern arrays don't have them). But it is not documented that the column indices may also be missing. In fact not even the included example program (demo_sparse.c) is prepared for this eventuality (and will crash if such a sparse array is passed to it). Mathematica itself never passes such an MSparseArray to the library. Thus I think the behaviour is a bug.

What I need is a convenient workaround. Is it safe to manually insert an empty (but non-NULL!) column indices vector into the MSparseArray data structure?


MTensor *ci = libData->sparseLibraryFunctions->MSparseArray_getColumnIndices(msa);

if (*ci == NULL) {
    mint dims[2] = {0, libData->sparseLibraryFunctions->MSparseArray_getRank(msa)};
    libData->MTensor_new(MType_Integer, 2, dims, ci);

Is it safe to do this for every single MSparseArray in my program, even for those that were passed as "Constant" from the kernel?

I am using a C++ wrapper class for sparse arrays, and it would be most convenient to simply do this correction in the constructor of that class.

Also note that while I have not found a way to create such a problematic sparse array directly in Mathematica, if a LibraryLink library returns one, it will stay in that form. That means that in principle someone else's library may generate such a sparse array, which may then be passed to my own library. This means that I absolutely need to be prepared for getting a "Constant" sparse array with no column indices as an input to my library, and I need to have explicit checks for it so that I don't accidentally call functions like MTensor_getFlattenedLength on NULL and crash the kernel. If I cannot normalize the sparse array structure by manually replacing the column indices when needed, then I would have to have these checks at almost every place in the program that manipulates sparse arrays, which would be extremely inconvenient.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.