[SciPy-user] C extension to manipulate sparse lil matrix
Andy Fraser
afraser@lanl....
Mon Jan 12 14:36:43 CST 2009
>>>>> "A" == Andy Fraser <afraser@lanl.gov> writes:
A> I want to move some time critical bits of code for hidden
A> Markov models from python to C. [...]
A> Now, I am trying to figure out how to manipulate lil sparse
A> matrices. In particular calling such a matrix "SM", and
A> supposing that "t" is the index for a row, I want to assign new
A> arrays to "SM.rows[t]" and "SM.data[t]".
A> I would be grateful if someone posted C code that interchanged
A> two rows of a lil sparse matrix. [...]
I've answered my own question. I append the code below. I found that
lil matrices consist of numpy arrays of python lists. I also found
that I could replace the python lists with numpy arrays. Here are
some resources that helped:
http://www.tramy.us/ Oliphant's "Guide to Numpy"
http://docs.python.org/extending/
http://docs.python.org/c-api/memory.html
http://www.scipy.org/Cookbook/C_Extensions/NumPy_arrays
http://docs.python.org/c-api/arg.html#arg-parsing
Here is code that swaps "rows":
static PyObject *
hmm_test1(PyObject *self, PyObject *args)
/* Python equivalent of:
def test1(A_O # An array of objects like the "rows" of a sparse lil matrix
):
temp = A_O[0]
A_O[0] = A_O[1]
A_O[1] = temp
return
*/
{
PyObject **object0, **object1, *temp;
PyArrayObject *A_O;
if (!PyArg_ParseTuple(args, "O&",
PyArray_Converter, &A_O
))
return NULL;
object0 = PyArray_GETPTR1(A_O, 0);
object1 = PyArray_GETPTR1(A_O, 1);
temp = *object0;
*object0 = *object1;
*object1 = temp;
return Py_BuildValue(""); /* return None */
}
More information about the SciPy-user
mailing list