Skip to content

Commit

Permalink
Expand SWEEP_LIKE to work for {'t': [0, 1, 3]} (#2786)
Browse files Browse the repository at this point in the history
Fixes: #2698
  • Loading branch information
crystalzhaizhai committed Mar 28, 2020
1 parent 2dd6e2e commit 6c57f2e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
18 changes: 17 additions & 1 deletion cirq/study/sweepable.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""Defines which types are Sweepable."""

from typing import Dict, Iterable, Iterator, List, Union, cast
import itertools

from cirq._doc import document
from cirq.study.resolver import ParamResolver, ParamResolverOrSimilarType
Expand Down Expand Up @@ -55,7 +56,22 @@ def to_sweeps(sweepable: Sweepable) -> List[Sweep]:
if isinstance(sweepable, Sweep):
return [sweepable]
if isinstance(sweepable, dict):
return [_resolver_to_sweep(ParamResolver(cast(Dict, sweepable)))]
# change dictionary of lists to list of dictionaries
# of single values using Cartesian product.
newsweepable = {}
for key, value in sweepable.items():
if isinstance(value, Iterable):
newsweepable[key] = value
else:
newsweepable[key] = [value]
expandsweepable = [
dict(zip(newsweepable.keys(), v))
for v in itertools.product(*newsweepable.values())
]
return [
_resolver_to_sweep(ParamResolver(cast(Dict, dictitem)))
for dictitem in expandsweepable
]
if isinstance(sweepable, Iterable) and not isinstance(sweepable, str):
return [
sweep for item in sweepable for sweep in to_sweeps(
Expand Down
13 changes: 12 additions & 1 deletion cirq/study/sweepable_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import cirq


def test_to_resolvers_none():
assert list(cirq.to_resolvers(None)) == [cirq.ParamResolver({})]

Expand Down Expand Up @@ -83,6 +82,18 @@ def test_to_sweeps_iterable_sweeps():
assert cirq.study.to_sweeps(sweeps) == sweeps


def test_to_sweeps_dictionary_of_list():
assert cirq.study.to_sweeps({'t': [0, 2, 3]}) == \
cirq.study.to_sweeps([{'t': 0}, {'t': 2}, {'t': 3}])
assert cirq.study.to_sweeps({'t': [0, 1], 's': [2, 3], 'r': 4}) == \
cirq.study.to_sweeps([
{'t': 0, 's': 2, 'r': 4},
{'t': 0, 's': 3, 'r': 4},
{'t': 1, 's': 2, 'r': 4},
{'t': 1, 's': 3, 'r': 4},
])


def test_to_sweeps_invalid():
with pytest.raises(TypeError, match='Unrecognized sweepable'):
cirq.study.to_sweeps('nope')
Expand Down

0 comments on commit 6c57f2e

Please sign in to comment.