Skip to content

Commit

Permalink
Add testing routine for generating random QubitOperators (#500)
Browse files Browse the repository at this point in the history
* add random_qubit_operator

* disallow 0 terms

* use scipy.special instead of scipy.misc
  • Loading branch information
kevinsung committed Jan 9, 2019
1 parent a88394e commit 06bca71
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/openfermion/utils/__init__.py
Expand Up @@ -60,6 +60,7 @@
random_hermitian_matrix,
random_interaction_operator,
random_quadratic_hamiltonian,
random_qubit_operator,
random_unitary_matrix,
module_importable)

Expand Down
2 changes: 1 addition & 1 deletion src/openfermion/utils/_bch_expansion.py
Expand Up @@ -13,7 +13,7 @@
"""Module to efficiently compute the Baker-Campbell-Hausdorff formula."""

import itertools
from scipy.misc import comb, factorial
from scipy.special import comb, factorial


def bch_expand(*ops, **kwargs):
Expand Down
22 changes: 21 additions & 1 deletion src/openfermion/utils/_testing_utils.py
Expand Up @@ -20,7 +20,27 @@

from openfermion.ops import (DiagonalCoulombHamiltonian,
InteractionOperator,
QuadraticHamiltonian)
QuadraticHamiltonian,
QubitOperator)


def random_qubit_operator(n_qubits=16,
max_num_terms=16,
max_many_body_order=16,
seed=None):
prng = numpy.random.RandomState(seed)
op = QubitOperator()
num_terms = prng.randint(1, max_num_terms+1)
for _ in range(num_terms):
many_body_order = prng.randint(max_many_body_order+1)
term = []
for _ in range(many_body_order):
index = prng.randint(n_qubits)
action = prng.choice(('X', 'Y', 'Z'))
term.append((index, action))
coefficient = prng.randn()
op += QubitOperator(term, coefficient)
return op


def haar_random_vector(n, seed=None):
Expand Down
18 changes: 17 additions & 1 deletion src/openfermion/utils/_testing_utils_test.py
Expand Up @@ -16,8 +16,9 @@

import numpy

from openfermion.ops import QubitOperator
from openfermion.transforms import get_fermion_operator
from openfermion.utils import is_hermitian
from openfermion.utils import count_qubits, is_hermitian
from openfermion.utils._testing_utils import (
EqualsTester,
haar_random_vector,
Expand All @@ -26,9 +27,24 @@
random_hermitian_matrix,
random_interaction_operator,
random_quadratic_hamiltonian,
random_qubit_operator,
random_unitary_matrix)


def test_random_qubit_operator():
op = random_qubit_operator(
n_qubits=20,
max_num_terms=20,
max_many_body_order=20
)

assert isinstance(op, QubitOperator)
assert op.many_body_order() <= 20
assert len(op.terms) <= 20
assert count_qubits(op) <= 20



class EqualsTesterTest(unittest.TestCase):

def test_add_equality_group_correct(self):
Expand Down

0 comments on commit 06bca71

Please sign in to comment.