Hide keyboard shortcuts

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. 

13 

14from typing import Dict, Iterable, Union 

15 

16from boltons.setutils import IndexedSet 

17from braket.circuits.qubit import Qubit, QubitInput 

18 

19QubitSetInput = Union[QubitInput, Iterable[QubitInput]] 

20 

21 

22class QubitSet(IndexedSet): 

23 """ 

24 An ordered, unique set of quantum bits. 

25 

26 Note: 

27 QubitSet implements __hash__() but is a mutable object, therefore be careful when 

28 mutating this object. 

29 """ 

30 

31 def __init__(self, qubits: QubitSetInput = []): 

32 """ 

33 Args: 

34 qubits (int, Qubit, or iterable of int / Qubit): Qubits to be included in the QubitSet. 

35 

36 Examples: 

37 >>> qubits = QubitSet([0, 1]) 

38 >>> for qubit in qubits: 

39 ... print(qubit) 

40 ... 

41 Qubit(0) 

42 Qubit(1) 

43 

44 >>> qubits = QubitSet([0, 1, [2, 3]]) 

45 >>> for qubit in qubits: 

46 ... print(qubit) 

47 ... 

48 Qubit(0) 

49 Qubit(1) 

50 Qubit(2) 

51 Qubit(3) 

52 """ 

53 

54 def _flatten(other): 

55 if isinstance(other, Iterable) and not isinstance(other, str): 

56 for item in other: 

57 yield from _flatten(item) 

58 else: 

59 yield other 

60 

61 _qubits = [Qubit.new(qubit) for qubit in _flatten(qubits)] 

62 super().__init__(_qubits) 

63 

64 def map(self, mapping: Dict[QubitInput, QubitInput]) -> "QubitSet": 

65 """ 

66 Creates a new QubitSet where this instance's qubits are mapped to the values in `mapping`. 

67 If this instance contains a qubit that is not in the `mapping` that qubit is not modified. 

68 

69 Args: 

70 mapping (dictionary[int or Qubit, int or Qubit]): A dictionary of qubit mappings to 

71 apply. Key is the qubit in this instance to target, and the value is what 

72 the key will be changed to. 

73 

74 Returns: 

75 QubitSet: A new QubitSet with the `mapping` applied. 

76 

77 Examples: 

78 >>> qubits = QubitSet([0, 1]) 

79 >>> mapping = {0: 10, Qubit(1): Qubit(11)} 

80 >>> qubits.map(mapping) 

81 QubitSet([Qubit(10), Qubit(11)]) 

82 """ 

83 

84 new_qubits = [mapping.get(qubit, qubit) for qubit in self] 

85 

86 return QubitSet(new_qubits) 

87 

88 def __hash__(self): 

89 return hash(tuple(self))