Python C extension to compute the permanent.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.7KB

  1. /* Computes the permanent, given a numpy array */
  2. #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
  3. #include <Python.h>
  4. #include <numpy/arrayobject.h>
  5. #include "bithacks.h"
  6. #include "npy_util.h"
  7. // Forward function declaration
  8. static PyObject *permanent(PyObject *self, PyObject *args);
  9. // Method list
  10. static PyMethodDef methods[] = {
  11. { "permanent", permanent, METH_VARARGS, "Compute the permanent"},
  12. { NULL, NULL, 0, NULL } // Sentinel
  13. };
  14. // Module initialization
  15. PyMODINIT_FUNC initpermanent(void) {
  16. (void) Py_InitModule("permanent", methods);
  17. import_array();
  18. }
  19. // Ryser's algorithm
  20. static npy_complex128 perm_ryser(PyArrayObject *submatrix) {
  21. int n = (int) PyArray_DIM(submatrix, 0);
  22. npy_complex128 rowsum, rowsumprod;
  23. npy_complex128 perm = complex_zero;
  24. int exp = 1 << n;
  25. int i, y, z;
  26. for (i=0; i<exp; ++i) {
  27. rowsumprod = complex_one;
  28. for (y=0; y<n; ++y) {
  29. rowsum = complex_zero;
  30. for (z=0; z<n; ++z) {
  31. if ((i & (1 << z)) != 0) { complex_inc(&rowsum, SM(z, y)); }
  32. }
  33. complex_multiply(&rowsumprod, rowsum);
  34. }
  35. complex_inc(&perm, complex_float_prod(rowsumprod, bitparity(i)));
  36. }
  37. if (n%2 == 1) {perm=complex_float_prod(perm, -1);}
  38. return perm;
  39. }
  40. // This is a wrapper which chooses the optimal permanent function
  41. static PyObject *permanent(PyObject *self, PyObject *args) {
  42. // Parse the input
  43. PyArrayObject *submatrix;
  44. if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &submatrix)) {return NULL;}
  45. // Compute the permanent
  46. npy_complex128 p = perm_ryser(submatrix);
  47. return PyComplex_FromDoubles(p.real, p.imag);
  48. }