Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sparse loop hafnian #245

Merged
merged 31 commits into from
Jun 24, 2021
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ae0d3a4
adds sparse hafnian
ziofil May 30, 2021
276e1f0
adds sparse hafnian
ziofil May 30, 2021
1bc870a
fixed codecov issues
ziofil May 30, 2021
9935fcb
fixed CodeFactor issue
ziofil May 30, 2021
3438904
complete coverage
ziofil May 30, 2021
db91ea9
updated changelog
ziofil May 30, 2021
05d315b
Update thewalrus/_hafnian.py
ziofil May 30, 2021
263a521
Update .github/CHANGELOG.md
ziofil May 30, 2021
33dbb8c
Update .github/CHANGELOG.md
ziofil Jun 1, 2021
21ddade
Update thewalrus/tests/test_hafnian.py
ziofil Jun 9, 2021
20cd252
Update thewalrus/_hafnian.py
ziofil Jun 11, 2021
e0d6c0f
Update thewalrus/_hafnian.py
ziofil Jun 11, 2021
24ba72b
Update thewalrus/_hafnian.py
ziofil Jun 11, 2021
8812504
Update thewalrus/_hafnian.py
ziofil Jun 11, 2021
397350c
Update thewalrus/tests/test_hafnian.py
ziofil Jun 11, 2021
d660550
Update .github/CHANGELOG.md
ziofil Jun 11, 2021
f53e75d
Update .github/CHANGELOG.md
ziofil Jun 11, 2021
2922b3a
Update thewalrus/_hafnian.py
ziofil Jun 11, 2021
a8bf92d
Update test_hafnian.py
ziofil Jun 11, 2021
3ec17da
adds loop bool
ziofil Jun 11, 2021
2e84a88
adds tests
ziofil Jun 11, 2021
8ef103a
adds loop logic
ziofil Jun 11, 2021
a4f7588
Merge branch 'master' into sparse_hafnian
nquesada Jun 22, 2021
240893f
removes unused files
nquesada Jun 22, 2021
abb4431
Apply suggestions from code review
nquesada Jun 22, 2021
5b997d5
Update thewalrus/_hafnian.py
ziofil Jun 23, 2021
aa442e7
Apply suggestions from code review
nquesada Jun 23, 2021
2f7aa5f
Adds the new algorithms into the docs
nquesada Jun 24, 2021
0d76f45
Merge branch 'master' into sparse_hafnian
nquesada Jun 24, 2021
66f2b22
Adds period
nquesada Jun 24, 2021
3f6fb5c
corrects typos
nquesada Jun 24, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

### New features

* Adds the function `hafnian_sparse` to compute sparse loop hafnians (pure python implementation). [#245](https://github.com/XanaduAI/thewalrus/pull/245)

### Improvements

* Speeds up the calculation of photon number variances/covariances [#224](https://github.com/XanaduAI/thewalrus/pull/224)
* Speeds up the calculation of photon number variances/covariances [#244](https://github.com/XanaduAI/thewalrus/pull/244)

### Bug fixes

Expand All @@ -14,7 +16,7 @@

This release contains contributions from (in alphabetical order):

Nicolas Quesada
Filippo Miatto, Nicolas Quesada

---

Expand Down
2 changes: 2 additions & 0 deletions thewalrus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
hafnian,
hafnian_repeated,
reduction,
hafnian_sparse,
)
from ._low_rank_haf import low_rank_hafnian
from ._hermite_multidimensional import hafnian_batched, hermite_multidimensional
Expand All @@ -112,6 +113,7 @@
"hafnian",
"hafnian_repeated",
"hafnian_batched",
"hafnian_sparse",
"tor",
"perm",
"permanent_repeated",
Expand Down
42 changes: 42 additions & 0 deletions thewalrus/_hafnian.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"""
Hafnian Python interface
"""
from functools import lru_cache
from collections import Counter
import numpy as np

from .libwalrus import haf_complex, haf_int, haf_real, haf_rpt_complex, haf_rpt_real
Expand Down Expand Up @@ -178,6 +180,46 @@ def hafnian(
)


def hafnian_sparse(A, D = None):
r"""Returns the hafnian of a sparse symmetric matrix.
ziofil marked this conversation as resolved.
Show resolved Hide resolved

This pure python implementation is very slow on full matrices, but faster the sparser a matrix is.
As a rule of thumb, the crossover in runtime with respect to :func:`~.hafnian` happens around 50% sparsity.

Args:
A (array): the symmetric matrix of which we want to compute the hafnian
D (set): set of indices that identify a submatrix. If ``None`` (default) it computes
the hafnian of the whole matrix.

Returns:
(float) hafnian of ``A`` or of the submatrix of ``A`` defined by the set of indices ``D``.
"""
if D is None:
D = frozenset(range(len(A)))
else:
D = frozenset(D)

if np.allclose(A, np.zeros_like(A)):
ziofil marked this conversation as resolved.
Show resolved Hide resolved
return 0.0

r, _ = np.nonzero(A)
m = max(Counter(r).values()) # max nonzero values per row/column

@lru_cache(maxsize=2 ** m)
def indices(d, k):
return d.intersection(set(np.nonzero(A[k])[0]))

@lru_cache(maxsize=2 ** m)
def lhaf(d: frozenset) -> float:
if not d:
return 1
d_ = set(d)
ziofil marked this conversation as resolved.
Show resolved Hide resolved
k = d_.pop()
return sum(A[i, k] * lhaf(frozenset(d_).difference({i})) for i in indices(d, k))
ziofil marked this conversation as resolved.
Show resolved Hide resolved

return lhaf(D)


def hafnian_repeated(A, rpt, mu=None, loop=False, rtol=1e-05, atol=1e-08):
r"""Returns the hafnian of matrix with repeated rows/columns.

Expand Down
4 changes: 3 additions & 1 deletion thewalrus/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ def random_matrix(dtype):
"""Returns a random symmetric matrix of type dtype
and of size n x n"""

def _wrapper(n):
def _wrapper(n, fill_factor=1.0):
"""wrapper function"""
A = np.complex128(np.random.random([n, n]))
A += 1j * np.random.random([n, n])
mask = np.random.binomial(1, p=fill_factor, size=(n, n))
A *= mask
A += A.T

if not np.issubdtype(dtype, np.complexfloating):
Expand Down
11 changes: 10 additions & 1 deletion thewalrus/tests/test_hafnian.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from scipy.special import factorial as fac

import thewalrus as hf
from thewalrus import hafnian, reduction
from thewalrus import hafnian, reduction, hafnian_sparse
from thewalrus.libwalrus import haf_complex, haf_real, haf_int


Expand Down Expand Up @@ -277,3 +277,12 @@ def test_diag(self, n):
haf = hafnian(A, loop=True)
expected = np.prod(v)
assert np.allclose(haf, expected)


@pytest.mark.parametrize("n", [2, 3, 5, 10, 15, 20])
@pytest.mark.parametrize("fill", [0.5, 0.2, 0.1, 0.05])
def test_valid_output(self, random_matrix, n, fill):
"""Tests that sparse loop hafnian matches full implementation"""
A = random_matrix(n, fill_factor=fill)
assert np.allclose(hafnian_sparse(A), hafnian_sparse(A, D=set(range(len(A)))))
assert np.allclose(hafnian(A, loop=True), hafnian_sparse(A))