Skip to content

Commit

Permalink
ignore q in gridqubit ids (#3357)
Browse files Browse the repository at this point in the history
Extending the protocol to cater for some older pieces of the infrastructure that mark gridqubits with `q1_2` instead of `1_2`. 

Fixes #3219.
  • Loading branch information
balopat committed Sep 24, 2020
1 parent e0a078a commit 43aed78
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
11 changes: 7 additions & 4 deletions cirq/google/api/v2/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
from typing import TYPE_CHECKING

from cirq import devices, ops

if TYPE_CHECKING:
import cirq

GRID_QUBIT_ID_PATTERN = r'^q?(-?\d+)_(-?\d+)$'


def qubit_to_proto_id(q: 'cirq.Qid') -> str:
"""Return a proto id for a `cirq.Qid`.
Expand Down Expand Up @@ -93,13 +95,14 @@ def grid_qubit_from_proto_id(proto_id: str) -> 'cirq.GridQubit':
Raises:
ValueError: If the string not of the correct format.
"""
parts = proto_id.split('_')
if len(parts) != 2:

match = re.match(GRID_QUBIT_ID_PATTERN, proto_id)
if match is None:
raise ValueError(
'GridQubit proto id must be of the form <int>_<int> but was {}'.
format(proto_id))
try:
row, col = parts
row, col = match.groups()
return devices.GridQubit(row=int(row), col=int(col))
except ValueError:
raise ValueError(
Expand Down
8 changes: 8 additions & 0 deletions cirq/google/api/v2/program_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,21 @@ def test_grid_qubit_from_proto_id():
assert v2.grid_qubit_from_proto_id('1_2') == cirq.GridQubit(1, 2)
assert v2.grid_qubit_from_proto_id('10_2') == cirq.GridQubit(10, 2)
assert v2.grid_qubit_from_proto_id('-1_2') == cirq.GridQubit(-1, 2)
assert v2.grid_qubit_from_proto_id('q-1_2') == cirq.GridQubit(-1, 2)
assert v2.grid_qubit_from_proto_id('q1_2') == cirq.GridQubit(1, 2)


def test_grid_qubit_from_proto_id_invalid():
with pytest.raises(ValueError, match='3_3_3'):
_ = v2.grid_qubit_from_proto_id('3_3_3')
with pytest.raises(ValueError, match='a_2'):
_ = v2.grid_qubit_from_proto_id('a_2')
with pytest.raises(ValueError, match='q1_q2'):
v2.grid_qubit_from_proto_id('q1_q2')
with pytest.raises(ValueError, match='q-1_q2'):
v2.grid_qubit_from_proto_id('q-1_q2')
with pytest.raises(ValueError, match='-1_q2'):
v2.grid_qubit_from_proto_id('-1_q2')


def test_line_qubit_from_proto_id():
Expand Down

0 comments on commit 43aed78

Please sign in to comment.