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.

73 lines
2.5KB

  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_zero = {.real=0, .imag=0};
  12. static const npy_complex128 complex_one = {.real=1, .imag=0};
  13. static void complex_inc(npy_complex128 a, npy_complex128 b) { a.real+=b.real; a.imag+=b.imag;}
  14. static npy_complex128 complex_mult(npy_complex128 a, npy_complex128 b) {
  15. npy_complex128 x;
  16. x.real = a.real*b.real+a.imag*b.imag;
  17. x.imag = a.real*b.imag+a.imag*b.real;
  18. return x;
  19. }
  20. // Boilerplate: Forward function declaration, method list, module initialization
  21. static PyObject *permanent(PyObject *self, PyObject *args);
  22. static PyMethodDef methods[] = {
  23. { "permanent", permanent, METH_VARARGS, "Compute the permanent"},
  24. { NULL, NULL, 0, NULL } /* Sentinel */
  25. };
  26. PyMODINIT_FUNC initpermanent(void) {
  27. (void) Py_InitModule("permanent", methods);
  28. import_array();
  29. }
  30. // The parity
  31. /*static int parity(int x) { return 0; }*/
  32. // Ryser's algorithm takes exponential time
  33. // This just calculates the sum
  34. static npy_complex128 perm_ryser(PyArrayObject *submatrix) {
  35. int n = (int) PyArray_DIM(submatrix, 0);
  36. int i = 0; int z = 0; int y = 0;
  37. npy_complex128 prod;
  38. npy_complex128 perm = complex_zero;
  39. npy_complex128 sum = complex_zero;
  40. int exp=1 << n; //TODO: use a shift operator
  41. // Iterate over exponentially many index strings
  42. for (i=0; i<exp; ++i) {
  43. prod = complex_one;
  44. for (y=0; y<n; ++y) { // Rows
  45. sum = complex_zero;
  46. for (z=0; z<n; ++z) { // Columns
  47. if ((i & (1 << z)) > 0) { complex_inc(sum, SM(z,y)); }
  48. }
  49. prod = complex_mult(prod, sum);
  50. }
  51. /*complex_add(perm, parity(i) * prod);*/
  52. complex_inc(perm, prod);
  53. }
  54. /*return c_prod((pow(-1,n)), perm); #TODO power is fucked*/
  55. return perm;
  56. }
  57. // This is basically a wrapper which chooses the optimal permanent function
  58. static PyObject *permanent(PyObject *self, PyObject *args) {
  59. // Parse input
  60. PyArrayObject *submatrix;
  61. if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &submatrix)) {return NULL;}
  62. npy_complex128 p = perm_ryser(submatrix);
  63. return PyComplex_FromDoubles(p.real, p.imag);
  64. }