├── Chapter 1
├── Chapter01.ipynb
└── Chapter01.md
├── Chapter 2
├── Chapter02.ipynb
└── Chapter02.md
├── Chapter 3
├── Chapter03.ipynb
└── Chapter03.md
├── Chapter 4
├── Chapter04.ipynb
└── Chapter04.md
├── Chapter 5
├── Chapter05.ipynb
└── Chapter05.md
├── Chapter 6
├── Chapter06.ipynb
└── Chapter06.md
├── Chapter 7
├── Chapter07.ipynb
└── Chapter07.md
├── Chapter 8
├── Chapter08.ipynb
└── Chapter08.md
├── Chapter 9
├── Chapter09.ipynb
└── Chapter09.md
├── LICENSE
└── README.md
/Chapter 1/Chapter01.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "52e939f8-6f5f-46aa-9b02-5612a6b003ad",
6 | "metadata": {},
7 | "source": [
8 | "### Creating and displaying values"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "4decde35-7618-49ff-86ba-61db04dac65d",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "x = 7"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": null,
26 | "id": "98f90b8f-6b5a-4eef-ac92-1be95b63967e",
27 | "metadata": {
28 | "tags": []
29 | },
30 | "outputs": [],
31 | "source": [
32 | "print(x)"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": null,
38 | "id": "c67207a6-39ab-44c2-b68a-8b8e61d09064",
39 | "metadata": {},
40 | "outputs": [],
41 | "source": [
42 | "x = 1024"
43 | ]
44 | },
45 | {
46 | "cell_type": "code",
47 | "execution_count": null,
48 | "id": "e18840eb-f4b5-4f3c-afa3-1ee12ebfa973",
49 | "metadata": {
50 | "tags": []
51 | },
52 | "outputs": [],
53 | "source": [
54 | "x = 7\n",
55 | "x = 99\n",
56 | "x = 1024\n",
57 | "print(x)\n",
58 | "print(y)"
59 | ]
60 | },
61 | {
62 | "cell_type": "code",
63 | "execution_count": null,
64 | "id": "3574b8f7-d7a9-4dba-9ac5-ac24a674c710",
65 | "metadata": {
66 | "tags": []
67 | },
68 | "outputs": [],
69 | "source": [
70 | "import time\n",
71 | "\n",
72 | "while True:\n",
73 | " print('Hello')\n",
74 | " time.sleep(1)"
75 | ]
76 | },
77 | {
78 | "cell_type": "markdown",
79 | "id": "272c64df-ffd5-4193-a486-99e7941db699",
80 | "metadata": {},
81 | "source": [
82 | "### Matrices in Python"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": null,
88 | "id": "9e394d3f-2c6a-468b-ab2e-6c1245ef1bfe",
89 | "metadata": {
90 | "tags": []
91 | },
92 | "outputs": [],
93 | "source": [
94 | "import numpy as np"
95 | ]
96 | },
97 | {
98 | "cell_type": "code",
99 | "execution_count": null,
100 | "id": "8fe4e24b-c9b2-434b-ae5c-f618ebb4cf20",
101 | "metadata": {
102 | "tags": []
103 | },
104 | "outputs": [],
105 | "source": [
106 | "A = np.matrix( [[2, -3, 0], \n",
107 | " [1, 5, 19]] )\n",
108 | "print(np.dot(4, A))"
109 | ]
110 | },
111 | {
112 | "cell_type": "code",
113 | "execution_count": null,
114 | "id": "9279894d-0112-44b1-9926-0babb2b94ed0",
115 | "metadata": {
116 | "tags": []
117 | },
118 | "outputs": [],
119 | "source": [
120 | "A = np.matrix( [[5, 1, 3]] )\n",
121 | "B = np.matrix( [[2], \n",
122 | " [4], \n",
123 | " [6]] )\n",
124 | "print(np.dot(A, B))"
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": null,
130 | "id": "7e23ecf3-450f-4c3f-819a-9bd03a593dfb",
131 | "metadata": {
132 | "tags": []
133 | },
134 | "outputs": [],
135 | "source": [
136 | "A = np.matrix( [[1, 3, 2], \n",
137 | " [4, 0, -1]] )\n",
138 | "B = np.matrix( [[5, 10], \n",
139 | " [2, -2], \n",
140 | " [-3, 6]] )\n",
141 | "print(np.dot(A, B)) "
142 | ]
143 | },
144 | {
145 | "cell_type": "code",
146 | "execution_count": null,
147 | "id": "0404ede6-d788-4db0-b359-afd989c02d3f",
148 | "metadata": {
149 | "tags": []
150 | },
151 | "outputs": [],
152 | "source": [
153 | "print(A * B)"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": null,
159 | "id": "b19d9cbe-7fcd-4f37-9761-941b8acbe6de",
160 | "metadata": {
161 | "tags": []
162 | },
163 | "outputs": [],
164 | "source": [
165 | "A = np.matrix( [[3], \n",
166 | " [2]] )\n",
167 | "B = np.matrix( [[5], \n",
168 | " [4]] )\n",
169 | "print(np.kron(A, B))"
170 | ]
171 | },
172 | {
173 | "cell_type": "markdown",
174 | "id": "5131e5c3-e330-4f72-b07c-96550e9a1200",
175 | "metadata": {},
176 | "source": [
177 | "### Exercise 8"
178 | ]
179 | },
180 | {
181 | "cell_type": "code",
182 | "execution_count": null,
183 | "id": "b34be683-f260-4900-8818-f94bd49ec42d",
184 | "metadata": {
185 | "tags": []
186 | },
187 | "outputs": [],
188 | "source": [
189 | "import numpy as np\n",
190 | "\n",
191 | "A = np.matrix( [[1, 2, 3, 0],\n",
192 | " [2, 1, -1, 3]] )\n",
193 | "B = np.matrix( [[1, 1, -2],\n",
194 | " [3, 2, -1],\n",
195 | " [0, 4, 3],\n",
196 | " [3, -3, 5]] )\n",
197 | "print(np.dot(A, B))"
198 | ]
199 | },
200 | {
201 | "cell_type": "code",
202 | "execution_count": null,
203 | "id": "d1b0214b-9bd9-4b59-b0eb-72f2aabb93ff",
204 | "metadata": {
205 | "tags": []
206 | },
207 | "outputs": [],
208 | "source": [
209 | "import numpy as np\n",
210 | "\n",
211 | "A = np.matrix( [[2],\n",
212 | " [3],\n",
213 | " [1]] )\n",
214 | "B = np.matrix( [[8, 4, 0],\n",
215 | " [1, 3, 5]] )\n",
216 | "print(np.kron(A, B))"
217 | ]
218 | },
219 | {
220 | "cell_type": "code",
221 | "execution_count": null,
222 | "id": "265edfde-4b67-4c7a-a470-bed1fa9e9760",
223 | "metadata": {},
224 | "outputs": [],
225 | "source": []
226 | }
227 | ],
228 | "metadata": {
229 | "kernelspec": {
230 | "display_name": "Python 3 (ipykernel)",
231 | "language": "python",
232 | "name": "python3"
233 | },
234 | "language_info": {
235 | "codemirror_mode": {
236 | "name": "ipython",
237 | "version": 3
238 | },
239 | "file_extension": ".py",
240 | "mimetype": "text/x-python",
241 | "name": "python",
242 | "nbconvert_exporter": "python",
243 | "pygments_lexer": "ipython3",
244 | "version": "3.10.8"
245 | },
246 | "widgets": {
247 | "application/vnd.jupyter.widget-state+json": {
248 | "state": {},
249 | "version_major": 2,
250 | "version_minor": 0
251 | }
252 | }
253 | },
254 | "nbformat": 4,
255 | "nbformat_minor": 5
256 | }
257 |
--------------------------------------------------------------------------------
/Chapter 1/Chapter01.md:
--------------------------------------------------------------------------------
1 | ### Creating and displaying values
2 |
3 |
4 | ```python
5 | x = 7
6 | ```
7 |
8 |
9 | ```python
10 | print(x)
11 | ```
12 |
13 |
14 | ```python
15 | x = 1024
16 | ```
17 |
18 |
19 | ```python
20 | x = 7
21 | x = 99
22 | x = 1024
23 | print(x)
24 | print(y)
25 | ```
26 |
27 |
28 | ```python
29 | import time
30 |
31 | while True:
32 | print('Hello')
33 | time.sleep(1)
34 | ```
35 |
36 | ### Matrices in Python
37 |
38 |
39 | ```python
40 | import numpy as np
41 | ```
42 |
43 |
44 | ```python
45 | A = np.matrix( [[2, -3, 0],
46 | [1, 5, 19]] )
47 | print(np.dot(4, A))
48 | ```
49 |
50 |
51 | ```python
52 | A = np.matrix( [[5, 1, 3]] )
53 | B = np.matrix( [[2],
54 | [4],
55 | [6]] )
56 | print(np.dot(A, B))
57 | ```
58 |
59 |
60 | ```python
61 | A = np.matrix( [[1, 3, 2],
62 | [4, 0, -1]] )
63 | B = np.matrix( [[5, 10],
64 | [2, -2],
65 | [-3, 6]] )
66 | print(np.dot(A, B))
67 | ```
68 |
69 |
70 | ```python
71 | print(A * B)
72 | ```
73 |
74 |
75 | ```python
76 | A = np.matrix( [[3],
77 | [2]] )
78 | B = np.matrix( [[5],
79 | [4]] )
80 | print(np.kron(A, B))
81 | ```
82 |
83 | ### Exercise 8
84 |
85 |
86 | ```python
87 | import numpy as np
88 |
89 | A = np.matrix( [[1, 2, 3, 0],
90 | [2, 1, -1, 3]] )
91 | B = np.matrix( [[1, 1, -2],
92 | [3, 2, -1],
93 | [0, 4, 3],
94 | [3, -3, 5]] )
95 | print(np.dot(A, B))
96 | ```
97 |
98 |
99 | ```python
100 | import numpy as np
101 |
102 | A = np.matrix( [[2],
103 | [3],
104 | [1]] )
105 | B = np.matrix( [[8, 4, 0],
106 | [1, 3, 5]] )
107 | print(np.kron(A, B))
108 | ```
109 |
110 |
111 | ```python
112 |
113 | ```
114 |
--------------------------------------------------------------------------------
/Chapter 2/Chapter02.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "01df551e-ba87-4a6a-a149-1c0a3b4d9bff",
6 | "metadata": {},
7 | "source": [
8 | "### Creating and running a quantum circuit"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "b358649d-9501-46c3-9f11-1f6bd21acb45",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumRegister, \\\n",
21 | " ClassicalRegister, QuantumCircuit\n",
22 | "\n",
23 | "qReg = QuantumRegister(1, 'q')\n",
24 | "cReg = ClassicalRegister(1, 'c')\n",
25 | "circuit = QuantumCircuit(qReg, cReg)\n",
26 | "circuit.h(qReg[0])\n",
27 | "circuit.measure(qReg[0], cReg[0])\n",
28 | "display(circuit.draw('latex'))"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": null,
34 | "id": "e6c091d6-9da7-43ce-9435-08bdd0bebb5c",
35 | "metadata": {
36 | "tags": []
37 | },
38 | "outputs": [],
39 | "source": [
40 | "from qiskit import Aer\n",
41 | "device = Aer.get_backend('qasm_simulator')"
42 | ]
43 | },
44 | {
45 | "cell_type": "code",
46 | "execution_count": null,
47 | "id": "187a1ab4-fc39-474a-8f86-39df7cb8a40a",
48 | "metadata": {
49 | "tags": []
50 | },
51 | "outputs": [],
52 | "source": [
53 | "from qiskit import execute\n",
54 | "from qiskit.visualization import plot_histogram\n",
55 | "\n",
56 | "job = execute(circuit, backend=device, shots=1000)\n",
57 | "print(job.job_id())\n",
58 | "\n",
59 | "result = job.result()\n",
60 | "counts = result.get_counts(circuit)\n",
61 | "\n",
62 | "print(counts)\n",
63 | "display(plot_histogram(counts))"
64 | ]
65 | },
66 | {
67 | "cell_type": "markdown",
68 | "id": "c3787db1-ec30-41c6-839a-384c7d28fd05",
69 | "metadata": {},
70 | "source": [
71 | "### Finding a backend"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": null,
77 | "id": "ca9c1e8e-44e3-40d7-aa10-cc7603c25999",
78 | "metadata": {
79 | "tags": []
80 | },
81 | "outputs": [],
82 | "source": [
83 | "from qiskit_ibm_provider import IBMProvider \n",
84 | "\n",
85 | "provider = IBMProvider()\n",
86 | "IBM_cloud_backends = provider.backends(operational=True, \n",
87 | " min_num_qubits=5) \n",
88 | "for i in IBM_cloud_backends: \n",
89 | " print(i) "
90 | ]
91 | },
92 | {
93 | "cell_type": "markdown",
94 | "id": "bde3b881-7f71-49b3-992b-3c1ccba9a537",
95 | "metadata": {},
96 | "source": [
97 | "### Drawing circuits"
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": null,
103 | "id": "d7df633e-f5f9-41be-bbe9-cfbdba56cba0",
104 | "metadata": {
105 | "tags": []
106 | },
107 | "outputs": [],
108 | "source": [
109 | "from qiskit import QuantumRegister, \\\n",
110 | " ClassicalRegister, QuantumCircuit\n",
111 | "\n",
112 | "qReg = QuantumRegister(2, 'q')\n",
113 | "qRegNew = QuantumRegister(2, 'qNew')\n",
114 | "cReg = ClassicalRegister(2, 'c')\n",
115 | "cRegNew = ClassicalRegister(1, 'cNew')\n",
116 | "circuit = QuantumCircuit(qReg, qRegNew, cReg, cRegNew)\n",
117 | "display(circuit.draw('latex'))"
118 | ]
119 | },
120 | {
121 | "cell_type": "markdown",
122 | "id": "616aaf45-b480-468e-a46d-0c138c04d23e",
123 | "metadata": {},
124 | "source": [
125 | "### Creating a circuit with very little code"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": null,
131 | "id": "c1332726-0dca-4d0d-b629-b1ea9a3ee9ea",
132 | "metadata": {
133 | "tags": []
134 | },
135 | "outputs": [],
136 | "source": [
137 | "from qiskit import QuantumCircuit\n",
138 | "\n",
139 | "circuit = QuantumCircuit(1, 1)\n",
140 | "circuit.h(0)\n",
141 | "circuit.measure([0], [0])\n",
142 | "display(circuit.draw('latex'))"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": null,
148 | "id": "fe1e9755-6f72-4964-bb23-53f6f2c7cad6",
149 | "metadata": {
150 | "tags": []
151 | },
152 | "outputs": [],
153 | "source": [
154 | "from qiskit import QuantumCircuit\n",
155 | "\n",
156 | "circuit = QuantumCircuit(2, 4)\n",
157 | "circuit.h(0)\n",
158 | "circuit.barrier()\n",
159 | "circuit.measure([1, 0], [2, 3])\n",
160 | "display(circuit.draw('latex'))"
161 | ]
162 | },
163 | {
164 | "cell_type": "code",
165 | "execution_count": null,
166 | "id": "54d31085-fa11-4c36-80b8-8218baa54a41",
167 | "metadata": {
168 | "tags": []
169 | },
170 | "outputs": [],
171 | "source": [
172 | "from qiskit import QuantumCircuit\n",
173 | "\n",
174 | "circuit = QuantumCircuit(2)\n",
175 | "circuit.h([0, 1])\n",
176 | "circuit.measure_all()\n",
177 | "display(circuit.draw('latex'))"
178 | ]
179 | },
180 | {
181 | "cell_type": "code",
182 | "execution_count": null,
183 | "id": "1a49bd29-12d1-4e8e-9611-ec1b19d46010",
184 | "metadata": {},
185 | "outputs": [],
186 | "source": []
187 | }
188 | ],
189 | "metadata": {
190 | "kernelspec": {
191 | "display_name": "Python 3 (ipykernel)",
192 | "language": "python",
193 | "name": "python3"
194 | },
195 | "language_info": {
196 | "codemirror_mode": {
197 | "name": "ipython",
198 | "version": 3
199 | },
200 | "file_extension": ".py",
201 | "mimetype": "text/x-python",
202 | "name": "python",
203 | "nbconvert_exporter": "python",
204 | "pygments_lexer": "ipython3",
205 | "version": "3.10.8"
206 | },
207 | "widgets": {
208 | "application/vnd.jupyter.widget-state+json": {
209 | "state": {},
210 | "version_major": 2,
211 | "version_minor": 0
212 | }
213 | }
214 | },
215 | "nbformat": 4,
216 | "nbformat_minor": 5
217 | }
218 |
--------------------------------------------------------------------------------
/Chapter 2/Chapter02.md:
--------------------------------------------------------------------------------
1 | ### Creating and running a quantum circuit
2 |
3 |
4 | ```python
5 | from qiskit import QuantumRegister, \
6 | ClassicalRegister, QuantumCircuit
7 |
8 | qReg = QuantumRegister(1, 'q')
9 | cReg = ClassicalRegister(1, 'c')
10 | circuit = QuantumCircuit(qReg, cReg)
11 | circuit.h(qReg[0])
12 | circuit.measure(qReg[0], cReg[0])
13 | display(circuit.draw('latex'))
14 | ```
15 |
16 |
17 | ```python
18 | from qiskit import Aer
19 | device = Aer.get_backend('qasm_simulator')
20 | ```
21 |
22 |
23 | ```python
24 | from qiskit import execute
25 | from qiskit.visualization import plot_histogram
26 |
27 | job = execute(circuit, backend=device, shots=1000)
28 | print(job.job_id())
29 |
30 | result = job.result()
31 | counts = result.get_counts(circuit)
32 |
33 | print(counts)
34 | display(plot_histogram(counts))
35 | ```
36 |
37 | ### Finding a backend
38 |
39 |
40 | ```python
41 | from qiskit_ibm_provider import IBMProvider
42 |
43 | provider = IBMProvider()
44 | IBM_cloud_backends = provider.backends(operational=True,
45 | min_num_qubits=5)
46 | for i in IBM_cloud_backends:
47 | print(i)
48 | ```
49 |
50 | ### Drawing circuits
51 |
52 |
53 | ```python
54 | from qiskit import QuantumRegister, \
55 | ClassicalRegister, QuantumCircuit
56 |
57 | qReg = QuantumRegister(2, 'q')
58 | qRegNew = QuantumRegister(2, 'qNew')
59 | cReg = ClassicalRegister(2, 'c')
60 | cRegNew = ClassicalRegister(1, 'cNew')
61 | circuit = QuantumCircuit(qReg, qRegNew, cReg, cRegNew)
62 | display(circuit.draw('latex'))
63 | ```
64 |
65 | ### Creating a circuit with very little code
66 |
67 |
68 | ```python
69 | from qiskit import QuantumCircuit
70 |
71 | circuit = QuantumCircuit(1, 1)
72 | circuit.h(0)
73 | circuit.measure([0], [0])
74 | display(circuit.draw('latex'))
75 | ```
76 |
77 |
78 | ```python
79 | from qiskit import QuantumCircuit
80 |
81 | circuit = QuantumCircuit(2, 4)
82 | circuit.h(0)
83 | circuit.barrier()
84 | circuit.measure([1, 0], [2, 3])
85 | display(circuit.draw('latex'))
86 | ```
87 |
88 |
89 | ```python
90 | from qiskit import QuantumCircuit
91 |
92 | circuit = QuantumCircuit(2)
93 | circuit.h([0, 1])
94 | circuit.measure_all()
95 | display(circuit.draw('latex'))
96 | ```
97 |
98 |
99 | ```python
100 |
101 | ```
102 |
--------------------------------------------------------------------------------
/Chapter 3/Chapter03.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "8382e73c-f7e9-4669-b16b-44251dd648d1",
6 | "metadata": {},
7 | "source": [
8 | "### Combining gates along a single wire"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "2d8c30e4-1031-4aa1-bce1-ffd4a439f83d",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumRegister, QuantumCircuit\n",
21 | "reg = QuantumRegister(1)\n",
22 | "circuit = QuantumCircuit(reg)\n",
23 | "circuit.x(reg[0])\n",
24 | "circuit.h(reg[0])\n",
25 | "\n",
26 | "#circuit.x(reg[0])\n",
27 | "\n",
28 | "#circuit.h(reg[0])\n",
29 | "#circuit.h(reg[0])\n",
30 | "\n",
31 | "display(circuit.draw('latex', initial_state=True))"
32 | ]
33 | },
34 | {
35 | "cell_type": "code",
36 | "execution_count": null,
37 | "id": "484d66f2-33c4-4d72-8656-07fd4149f552",
38 | "metadata": {
39 | "tags": []
40 | },
41 | "outputs": [],
42 | "source": [
43 | "from qiskit.quantum_info import Statevector\n",
44 | "from qiskit.visualization \\\n",
45 | " import plot_bloch_multivector \n",
46 | "\n",
47 | "vector = Statevector(circuit) \n",
48 | "display(plot_bloch_multivector(vector.data))"
49 | ]
50 | },
51 | {
52 | "cell_type": "code",
53 | "execution_count": null,
54 | "id": "e13a1145-39f4-40d9-86e8-c67cf8fbba03",
55 | "metadata": {
56 | "tags": []
57 | },
58 | "outputs": [],
59 | "source": [
60 | "from qiskit import Aer, execute\n",
61 | "device = Aer.get_backend('qasm_simulator')\n",
62 | "\n",
63 | "#from qiskit_ibm_provider import IBMProvider\n",
64 | "#provider = IBMProvider()\n",
65 | "#device = provider.get_backend('ibmq_lima')\n",
66 | "\n",
67 | "circuit.measure_all()\n",
68 | "job = execute(circuit, backend=device, shots=1000)\n",
69 | "print(job.job_id())\n",
70 | "\n",
71 | "result = job.result()\n",
72 | "counts = result.get_counts(circuit)\n",
73 | "print(counts)"
74 | ]
75 | },
76 | {
77 | "cell_type": "markdown",
78 | "id": "2b2b258d-6763-4732-82e9-a6f04ad8b853",
79 | "metadata": {},
80 | "source": [
81 | "### Experimenting with rotations"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": null,
87 | "id": "02bc270a-4d47-4724-a76e-2880571f834a",
88 | "metadata": {
89 | "tags": []
90 | },
91 | "outputs": [],
92 | "source": [
93 | "from qiskit import QuantumRegister, QuantumCircuit\n",
94 | "from math import pi\n",
95 | "reg = QuantumRegister(1)\n",
96 | "circuit = QuantumCircuit(reg)\n",
97 | "circuit.ry(pi/2, reg[0])\n",
98 | "#circuit.ry(pi/3, reg[0])\n",
99 | "display(circuit.draw('latex'))"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": null,
105 | "id": "e95e0a67-f308-43d3-a0c3-b3ef74b3d5c5",
106 | "metadata": {
107 | "tags": []
108 | },
109 | "outputs": [],
110 | "source": [
111 | "from qiskit import Aer, execute\n",
112 | "device = Aer.get_backend('qasm_simulator')\n",
113 | "\n",
114 | "circuit.measure_all()\n",
115 | "job = execute(circuit, backend=device, shots=1000)\n",
116 | "print(job.job_id())\n",
117 | "\n",
118 | "result = job.result()\n",
119 | "counts = result.get_counts(circuit)\n",
120 | "print(counts)"
121 | ]
122 | },
123 | {
124 | "cell_type": "code",
125 | "execution_count": null,
126 | "id": "2001b977-92fb-42ce-9824-137ae6994706",
127 | "metadata": {},
128 | "outputs": [],
129 | "source": []
130 | }
131 | ],
132 | "metadata": {
133 | "kernelspec": {
134 | "display_name": "Python 3 (ipykernel)",
135 | "language": "python",
136 | "name": "python3"
137 | },
138 | "language_info": {
139 | "codemirror_mode": {
140 | "name": "ipython",
141 | "version": 3
142 | },
143 | "file_extension": ".py",
144 | "mimetype": "text/x-python",
145 | "name": "python",
146 | "nbconvert_exporter": "python",
147 | "pygments_lexer": "ipython3",
148 | "version": "3.10.8"
149 | },
150 | "widgets": {
151 | "application/vnd.jupyter.widget-state+json": {
152 | "state": {},
153 | "version_major": 2,
154 | "version_minor": 0
155 | }
156 | }
157 | },
158 | "nbformat": 4,
159 | "nbformat_minor": 5
160 | }
161 |
--------------------------------------------------------------------------------
/Chapter 3/Chapter03.md:
--------------------------------------------------------------------------------
1 | ### Combining gates along a single wire
2 |
3 |
4 | ```python
5 | from qiskit import QuantumRegister, QuantumCircuit
6 | reg = QuantumRegister(1)
7 | circuit = QuantumCircuit(reg)
8 | circuit.x(reg[0])
9 | circuit.h(reg[0])
10 |
11 | #circuit.x(reg[0])
12 |
13 | #circuit.h(reg[0])
14 | #circuit.h(reg[0])
15 |
16 | display(circuit.draw('latex', initial_state=True))
17 | ```
18 |
19 |
20 | ```python
21 | from qiskit.quantum_info import Statevector
22 | from qiskit.visualization \
23 | import plot_bloch_multivector
24 |
25 | vector = Statevector(circuit)
26 | display(plot_bloch_multivector(vector.data))
27 | ```
28 |
29 |
30 | ```python
31 | from qiskit import Aer, execute
32 | device = Aer.get_backend('qasm_simulator')
33 |
34 | #from qiskit_ibm_provider import IBMProvider
35 | #provider = IBMProvider()
36 | #device = provider.get_backend('ibmq_lima')
37 |
38 | circuit.measure_all()
39 | job = execute(circuit, backend=device, shots=1000)
40 | print(job.job_id())
41 |
42 | result = job.result()
43 | counts = result.get_counts(circuit)
44 | print(counts)
45 | ```
46 |
47 | ### Experimenting with rotations
48 |
49 |
50 | ```python
51 | from qiskit import QuantumRegister, QuantumCircuit
52 | from math import pi
53 | reg = QuantumRegister(1)
54 | circuit = QuantumCircuit(reg)
55 | circuit.ry(pi/2, reg[0])
56 | #circuit.ry(pi/3, reg[0])
57 | display(circuit.draw('latex'))
58 | ```
59 |
60 |
61 | ```python
62 | from qiskit import Aer, execute
63 | device = Aer.get_backend('qasm_simulator')
64 |
65 | circuit.measure_all()
66 | job = execute(circuit, backend=device, shots=1000)
67 | print(job.job_id())
68 |
69 | result = job.result()
70 | counts = result.get_counts(circuit)
71 | print(counts)
72 | ```
73 |
74 |
75 | ```python
76 |
77 | ```
78 |
--------------------------------------------------------------------------------
/Chapter 4/Chapter04.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "9f0251ac-2454-4ebb-bfbe-3819fbb3e994",
6 | "metadata": {},
7 | "source": [
8 | "### CNOT and flipped CNOT gates"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "6cc67eac-ae55-42f0-838b-f715dff0836a",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumRegister, QuantumCircuit\n",
21 | "reg = QuantumRegister(2)\n",
22 | "circuit = QuantumCircuit(reg)\n",
23 | "circuit.cnot(reg[0], reg[1])\n",
24 | "display(circuit.draw('latex'))"
25 | ]
26 | },
27 | {
28 | "cell_type": "markdown",
29 | "id": "551c8e24-8a48-4755-a5c4-5df6dbd4201d",
30 | "metadata": {},
31 | "source": [
32 | "### Toffoli gate"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": null,
38 | "id": "eb55d319-f95f-406f-8ebb-ee1530c407eb",
39 | "metadata": {
40 | "tags": []
41 | },
42 | "outputs": [],
43 | "source": [
44 | "from qiskit import QuantumRegister, QuantumCircuit\n",
45 | "reg = QuantumRegister(3)\n",
46 | "circuit = QuantumCircuit(reg)\n",
47 | "circuit.ccx(reg[0], reg[1], reg[2])\n",
48 | "display(circuit.draw('latex'))"
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "id": "de5d04a1-9221-458b-8e8e-38e0c4962518",
54 | "metadata": {},
55 | "source": [
56 | "### Working with Qiskit"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "id": "c24be059-92ae-428a-8490-a8df548b21e4",
63 | "metadata": {
64 | "tags": []
65 | },
66 | "outputs": [],
67 | "source": [
68 | "from qiskit import QuantumCircuit\n",
69 | "\n",
70 | "circ = QuantumCircuit(2)\n",
71 | "circ.h(0)\n",
72 | "circ.cnot(0, 1)\n",
73 | "display(circ.draw('latex', initial_state=True))"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": null,
79 | "id": "a4e3065e-2168-4b38-ba68-e38af034810a",
80 | "metadata": {
81 | "tags": []
82 | },
83 | "outputs": [],
84 | "source": [
85 | "from qiskit.quantum_info import Statevector\n",
86 | "\n",
87 | "vector = Statevector (circ)\n",
88 | "display(vector.draw(output='qsphere'))"
89 | ]
90 | },
91 | {
92 | "cell_type": "code",
93 | "execution_count": null,
94 | "id": "dfb15ba4-e71b-469c-a8d9-e353cb65c131",
95 | "metadata": {
96 | "tags": []
97 | },
98 | "outputs": [],
99 | "source": [
100 | "display(vector.draw(output='latex'))"
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": null,
106 | "id": "2ecd76c0-7551-402e-82b9-90ed0845bdad",
107 | "metadata": {},
108 | "outputs": [],
109 | "source": [
110 | "circ.measure_all()\n",
111 | "\n",
112 | "from qiskit import Aer, execute \n",
113 | "from qiskit.visualization import plot_histogram\n",
114 | "\n",
115 | "device = Aer.get_backend('qasm_simulator')\n",
116 | "job = execute(circ, backend=device, shots=1000)\n",
117 | "\n",
118 | "counts = job.result().get_counts(circ)\n",
119 | "print(counts)\n",
120 | "plot_histogram(counts)"
121 | ]
122 | },
123 | {
124 | "cell_type": "markdown",
125 | "id": "c8e601bf-d6e0-4bac-b6b4-2c7c879043d8",
126 | "metadata": {},
127 | "source": [
128 | "### Bell's experiment in Qiskit"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": null,
134 | "id": "235db8a0-e958-4293-ac32-8e1a2979440c",
135 | "metadata": {
136 | "tags": []
137 | },
138 | "outputs": [],
139 | "source": [
140 | "from qiskit import QuantumCircuit\n",
141 | "\n",
142 | "\n",
143 | "def get_circuit(angle_left, angle_right):\n",
144 | " circ = QuantumCircuit(2)\n",
145 | " circ.h(0)\n",
146 | " circ.cnot(0, 1)\n",
147 | " circ.x(1)\n",
148 | " circ.barrier()\n",
149 | " circ.ry(angle_left, 0)\n",
150 | " circ.ry(angle_right, 1)\n",
151 | " circ.measure_all()\n",
152 | " display(circ.draw('latex'))\n",
153 | " return circ"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": null,
159 | "id": "45f762dc-ddf8-438a-90ac-6d58ae3d682d",
160 | "metadata": {
161 | "tags": []
162 | },
163 | "outputs": [],
164 | "source": [
165 | "from math import pi\n",
166 | "\n",
167 | "northwest = pi / 6\n",
168 | "southwest = 5 * pi / 6\n",
169 | "east = 9 * pi / 6\n",
170 | "directions = [northwest, southwest, east]\n",
171 | "\n",
172 | "circuits = []\n",
173 | "for dir_left in directions:\n",
174 | " for dir_right in directions:\n",
175 | " circuits.append(\n",
176 | " get_circuit(dir_left, dir_right))"
177 | ]
178 | },
179 | {
180 | "cell_type": "code",
181 | "execution_count": null,
182 | "id": "b77f4947-987d-4cab-8fc3-d1ef9486bd99",
183 | "metadata": {},
184 | "outputs": [],
185 | "source": [
186 | "from qiskit_ibm_provider import IBMProvider\n",
187 | "from qiskit import execute\n",
188 | "\n",
189 | "provider = IBMProvider()\n",
190 | "device = provider.get_backend('ibm_perth')\n",
191 | "# For a real test, run on a quantum backend \n",
192 | "# with at least two qubits\n",
193 | "\n",
194 | "shots=100\n",
195 | "job = execute(circuits, backend=device, \\\n",
196 | " shots=shots, memory=True)\n",
197 | "result = job.result()"
198 | ]
199 | },
200 | {
201 | "cell_type": "code",
202 | "execution_count": null,
203 | "id": "a5b5a829-431a-4389-a134-b21d91906a9b",
204 | "metadata": {},
205 | "outputs": [],
206 | "source": [
207 | "disagree = 0\n",
208 | "for circ in circuits:\n",
209 | " memory = result.get_memory(circ)\n",
210 | " for meas in memory:\n",
211 | " if meas[0] != meas[1]:\n",
212 | " disagree += 1\n",
213 | "print('\\nProbability of disagreement: ', end='')\n",
214 | "print(disagree / (9 * shots))"
215 | ]
216 | },
217 | {
218 | "cell_type": "markdown",
219 | "id": "861d3ba5-6783-4ed5-9c03-443e4791c640",
220 | "metadata": {},
221 | "source": [
222 | "### Question 4"
223 | ]
224 | },
225 | {
226 | "cell_type": "code",
227 | "execution_count": null,
228 | "id": "4dc011fe-fd5f-4dff-af90-c6706d27b829",
229 | "metadata": {},
230 | "outputs": [],
231 | "source": [
232 | "from qiskit import QuantumCircuit\n",
233 | "\n",
234 | "circ = QuantumCircuit(2)\n",
235 | "circ.h(0)\n",
236 | "circ.cnot(0, 1)\n",
237 | "circ.x(1)\n",
238 | "circ.z(1)\n",
239 | "display(circ.draw('latex', initial_state=True))"
240 | ]
241 | }
242 | ],
243 | "metadata": {
244 | "kernelspec": {
245 | "display_name": "Python 3 (ipykernel)",
246 | "language": "python",
247 | "name": "python3"
248 | },
249 | "language_info": {
250 | "codemirror_mode": {
251 | "name": "ipython",
252 | "version": 3
253 | },
254 | "file_extension": ".py",
255 | "mimetype": "text/x-python",
256 | "name": "python",
257 | "nbconvert_exporter": "python",
258 | "pygments_lexer": "ipython3",
259 | "version": "3.10.8"
260 | },
261 | "widgets": {
262 | "application/vnd.jupyter.widget-state+json": {
263 | "state": {},
264 | "version_major": 2,
265 | "version_minor": 0
266 | }
267 | }
268 | },
269 | "nbformat": 4,
270 | "nbformat_minor": 5
271 | }
272 |
--------------------------------------------------------------------------------
/Chapter 4/Chapter04.md:
--------------------------------------------------------------------------------
1 | ### CNOT and flipped CNOT gates
2 |
3 |
4 | ```python
5 | from qiskit import QuantumRegister, QuantumCircuit
6 | reg = QuantumRegister(2)
7 | circuit = QuantumCircuit(reg)
8 | circuit.cnot(reg[0], reg[1])
9 | display(circuit.draw('latex'))
10 | ```
11 |
12 | ### Toffoli gate
13 |
14 |
15 | ```python
16 | from qiskit import QuantumRegister, QuantumCircuit
17 | reg = QuantumRegister(3)
18 | circuit = QuantumCircuit(reg)
19 | circuit.ccx(reg[0], reg[1], reg[2])
20 | display(circuit.draw('latex'))
21 | ```
22 |
23 | ### Working with Qiskit
24 |
25 |
26 | ```python
27 | from qiskit import QuantumCircuit
28 |
29 | circ = QuantumCircuit(2)
30 | circ.h(0)
31 | circ.cnot(0, 1)
32 | display(circ.draw('latex', initial_state=True))
33 | ```
34 |
35 |
36 | ```python
37 | from qiskit.quantum_info import Statevector
38 |
39 | vector = Statevector (circ)
40 | display(vector.draw(output='qsphere'))
41 | ```
42 |
43 |
44 | ```python
45 | display(vector.draw(output='latex'))
46 | ```
47 |
48 |
49 | ```python
50 | circ.measure_all()
51 |
52 | from qiskit import Aer, execute
53 | from qiskit.visualization import plot_histogram
54 |
55 | device = Aer.get_backend('qasm_simulator')
56 | job = execute(circ, backend=device, shots=1000)
57 |
58 | counts = job.result().get_counts(circ)
59 | print(counts)
60 | plot_histogram(counts)
61 | ```
62 |
63 | ### Bell's experiment in Qiskit
64 |
65 |
66 | ```python
67 | from qiskit import QuantumCircuit
68 |
69 |
70 | def get_circuit(angle_left, angle_right):
71 | circ = QuantumCircuit(2)
72 | circ.h(0)
73 | circ.cnot(0, 1)
74 | circ.x(1)
75 | circ.barrier()
76 | circ.ry(angle_left, 0)
77 | circ.ry(angle_right, 1)
78 | circ.measure_all()
79 | display(circ.draw('latex'))
80 | return circ
81 | ```
82 |
83 |
84 | ```python
85 | from math import pi
86 |
87 | northwest = pi / 6
88 | southwest = 5 * pi / 6
89 | east = 9 * pi / 6
90 | directions = [northwest, southwest, east]
91 |
92 | circuits = []
93 | for dir_left in directions:
94 | for dir_right in directions:
95 | circuits.append(
96 | get_circuit(dir_left, dir_right))
97 | ```
98 |
99 |
100 | ```python
101 | from qiskit_ibm_provider import IBMProvider
102 | from qiskit import execute
103 |
104 | provider = IBMProvider()
105 | device = provider.get_backend('ibm_perth')
106 | # For a real test, run on a quantum backend
107 | # with at least two qubits
108 |
109 | shots=100
110 | job = execute(circuits, backend=device, \
111 | shots=shots, memory=True)
112 | result = job.result()
113 | ```
114 |
115 |
116 | ```python
117 | disagree = 0
118 | for circ in circuits:
119 | memory = result.get_memory(circ)
120 | for meas in memory:
121 | if meas[0] != meas[1]:
122 | disagree += 1
123 | print('\nProbability of disagreement: ', end='')
124 | print(disagree / (9 * shots))
125 | ```
126 |
127 | ### Question 4
128 |
129 |
130 | ```python
131 | from qiskit import QuantumCircuit
132 |
133 | circ = QuantumCircuit(2)
134 | circ.h(0)
135 | circ.cnot(0, 1)
136 | circ.x(1)
137 | circ.z(1)
138 | display(circ.draw('latex', initial_state=True))
139 | ```
140 |
--------------------------------------------------------------------------------
/Chapter 5/Chapter05.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "57d2c9cf-e2f4-4b42-8271-e6cb30d0cc2b",
6 | "metadata": {},
7 | "source": [
8 | "### Qiskit code for the BB84 algorithm"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "77dd79fd-1a68-496f-b3f8-85b6adf5f1c9",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "import random\n",
21 | "from qiskit import QuantumCircuit, QuantumRegister, \\\n",
22 | " ClassicalRegister, Aer, execute\n",
23 | "\n",
24 | "NUMBER_OF_CIRCUITS = 100\n",
25 | "DOES_EVE_EXIST = False\n",
26 | "CHECK_MARK = u'\\u2713'"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": null,
32 | "id": "830f9a18-1593-4351-a28c-fa9df03b35c2",
33 | "metadata": {
34 | "tags": []
35 | },
36 | "outputs": [],
37 | "source": [
38 | "def create_registers(eve_exists):\n",
39 | " alice_q = QuantumRegister(1, 'alice_q')\n",
40 | " bob_q = QuantumRegister(1, 'bob_q')\n",
41 | " bob_c = ClassicalRegister(1, 'bob_c')\n",
42 | "\n",
43 | " if eve_exists:\n",
44 | " eve_c = ClassicalRegister(1, 'eve_c')\n",
45 | " circ = QuantumCircuit(alice_q, bob_q, bob_c, eve_c)\n",
46 | " else:\n",
47 | " circ = QuantumCircuit(alice_q, bob_q, bob_c)\n",
48 | " return circ"
49 | ]
50 | },
51 | {
52 | "cell_type": "code",
53 | "execution_count": null,
54 | "id": "dcc5a25b-5962-4edf-8b94-91f23bbe4add",
55 | "metadata": {
56 | "tags": []
57 | },
58 | "outputs": [],
59 | "source": [
60 | "def setup_alice(circ):\n",
61 | " alice_q = circ.qubits[0]\n",
62 | "\n",
63 | " if random.getrandbits(1):\n",
64 | " circ.x(alice_q)\n",
65 | "\n",
66 | " if random.getrandbits(1):\n",
67 | " circ.h(alice_q)\n",
68 | "\n",
69 | " return circ\n",
70 | "\n",
71 | "\n",
72 | "def setup_bob(circ):\n",
73 | " bob_q = circ.qubits[1]\n",
74 | " bob_c = circ.clbits[0]\n",
75 | "\n",
76 | " if random.getrandbits(1):\n",
77 | " circ.h(bob_q)\n",
78 | "\n",
79 | " circ.measure(bob_q, bob_c)\n",
80 | " return circ\n",
81 | "\n",
82 | "\n",
83 | "def setup_eve(circ):\n",
84 | " bob_q = circ.qubits[1]\n",
85 | " eve_c = circ.clbits[1]\n",
86 | "\n",
87 | " circ.barrier()\n",
88 | " circ.measure(bob_q, eve_c)\n",
89 | " circ.barrier()\n",
90 | " return circ"
91 | ]
92 | },
93 | {
94 | "cell_type": "code",
95 | "execution_count": null,
96 | "id": "047d1fd8-beee-4b9b-bc26-400bb7be1dd0",
97 | "metadata": {
98 | "tags": []
99 | },
100 | "outputs": [],
101 | "source": [
102 | "def make_new_circuit(eve_exists):\n",
103 | " circ = create_registers(eve_exists)\n",
104 | " alice_q = circ.qubits[0]\n",
105 | " bob_q = circ.qubits[1]\n",
106 | " bob_c = circ.clbits[0]\n",
107 | "\n",
108 | " circ = setup_alice(circ)\n",
109 | "\n",
110 | " circ.swap(alice_q, bob_q)\n",
111 | "\n",
112 | " if eve_exists:\n",
113 | " circ = setup_eve(circ)\n",
114 | "\n",
115 | " circ = setup_bob(circ)\n",
116 | "\n",
117 | " return circ"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": null,
123 | "id": "b26c3a92-0997-44ae-a62a-833c4eb2531b",
124 | "metadata": {
125 | "tags": []
126 | },
127 | "outputs": [],
128 | "source": [
129 | "def create_circuits(how_many, does_eve_exist):\n",
130 | " circuits = []\n",
131 | " for i in range(how_many):\n",
132 | " circuits.append(make_new_circuit(does_eve_exist)) \n",
133 | " return circuits"
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "id": "754de332-2680-458d-9e68-ca2913fa97ae",
140 | "metadata": {
141 | "tags": []
142 | },
143 | "outputs": [],
144 | "source": [
145 | "def run_the_job(circuits):\n",
146 | " device = Aer.get_backend('qasm_simulator')\n",
147 | " job = execute(circuits, backend=device, shots=1, memory=True)\n",
148 | " return job.result()"
149 | ]
150 | },
151 | {
152 | "cell_type": "code",
153 | "execution_count": null,
154 | "id": "9feab346-f4a8-4b08-9de3-da5daf3dd05d",
155 | "metadata": {
156 | "tags": []
157 | },
158 | "outputs": [],
159 | "source": [
160 | "def print_alice_bits(circuits):\n",
161 | " print('alice bits: ', end='')\n",
162 | " for circ in circuits:\n",
163 | " bit = 1 if 'x' in circ.count_ops() else 0\n",
164 | " print(bit, end='')\n",
165 | " print('')"
166 | ]
167 | },
168 | {
169 | "cell_type": "code",
170 | "execution_count": null,
171 | "id": "0ad1732e-c509-4b76-a7fc-4a0c90dca190",
172 | "metadata": {
173 | "tags": []
174 | },
175 | "outputs": [],
176 | "source": [
177 | "def bob_bit_value(circ, memory):\n",
178 | " return memory[0][0]"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "execution_count": null,
184 | "id": "6edef2af-fced-4f16-a4d2-9c042681203d",
185 | "metadata": {
186 | "tags": []
187 | },
188 | "outputs": [],
189 | "source": [
190 | "def print_bob_bits(circuits, result):\n",
191 | " print('bob bits : ', end='')\n",
192 | " for circ in circuits:\n",
193 | " memory = result.get_memory(circ)\n",
194 | " print(bob_bit_value(circ, memory), end='')\n",
195 | " print('')"
196 | ]
197 | },
198 | {
199 | "cell_type": "code",
200 | "execution_count": null,
201 | "id": "37fd9d07-2899-4485-85b8-90016aa3d539",
202 | "metadata": {
203 | "tags": []
204 | },
205 | "outputs": [],
206 | "source": [
207 | "def had_agreement(circ):\n",
208 | " gate_counts = circ.count_ops()\n",
209 | " return not ('h' in gate_counts and gate_counts['h'] == 1)"
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": null,
215 | "id": "6f4bc208-da32-4a50-ab09-fc21f5cb5f14",
216 | "metadata": {
217 | "tags": []
218 | },
219 | "outputs": [],
220 | "source": [
221 | "def print_had_agreements(circuits):\n",
222 | " number_of_agreements = 0\n",
223 | " print('hads agree? ', end='')\n",
224 | " for circ in circuits:\n",
225 | " if had_agreement(circ):\n",
226 | " print(CHECK_MARK, end='')\n",
227 | " number_of_agreements += 1\n",
228 | " else:\n",
229 | " print(' ', end='')\n",
230 | " print('')\n",
231 | " return number_of_agreements"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": null,
237 | "id": "28948bd2-6a43-4bf7-9276-10bbd2c8d742",
238 | "metadata": {
239 | "tags": []
240 | },
241 | "outputs": [],
242 | "source": [
243 | "def alice_bit_value(circ):\n",
244 | " return 1 if 'x' in circ.count_ops() else 0"
245 | ]
246 | },
247 | {
248 | "cell_type": "code",
249 | "execution_count": null,
250 | "id": "b79b547f-b144-4db5-a605-b31f82bd53b9",
251 | "metadata": {
252 | "tags": []
253 | },
254 | "outputs": [],
255 | "source": [
256 | "def bit_value_agreement(circ, result):\n",
257 | " memory = result.get_memory(circ)\n",
258 | " return alice_bit_value(circ) == int(\n",
259 | " bob_bit_value(circ, memory))"
260 | ]
261 | },
262 | {
263 | "cell_type": "code",
264 | "execution_count": null,
265 | "id": "b8774cbc-9681-4ff3-b1e2-a87e015eeab5",
266 | "metadata": {
267 | "tags": []
268 | },
269 | "outputs": [],
270 | "source": [
271 | "def print_bit_agreements(circuits, result,\n",
272 | " number_of_agreements):\n",
273 | " number_tested = 0\n",
274 | " is_eve_detected = False\n",
275 | " i = 0\n",
276 | "\n",
277 | " print('bits agree? ', end='')\n",
278 | " while number_tested < number_of_agreements // 2:\n",
279 | " if had_agreement(circuits[i]):\n",
280 | " if bit_value_agreement(circuits[i], result):\n",
281 | " print(CHECK_MARK, end='')\n",
282 | " number_tested += 1\n",
283 | " else:\n",
284 | " is_eve_detected = True\n",
285 | " print('X')\n",
286 | " break\n",
287 | " else:\n",
288 | " print(' ', end='')\n",
289 | " i += 1\n",
290 | "\n",
291 | " print()\n",
292 | "\n",
293 | " return i, is_eve_detected"
294 | ]
295 | },
296 | {
297 | "cell_type": "code",
298 | "execution_count": null,
299 | "id": "f4f9b2f7-4e7e-4e25-9863-6036bb74a61b",
300 | "metadata": {
301 | "tags": []
302 | },
303 | "outputs": [],
304 | "source": [
305 | "def print_key(circuits, number_of_circuits, how_many_for_testing):\n",
306 | " print('key :', end='')\n",
307 | " for i in range(how_many_for_testing + 1):\n",
308 | " print(' ', end='')\n",
309 | " for i in range(i, NUMBER_OF_CIRCUITS):\n",
310 | " if had_agreement(circuits[i]):\n",
311 | " print(alice_bit_value(circuits[i]), end='')\n",
312 | " else:\n",
313 | " print(' ', end='')"
314 | ]
315 | },
316 | {
317 | "cell_type": "code",
318 | "execution_count": null,
319 | "id": "ab4fdda0-bbf9-4aaa-8752-6540eb71e9a4",
320 | "metadata": {
321 | "tags": []
322 | },
323 | "outputs": [],
324 | "source": [
325 | "circuits = create_circuits(NUMBER_OF_CIRCUITS,\n",
326 | " DOES_EVE_EXIST) # 1\n",
327 | "\n",
328 | "result = run_the_job(circuits) # 2\n",
329 | "\n",
330 | "print_alice_bits(circuits) # 3\n",
331 | "\n",
332 | "print_bob_bits(circuits, result) # 4\n",
333 | "\n",
334 | "number_of_agreements = print_had_agreements(circuits) # 5\n",
335 | "\n",
336 | "how_many_for_testing, is_eve_detected = \\\n",
337 | " print_bit_agreements(circuits, result,\n",
338 | " number_of_agreements) # 6\n",
339 | "\n",
340 | "if is_eve_detected: # 7\n",
341 | " print('INTRUDER ALERT!')\n",
342 | "else:\n",
343 | " print_key(circuits, NUMBER_OF_CIRCUITS,\n",
344 | " how_many_for_testing) "
345 | ]
346 | },
347 | {
348 | "cell_type": "markdown",
349 | "id": "cc0af498-19b8-4be2-8092-90237ba8a93a",
350 | "metadata": {},
351 | "source": [
352 | "### Question 6"
353 | ]
354 | },
355 | {
356 | "cell_type": "code",
357 | "execution_count": null,
358 | "id": "33e294a5-3849-4b0e-80b6-b3892bd08de1",
359 | "metadata": {
360 | "tags": []
361 | },
362 | "outputs": [],
363 | "source": [
364 | "from qiskit import QuantumRegister, QuantumCircuit\n",
365 | "from math import pi\n",
366 | "import random\n",
367 | "alice_q = QuantumRegister(1, 'alice_q')\n",
368 | "bob_q = QuantumRegister(1, 'bob_q')\n",
369 | "circ = QuantumCircuit(alice_q, bob_q)\n",
370 | "circ.ry(pi/(random.uniform(2, 20)), alice_q[0])\n",
371 | "circ.cnot(0, 1)\n",
372 | "circ.measure_all()\n",
373 | "display(circ.draw('latex'))"
374 | ]
375 | },
376 | {
377 | "cell_type": "markdown",
378 | "id": "eec91451-2a70-405d-8c3a-ab2bb5c60fc6",
379 | "metadata": {},
380 | "source": [
381 | "### Question 7"
382 | ]
383 | },
384 | {
385 | "cell_type": "code",
386 | "execution_count": null,
387 | "id": "718262e6-5b96-47e8-9fe1-515f89d6bbed",
388 | "metadata": {},
389 | "outputs": [],
390 | "source": [
391 | "def setup_eve(circ):\n",
392 | " bob_q = circ.qubits[1]\n",
393 | " eve_c = circ.clbits[1]\n",
394 | " \n",
395 | " has_had = random.getrandbits(1)\n",
396 | " circ.barrier()\n",
397 | " if has_had:\n",
398 | " circ.h(bob_q)\n",
399 | " circ.measure(bob_q, eve_c)\n",
400 | " if has_had:\n",
401 | " circ.h(bob_q)\n",
402 | " circ.barrier()\n",
403 | " return circ\n",
404 | "\n",
405 | "def had_agreement(circ):\n",
406 | " gate_counts = circ.count_ops()\n",
407 | " return not ('h' in gate_counts and gate_counts['h'] % 2 == 1)"
408 | ]
409 | }
410 | ],
411 | "metadata": {
412 | "kernelspec": {
413 | "display_name": "Python 3 (ipykernel)",
414 | "language": "python",
415 | "name": "python3"
416 | },
417 | "language_info": {
418 | "codemirror_mode": {
419 | "name": "ipython",
420 | "version": 3
421 | },
422 | "file_extension": ".py",
423 | "mimetype": "text/x-python",
424 | "name": "python",
425 | "nbconvert_exporter": "python",
426 | "pygments_lexer": "ipython3",
427 | "version": "3.10.8"
428 | },
429 | "widgets": {
430 | "application/vnd.jupyter.widget-state+json": {
431 | "state": {},
432 | "version_major": 2,
433 | "version_minor": 0
434 | }
435 | }
436 | },
437 | "nbformat": 4,
438 | "nbformat_minor": 5
439 | }
440 |
--------------------------------------------------------------------------------
/Chapter 5/Chapter05.md:
--------------------------------------------------------------------------------
1 | ### Qiskit code for the BB84 algorithm
2 |
3 |
4 | ```python
5 | import random
6 | from qiskit import QuantumCircuit, QuantumRegister, \
7 | ClassicalRegister, Aer, execute
8 |
9 | NUMBER_OF_CIRCUITS = 100
10 | DOES_EVE_EXIST = False
11 | CHECK_MARK = u'\u2713'
12 | ```
13 |
14 |
15 | ```python
16 | def create_registers(eve_exists):
17 | alice_q = QuantumRegister(1, 'alice_q')
18 | bob_q = QuantumRegister(1, 'bob_q')
19 | bob_c = ClassicalRegister(1, 'bob_c')
20 |
21 | if eve_exists:
22 | eve_c = ClassicalRegister(1, 'eve_c')
23 | circ = QuantumCircuit(alice_q, bob_q, bob_c, eve_c)
24 | else:
25 | circ = QuantumCircuit(alice_q, bob_q, bob_c)
26 | return circ
27 | ```
28 |
29 |
30 | ```python
31 | def setup_alice(circ):
32 | alice_q = circ.qubits[0]
33 |
34 | if random.getrandbits(1):
35 | circ.x(alice_q)
36 |
37 | if random.getrandbits(1):
38 | circ.h(alice_q)
39 |
40 | return circ
41 |
42 |
43 | def setup_bob(circ):
44 | bob_q = circ.qubits[1]
45 | bob_c = circ.clbits[0]
46 |
47 | if random.getrandbits(1):
48 | circ.h(bob_q)
49 |
50 | circ.measure(bob_q, bob_c)
51 | return circ
52 |
53 |
54 | def setup_eve(circ):
55 | bob_q = circ.qubits[1]
56 | eve_c = circ.clbits[1]
57 |
58 | circ.barrier()
59 | circ.measure(bob_q, eve_c)
60 | circ.barrier()
61 | return circ
62 | ```
63 |
64 |
65 | ```python
66 | def make_new_circuit(eve_exists):
67 | circ = create_registers(eve_exists)
68 | alice_q = circ.qubits[0]
69 | bob_q = circ.qubits[1]
70 | bob_c = circ.clbits[0]
71 |
72 | circ = setup_alice(circ)
73 |
74 | circ.swap(alice_q, bob_q)
75 |
76 | if eve_exists:
77 | circ = setup_eve(circ)
78 |
79 | circ = setup_bob(circ)
80 |
81 | return circ
82 | ```
83 |
84 |
85 | ```python
86 | def create_circuits(how_many, does_eve_exist):
87 | circuits = []
88 | for i in range(how_many):
89 | circuits.append(make_new_circuit(does_eve_exist))
90 | return circuits
91 | ```
92 |
93 |
94 | ```python
95 | def run_the_job(circuits):
96 | device = Aer.get_backend('qasm_simulator')
97 | job = execute(circuits, backend=device, shots=1, memory=True)
98 | return job.result()
99 | ```
100 |
101 |
102 | ```python
103 | def print_alice_bits(circuits):
104 | print('alice bits: ', end='')
105 | for circ in circuits:
106 | bit = 1 if 'x' in circ.count_ops() else 0
107 | print(bit, end='')
108 | print('')
109 | ```
110 |
111 |
112 | ```python
113 | def bob_bit_value(circ, memory):
114 | return memory[0][0]
115 | ```
116 |
117 |
118 | ```python
119 | def print_bob_bits(circuits, result):
120 | print('bob bits : ', end='')
121 | for circ in circuits:
122 | memory = result.get_memory(circ)
123 | print(bob_bit_value(circ, memory), end='')
124 | print('')
125 | ```
126 |
127 |
128 | ```python
129 | def had_agreement(circ):
130 | gate_counts = circ.count_ops()
131 | return not ('h' in gate_counts and gate_counts['h'] == 1)
132 | ```
133 |
134 |
135 | ```python
136 | def print_had_agreements(circuits):
137 | number_of_agreements = 0
138 | print('hads agree? ', end='')
139 | for circ in circuits:
140 | if had_agreement(circ):
141 | print(CHECK_MARK, end='')
142 | number_of_agreements += 1
143 | else:
144 | print(' ', end='')
145 | print('')
146 | return number_of_agreements
147 | ```
148 |
149 |
150 | ```python
151 | def alice_bit_value(circ):
152 | return 1 if 'x' in circ.count_ops() else 0
153 | ```
154 |
155 |
156 | ```python
157 | def bit_value_agreement(circ, result):
158 | memory = result.get_memory(circ)
159 | return alice_bit_value(circ) == int(
160 | bob_bit_value(circ, memory))
161 | ```
162 |
163 |
164 | ```python
165 | def print_bit_agreements(circuits, result,
166 | number_of_agreements):
167 | number_tested = 0
168 | is_eve_detected = False
169 | i = 0
170 |
171 | print('bits agree? ', end='')
172 | while number_tested < number_of_agreements // 2:
173 | if had_agreement(circuits[i]):
174 | if bit_value_agreement(circuits[i], result):
175 | print(CHECK_MARK, end='')
176 | number_tested += 1
177 | else:
178 | is_eve_detected = True
179 | print('X')
180 | break
181 | else:
182 | print(' ', end='')
183 | i += 1
184 |
185 | print()
186 |
187 | return i, is_eve_detected
188 | ```
189 |
190 |
191 | ```python
192 | def print_key(circuits, number_of_circuits, how_many_for_testing):
193 | print('key :', end='')
194 | for i in range(how_many_for_testing + 1):
195 | print(' ', end='')
196 | for i in range(i, NUMBER_OF_CIRCUITS):
197 | if had_agreement(circuits[i]):
198 | print(alice_bit_value(circuits[i]), end='')
199 | else:
200 | print(' ', end='')
201 | ```
202 |
203 |
204 | ```python
205 | circuits = create_circuits(NUMBER_OF_CIRCUITS,
206 | DOES_EVE_EXIST) # 1
207 |
208 | result = run_the_job(circuits) # 2
209 |
210 | print_alice_bits(circuits) # 3
211 |
212 | print_bob_bits(circuits, result) # 4
213 |
214 | number_of_agreements = print_had_agreements(circuits) # 5
215 |
216 | how_many_for_testing, is_eve_detected = \
217 | print_bit_agreements(circuits, result,
218 | number_of_agreements) # 6
219 |
220 | if is_eve_detected: # 7
221 | print('INTRUDER ALERT!')
222 | else:
223 | print_key(circuits, NUMBER_OF_CIRCUITS,
224 | how_many_for_testing)
225 | ```
226 |
227 | ### Question 6
228 |
229 |
230 | ```python
231 | from qiskit import QuantumRegister, QuantumCircuit
232 | from math import pi
233 | import random
234 | alice_q = QuantumRegister(1, 'alice_q')
235 | bob_q = QuantumRegister(1, 'bob_q')
236 | circ = QuantumCircuit(alice_q, bob_q)
237 | circ.ry(pi/(random.uniform(2, 20)), alice_q[0])
238 | circ.cnot(0, 1)
239 | circ.measure_all()
240 | display(circ.draw('latex'))
241 | ```
242 |
243 | ### Question 7
244 |
245 |
246 | ```python
247 | def setup_eve(circ):
248 | bob_q = circ.qubits[1]
249 | eve_c = circ.clbits[1]
250 |
251 | has_had = random.getrandbits(1)
252 | circ.barrier()
253 | if has_had:
254 | circ.h(bob_q)
255 | circ.measure(bob_q, eve_c)
256 | if has_had:
257 | circ.h(bob_q)
258 | circ.barrier()
259 | return circ
260 |
261 | def had_agreement(circ):
262 | gate_counts = circ.count_ops()
263 | return not ('h' in gate_counts and gate_counts['h'] % 2 == 1)
264 | ```
265 |
--------------------------------------------------------------------------------
/Chapter 6/Chapter06.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "0bac34f6-06a2-4d03-9b8f-134f44110acc",
6 | "metadata": {},
7 | "source": [
8 | "### Coding the teleportation circuitry"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "6eb4b5e8-7a41-469b-b716-b9935abb6807",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumCircuit, QuantumRegister, \\\n",
21 | " ClassicalRegister, Aer\n",
22 | "import random\n",
23 | "import numpy as np\n",
24 | "from qiskit.result import marginal_counts"
25 | ]
26 | },
27 | {
28 | "cell_type": "code",
29 | "execution_count": null,
30 | "id": "7fa04b3f-5925-4e3e-8d29-6db571fa3e95",
31 | "metadata": {
32 | "tags": []
33 | },
34 | "outputs": [],
35 | "source": [
36 | "def create_registers():\n",
37 | " alice_q = QuantumRegister(1, 'alice (q)')\n",
38 | " peter_alice_q = \\\n",
39 | " QuantumRegister(1, 'peter/alice (q)')\n",
40 | " peter_bob_q = QuantumRegister(1, 'peter/bob (q)')\n",
41 | " bob_c = ClassicalRegister(3, 'bob (c)')\n",
42 | " circ = QuantumCircuit(alice_q, peter_alice_q,\n",
43 | " peter_bob_q, bob_c)\n",
44 | " return circ"
45 | ]
46 | },
47 | {
48 | "cell_type": "code",
49 | "execution_count": null,
50 | "id": "35c82ab3-e220-41ed-a19b-4be521a46f9e",
51 | "metadata": {
52 | "tags": []
53 | },
54 | "outputs": [],
55 | "source": [
56 | "def generate_amplitudes():\n",
57 | " alpha = np.sqrt(random.uniform(0, 1))\n",
58 | " beta = np.sqrt(1 - alpha**2)\n",
59 | " return alpha, beta"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "id": "33deeee7-a63f-441b-9c6e-d5ac8b2611f0",
66 | "metadata": {
67 | "tags": []
68 | },
69 | "outputs": [],
70 | "source": [
71 | "def add_gates(circ, alpha, beta):\n",
72 | " circ.initialize([alpha, beta], 0)\n",
73 | " circ.barrier()\n",
74 | " circ.h(1)\n",
75 | " circ.cnot(1, 2)\n",
76 | " circ.barrier()\n",
77 | " circ.cnot(0, 1)\n",
78 | " circ.h(0)\n",
79 | " circ.barrier()\n",
80 | " circ.measure(0, 0)\n",
81 | " circ.measure(1, 1)\n",
82 | " with circ.if_test((1, 1)):\n",
83 | " circ.x(2)\n",
84 | " with circ.if_test((0, 1)):\n",
85 | " circ.z(2)\n",
86 | " circ.measure(2, 2)\n",
87 | " return circ"
88 | ]
89 | },
90 | {
91 | "cell_type": "code",
92 | "execution_count": null,
93 | "id": "b8e9fb19-3eb6-4770-a8fa-92c4bf753c93",
94 | "metadata": {
95 | "tags": []
96 | },
97 | "outputs": [],
98 | "source": [
99 | "alpha, beta = generate_amplitudes()\n",
100 | "circ = create_registers()\n",
101 | "circ = add_gates(circ, alpha, beta)\n",
102 | "display(circ.draw('latex', cregbundle=False))"
103 | ]
104 | },
105 | {
106 | "cell_type": "code",
107 | "execution_count": null,
108 | "id": "3ee06ca2-4ab0-407f-ab68-3d1f3fa27b31",
109 | "metadata": {
110 | "tags": []
111 | },
112 | "outputs": [],
113 | "source": [
114 | "device = Aer.get_backend(\"qasm_simulator\")\n",
115 | "\n",
116 | "shots = 1000\n",
117 | "job = device.run(circ, shots=shots)\n",
118 | "print(job.job_id())\n",
119 | "\n",
120 | "result = job.result()\n",
121 | "counts = result.get_counts(circ)\n",
122 | "counts_m = marginal_counts(counts, [2])\n",
123 | "number_of_0s = counts_m.get('0') \n",
124 | "number_of_1s = counts_m.get('1') \n",
125 | "alpha = np.sqrt(number_of_0s / shots)\n",
126 | "beta = np.sqrt(number_of_1s / shots)\n",
127 | "print(\"|\\u03C8\\u27E9 ({:.4f}, {:.4f})\".format(alpha, beta))"
128 | ]
129 | },
130 | {
131 | "cell_type": "markdown",
132 | "id": "1f491433-25f1-4a45-826f-19c9c79362b0",
133 | "metadata": {},
134 | "source": [
135 | "### Question 2"
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": null,
141 | "id": "055dded7-99da-4650-8169-2ea55a4f0da2",
142 | "metadata": {},
143 | "outputs": [],
144 | "source": [
145 | "def generate_amplitudes():\n",
146 | " alpha = 0.8228 \n",
147 | " beta = 0.5683 \n",
148 | " return alpha, beta"
149 | ]
150 | },
151 | {
152 | "cell_type": "markdown",
153 | "id": "a48330cf-f997-40a2-8e46-2570c6726547",
154 | "metadata": {},
155 | "source": [
156 | "### Question 3"
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "id": "233bb996-003c-4395-b462-2735cfd9f81a",
163 | "metadata": {},
164 | "outputs": [],
165 | "source": [
166 | "def create_registers():\n",
167 | " alice_q = QuantumRegister(1, 'alice (q)')\n",
168 | " bob_q = QuantumRegister(1, 'bob (q)')\n",
169 | " circ = QuantumCircuit(alice_q, bob_q)\n",
170 | " return circ\n",
171 | "\n",
172 | "def add_gates(circ, alpha, beta):\n",
173 | " circ.initialize([alpha, beta], 0)\n",
174 | " circ.cnot(0, 1)\n",
175 | " circ.measure_all()\n",
176 | " return circ"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "id": "9b646a19-a707-4d35-8b2c-2bd14ebe2364",
182 | "metadata": {},
183 | "source": [
184 | "### Question 5"
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": null,
190 | "id": "f3ab43ed-d827-4afb-8a7b-2f561fc7c49c",
191 | "metadata": {},
192 | "outputs": [],
193 | "source": [
194 | "def create_registers():\n",
195 | " alice_q = QuantumRegister(1, 'alice (q)')\n",
196 | " peter_alice_q = QuantumRegister(1, 'peter/alice (q)')\n",
197 | " peter_bob_q = QuantumRegister(1, 'peter/bob (q)')\n",
198 | " bob_c = ClassicalRegister(3, 'bob (c)')\n",
199 | " pedro_bob_q = QuantumRegister(1, 'pedro/bob (q)')\n",
200 | " pedro_carol_q = QuantumRegister(1, 'pedro/carol (q)')\n",
201 | " carol_c = ClassicalRegister(3, 'carol (c)')\n",
202 | " circ = QuantumCircuit(alice_q, peter_alice_q,\n",
203 | " peter_bob_q, bob_c,\n",
204 | " pedro_bob_q, pedro_carol_q,\n",
205 | " carol_c)\n",
206 | " return circ\n",
207 | "\n",
208 | "def add_gates(circ, alpha, beta):\n",
209 | " circ.initialize([alpha, beta], 0)\n",
210 | " circ.barrier()\n",
211 | " circ.h(1)\n",
212 | " circ.cnot(1, 2)\n",
213 | " circ.barrier()\n",
214 | " circ.cnot(0, 1)\n",
215 | " circ.h(0)\n",
216 | " circ.barrier()\n",
217 | " circ.measure(0, 0)\n",
218 | " circ.measure(1, 1)\n",
219 | " with circ.if_test((1, 1)):\n",
220 | " circ.x(2) \n",
221 | " with circ.if_test((0, 1)):\n",
222 | " circ.z(2)\n",
223 | " circ.barrier()\n",
224 | " \n",
225 | " circ.h(3)\n",
226 | " circ.cnot(3, 4)\n",
227 | " circ.barrier()\n",
228 | " circ.cnot(2, 3)\n",
229 | " circ.h(2)\n",
230 | " circ.barrier()\n",
231 | " circ.measure(2, 3)\n",
232 | " circ.measure(3, 4)\n",
233 | " with circ.if_test((4, 1)):\n",
234 | " circ.x(4) \n",
235 | " with circ.if_test((3, 1)):\n",
236 | " circ.z(4) \n",
237 | " \n",
238 | " circ.measure(4, 5)\n",
239 | " return circ\n",
240 | "\n",
241 | "result = job.result()\n",
242 | "counts = result.get_counts(circ)\n",
243 | "counts_m = marginal_counts(counts, [5])\n",
244 | "number_of_0s = counts_m.get('0') \n",
245 | "number_of_1s = counts_m.get('1') \n",
246 | "alpha = np.sqrt(number_of_0s / shots)\n",
247 | "beta = np.sqrt(number_of_1s / shots)\n",
248 | "print(\"|\\u03C8\\u27E9 ({:.4f}, {:.4f})\".format(alpha, beta))"
249 | ]
250 | }
251 | ],
252 | "metadata": {
253 | "kernelspec": {
254 | "display_name": "Python 3 (ipykernel)",
255 | "language": "python",
256 | "name": "python3"
257 | },
258 | "language_info": {
259 | "codemirror_mode": {
260 | "name": "ipython",
261 | "version": 3
262 | },
263 | "file_extension": ".py",
264 | "mimetype": "text/x-python",
265 | "name": "python",
266 | "nbconvert_exporter": "python",
267 | "pygments_lexer": "ipython3",
268 | "version": "3.10.8"
269 | },
270 | "widgets": {
271 | "application/vnd.jupyter.widget-state+json": {
272 | "state": {},
273 | "version_major": 2,
274 | "version_minor": 0
275 | }
276 | }
277 | },
278 | "nbformat": 4,
279 | "nbformat_minor": 5
280 | }
281 |
--------------------------------------------------------------------------------
/Chapter 6/Chapter06.md:
--------------------------------------------------------------------------------
1 | ### Coding the teleportation circuitry
2 |
3 |
4 | ```python
5 | from qiskit import QuantumCircuit, QuantumRegister, \
6 | ClassicalRegister, Aer
7 | import random
8 | import numpy as np
9 | from qiskit.result import marginal_counts
10 | ```
11 |
12 |
13 | ```python
14 | def create_registers():
15 | alice_q = QuantumRegister(1, 'alice (q)')
16 | peter_alice_q = \
17 | QuantumRegister(1, 'peter/alice (q)')
18 | peter_bob_q = QuantumRegister(1, 'peter/bob (q)')
19 | bob_c = ClassicalRegister(3, 'bob (c)')
20 | circ = QuantumCircuit(alice_q, peter_alice_q,
21 | peter_bob_q, bob_c)
22 | return circ
23 | ```
24 |
25 |
26 | ```python
27 | def generate_amplitudes():
28 | alpha = np.sqrt(random.uniform(0, 1))
29 | beta = np.sqrt(1 - alpha**2)
30 | return alpha, beta
31 | ```
32 |
33 |
34 | ```python
35 | def add_gates(circ, alpha, beta):
36 | circ.initialize([alpha, beta], 0)
37 | circ.barrier()
38 | circ.h(1)
39 | circ.cnot(1, 2)
40 | circ.barrier()
41 | circ.cnot(0, 1)
42 | circ.h(0)
43 | circ.barrier()
44 | circ.measure(0, 0)
45 | circ.measure(1, 1)
46 | with circ.if_test((1, 1)):
47 | circ.x(2)
48 | with circ.if_test((0, 1)):
49 | circ.z(2)
50 | circ.measure(2, 2)
51 | return circ
52 | ```
53 |
54 |
55 | ```python
56 | alpha, beta = generate_amplitudes()
57 | circ = create_registers()
58 | circ = add_gates(circ, alpha, beta)
59 | display(circ.draw('latex', cregbundle=False))
60 | ```
61 |
62 |
63 | ```python
64 | device = Aer.get_backend("qasm_simulator")
65 |
66 | shots = 1000
67 | job = device.run(circ, shots=shots)
68 | print(job.job_id())
69 |
70 | result = job.result()
71 | counts = result.get_counts(circ)
72 | counts_m = marginal_counts(counts, [2])
73 | number_of_0s = counts_m.get('0')
74 | number_of_1s = counts_m.get('1')
75 | alpha = np.sqrt(number_of_0s / shots)
76 | beta = np.sqrt(number_of_1s / shots)
77 | print("|\u03C8\u27E9 ({:.4f}, {:.4f})".format(alpha, beta))
78 | ```
79 |
80 | ### Question 2
81 |
82 |
83 | ```python
84 | def generate_amplitudes():
85 | alpha = 0.8228
86 | beta = 0.5683
87 | return alpha, beta
88 | ```
89 |
90 | ### Question 3
91 |
92 |
93 | ```python
94 | def create_registers():
95 | alice_q = QuantumRegister(1, 'alice (q)')
96 | bob_q = QuantumRegister(1, 'bob (q)')
97 | circ = QuantumCircuit(alice_q, bob_q)
98 | return circ
99 |
100 | def add_gates(circ, alpha, beta):
101 | circ.initialize([alpha, beta], 0)
102 | circ.cnot(0, 1)
103 | circ.measure_all()
104 | return circ
105 | ```
106 |
107 | ### Question 5
108 |
109 |
110 | ```python
111 | def create_registers():
112 | alice_q = QuantumRegister(1, 'alice (q)')
113 | peter_alice_q = QuantumRegister(1, 'peter/alice (q)')
114 | peter_bob_q = QuantumRegister(1, 'peter/bob (q)')
115 | bob_c = ClassicalRegister(3, 'bob (c)')
116 | pedro_bob_q = QuantumRegister(1, 'pedro/bob (q)')
117 | pedro_carol_q = QuantumRegister(1, 'pedro/carol (q)')
118 | carol_c = ClassicalRegister(3, 'carol (c)')
119 | circ = QuantumCircuit(alice_q, peter_alice_q,
120 | peter_bob_q, bob_c,
121 | pedro_bob_q, pedro_carol_q,
122 | carol_c)
123 | return circ
124 |
125 | def add_gates(circ, alpha, beta):
126 | circ.initialize([alpha, beta], 0)
127 | circ.barrier()
128 | circ.h(1)
129 | circ.cnot(1, 2)
130 | circ.barrier()
131 | circ.cnot(0, 1)
132 | circ.h(0)
133 | circ.barrier()
134 | circ.measure(0, 0)
135 | circ.measure(1, 1)
136 | with circ.if_test((1, 1)):
137 | circ.x(2)
138 | with circ.if_test((0, 1)):
139 | circ.z(2)
140 | circ.barrier()
141 |
142 | circ.h(3)
143 | circ.cnot(3, 4)
144 | circ.barrier()
145 | circ.cnot(2, 3)
146 | circ.h(2)
147 | circ.barrier()
148 | circ.measure(2, 3)
149 | circ.measure(3, 4)
150 | with circ.if_test((4, 1)):
151 | circ.x(4)
152 | with circ.if_test((3, 1)):
153 | circ.z(4)
154 |
155 | circ.measure(4, 5)
156 | return circ
157 |
158 | result = job.result()
159 | counts = result.get_counts(circ)
160 | counts_m = marginal_counts(counts, [5])
161 | number_of_0s = counts_m.get('0')
162 | number_of_1s = counts_m.get('1')
163 | alpha = np.sqrt(number_of_0s / shots)
164 | beta = np.sqrt(number_of_1s / shots)
165 | print("|\u03C8\u27E9 ({:.4f}, {:.4f})".format(alpha, beta))
166 | ```
167 |
--------------------------------------------------------------------------------
/Chapter 7/Chapter07.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "a7737503-5b17-445c-b2a7-0ff4c6898688",
6 | "metadata": {},
7 | "source": [
8 | "### Phase kickback"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "10afb7b5-b3ea-46c8-aab2-128c3a0883d4",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumCircuit\n",
21 | "from qiskit.quantum_info import Statevector\n",
22 | "from qiskit.visualization import plot_bloch_multivector\n",
23 | "\n",
24 | "circ = QuantumCircuit(2)\n",
25 | "circ.x(1)\n",
26 | "circ.h(0)\n",
27 | "circ.h(1)\n",
28 | "display(circ.draw('latex'))\n",
29 | "\n",
30 | "state = Statevector(circ)\n",
31 | "display(plot_bloch_multivector(state, reverse_bits=True))"
32 | ]
33 | },
34 | {
35 | "cell_type": "code",
36 | "execution_count": null,
37 | "id": "9f3e255c-a62c-461a-be05-b236a522d6d4",
38 | "metadata": {
39 | "tags": []
40 | },
41 | "outputs": [],
42 | "source": [
43 | "circ.cnot(0, 1)\n",
44 | "display(circ.draw('latex'))\n",
45 | "state = Statevector(circ)\n",
46 | "display(plot_bloch_multivector(state, reverse_bits=True))"
47 | ]
48 | },
49 | {
50 | "cell_type": "markdown",
51 | "id": "675be9ef-a315-4699-bdc2-7ae19d5dddd0",
52 | "metadata": {},
53 | "source": [
54 | "### When does phase kickback kick in?"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": null,
60 | "id": "ab6b934e-acf4-4bd7-965b-22f245527619",
61 | "metadata": {
62 | "tags": []
63 | },
64 | "outputs": [],
65 | "source": [
66 | "circ = QuantumCircuit(2)\n",
67 | "circ.h(0)\n",
68 | "circ.x(1)\n",
69 | "#circ.cz(0, 1) # Controlled Z gate\n",
70 | "\n",
71 | "display(circ.draw('latex'))\n",
72 | "state = Statevector(circ)\n",
73 | "display(plot_bloch_multivector(state, reverse_bits=True))"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": null,
79 | "id": "3b2ca7c0-ad76-4b9b-97c5-31fec72afa16",
80 | "metadata": {
81 | "tags": []
82 | },
83 | "outputs": [],
84 | "source": [
85 | "circ = QuantumCircuit(2)\n",
86 | "circ.h([0, 1])\n",
87 | "#circ.cnot(0, 1)\n",
88 | "\n",
89 | "display(circ.draw('latex'))\n",
90 | "state = Statevector(circ)\n",
91 | "display(plot_bloch_multivector(state, reverse_bits=True))"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "id": "bb3123ed-1ab6-431a-bf77-3ff8c148e871",
97 | "metadata": {},
98 | "source": [
99 | "### Coding Deutsch's algorithm"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": null,
105 | "id": "4cde10ed-5330-4721-a042-0128333b611c",
106 | "metadata": {
107 | "tags": []
108 | },
109 | "outputs": [],
110 | "source": [
111 | "from qiskit import QuantumCircuit, Aer, execute\n",
112 | "from enum import Enum"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": null,
118 | "id": "69793787-718b-47a8-b972-c87645f04703",
119 | "metadata": {
120 | "tags": []
121 | },
122 | "outputs": [],
123 | "source": [
124 | "class SimpleBinary(Enum):\n",
125 | " ZERO = 0\n",
126 | " ONE = 1\n",
127 | " SAME_AS = 2\n",
128 | " OPPOSITE_OF = 3"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": null,
134 | "id": "2f498ed7-929e-4f17-9b1e-6c67c66d6db7",
135 | "metadata": {
136 | "tags": []
137 | },
138 | "outputs": [],
139 | "source": [
140 | "def get_oracle(circ, function):\n",
141 | " # if function == SimpleBinary.ZERO:\n",
142 | " # Do nothing\n",
143 | " if function == SimpleBinary.ONE:\n",
144 | " circ.x(1) \n",
145 | " elif function == SimpleBinary.SAME_AS:\n",
146 | " circ.cnot(0, 1)\n",
147 | " elif function == SimpleBinary.OPPOSITE_OF:\n",
148 | " circ.cnot(0, 1)\n",
149 | " circ.x(1)\n",
150 | " return circ"
151 | ]
152 | },
153 | {
154 | "cell_type": "code",
155 | "execution_count": null,
156 | "id": "e93234c2-7ae3-47f9-9e2b-175e7f941d48",
157 | "metadata": {
158 | "tags": []
159 | },
160 | "outputs": [],
161 | "source": [
162 | "def get_function():\n",
163 | " print('Which function? (0/1/2/3)')\n",
164 | " print(' 0: ZERO')\n",
165 | " print(' 1: ONE')\n",
166 | " print(' 2: SAME_AS')\n",
167 | " print(' 3: OPPOSITE_OF')\n",
168 | " value = input('> ')\n",
169 | " return SimpleBinary(int(value))"
170 | ]
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": null,
175 | "id": "5b5a7027-9c7d-4b15-95ab-29f52e13a76b",
176 | "metadata": {
177 | "tags": []
178 | },
179 | "outputs": [],
180 | "source": [
181 | "circ = QuantumCircuit(2, 1)\n",
182 | "function = get_function()\n",
183 | "\n",
184 | "circ.x(1)\n",
185 | "circ.h(0)\n",
186 | "circ.h(1)\n",
187 | "circ.barrier()\n",
188 | "circ = get_oracle(circ, function)\n",
189 | "circ.barrier()\n",
190 | "circ.h(0)\n",
191 | "circ.measure(0, 0)\n",
192 | "display(circ.draw('latex'))"
193 | ]
194 | },
195 | {
196 | "cell_type": "code",
197 | "execution_count": null,
198 | "id": "943dddc9-551c-4d07-8003-153605d7681a",
199 | "metadata": {
200 | "tags": []
201 | },
202 | "outputs": [],
203 | "source": [
204 | "device = Aer.get_backend('qasm_simulator')\n",
205 | "\n",
206 | "shots = 1\n",
207 | "job = execute(circ, backend=device, shots=shots)\n",
208 | "print(job.job_id())\n",
209 | "\n",
210 | "result = job.result()\n",
211 | "counts = result.get_counts(circ)\n",
212 | "\n",
213 | "print(function)\n",
214 | "print(counts)\n",
215 | "number_of_0s = counts.get('0') \n",
216 | "number_of_1s = counts.get('1') \n",
217 | "\n",
218 | "if number_of_0s is not None and number_of_0s == shots:\n",
219 | " print('Constant')\n",
220 | "elif number_of_1s is not None and number_of_1s == shots:\n",
221 | " print('Balanced')\n",
222 | "else:\n",
223 | " print(\"Results aren't conclusive\")"
224 | ]
225 | },
226 | {
227 | "cell_type": "markdown",
228 | "id": "35ea8638-fda6-4c5b-a2fe-4d9f42efca36",
229 | "metadata": {},
230 | "source": [
231 | "### Question 5"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": null,
237 | "id": "a8467539-9e8f-4e1d-b84a-0d5ff302923c",
238 | "metadata": {
239 | "tags": []
240 | },
241 | "outputs": [],
242 | "source": [
243 | "def get_oracle(function):\n",
244 | " oracle = QuantumCircuit(2)\n",
245 | " # if function == SimpleBinary.ZERO:\n",
246 | " # Do nothing\n",
247 | " if function == SimpleBinary.ONE:\n",
248 | " oracle.x(1) \n",
249 | " elif function == SimpleBinary.SAME_AS:\n",
250 | " oracle.cnot(0, 1)\n",
251 | " elif function == SimpleBinary.OPPOSITE_OF:\n",
252 | " oracle.cnot(0, 1)\n",
253 | " oracle.x(1)\n",
254 | " return oracle"
255 | ]
256 | },
257 | {
258 | "cell_type": "code",
259 | "execution_count": null,
260 | "id": "84c5ef9e-b5e9-4dc6-b3ac-11aff8375c0a",
261 | "metadata": {
262 | "tags": []
263 | },
264 | "outputs": [],
265 | "source": [
266 | "circ = QuantumCircuit(2, 1)\n",
267 | "function = get_function()\n",
268 | "\n",
269 | "circ.x(1)\n",
270 | "circ.h(0)\n",
271 | "circ.h(1)\n",
272 | "circ.barrier()\n",
273 | "oracle = get_oracle(function)\n",
274 | "circ = circ.compose(oracle)\n",
275 | "circ.barrier()\n",
276 | "circ.h(0)\n",
277 | "circ.measure(0, 0)\n",
278 | "display(circ.draw('latex'))"
279 | ]
280 | },
281 | {
282 | "cell_type": "code",
283 | "execution_count": null,
284 | "id": "c2cf8170-d03f-4ff3-926d-02aecc65fc8f",
285 | "metadata": {},
286 | "outputs": [],
287 | "source": []
288 | }
289 | ],
290 | "metadata": {
291 | "kernelspec": {
292 | "display_name": "Python 3 (ipykernel)",
293 | "language": "python",
294 | "name": "python3"
295 | },
296 | "language_info": {
297 | "codemirror_mode": {
298 | "name": "ipython",
299 | "version": 3
300 | },
301 | "file_extension": ".py",
302 | "mimetype": "text/x-python",
303 | "name": "python",
304 | "nbconvert_exporter": "python",
305 | "pygments_lexer": "ipython3",
306 | "version": "3.10.8"
307 | },
308 | "widgets": {
309 | "application/vnd.jupyter.widget-state+json": {
310 | "state": {},
311 | "version_major": 2,
312 | "version_minor": 0
313 | }
314 | }
315 | },
316 | "nbformat": 4,
317 | "nbformat_minor": 5
318 | }
319 |
--------------------------------------------------------------------------------
/Chapter 7/Chapter07.md:
--------------------------------------------------------------------------------
1 | ### Phase kickback
2 |
3 |
4 | ```python
5 | from qiskit import QuantumCircuit
6 | from qiskit.quantum_info import Statevector
7 | from qiskit.visualization import plot_bloch_multivector
8 |
9 | circ = QuantumCircuit(2)
10 | circ.x(1)
11 | circ.h(0)
12 | circ.h(1)
13 | display(circ.draw('latex'))
14 |
15 | state = Statevector(circ)
16 | display(plot_bloch_multivector(state, reverse_bits=True))
17 | ```
18 |
19 |
20 | ```python
21 | circ.cnot(0, 1)
22 | display(circ.draw('latex'))
23 | state = Statevector(circ)
24 | display(plot_bloch_multivector(state, reverse_bits=True))
25 | ```
26 |
27 | ### When does phase kickback kick in?
28 |
29 |
30 | ```python
31 | circ = QuantumCircuit(2)
32 | circ.h(0)
33 | circ.x(1)
34 | #circ.cz(0, 1) # Controlled Z gate
35 |
36 | display(circ.draw('latex'))
37 | state = Statevector(circ)
38 | display(plot_bloch_multivector(state, reverse_bits=True))
39 | ```
40 |
41 |
42 | ```python
43 | circ = QuantumCircuit(2)
44 | circ.h([0, 1])
45 | #circ.cnot(0, 1)
46 |
47 | display(circ.draw('latex'))
48 | state = Statevector(circ)
49 | display(plot_bloch_multivector(state, reverse_bits=True))
50 | ```
51 |
52 | ### Coding Deutsch's algorithm
53 |
54 |
55 | ```python
56 | from qiskit import QuantumCircuit, Aer, execute
57 | from enum import Enum
58 | ```
59 |
60 |
61 | ```python
62 | class SimpleBinary(Enum):
63 | ZERO = 0
64 | ONE = 1
65 | SAME_AS = 2
66 | OPPOSITE_OF = 3
67 | ```
68 |
69 |
70 | ```python
71 | def get_oracle(circ, function):
72 | # if function == SimpleBinary.ZERO:
73 | # Do nothing
74 | if function == SimpleBinary.ONE:
75 | circ.x(1)
76 | elif function == SimpleBinary.SAME_AS:
77 | circ.cnot(0, 1)
78 | elif function == SimpleBinary.OPPOSITE_OF:
79 | circ.cnot(0, 1)
80 | circ.x(1)
81 | return circ
82 | ```
83 |
84 |
85 | ```python
86 | def get_function():
87 | print('Which function? (0/1/2/3)')
88 | print(' 0: ZERO')
89 | print(' 1: ONE')
90 | print(' 2: SAME_AS')
91 | print(' 3: OPPOSITE_OF')
92 | value = input('> ')
93 | return SimpleBinary(int(value))
94 | ```
95 |
96 |
97 | ```python
98 | circ = QuantumCircuit(2, 1)
99 | function = get_function()
100 |
101 | circ.x(1)
102 | circ.h(0)
103 | circ.h(1)
104 | circ.barrier()
105 | circ = get_oracle(circ, function)
106 | circ.barrier()
107 | circ.h(0)
108 | circ.measure(0, 0)
109 | display(circ.draw('latex'))
110 | ```
111 |
112 |
113 | ```python
114 | device = Aer.get_backend('qasm_simulator')
115 |
116 | shots = 1
117 | job = execute(circ, backend=device, shots=shots)
118 | print(job.job_id())
119 |
120 | result = job.result()
121 | counts = result.get_counts(circ)
122 |
123 | print(function)
124 | print(counts)
125 | number_of_0s = counts.get('0')
126 | number_of_1s = counts.get('1')
127 |
128 | if number_of_0s is not None and number_of_0s == shots:
129 | print('Constant')
130 | elif number_of_1s is not None and number_of_1s == shots:
131 | print('Balanced')
132 | else:
133 | print("Results aren't conclusive")
134 | ```
135 |
136 | ### Question 5
137 |
138 |
139 | ```python
140 | def get_oracle(function):
141 | oracle = QuantumCircuit(2)
142 | # if function == SimpleBinary.ZERO:
143 | # Do nothing
144 | if function == SimpleBinary.ONE:
145 | oracle.x(1)
146 | elif function == SimpleBinary.SAME_AS:
147 | oracle.cnot(0, 1)
148 | elif function == SimpleBinary.OPPOSITE_OF:
149 | oracle.cnot(0, 1)
150 | oracle.x(1)
151 | return oracle
152 | ```
153 |
154 |
155 | ```python
156 | circ = QuantumCircuit(2, 1)
157 | function = get_function()
158 |
159 | circ.x(1)
160 | circ.h(0)
161 | circ.h(1)
162 | circ.barrier()
163 | oracle = get_oracle(function)
164 | circ = circ.compose(oracle)
165 | circ.barrier()
166 | circ.h(0)
167 | circ.measure(0, 0)
168 | display(circ.draw('latex'))
169 | ```
170 |
171 |
172 | ```python
173 |
174 | ```
175 |
--------------------------------------------------------------------------------
/Chapter 8/Chapter08.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "f00df8a1-31c9-4c07-96bd-b9c2a0afb245",
6 | "metadata": {},
7 | "source": [
8 | "### Coding Grover's algorithm with matrices"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "cb5a7dc5-5530-43be-ae30-4d317192562f",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumCircuit, Aer, execute\n",
21 | "from qiskit.visualization import plot_histogram"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": null,
27 | "id": "6196e0ed-fa7f-485d-a5bf-44ce9b99246b",
28 | "metadata": {
29 | "tags": []
30 | },
31 | "outputs": [],
32 | "source": [
33 | "oracle_matrix = [\n",
34 | " [1, 0, 0, 0, 0, 0, 0, 0],\n",
35 | " [0, 1, 0, 0, 0, 0, 0, 0],\n",
36 | " [0, 0, 1, 0, 0, 0, 0, 0],\n",
37 | " [0, 0, 0, 1, 0, 0, 0, 0],\n",
38 | " [0, 0, 0, 0, -1, 0, 0, 0],\n",
39 | " [0, 0, 0, 0, 0, 1, 0, 0],\n",
40 | " [0, 0, 0, 0, 0, 0, 1, 0],\n",
41 | " [0, 0, 0, 0, 0, 0, 0, 1]\n",
42 | "]\n",
43 | "oracle = QuantumCircuit(3)\n",
44 | "oracle.unitary(oracle_matrix, qubits=[0, 1, 2], label='oracle')\n",
45 | "oracle.barrier()\n",
46 | "display(oracle.draw('latex'))"
47 | ]
48 | },
49 | {
50 | "cell_type": "code",
51 | "execution_count": null,
52 | "id": "42683216-6e9d-4a5c-816d-5d5a1004fb6c",
53 | "metadata": {
54 | "tags": []
55 | },
56 | "outputs": [],
57 | "source": [
58 | "flip_matrix = [\n",
59 | " [-1, 0, 0, 0, 0, 0, 0, 0],\n",
60 | " [ 0, 1, 0, 0, 0, 0, 0, 0],\n",
61 | " [ 0, 0, 1, 0, 0, 0, 0, 0],\n",
62 | " [ 0, 0, 0, 1, 0, 0, 0, 0],\n",
63 | " [ 0, 0, 0, 0, 1, 0, 0, 0],\n",
64 | " [ 0, 0, 0, 0, 0, 1, 0, 0],\n",
65 | " [ 0, 0, 0, 0, 0, 0, 1, 0],\n",
66 | " [ 0, 0, 0, 0, 0, 0, 0, 1]\n",
67 | "]\n",
68 | "flip = QuantumCircuit(3)\n",
69 | "flip.unitary(flip_matrix, qubits=[0, 1, 2], label='flip')\n",
70 | "h3 = QuantumCircuit(3)\n",
71 | "h3.h([0, 1, 2])\n",
72 | "\n",
73 | "diffuser = h3.compose(flip).compose(h3)\n",
74 | "diffuser.barrier()\n",
75 | "display(diffuser.draw('latex'))"
76 | ]
77 | },
78 | {
79 | "cell_type": "code",
80 | "execution_count": null,
81 | "id": "dbf4a2cb-db90-481d-93e5-83da765f98e6",
82 | "metadata": {
83 | "tags": []
84 | },
85 | "outputs": [],
86 | "source": [
87 | "grover_iterate = oracle.compose(diffuser)"
88 | ]
89 | },
90 | {
91 | "cell_type": "code",
92 | "execution_count": null,
93 | "id": "02ba9a6a-83bf-4015-95fb-3d21b4d7ee40",
94 | "metadata": {
95 | "tags": []
96 | },
97 | "outputs": [],
98 | "source": [
99 | "circ = QuantumCircuit(4, 3) # We use the fourth qubit\n",
100 | " # later in this chapter.\n",
101 | "circ.h([0, 1, 2])\n",
102 | "circ.barrier()\n",
103 | "circ = circ.compose(grover_iterate).compose(grover_iterate)\n",
104 | "circ.measure([0, 1, 2], [0, 1, 2]) \n",
105 | "display(circ.draw('latex'))"
106 | ]
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": null,
111 | "id": "178da2a3-7261-40b0-9ce4-62e8f06aa82e",
112 | "metadata": {
113 | "tags": []
114 | },
115 | "outputs": [],
116 | "source": [
117 | "device = Aer.get_backend('qasm_simulator') \n",
118 | "job = execute(circ,backend = device,shots = 1000)\n",
119 | "print(job.job_id())\n",
120 | "\n",
121 | "result = job.result()\n",
122 | "counts = result.get_counts(circ)\n",
123 | "\n",
124 | "print(counts)\n",
125 | "display(plot_histogram(counts))"
126 | ]
127 | },
128 | {
129 | "cell_type": "markdown",
130 | "id": "190a3591-ba8e-44e7-8dfb-523d9cd7ef70",
131 | "metadata": {},
132 | "source": [
133 | "### When to use Grover's algorithm"
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "id": "0d546783-62f2-432b-9a1c-1f89e031fccc",
140 | "metadata": {
141 | "tags": []
142 | },
143 | "outputs": [],
144 | "source": [
145 | "x = float(input())\n",
146 | "if x**5 - 2*(x**4) + 4*(x**3) - 8*(x**2) + 3*x - 6 == 0:\n",
147 | " print(1)\n",
148 | "else:\n",
149 | " print(-1)"
150 | ]
151 | },
152 | {
153 | "cell_type": "markdown",
154 | "id": "0ead933c-1952-44bb-95c9-fbd33c365ad4",
155 | "metadata": {
156 | "tags": []
157 | },
158 | "source": [
159 | "### Coding Grover's algorithm with high-level functions"
160 | ]
161 | },
162 | {
163 | "cell_type": "code",
164 | "execution_count": null,
165 | "id": "72c80a0f-0da0-4fa7-9fe2-ec5dd7cdd9ae",
166 | "metadata": {
167 | "tags": []
168 | },
169 | "outputs": [],
170 | "source": [
171 | "pip install tweedledum"
172 | ]
173 | },
174 | {
175 | "cell_type": "code",
176 | "execution_count": null,
177 | "id": "0c63dfce-7282-4045-8735-148e2956555b",
178 | "metadata": {
179 | "tags": []
180 | },
181 | "outputs": [],
182 | "source": [
183 | "pip install qiskit_algorithms"
184 | ]
185 | },
186 | {
187 | "cell_type": "code",
188 | "execution_count": null,
189 | "id": "9dd14820-f0cf-42a3-86e2-99350c96ab2a",
190 | "metadata": {
191 | "tags": []
192 | },
193 | "outputs": [],
194 | "source": [
195 | "from qiskit.circuit.library.phase_oracle import PhaseOracle\n",
196 | "from qiskit_algorithms import AmplificationProblem, Grover\n",
197 | "from qiskit.tools.visualization import plot_histogram"
198 | ]
199 | },
200 | {
201 | "cell_type": "code",
202 | "execution_count": null,
203 | "id": "6f455326-b3cc-4acc-b3ca-04ee0069c928",
204 | "metadata": {
205 | "tags": []
206 | },
207 | "outputs": [],
208 | "source": [
209 | "expression = ('(sausage & ~anchovies & pineapple)' \\\n",
210 | " ' & (mushrooms | anchovies)')\n",
211 | "print(expression)\n",
212 | "\n",
213 | "oracle = PhaseOracle(expression)\n",
214 | "problem = AmplificationProblem(oracle)\n",
215 | "grover = Grover(iterations=2) \n",
216 | "circ = grover.construct_circuit(problem)\n",
217 | "circ.measure_all()\n",
218 | "display(circ.draw('latex'))"
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": null,
224 | "id": "b77b0f03-6e5c-4729-83ae-3bada7dab6c5",
225 | "metadata": {
226 | "tags": []
227 | },
228 | "outputs": [],
229 | "source": [
230 | "from qiskit import Aer, execute\n",
231 | "from qiskit.visualization import plot_histogram\n",
232 | "\n",
233 | "device = Aer.get_backend('qasm_simulator') \n",
234 | "\n",
235 | "job = execute(circ,backend = device, shots = 1000)\n",
236 | "print(job.job_id())\n",
237 | "\n",
238 | "result = job.result()\n",
239 | "counts = result.get_counts(circ)\n",
240 | "\n",
241 | "print(counts)\n",
242 | "display(plot_histogram(counts))"
243 | ]
244 | },
245 | {
246 | "cell_type": "markdown",
247 | "id": "f20a5320-0ee1-4496-b043-d076b9f623e4",
248 | "metadata": {},
249 | "source": [
250 | "### Coding Grover's algorithm with quantum gates"
251 | ]
252 | },
253 | {
254 | "cell_type": "code",
255 | "execution_count": null,
256 | "id": "3ba95140-207d-4000-a1a0-a41837af73d9",
257 | "metadata": {
258 | "tags": []
259 | },
260 | "outputs": [],
261 | "source": [
262 | "from qiskit.circuit.library.standard_gates import XGate"
263 | ]
264 | },
265 | {
266 | "cell_type": "code",
267 | "execution_count": null,
268 | "id": "139b35fd-e0ec-427b-84d9-43acf1dd293c",
269 | "metadata": {
270 | "tags": []
271 | },
272 | "outputs": [],
273 | "source": [
274 | "oracle = QuantumCircuit(4)\n",
275 | "oracle.x(3)\n",
276 | "oracle.h(3)\n",
277 | "\n",
278 | "ctrl = XGate().control(3, ctrl_state='100')\n",
279 | "oracle.append(ctrl, qargs=[0, 1, 2, 3])\n",
280 | "\n",
281 | "oracle.barrier()\n",
282 | "display(oracle.draw('latex'))"
283 | ]
284 | },
285 | {
286 | "cell_type": "code",
287 | "execution_count": null,
288 | "id": "e5e671fa-2010-43b2-b5b2-4214288ef8e6",
289 | "metadata": {
290 | "tags": []
291 | },
292 | "outputs": [],
293 | "source": [
294 | "diffuser = QuantumCircuit(4)\n",
295 | "diffuser.h([0, 1, 2]) \n",
296 | "\n",
297 | "ctrl = XGate().control(3, ctrl_state='000')\n",
298 | "diffuser.append(ctrl, qargs=[0, 1, 2, 3])\n",
299 | "\n",
300 | "diffuser.h([0, 1, 2])\n",
301 | "\n",
302 | "diffuser.barrier()\n",
303 | "display(diffuser.draw('latex'))"
304 | ]
305 | },
306 | {
307 | "cell_type": "markdown",
308 | "id": "d9d13435-a66d-4884-88d6-33efc2b45422",
309 | "metadata": {},
310 | "source": [
311 | "### Question 3"
312 | ]
313 | },
314 | {
315 | "cell_type": "code",
316 | "execution_count": null,
317 | "id": "81cb117d-faa2-458d-a6ee-5e32acdd9956",
318 | "metadata": {
319 | "tags": []
320 | },
321 | "outputs": [],
322 | "source": [
323 | "import random\n",
324 | "\n",
325 | "oracle_matrix = [\n",
326 | " [1, 0, 0, 0, 0, 0, 0, 0],\n",
327 | " [0, 1, 0, 0, 0, 0, 0, 0],\n",
328 | " [0, 0, 1, 0, 0, 0, 0, 0],\n",
329 | " [0, 0, 0, 1, 0, 0, 0, 0],\n",
330 | " [0, 0, 0, 0, 1, 0, 0, 0],\n",
331 | " [0, 0, 0, 0, 0, 1, 0, 0],\n",
332 | " [0, 0, 0, 0, 0, 0, 1, 0],\n",
333 | " [0, 0, 0, 0, 0, 0, 0, 1]\n",
334 | "]\n",
335 | "\n",
336 | "entry = random.randint(0, 7)\n",
337 | "print(entry)\n",
338 | "oracle_matrix[entry][entry] = -1\n",
339 | "\n",
340 | "oracle = QuantumCircuit(3)\n",
341 | "oracle.unitary(oracle_matrix, qubits=[0, 1, 2], label='oracle')\n",
342 | "oracle.barrier()\n",
343 | "display(oracle.draw('latex'))"
344 | ]
345 | },
346 | {
347 | "cell_type": "markdown",
348 | "id": "3194ba52-e3d4-46a9-93a3-8cb6bf8c5ff6",
349 | "metadata": {},
350 | "source": [
351 | "### Question 7"
352 | ]
353 | },
354 | {
355 | "cell_type": "code",
356 | "execution_count": null,
357 | "id": "d9eae53d-54ed-4cef-97ce-81e73be1253a",
358 | "metadata": {
359 | "tags": []
360 | },
361 | "outputs": [],
362 | "source": [
363 | "# ((m | t) & ~n) & ((t | n) & ~m)\n",
364 | "# (~~(m | t) & ~n) & (~~(t | n) & ~m)\n",
365 | "# (~(~m & ~t) & ~n) & (~(~t & ~n) & ~m)\n",
366 | "\n",
367 | "from qiskit import QuantumRegister, QuantumCircuit\n",
368 | "from qiskit.circuit.library.standard_gates import XGate \n",
369 | "\n",
370 | "m = QuantumRegister(1, 'm')\n",
371 | "t = QuantumRegister(1, 't')\n",
372 | "n = QuantumRegister(1, 'n')\n",
373 | "mt = QuantumRegister(1, 'not m and not t')\n",
374 | "mtn = QuantumRegister(1, 'alice')\n",
375 | "tn = QuantumRegister(1, 'not t and not n')\n",
376 | "tnm = QuantumRegister(1, 'bob')\n",
377 | "exp = QuantumRegister(1, 'alice and bob')\n",
378 | "circ = QuantumCircuit(m, t, n, mt, mtn, tn, tnm, exp)\n",
379 | "\n",
380 | "circ.h([0, 1, 2])\n",
381 | "\n",
382 | "ctrl = XGate().control(2, ctrl_state='00')\n",
383 | "circ.append(ctrl, qargs=[0, 1, 3])\n",
384 | "circ.append(ctrl, qargs=[2, 3, 4])\n",
385 | "circ.append(ctrl, qargs=[1, 2, 5])\n",
386 | "circ.append(ctrl, qargs=[0, 5, 6])\n",
387 | "\n",
388 | "circ.append(ctrl, qargs=[4, 6, 7])\n",
389 | "\n",
390 | "circ.append(ctrl, qargs=[0, 5, 6])\n",
391 | "circ.append(ctrl, qargs=[1, 2, 5])\n",
392 | "circ.append(ctrl, qargs=[2, 3, 4])\n",
393 | "circ.append(ctrl, qargs=[0, 1, 3])\n",
394 | "\n",
395 | "circ.h([0, 1, 2])\n",
396 | "\n",
397 | "display(circ.draw('latex'))"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": null,
403 | "id": "63de622c-d717-4f56-9564-f463beca85f1",
404 | "metadata": {},
405 | "outputs": [],
406 | "source": []
407 | }
408 | ],
409 | "metadata": {
410 | "kernelspec": {
411 | "display_name": "Python 3 (ipykernel)",
412 | "language": "python",
413 | "name": "python3"
414 | },
415 | "language_info": {
416 | "codemirror_mode": {
417 | "name": "ipython",
418 | "version": 3
419 | },
420 | "file_extension": ".py",
421 | "mimetype": "text/x-python",
422 | "name": "python",
423 | "nbconvert_exporter": "python",
424 | "pygments_lexer": "ipython3",
425 | "version": "3.10.8"
426 | },
427 | "widgets": {
428 | "application/vnd.jupyter.widget-state+json": {
429 | "state": {},
430 | "version_major": 2,
431 | "version_minor": 0
432 | }
433 | }
434 | },
435 | "nbformat": 4,
436 | "nbformat_minor": 5
437 | }
438 |
--------------------------------------------------------------------------------
/Chapter 8/Chapter08.md:
--------------------------------------------------------------------------------
1 | ### Coding Grover's algorithm with matrices
2 |
3 |
4 | ```python
5 | from qiskit import QuantumCircuit, Aer, execute
6 | from qiskit.visualization import plot_histogram
7 | ```
8 |
9 |
10 | ```python
11 | oracle_matrix = [
12 | [1, 0, 0, 0, 0, 0, 0, 0],
13 | [0, 1, 0, 0, 0, 0, 0, 0],
14 | [0, 0, 1, 0, 0, 0, 0, 0],
15 | [0, 0, 0, 1, 0, 0, 0, 0],
16 | [0, 0, 0, 0, -1, 0, 0, 0],
17 | [0, 0, 0, 0, 0, 1, 0, 0],
18 | [0, 0, 0, 0, 0, 0, 1, 0],
19 | [0, 0, 0, 0, 0, 0, 0, 1]
20 | ]
21 | oracle = QuantumCircuit(3)
22 | oracle.unitary(oracle_matrix, qubits=[0, 1, 2], label='oracle')
23 | oracle.barrier()
24 | display(oracle.draw('latex'))
25 | ```
26 |
27 |
28 | ```python
29 | flip_matrix = [
30 | [-1, 0, 0, 0, 0, 0, 0, 0],
31 | [ 0, 1, 0, 0, 0, 0, 0, 0],
32 | [ 0, 0, 1, 0, 0, 0, 0, 0],
33 | [ 0, 0, 0, 1, 0, 0, 0, 0],
34 | [ 0, 0, 0, 0, 1, 0, 0, 0],
35 | [ 0, 0, 0, 0, 0, 1, 0, 0],
36 | [ 0, 0, 0, 0, 0, 0, 1, 0],
37 | [ 0, 0, 0, 0, 0, 0, 0, 1]
38 | ]
39 | flip = QuantumCircuit(3)
40 | flip.unitary(flip_matrix, qubits=[0, 1, 2], label='flip')
41 | h3 = QuantumCircuit(3)
42 | h3.h([0, 1, 2])
43 |
44 | diffuser = h3.compose(flip).compose(h3)
45 | diffuser.barrier()
46 | display(diffuser.draw('latex'))
47 | ```
48 |
49 |
50 | ```python
51 | grover_iterate = oracle.compose(diffuser)
52 | ```
53 |
54 |
55 | ```python
56 | circ = QuantumCircuit(4, 3) # We use the fourth qubit
57 | # later in this chapter.
58 | circ.h([0, 1, 2])
59 | circ.barrier()
60 | circ = circ.compose(grover_iterate).compose(grover_iterate)
61 | circ.measure([0, 1, 2], [0, 1, 2])
62 | display(circ.draw('latex'))
63 | ```
64 |
65 |
66 | ```python
67 | device = Aer.get_backend('qasm_simulator')
68 | job = execute(circ,backend = device,shots = 1000)
69 | print(job.job_id())
70 |
71 | result = job.result()
72 | counts = result.get_counts(circ)
73 |
74 | print(counts)
75 | display(plot_histogram(counts))
76 | ```
77 |
78 | ### When to use Grover's algorithm
79 |
80 |
81 | ```python
82 | x = float(input())
83 | if x**5 - 2*(x**4) + 4*(x**3) - 8*(x**2) + 3*x - 6 == 0:
84 | print(1)
85 | else:
86 | print(-1)
87 | ```
88 |
89 | ### Coding Grover's algorithm with high-level functions
90 |
91 |
92 | ```python
93 | pip install tweedledum
94 | ```
95 |
96 |
97 | ```python
98 | pip install qiskit_algorithms
99 | ```
100 |
101 |
102 | ```python
103 | from qiskit.circuit.library.phase_oracle import PhaseOracle
104 | from qiskit_algorithms import AmplificationProblem, Grover
105 | from qiskit.tools.visualization import plot_histogram
106 | ```
107 |
108 |
109 | ```python
110 | expression = ('(sausage & ~anchovies & pineapple)' \
111 | ' & (mushrooms | anchovies)')
112 | print(expression)
113 |
114 | oracle = PhaseOracle(expression)
115 | problem = AmplificationProblem(oracle)
116 | grover = Grover(iterations=2)
117 | circ = grover.construct_circuit(problem)
118 | circ.measure_all()
119 | display(circ.draw('latex'))
120 | ```
121 |
122 |
123 | ```python
124 | from qiskit import Aer, execute
125 | from qiskit.visualization import plot_histogram
126 |
127 | device = Aer.get_backend('qasm_simulator')
128 |
129 | job = execute(circ,backend = device, shots = 1000)
130 | print(job.job_id())
131 |
132 | result = job.result()
133 | counts = result.get_counts(circ)
134 |
135 | print(counts)
136 | display(plot_histogram(counts))
137 | ```
138 |
139 | ### Coding Grover's algorithm with quantum gates
140 |
141 |
142 | ```python
143 | from qiskit.circuit.library.standard_gates import XGate
144 | ```
145 |
146 |
147 | ```python
148 | oracle = QuantumCircuit(4)
149 | oracle.x(3)
150 | oracle.h(3)
151 |
152 | ctrl = XGate().control(3, ctrl_state='100')
153 | oracle.append(ctrl, qargs=[0, 1, 2, 3])
154 |
155 | oracle.barrier()
156 | display(oracle.draw('latex'))
157 | ```
158 |
159 |
160 | ```python
161 | diffuser = QuantumCircuit(4)
162 | diffuser.h([0, 1, 2])
163 |
164 | ctrl = XGate().control(3, ctrl_state='000')
165 | diffuser.append(ctrl, qargs=[0, 1, 2, 3])
166 |
167 | diffuser.h([0, 1, 2])
168 |
169 | diffuser.barrier()
170 | display(diffuser.draw('latex'))
171 | ```
172 |
173 | ### Question 3
174 |
175 |
176 | ```python
177 | import random
178 |
179 | oracle_matrix = [
180 | [1, 0, 0, 0, 0, 0, 0, 0],
181 | [0, 1, 0, 0, 0, 0, 0, 0],
182 | [0, 0, 1, 0, 0, 0, 0, 0],
183 | [0, 0, 0, 1, 0, 0, 0, 0],
184 | [0, 0, 0, 0, 1, 0, 0, 0],
185 | [0, 0, 0, 0, 0, 1, 0, 0],
186 | [0, 0, 0, 0, 0, 0, 1, 0],
187 | [0, 0, 0, 0, 0, 0, 0, 1]
188 | ]
189 |
190 | entry = random.randint(0, 7)
191 | print(entry)
192 | oracle_matrix[entry][entry] = -1
193 |
194 | oracle = QuantumCircuit(3)
195 | oracle.unitary(oracle_matrix, qubits=[0, 1, 2], label='oracle')
196 | oracle.barrier()
197 | display(oracle.draw('latex'))
198 | ```
199 |
200 | ### Question 7
201 |
202 |
203 | ```python
204 | # ((m | t) & ~n) & ((t | n) & ~m)
205 | # (~~(m | t) & ~n) & (~~(t | n) & ~m)
206 | # (~(~m & ~t) & ~n) & (~(~t & ~n) & ~m)
207 |
208 | from qiskit import QuantumRegister, QuantumCircuit
209 | from qiskit.circuit.library.standard_gates import XGate
210 |
211 | m = QuantumRegister(1, 'm')
212 | t = QuantumRegister(1, 't')
213 | n = QuantumRegister(1, 'n')
214 | mt = QuantumRegister(1, 'not m and not t')
215 | mtn = QuantumRegister(1, 'alice')
216 | tn = QuantumRegister(1, 'not t and not n')
217 | tnm = QuantumRegister(1, 'bob')
218 | exp = QuantumRegister(1, 'alice and bob')
219 | circ = QuantumCircuit(m, t, n, mt, mtn, tn, tnm, exp)
220 |
221 | circ.h([0, 1, 2])
222 |
223 | ctrl = XGate().control(2, ctrl_state='00')
224 | circ.append(ctrl, qargs=[0, 1, 3])
225 | circ.append(ctrl, qargs=[2, 3, 4])
226 | circ.append(ctrl, qargs=[1, 2, 5])
227 | circ.append(ctrl, qargs=[0, 5, 6])
228 |
229 | circ.append(ctrl, qargs=[4, 6, 7])
230 |
231 | circ.append(ctrl, qargs=[0, 5, 6])
232 | circ.append(ctrl, qargs=[1, 2, 5])
233 | circ.append(ctrl, qargs=[2, 3, 4])
234 | circ.append(ctrl, qargs=[0, 1, 3])
235 |
236 | circ.h([0, 1, 2])
237 |
238 | display(circ.draw('latex'))
239 | ```
240 |
241 |
242 | ```python
243 |
244 | ```
245 |
--------------------------------------------------------------------------------
/Chapter 9/Chapter09.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "61c9ad6a-4e9e-4621-a1a2-0738cfff7667",
6 | "metadata": {},
7 | "source": [
8 | "### Unitary matrices"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": null,
14 | "id": "6ad3c5c5-6614-42b0-b81a-4f0dfa04b50f",
15 | "metadata": {
16 | "tags": []
17 | },
18 | "outputs": [],
19 | "source": [
20 | "from qiskit import QuantumCircuit\n",
21 | "from qiskit.visualization import visualize_transition\n",
22 | "\n",
23 | "circ = QuantumCircuit(1)\n",
24 | "circ.h(0)\n",
25 | "circ.s(0)\n",
26 | "\n",
27 | "display(circ.draw('latex', scale=2.5))\n",
28 | "visualize_transition(circ, trace=True)"
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "id": "bb139fe9-bc74-46de-a031-7dc675b8e879",
34 | "metadata": {},
35 | "source": [
36 | "### Illustrating Shor's algorithm with Qiskit code"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": null,
42 | "id": "21dfd6a6-f1e2-4dfc-b1f4-e6cbb40a7af0",
43 | "metadata": {
44 | "tags": []
45 | },
46 | "outputs": [],
47 | "source": [
48 | "from qiskit import QuantumCircuit, Aer, execute\n",
49 | "from qiskit.circuit.library import QFT\n",
50 | "from qiskit.tools.visualization import plot_histogram\n",
51 | "import numpy as np"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": null,
57 | "id": "75264682-28bf-4db8-a68e-12f3b4052b03",
58 | "metadata": {
59 | "tags": []
60 | },
61 | "outputs": [],
62 | "source": [
63 | "public_key = 15\n",
64 | "coprime = 7\n",
65 | "#coprime = 11\n",
66 | "\n",
67 | "vector = []\n",
68 | "for i in range(8):\n",
69 | " vector.append(coprime**i % public_key)\n",
70 | "\n",
71 | "norm = np.linalg.norm(vector)\n",
72 | "statevector = vector / norm\n",
73 | "\n",
74 | "print('vector:')\n",
75 | "print(vector)\n",
76 | "print()\n",
77 | "print('statevector:')\n",
78 | "print(statevector)"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": null,
84 | "id": "7cbe8a09-9bf4-425b-bab9-4d71231166eb",
85 | "metadata": {
86 | "tags": []
87 | },
88 | "outputs": [],
89 | "source": [
90 | "circ = QuantumCircuit(3)\n",
91 | "circ.initialize(statevector)"
92 | ]
93 | },
94 | {
95 | "cell_type": "code",
96 | "execution_count": null,
97 | "id": "97c39a1a-4180-478a-b3f9-9926bc7a60eb",
98 | "metadata": {
99 | "tags": []
100 | },
101 | "outputs": [],
102 | "source": [
103 | "circ.append(QFT(3), [0, 1, 2])\n",
104 | "circ.measure_all()\n",
105 | "display(circ.draw('latex'))"
106 | ]
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": null,
111 | "id": "49f50089-392c-4c13-90a2-154965ef82de",
112 | "metadata": {
113 | "tags": []
114 | },
115 | "outputs": [],
116 | "source": [
117 | "device = Aer.get_backend('qasm_simulator') \n",
118 | "job = execute(circ,backend = device,shots = 1000)\n",
119 | "print(job.job_id())\n",
120 | "\n",
121 | "result = job.result()\n",
122 | "counts = result.get_counts(circ)\n",
123 | "\n",
124 | "print(counts)\n",
125 | "display(plot_histogram(counts))"
126 | ]
127 | },
128 | {
129 | "cell_type": "markdown",
130 | "id": "d961d28b-1344-4b78-af5b-20bdc6f3a8ec",
131 | "metadata": {},
132 | "source": [
133 | "### Another implementation of Shor's algorithm"
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "id": "e4bc7304-781a-4a95-9178-1c60511bac5f",
140 | "metadata": {
141 | "tags": []
142 | },
143 | "outputs": [],
144 | "source": [
145 | "from qiskit import QuantumCircuit, Aer, execute\n",
146 | "from qiskit.circuit.library import QFT\n",
147 | "from qiskit.visualization import plot_histogram"
148 | ]
149 | },
150 | {
151 | "cell_type": "code",
152 | "execution_count": null,
153 | "id": "eb6a04a2-44cd-499c-afff-e6997eb881ab",
154 | "metadata": {
155 | "tags": []
156 | },
157 | "outputs": [],
158 | "source": [
159 | "_7k_mod15 = QuantumCircuit(4)\n",
160 | "_7k_mod15.x([0, 1, 2, 3])\n",
161 | "_7k_mod15.swap(1, 2)\n",
162 | "_7k_mod15.swap(2, 3)\n",
163 | "_7k_mod15.swap(0, 3)\n",
164 | "display(_7k_mod15.draw('latex'))"
165 | ]
166 | },
167 | {
168 | "cell_type": "code",
169 | "execution_count": null,
170 | "id": "54d9fb88-60ec-4351-a173-8f744f0f1366",
171 | "metadata": {
172 | "tags": []
173 | },
174 | "outputs": [],
175 | "source": [
176 | "def _7EPXn_mod15(n):\n",
177 | " circ = QuantumCircuit(4)\n",
178 | " for k in range(n):\n",
179 | " circ = circ.compose(_7k_mod15, qubits=[0, 1, 2, 3]) \n",
180 | " \n",
181 | " gate = circ.to_gate(label='(7^' + str(n) + ') mod 15') \n",
182 | " return gate.control(1, ctrl_state='1')"
183 | ]
184 | },
185 | {
186 | "cell_type": "code",
187 | "execution_count": null,
188 | "id": "215cea64-a3ca-476a-9f8e-93f2c9992d91",
189 | "metadata": {
190 | "tags": []
191 | },
192 | "outputs": [],
193 | "source": [
194 | "circ = QuantumCircuit(7, 3)\n",
195 | "circ.h([0, 1, 2])\n",
196 | "circ.x(3)\n",
197 | "circ.barrier()\n",
198 | "\n",
199 | "circ.append(_7EPXn_mod15(1), [0, 3, 4, 5, 6])\n",
200 | "circ.append(_7EPXn_mod15(2), [1, 3, 4, 5, 6])\n",
201 | "circ.append(_7EPXn_mod15(4), [2, 3, 4, 5, 6]) # NOT NEEDED\n",
202 | "\n",
203 | "circ.append(QFT(3).inverse(), [0, 1, 2])\n",
204 | "circ.measure([0, 1, 2], [0, 1, 2])\n",
205 | "\n",
206 | "display(circ.draw('latex'))"
207 | ]
208 | },
209 | {
210 | "cell_type": "code",
211 | "execution_count": null,
212 | "id": "47f432dc-5b34-4394-a8e1-c157fd0b07f1",
213 | "metadata": {
214 | "tags": []
215 | },
216 | "outputs": [],
217 | "source": [
218 | "device = Aer.get_backend('qasm_simulator') \n",
219 | "job = execute(circ,backend = device,shots = 1000)\n",
220 | "print(job.job_id())\n",
221 | "\n",
222 | "result = job.result()\n",
223 | "counts = result.get_counts(circ)\n",
224 | "\n",
225 | "print(counts)\n",
226 | "display(plot_histogram(counts))"
227 | ]
228 | },
229 | {
230 | "cell_type": "markdown",
231 | "id": "eb7c0f69-a8fb-4fc9-a79b-f8dbce9db2ea",
232 | "metadata": {},
233 | "source": [
234 | "### Question 10"
235 | ]
236 | },
237 | {
238 | "cell_type": "code",
239 | "execution_count": null,
240 | "id": "e4dccd12-1945-4ae9-99d5-321c5076165e",
241 | "metadata": {},
242 | "outputs": [],
243 | "source": [
244 | "phase = None\n",
245 | "circ = QuantumCircuit(2, 1)\n",
246 | "circ.h([0, 1])\n",
247 | "circ.rz(phase, 1)\n",
248 | "circ.cnot(0, 1)\n",
249 | "circ.h(0)\n",
250 | "circ.measure([0], [0])\n",
251 | "display(circ.draw('latex'))\n",
252 | "\n",
253 | "provider = IBMProvider()\n",
254 | "device = provider.get_backend('ibmq_qasm_simulator')\n",
255 | "job = execute(circ, device, shots=1000)\n",
256 | "result = job.result()\n",
257 | "counts = result.get_counts(circ) \n",
258 | "print(counts)"
259 | ]
260 | }
261 | ],
262 | "metadata": {
263 | "kernelspec": {
264 | "display_name": "Python 3 (ipykernel)",
265 | "language": "python",
266 | "name": "python3"
267 | },
268 | "language_info": {
269 | "codemirror_mode": {
270 | "name": "ipython",
271 | "version": 3
272 | },
273 | "file_extension": ".py",
274 | "mimetype": "text/x-python",
275 | "name": "python",
276 | "nbconvert_exporter": "python",
277 | "pygments_lexer": "ipython3",
278 | "version": "3.10.8"
279 | },
280 | "widgets": {
281 | "application/vnd.jupyter.widget-state+json": {
282 | "state": {},
283 | "version_major": 2,
284 | "version_minor": 0
285 | }
286 | }
287 | },
288 | "nbformat": 4,
289 | "nbformat_minor": 5
290 | }
291 |
--------------------------------------------------------------------------------
/Chapter 9/Chapter09.md:
--------------------------------------------------------------------------------
1 | ### Unitary matrices
2 |
3 |
4 | ```python
5 | from qiskit import QuantumCircuit
6 | from qiskit.visualization import visualize_transition
7 |
8 | circ = QuantumCircuit(1)
9 | circ.h(0)
10 | circ.s(0)
11 |
12 | display(circ.draw('latex', scale=2.5))
13 | visualize_transition(circ, trace=True)
14 | ```
15 |
16 | ### Illustrating Shor's algorithm with Qiskit code
17 |
18 |
19 | ```python
20 | from qiskit import QuantumCircuit, Aer, execute
21 | from qiskit.circuit.library import QFT
22 | from qiskit.tools.visualization import plot_histogram
23 | import numpy as np
24 | ```
25 |
26 |
27 | ```python
28 | public_key = 15
29 | coprime = 7
30 | #coprime = 11
31 |
32 | vector = []
33 | for i in range(8):
34 | vector.append(coprime**i % public_key)
35 |
36 | norm = np.linalg.norm(vector)
37 | statevector = vector / norm
38 |
39 | print('vector:')
40 | print(vector)
41 | print()
42 | print('statevector:')
43 | print(statevector)
44 | ```
45 |
46 |
47 | ```python
48 | circ = QuantumCircuit(3)
49 | circ.initialize(statevector)
50 | ```
51 |
52 |
53 | ```python
54 | circ.append(QFT(3), [0, 1, 2])
55 | circ.measure_all()
56 | display(circ.draw('latex'))
57 | ```
58 |
59 |
60 | ```python
61 | device = Aer.get_backend('qasm_simulator')
62 | job = execute(circ,backend = device,shots = 1000)
63 | print(job.job_id())
64 |
65 | result = job.result()
66 | counts = result.get_counts(circ)
67 |
68 | print(counts)
69 | display(plot_histogram(counts))
70 | ```
71 |
72 | ### Another implementation of Shor's algorithm
73 |
74 |
75 | ```python
76 | from qiskit import QuantumCircuit, Aer, execute
77 | from qiskit.circuit.library import QFT
78 | from qiskit.visualization import plot_histogram
79 | ```
80 |
81 |
82 | ```python
83 | _7k_mod15 = QuantumCircuit(4)
84 | _7k_mod15.x([0, 1, 2, 3])
85 | _7k_mod15.swap(1, 2)
86 | _7k_mod15.swap(2, 3)
87 | _7k_mod15.swap(0, 3)
88 | display(_7k_mod15.draw('latex'))
89 | ```
90 |
91 |
92 | ```python
93 | def _7EPXn_mod15(n):
94 | circ = QuantumCircuit(4)
95 | for k in range(n):
96 | circ = circ.compose(_7k_mod15, qubits=[0, 1, 2, 3])
97 |
98 | gate = circ.to_gate(label='(7^' + str(n) + ') mod 15')
99 | return gate.control(1, ctrl_state='1')
100 | ```
101 |
102 |
103 | ```python
104 | circ = QuantumCircuit(7, 3)
105 | circ.h([0, 1, 2])
106 | circ.x(3)
107 | circ.barrier()
108 |
109 | circ.append(_7EPXn_mod15(1), [0, 3, 4, 5, 6])
110 | circ.append(_7EPXn_mod15(2), [1, 3, 4, 5, 6])
111 | circ.append(_7EPXn_mod15(4), [2, 3, 4, 5, 6]) # NOT NEEDED
112 |
113 | circ.append(QFT(3).inverse(), [0, 1, 2])
114 | circ.measure([0, 1, 2], [0, 1, 2])
115 |
116 | display(circ.draw('latex'))
117 | ```
118 |
119 |
120 | ```python
121 | device = Aer.get_backend('qasm_simulator')
122 | job = execute(circ,backend = device,shots = 1000)
123 | print(job.job_id())
124 |
125 | result = job.result()
126 | counts = result.get_counts(circ)
127 |
128 | print(counts)
129 | display(plot_histogram(counts))
130 | ```
131 |
132 | ### Question 10
133 |
134 |
135 | ```python
136 | phase = None
137 | circ = QuantumCircuit(2, 1)
138 | circ.h([0, 1])
139 | circ.rz(phase, 1)
140 | circ.cnot(0, 1)
141 | circ.h(0)
142 | circ.measure([0], [0])
143 | display(circ.draw('latex'))
144 |
145 | provider = IBMProvider()
146 | device = provider.get_backend('ibmq_qasm_simulator')
147 | job = execute(circ, device, shots=1000)
148 | result = job.result()
149 | counts = result.get_counts(circ)
150 | print(counts)
151 | ```
152 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Packt
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Quantum Computing Algorithms
2 |
3 |
4 |
5 | This is the code repository for [Quantum Computing Algorithms](https://www.packtpub.com/product/quantum-computing-algorithms/9781804617373?utm_source=github&utm_medium=repository&utm_campaign=), published by Packt.
6 |
7 | **Discover how a little math goes a long way**
8 |
9 | ## What is this book about?
10 | Navigate the quantum computing spectrum with this book, bridging the gap between abstract, math-heavy texts and math-avoidant beginner guides. Unlike intermediate-level books that often leave gaps in comprehension, this all-encompassing guide offers the missing links you need to truly understand the subject.
11 |
12 | This book covers the following exciting features:
13 | * Define quantum circuits
14 | * Harness superposition and entanglement to solve classical problems
15 | * Gain insights into the implementation of quantum teleportation
16 | * Explore the impact of quantum computing on cryptography
17 | * Translate theoretical knowledge into practical skills by writing and executing code on real quantum hardware
18 | * Expand your understanding of this domain by uncovering alternative quantum computing models
19 |
20 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1804617377) today!
21 |
22 |
24 |
25 | ## Instructions and Navigations
26 | All of the code is organized into folders. For example, Chapter07.
27 |
28 | The code will look like the following:
29 | ```
30 | circ = QuantumCircuit(2, 1)
31 | circ.h(1)
32 | circ = get_oracle(circ, function)
33 | circ.measure(0, 0)
34 | display(circ.draw('latex'))
35 | ```
36 |
37 | **Following is what you need for this book:**
38 | This book is for individuals familiar with algebra and computer programming, eager to delve into modern physics concepts. Whether you've dabbled in introductory quantum computing material or are seeking deeper insights, this quantum computing book is your gateway to in-depth exploration.
39 |
40 | With the following software and hardware list you can run all code files present in the book (Chapter 1-10).
41 | ### Software and Hardware List
42 | | Chapter | Software required | OS required |
43 | | -------- | ------------------------------------ | ----------------------------------- |
44 | | 1-10 | Python | A modern web browser running on any operating system |
45 | | 1-10 | IBM Qiskit | A modern web browser running on any operating system |
46 | | 1-10 | Quantum computers on the IBM cloud | |
47 |
48 | ## Errata
49 | * All errata for the book can be found [here](https://users.drew.edu/bburd/quantum/errata.html).
50 |
51 | ### Related products
52 | * A Practical Guide to Quantum Machine Learning and Quantum Optimization [[Packt]](https://www.packtpub.com/product/a-practical-guide-to-quantum-machine-learning-and-quantum-optimization/9781804613832?utm_source=github&utm_medium=repository&utm_campaign=9781804613832) [[Amazon]](https://www.amazon.com/dp/1804613835)
53 |
54 | * Quantum Chemistry and Computing for the Curious [[Packt]](https://www.packtpub.com/product/quantum-chemistry-and-computing-for-the-curious/9781803243900?utm_source=github&utm_medium=repository&utm_campaign=9781803243900) [[Amazon]](https://www.amazon.com/dp/1803243902)
55 |
56 |
57 | ## Get to Know the Author
58 | **Barry Burd**
59 | received a master’s degree in computer science at Rutgers University and a Ph.D. in mathematics at the University of Illinois. As a teaching assistant in Champaign–Urbana, Illinois, he was elected five times to the university-wide List of Teachers Ranked as Excellent by Their Students.
60 | Since 1980, Dr. Burd has been a professor in the department of mathematics and computer science at Drew University in Madison, New Jersey. He has spoken at conferences in the United States, Europe, Australia, and Asia. In 2020, he was honored to be named a Java Champion.
61 | Dr. Burd lives in Madison, New Jersey, USA, where he spends most of his waking hours in front of a computer screen.
62 |
--------------------------------------------------------------------------------