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.

78 lines
2.6KB

  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. // Array access macros.
  6. #define SM(x0, x1) (*(npy_complex128*)((PyArray_DATA(submatrix) + \
  7. (x0) * PyArray_STRIDES(submatrix)[0] + \
  8. (x1) * PyArray_STRIDES(submatrix)[1])))
  9. #define SM_shape(x0) (int) PyArray_DIM(submatrix, x0)
  10. // Complex numbers
  11. static const npy_complex128 complex_one = {.real=1, .imag=0};
  12. static const npy_complex128 complex_zero = {.real=0, .imag=0};
  13. static npy_complex128 complex_add(npy_complex128 a, npy_complex128 b) {
  14. npy_complex128 x;
  15. x.real = a.real+b.real;
  16. x.imag = a.imag+b.imag;
  17. return x;
  18. }
  19. static npy_complex128 complex_prod(npy_complex128 a, npy_complex128 b) {
  20. npy_complex128 x;
  21. x.real = a.real*b.real+a.imag*b.imag;
  22. x.imag = a.real*b.imag+a.imag*b.real;
  23. return x;
  24. }
  25. // Boilerplate
  26. static PyObject *permanent(PyObject *self, PyObject *args); // Forward function declaration
  27. static PyMethodDef methods[] = { // Method list
  28. { "permanent", permanent, METH_VARARGS, "Compute the permanent"},
  29. { NULL, NULL, 0, NULL } /* Sentinel */
  30. };
  31. PyMODINIT_FUNC initpermanent(void) { // Module initialization
  32. (void) Py_InitModule("permanent", methods);
  33. import_array();
  34. }
  35. // Ryser's algorithm
  36. static npy_complex128 perm_ryser(PyArrayObject *submatrix) {
  37. int n = (int) PyArray_DIM(submatrix, 0);
  38. int i = 0; int z = 0; int y = 0;
  39. npy_complex128 prod;
  40. npy_complex128 perm = complex_zero;
  41. npy_complex128 sum = complex_zero;
  42. int exp = 1 << n;
  43. // Iterate over exponentially many index strings
  44. for (i=0; i<exp; ++i) {
  45. prod = complex_one;
  46. for (y=0; y<n; ++y) { // Rows
  47. sum = complex_zero;
  48. for (z=0; z<n; ++z) { // Columns
  49. if ((i & (1 << z)) > 0) {
  50. sum = complex_add(sum, SM(z,y));
  51. }
  52. }
  53. prod = complex_prod(prod, sum);
  54. }
  55. /*if (i%2 == 0) {prod.real*=-1; prod.imag*=-1;}*/
  56. perm = complex_add(perm, prod);
  57. }
  58. /*if (i%2 == 0) {perm.real*=-1; perm.imag*=-1;}*/
  59. return perm;
  60. }
  61. // This is a wrapper which chooses the optimal permanent function
  62. static PyObject *permanent(PyObject *self, PyObject *args) {
  63. // Parse the input
  64. PyArrayObject *submatrix;
  65. if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &submatrix)) {return NULL;}
  66. // Compute the permanent
  67. npy_complex128 p = perm_ryser(submatrix);
  68. return PyComplex_FromDoubles(p.real, p.imag);
  69. }