Coverage for src/braket/circuits/qubit_set.py : 100%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"). You
4# may not use this file except in compliance with the License. A copy of
5# the License is located at
6#
7# http://aws.amazon.com/apache2.0/
8#
9# or in the "license" file accompanying this file. This file is
10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11# ANY KIND, either express or implied. See the License for the specific
12# language governing permissions and limitations under the License.
14from __future__ import annotations
16from typing import Dict, Iterable, Union
18from boltons.setutils import IndexedSet
19from braket.circuits.qubit import Qubit, QubitInput
21QubitSetInput = Union[QubitInput, Iterable[QubitInput]]
24class QubitSet(IndexedSet):
25 """
26 An ordered, unique set of quantum bits.
28 Note:
29 QubitSet implements __hash__() but is a mutable object, therefore be careful when
30 mutating this object.
31 """
33 def __init__(self, qubits: QubitSetInput = None):
34 """
35 Args:
36 qubits (int, Qubit, or iterable of int / Qubit, optional): Qubits to be included in
37 the QubitSet. Default is None.
39 Examples:
40 >>> qubits = QubitSet([0, 1])
41 >>> for qubit in qubits:
42 ... print(qubit)
43 ...
44 Qubit(0)
45 Qubit(1)
47 >>> qubits = QubitSet([0, 1, [2, 3]])
48 >>> for qubit in qubits:
49 ... print(qubit)
50 ...
51 Qubit(0)
52 Qubit(1)
53 Qubit(2)
54 Qubit(3)
55 """
57 def _flatten(other):
58 if isinstance(other, Iterable) and not isinstance(other, str):
59 for item in other:
60 yield from _flatten(item)
61 else:
62 yield other
64 _qubits = [Qubit.new(qubit) for qubit in _flatten(qubits)] if qubits is not None else None
65 super().__init__(_qubits)
67 def map(self, mapping: Dict[QubitInput, QubitInput]) -> QubitSet:
68 """
69 Creates a new QubitSet where this instance's qubits are mapped to the values in `mapping`.
70 If this instance contains a qubit that is not in the `mapping` that qubit is not modified.
72 Args:
73 mapping (dictionary[int or Qubit, int or Qubit]): A dictionary of qubit mappings to
74 apply. Key is the qubit in this instance to target, and the value is what
75 the key will be changed to.
77 Returns:
78 QubitSet: A new QubitSet with the `mapping` applied.
80 Examples:
81 >>> qubits = QubitSet([0, 1])
82 >>> mapping = {0: 10, Qubit(1): Qubit(11)}
83 >>> qubits.map(mapping)
84 QubitSet([Qubit(10), Qubit(11)])
85 """
87 new_qubits = [mapping.get(qubit, qubit) for qubit in self]
89 return QubitSet(new_qubits)
91 def __hash__(self):
92 return hash(tuple(self))