/
quantum_xor.py
71 lines (55 loc) · 2.26 KB
/
quantum_xor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""XOR circuit."""
from typing import Optional
import numpy as np
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
class XOR(QuantumCircuit):
"""An n_qubit circuit for bitwise xor-ing the input with some integer ``amount``.
The ``amount`` is xor-ed in bitstring form with the input.
This circuit can also represent addition by ``amount`` over the finite field GF(2).
"""
def __init__(
self,
num_qubits: int,
amount: Optional[int] = None,
seed: Optional[int] = None,
) -> None:
"""Return a circuit implementing bitwise xor.
Args:
num_qubits: the width of circuit.
amount: the xor amount in decimal form.
seed: random seed in case a random xor is requested.
Raises:
CircuitError: if the xor bitstring exceeds available qubits.
Reference Circuit:
.. plot::
from qiskit.circuit.library import XOR
from qiskit.visualization.library import _generate_circuit_library_visualization
circuit = XOR(5, seed=42)
_generate_circuit_library_visualization(circuit)
"""
circuit = QuantumCircuit(num_qubits, name="xor")
if amount is not None:
if len(bin(amount)[2:]) > num_qubits:
raise CircuitError("Bits in 'amount' exceed circuit width")
else:
rng = np.random.default_rng(seed)
amount = rng.integers(0, 2**num_qubits)
for i in range(num_qubits):
bit = amount & 1
amount = amount >> 1
if bit == 1:
circuit.x(i)
super().__init__(*circuit.qregs, name="xor")
self.compose(circuit.to_gate(), qubits=self.qubits, inplace=True)