├── Chapter01
└── ch-1.ipynb
├── Chapter02
└── ch-2.ipynb
├── Chapter03
└── ch-3.ipynb
├── Chapter04
└── ch-4.ipynb
├── Chapter05
└── ch-5.ipynb
├── Chapter06
└── ch-6.ipynb
├── Chapter07
└── ch-7.ipynb
├── Chapter08
└── ch-8.ipynb
├── Chapter09
└── ch-9.ipynb
├── LICENSE
└── README.md
/Chapter01/ch-1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 1\n",
8 | "\n",
9 | "This notebook provides details about the installation of packages used in the book \"Hands-on Quantum Information Processing with Python\"."
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": null,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "#installation of required QIP packages.\n",
19 | "pip install qiskit #from www.qiskit.org"
20 | ]
21 | },
22 | {
23 | "cell_type": "code",
24 | "execution_count": null,
25 | "metadata": {},
26 | "outputs": [],
27 | "source": [
28 | "# Install qutip\n",
29 | "pip install qutip"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": null,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "#install qiskit textbook \n",
39 | "pip install ./qiskit-textbook-src"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": null,
45 | "metadata": {},
46 | "outputs": [],
47 | "source": [
48 | "# Install pylatexenc for mpldrawer\n",
49 | "pip install pylatexenc"
50 | ]
51 | },
52 | {
53 | "cell_type": "markdown",
54 | "metadata": {},
55 | "source": [
56 | "Installation of Google's Tensorflow quantum (which incorporates both Tensorflow and Cirq). Start with the dependencies first. Source: https://github.com/tensorflow/quantum/blob/master/docs/install.md"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "metadata": {},
63 | "outputs": [],
64 | "source": [
65 | "pip3 install --upgrade pip\n",
66 | "pip3 install tensorflow==2.1.0\n",
67 | "pip3 install cirq==0.7.0"
68 | ]
69 | },
70 | {
71 | "cell_type": "markdown",
72 | "metadata": {},
73 | "source": [
74 | "Then install the Tensorflow quantum package."
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": null,
80 | "metadata": {},
81 | "outputs": [],
82 | "source": [
83 | "pip3 install -U tensorflow-quantum #Install the latest stable release of TensorFlow Quantum\n",
84 | "pip3 install -U tfq-nightly #Install the latest nightly version of TensorFlow Quantum"
85 | ]
86 | }
87 | ],
88 | "metadata": {
89 | "kernelspec": {
90 | "display_name": "Python 3",
91 | "language": "python",
92 | "name": "python3"
93 | },
94 | "language_info": {
95 | "codemirror_mode": {
96 | "name": "ipython",
97 | "version": 3
98 | },
99 | "file_extension": ".py",
100 | "mimetype": "text/x-python",
101 | "name": "python",
102 | "nbconvert_exporter": "python",
103 | "pygments_lexer": "ipython3",
104 | "version": "3.7.6"
105 | }
106 | },
107 | "nbformat": 4,
108 | "nbformat_minor": 4
109 | }
110 |
--------------------------------------------------------------------------------
/Chapter02/ch-2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 2 stuff. First, code for vector, matrix, and tensor manipulation."
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "import numpy as np\n",
17 | "\n",
18 | "x = np.array([1,2,3]) # a vector with three components.\n",
19 | "y = np.array([4,5,6]) # another vector.\n",
20 | "\n",
21 | "A = np.array([[1,2,3], [4,5,6], [7,5,6]]) # a 3x3 matrix.\n",
22 | "B = np.array([[2,3,4], [1,2,0], [3,3,3]]) # another 3x3 matrix.\n",
23 | "\n",
24 | "v = np.kron(x,A) # a tensor product of vector x and matrix A.\n",
25 | "w = np.kron(y,B) # a tensor product of vector y and matrix B.\n",
26 | "\n",
27 | "# Arithmetic operations\n",
28 | "#vectors\n",
29 | "z = x + y # vector addition\n",
30 | "z = x - y # vector subtraction\n",
31 | "z = 2 * z # scalar multiplication\n",
32 | "#matrices\n",
33 | "C = A - B # matrix multiplication\n",
34 | "C = x * A # a product of a vector and a matrix\n",
35 | "#tensors\n",
36 | "u = v + w # tensor addition\n",
37 | "u = 5 * u # multiplication of a tensor by a scalar"
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": null,
43 | "metadata": {},
44 | "outputs": [],
45 | "source": [
46 | "import numpy as np\n",
47 | "\n",
48 | "x = np.array([1,2,3]) # a vector with three components.\n",
49 | "y = np.array([4,5,6]) # another vector.\n",
50 | "\n",
51 | "a = np.inner(x,y) # The output of an inner product of vectors is a scalar \n",
52 | "print(a)"
53 | ]
54 | },
55 | {
56 | "cell_type": "code",
57 | "execution_count": null,
58 | "metadata": {},
59 | "outputs": [],
60 | "source": [
61 | "import numpy as np\n",
62 | "\n",
63 | "x = np.array([1,2,3]) # a vector with three components.\n",
64 | "y = np.array([4,5,6]) # another vector.\n",
65 | "\n",
66 | "a = np.outer(x,y) # The output of an outer product of vectors is a matrix \n",
67 | "print(a)"
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": null,
73 | "metadata": {},
74 | "outputs": [],
75 | "source": [
76 | "import numpy as np\n",
77 | "\n",
78 | "A = np.array([[1,2,3], [4,5,6], [1,5,1]]) # a 3x3 matrix.\n",
79 | "det_A = np.linalg.det(A)\n",
80 | "print(det_A)"
81 | ]
82 | },
83 | {
84 | "cell_type": "code",
85 | "execution_count": null,
86 | "metadata": {},
87 | "outputs": [],
88 | "source": [
89 | "import numpy as np\n",
90 | "\n",
91 | "A = np.array([[1,2,3], [4,5,9], [5,2,1]]) # a 3x3 matrix.\n",
92 | "det_A = np.linalg.det(A)\n",
93 | "np.transpose(A)"
94 | ]
95 | },
96 | {
97 | "cell_type": "markdown",
98 | "metadata": {},
99 | "source": [
100 | "Compute tensor product of matrices A and B using both numpy and qutip"
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": null,
106 | "metadata": {},
107 | "outputs": [],
108 | "source": [
109 | "from qutip import *\n",
110 | "import numpy as np\n",
111 | "\n",
112 | "A = np.array([[2,3], [4,5]])\n",
113 | "B = np.array([[2,4], [1,0]])\n",
114 | "\n",
115 | "A = Qobj(A); B = Qobj(B)\n",
116 | "C = tensor(A,B); print(C) # computing tensor product using qutip\n",
117 | "\n",
118 | "D = np.kron(A,B); print(D) #computing tensor product using numpy"
119 | ]
120 | },
121 | {
122 | "cell_type": "markdown",
123 | "metadata": {},
124 | "source": [
125 | "Computing trace and partial trace of a tensor product using qutip"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": null,
131 | "metadata": {},
132 | "outputs": [],
133 | "source": [
134 | "from qutip import *\n",
135 | "import numpy as np\n",
136 | "\n",
137 | "A = np.array([[2,3], [4,5]])\n",
138 | "B = np.array([[2,4], [1,1]]) \n",
139 | "\n",
140 | "A = Qobj(A); B = Qobj(B)\n",
141 | "T = tensor(A,B); \n",
142 | "print(\"The tensor product is\", T) \n",
143 | "print(\"The trace of C is\", T.tr())\n",
144 | "Tr_B = T.ptrace(0) # trace out B by selecting A; thus A Tr(B) \n",
145 | "print(\"Tr_B is\", Tr_B)\n",
146 | "Tr_A = T.ptrace(1) # trace out A by selecting B; thus B Tr(A)\n",
147 | "print(\"Tr_A is\", Tr_A) "
148 | ]
149 | },
150 | {
151 | "cell_type": "code",
152 | "execution_count": null,
153 | "metadata": {},
154 | "outputs": [],
155 | "source": [
156 | "from qutip import *\n",
157 | "import numpy as np\n",
158 | "\n",
159 | "A = np.array([[1], [0]])\n",
160 | "B = np.array([[0], [1]])\n",
161 | "Rho_x = sigmax()\n",
162 | "\n",
163 | "A = Qobj(A)\n",
164 | "B = Qobj(B)\n",
165 | "\n",
166 | "C = Rho_x * A\n",
167 | "D = Rho_x * B \n",
168 | "print(C)\n",
169 | "print(D) "
170 | ]
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": null,
175 | "metadata": {},
176 | "outputs": [],
177 | "source": [
178 | "from qutip import *\n",
179 | "import numpy as np\n",
180 | "\n",
181 | "A = np.array([[1], [0]])\n",
182 | "B = np.array([[0], [1]])\n",
183 | "Rho_z = sigmaz()\n",
184 | "\n",
185 | "A = Qobj(A)\n",
186 | "B = Qobj(B)\n",
187 | "\n",
188 | "C = Rho_z * A\n",
189 | "D = Rho_z * B \n",
190 | "print(C)\n",
191 | "print(D) "
192 | ]
193 | },
194 | {
195 | "cell_type": "code",
196 | "execution_count": null,
197 | "metadata": {},
198 | "outputs": [],
199 | "source": [
200 | "from qutip import *\n",
201 | "import numpy as np\n",
202 | "\n",
203 | "A = np.array([[1], [0]])\n",
204 | "B = np.array([[0], [1]])\n",
205 | "Rho_y = sigmay()\n",
206 | "\n",
207 | "A = Qobj(A)\n",
208 | "B = Qobj(B)\n",
209 | "\n",
210 | "C = Rho_y * A\n",
211 | "D = Rho_y * B \n",
212 | "print(C)\n",
213 | "print(D) "
214 | ]
215 | }
216 | ],
217 | "metadata": {
218 | "kernelspec": {
219 | "display_name": "Python 3",
220 | "language": "python",
221 | "name": "python3"
222 | },
223 | "language_info": {
224 | "codemirror_mode": {
225 | "name": "ipython",
226 | "version": 3
227 | },
228 | "file_extension": ".py",
229 | "mimetype": "text/x-python",
230 | "name": "python",
231 | "nbconvert_exporter": "python",
232 | "pygments_lexer": "ipython3",
233 | "version": "3.7.6"
234 | }
235 | },
236 | "nbformat": 4,
237 | "nbformat_minor": 4
238 | }
239 |
--------------------------------------------------------------------------------
/Chapter03/ch-3.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | " **For Chapter 3 stuff.** "
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "The basic Bell state generation."
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": null,
20 | "metadata": {},
21 | "outputs": [],
22 | "source": [
23 | "from qutip import *\n",
24 | "\n",
25 | "w1 = bell_state(state=\"00\")\n",
26 | "print(\"A matrix for the Bell pair generated is:\\n\", w1)"
27 | ]
28 | },
29 | {
30 | "cell_type": "markdown",
31 | "metadata": {},
32 | "source": [
33 | "Generating four Bell states"
34 | ]
35 | },
36 | {
37 | "cell_type": "code",
38 | "execution_count": null,
39 | "metadata": {},
40 | "outputs": [],
41 | "source": [
42 | "from qutip import *\n",
43 | "\n",
44 | "v_00 = bell_state(state=\"00\")\n",
45 | "\n",
46 | "v_01 = bell_state(state=\"01\")\n",
47 | "\n",
48 | "v_10 = bell_state(state=\"10\")\n",
49 | "\n",
50 | "v_11 = bell_state(state=\"11\")\n",
51 | "\n",
52 | "\n",
53 | "print(\"v_00 is:\", v_00)\n",
54 | "print(\"v_01 is:\", v_01)\n",
55 | "print(\"v_10 is:\", v_10)\n",
56 | "print(\"v_11 is:\", v_11)"
57 | ]
58 | },
59 | {
60 | "cell_type": "markdown",
61 | "metadata": {},
62 | "source": [
63 | "Three-qubit GHZ state"
64 | ]
65 | },
66 | {
67 | "cell_type": "code",
68 | "execution_count": null,
69 | "metadata": {},
70 | "outputs": [],
71 | "source": [
72 | "from qutip import *\n",
73 | "\n",
74 | "GHZ = ghz_state(N=3)\n",
75 | "print(GHZ)"
76 | ]
77 | },
78 | {
79 | "cell_type": "markdown",
80 | "metadata": {},
81 | "source": [
82 | "The three-qubit W state"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": null,
88 | "metadata": {},
89 | "outputs": [],
90 | "source": [
91 | "from qutip import *\n",
92 | "import numpy as np\n",
93 | "\n",
94 | "a = np.array([[1], [0]]) \n",
95 | "b = np.array([[0], [1]]) \n",
96 | "\n",
97 | "a = Qobj(a)\n",
98 | "b = Qobj(b)\n",
99 | "\n",
100 | "W = (1/np.sqrt(3))* (tensor(b, a, a) + tensor(a, b, a) + tensor(a, a, b)) \n",
101 | "print(\"The W state is:\", W)"
102 | ]
103 | },
104 | {
105 | "cell_type": "markdown",
106 | "metadata": {},
107 | "source": [
108 | "Quantum Teleportation using cirq"
109 | ]
110 | },
111 | {
112 | "cell_type": "code",
113 | "execution_count": null,
114 | "metadata": {},
115 | "outputs": [],
116 | "source": [
117 | "import random\n",
118 | "import numpy as np\n",
119 | "import cirq\n",
120 | "\n",
121 | "\n",
122 | "def make_quantum_teleportation_circuit(ranX, ranY):\n",
123 | " circuit = cirq.Circuit()\n",
124 | " msg, alice, bob = cirq.LineQubit.range(3)\n",
125 | "\n",
126 | " # Creates Bell state to be shared between Alice and Bob\n",
127 | " circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])\n",
128 | " # Creates a random state for the Message\n",
129 | " circuit.append([cirq.X(msg)**ranX, cirq.Y(msg)**ranY])\n",
130 | " # Bell measurement of the Message and Alice's entangled qubit\n",
131 | " circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)])\n",
132 | " circuit.append(cirq.measure(msg, alice))\n",
133 | " # Uses the two classical bits from the Bell measurement to recover the\n",
134 | " # original quantum Message on Bob's entangled qubit\n",
135 | " circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])\n",
136 | "\n",
137 | " return circuit\n",
138 | "\n",
139 | "\n",
140 | "def main():\n",
141 | " ranX = random.random()\n",
142 | " ranY = random.random()\n",
143 | " circuit = make_quantum_teleportation_circuit(ranX, ranY)\n",
144 | "\n",
145 | " print(\"Circuit:\")\n",
146 | " print(circuit)\n",
147 | "\n",
148 | " sim = cirq.Simulator()\n",
149 | "\n",
150 | " # Create qubits.\n",
151 | " q0 = cirq.LineQubit(0)\n",
152 | "\n",
153 | " # Produces the message using random X and Y gates\n",
154 | " message = sim.simulate(cirq.Circuit([cirq.X(q0)**ranX, cirq.Y(q0)**ranY]))\n",
155 | "\n",
156 | " print(\"\\nBloch Sphere of Message After Random X and Y Gates:\")\n",
157 | " # Prints the Bloch Sphere of the Message after the X and Y gates\n",
158 | " expected = cirq.bloch_vector_from_state_vector(message.final_state, 0)\n",
159 | " print(\"x: \", np.around(expected[0], 4), \"y: \", np.around(expected[1], 4),\n",
160 | " \"z: \", np.around(expected[2], 4))\n",
161 | "\n",
162 | " # Records the final state of the simulation\n",
163 | " final_results = sim.simulate(circuit)\n",
164 | "\n",
165 | " print(\"\\nBloch Sphere of Qubit 2 at Final State:\")\n",
166 | " # Prints the Bloch Sphere of Bob's entangled qubit at the final state\n",
167 | " teleported = cirq.bloch_vector_from_state_vector(final_results.final_state,\n",
168 | " 2)\n",
169 | " print(\"x: \", np.around(teleported[0], 4), \"y: \",\n",
170 | " np.around(teleported[1], 4), \"z: \", np.around(teleported[2], 4))\n",
171 | "\n",
172 | " return expected, teleported\n",
173 | "\n",
174 | "\n",
175 | "if __name__ == '__main__':\n",
176 | " main()"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "metadata": {},
182 | "source": [
183 | "Quantum teleportation using qiskit"
184 | ]
185 | },
186 | {
187 | "cell_type": "code",
188 | "execution_count": null,
189 | "metadata": {},
190 | "outputs": [],
191 | "source": [
192 | "from qiskit import *\n",
193 | "from qiskit.visualization import plot_histogram\n",
194 | "\n",
195 | "circuit = QuantumCircuit(3,3)\n",
196 | "\n",
197 | "\n",
198 | "circuit.h(0)\n",
199 | "\n",
200 | "circuit.h(1)\n",
201 | "circuit.cx(1,2)\n",
202 | "\n",
203 | "circuit.cx(0,1)\n",
204 | "circuit.h(0)\n",
205 | "\n",
206 | "circuit.measure([0, 1], [0, 1])\n",
207 | "\n",
208 | "circuit.cx(1, 2)\n",
209 | "circuit.cz(0, 2)\n",
210 | "\n",
211 | "circuit.measure([2], [2])\n",
212 | "\n",
213 | "circuit.draw(output='text')\n",
214 | "\n",
215 | "simulator = Aer.get_backend('qasm_simulator')\n",
216 | "result = execute(circuit, backend=simulator, shots=1024).result()\n",
217 | "plot_histogram(result.get_counts(circuit))"
218 | ]
219 | }
220 | ],
221 | "metadata": {
222 | "kernelspec": {
223 | "display_name": "Python 3",
224 | "language": "python",
225 | "name": "python3"
226 | },
227 | "language_info": {
228 | "codemirror_mode": {
229 | "name": "ipython",
230 | "version": 3
231 | },
232 | "file_extension": ".py",
233 | "mimetype": "text/x-python",
234 | "name": "python",
235 | "nbconvert_exporter": "python",
236 | "pygments_lexer": "ipython3",
237 | "version": "3.7.6"
238 | }
239 | },
240 | "nbformat": 4,
241 | "nbformat_minor": 4
242 | }
243 |
--------------------------------------------------------------------------------
/Chapter04/ch-4.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "#Identity gate \n",
10 | "def IDTY(a):\n",
11 | " if a == 0:\n",
12 | " return 0\n",
13 | " else:\n",
14 | " return 1\n",
15 | "\n",
16 | "if __name__ == '__main__':\n",
17 | " print(\"The output of input 0 is: \\n\", IDTY(0))\n",
18 | " print(\"The output of input 1 is: \\n\", IDTY(1))"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {},
25 | "outputs": [],
26 | "source": [
27 | "#NOT gate\n",
28 | "def NOT(a):\n",
29 | " if a == 0:\n",
30 | " return 1\n",
31 | " else:\n",
32 | " return 0\n",
33 | "\n",
34 | "if __name__ == '__main__':\n",
35 | " print(\"The output of NOT gate for input 0 is: \\n\", NOT(0))\n",
36 | " print(\"The output of NOT gate for input 1 is: \\n\", NOT(1))"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": null,
42 | "metadata": {},
43 | "outputs": [],
44 | "source": [
45 | "#OR gate\n",
46 | "def OR(a,b):\n",
47 | " if a == 0 and b == 0:\n",
48 | " return 0\n",
49 | " else:\n",
50 | " return 1\n",
51 | "\n",
52 | "if __name__ == '__main__':\n",
53 | " print(\"The output of OR gate for inputs 0,0 is: \\n\", OR(0,0))\n",
54 | " print(\"The output of OR gate for inputs 0,1 is: \\n\", OR(0,1))\n",
55 | " print(\"The output of OR gate for inputs 1,0 is: \\n\", OR(1,0))\n",
56 | " print(\"The output of OR gate for inputs 1,1 is: \\n\", OR(1,1))"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "metadata": {},
63 | "outputs": [],
64 | "source": [
65 | "#AND gate \n",
66 | "def AND(a,b):\n",
67 | " if a == 1 and b == 1:\n",
68 | " return 1\n",
69 | " else:\n",
70 | " return 0\n",
71 | "\n",
72 | "if __name__ == '__main__':\n",
73 | " print(\"The output of AND gate for inputs 0,0 is: \\n\", AND(0,0))\n",
74 | " print(\"The output of AND gate for inputs 0,1 is: \\n\", AND(0,1))\n",
75 | " print(\"The output of AND gate for inputs 1,0 is: \\n\", AND(1,0))\n",
76 | " print(\"The output of AND gate for inputs 1,1 is: \\n\", AND(1,1))"
77 | ]
78 | },
79 | {
80 | "cell_type": "code",
81 | "execution_count": null,
82 | "metadata": {},
83 | "outputs": [],
84 | "source": [
85 | "#XOR gate\n",
86 | "def XOR(a,b):\n",
87 | " if a != b:\n",
88 | " return 1\n",
89 | " else:\n",
90 | " return 0\n",
91 | "\n",
92 | "if __name__ == '__main__':\n",
93 | " print(\"The output of XOR gate for inputs 0,0 is: \\n\", XOR(0,0))\n",
94 | " print(\"The output of XOR gate for inputs 0,1 is: \\n\", XOR(0,1))\n",
95 | " print(\"The output of XOR gate for inputs 1,0 is: \\n\", XOR(1,0))\n",
96 | " print(\"The output of XOR gate for inputs 1,1 is: \\n\", XOR(1,1))"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "metadata": {},
103 | "outputs": [],
104 | "source": [
105 | "#NOR gate\n",
106 | "def NOR(a,b):\n",
107 | " if a == 0 and b == 0:\n",
108 | " return 1\n",
109 | " else:\n",
110 | " return 0\n",
111 | "\n",
112 | "if __name__ == '__main__':\n",
113 | " print(\"The output of NOR gate for inputs 0,0 is: \\n\", NOR(0,0))\n",
114 | " print(\"The output of NOR gate for inputs 0,1 is: \\n\", NOR(0,1))\n",
115 | " print(\"The output of NOR gate for inputs 1,0 is: \\n\", NOR(1,0))\n",
116 | " print(\"The output of NOR gate for inputs 1,1 is: \\n\", NOR(1,1))"
117 | ]
118 | },
119 | {
120 | "cell_type": "code",
121 | "execution_count": null,
122 | "metadata": {},
123 | "outputs": [],
124 | "source": [
125 | "#Import packages required\n",
126 | "from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer\n",
127 | "from qiskit.visualization import plot_histogram\n",
128 | "import matplotlib.pyplot as plt\n",
129 | "import numpy as np\n",
130 | "\n",
131 | "np.random.seed(42) #for reproducibility\n",
132 | "\n",
133 | "# Define the Quantum and Classical Registers\n",
134 | "qr = QuantumRegister(1)\n",
135 | "cr = ClassicalRegister(1)\n",
136 | "\n",
137 | "# Build the circuit\n",
138 | "sup = QuantumCircuit(qr, cr)\n",
139 | "sup.x(qr) #invert the qubit (qubits are initialized to |0>, so this turns |0>. to |1>)\n",
140 | "sup.h(qr)\n",
141 | "sup.measure(qr, cr)\n",
142 | "sup.draw(output='mpl')\n",
143 | "plt.show()\n",
144 | "\n",
145 | "# Execute the circuit (using the qasm simulator)\n",
146 | "job = execute(sup, backend = Aer.get_backend('qasm_simulator'), shots=1024)\n",
147 | "result = job.result()\n",
148 | "\n",
149 | "# Print the result\n",
150 | "print(result.get_counts(sup))\n",
151 | "\n",
152 | "#plot the results\n",
153 | "counts = result.get_counts(sup)\n",
154 | "plot_histogram(counts)\n",
155 | "plt.show()"
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": null,
161 | "metadata": {},
162 | "outputs": [],
163 | "source": [
164 | "#QECC Code\n",
165 | "\n",
166 | "from qiskit import *\n",
167 | "from qiskit.ignis.verification.topological_codes import RepetitionCode\n",
168 | "from qiskit.ignis.verification.topological_codes import GraphDecoder\n",
169 | "from qiskit.ignis.verification.topological_codes import lookuptable_decoding, postselection_decoding\n",
170 | "from qiskit.compiler import transpile\n",
171 | "from qiskit.transpiler import PassManager\n",
172 | "from qiskit import QuantumCircuit, execute, Aer\n",
173 | "from qiskit.providers.aer import noise\n",
174 | "from qiskit.providers.aer.noise import NoiseModel\n",
175 | "from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error\n",
176 | "from qiskit import QuantumRegister, ClassicalRegister\n",
177 | "import numpy as np\n",
178 | "import matplotlib.pyplot as plt\n",
179 | "\n",
180 | "np.random.seed(42) #for reproducibility\n",
181 | "\n",
182 | "def get_noise(p_meas,p_gate):\n",
183 | "\n",
184 | "\terror_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])\n",
185 | "\terror_gate1 = depolarizing_error(p_gate, 1)\n",
186 | "\terror_gate2 = error_gate1.tensor(error_gate1)\n",
187 | "\n",
188 | "\tnoise_model = NoiseModel()\n",
189 | "\tnoise_model.add_all_qubit_quantum_error(error_meas, \"measure\") # measurement error is applied to measurements\n",
190 | "\tnoise_model.add_all_qubit_quantum_error(error_gate1, [\"x\"]) # single qubit gate error is applied to x gates\n",
191 | "\tnoise_model.add_all_qubit_quantum_error(error_gate2, [\"cx\"]) # two qubit gate error is applied to cx gates\n",
192 | " \t \n",
193 | "\treturn noise_model\n",
194 | " \n",
195 | "noise_model = get_noise(0.05,0.05)\n",
196 | "\n",
197 | "qc0 = QuantumCircuit(3,3,name='0') # initialize circuit with three qubits in the 0 state\n",
198 | "\n",
199 | "qc0.measure(qc0.qregs[0],qc0.cregs[0]) # measure the qubits\n",
200 | "\n",
201 | "# run the circuit with th noise model and extract the counts\n",
202 | "counts = execute( qc0, Aer.get_backend('qasm_simulator'),noise_model=noise_model).result().get_counts()\n",
203 | "\n",
204 | "print(counts)\n",
205 | "\n",
206 | "qc1 = QuantumCircuit(3,3,name='0') # initialize circuit with three qubits in the 0 state\n",
207 | "qc1.x(qc1.qregs[0]) # flip each 0 to 1\n",
208 | "\n",
209 | "qc1.measure(qc1.qregs[0],qc1.cregs[0]) # measure the qubits\n",
210 | "\n",
211 | "# run the circuit with th noise model and extract the counts\n",
212 | "counts = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model).result().get_counts()\n",
213 | "\n",
214 | "print(counts)\n",
215 | "\n",
216 | "noise_model = get_noise(0.5,0.0)\n",
217 | "counts = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model).result().get_counts()\n",
218 | "print(counts)\n",
219 | "\n",
220 | "cq = QuantumRegister(2,'code\\ qubit\\ ')\n",
221 | "lq = QuantumRegister(1,'auxiliary\\ qubit\\ ')\n",
222 | "sb = ClassicalRegister(1,'syndrome\\ bit\\ ')\n",
223 | "qc = QuantumCircuit(cq,lq,sb)\n",
224 | "qc.cx(cq[0],lq[0])\n",
225 | "qc.cx(cq[1],lq[0])\n",
226 | "qc.measure(lq,sb)\n",
227 | "qc.draw(output='mpl')\n",
228 | "\n",
229 | "qc_init = QuantumCircuit(cq)\n",
230 | "(qc_init+qc).draw(output='mpl')\n",
231 | "\n",
232 | "counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()\n",
233 | "print('Results:',counts)\n",
234 | "\n",
235 | "qc_init = QuantumCircuit(cq)\n",
236 | "qc_init.x(cq)\n",
237 | "(qc_init+qc).draw(output='mpl')\n",
238 | "\n",
239 | "counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()\n",
240 | "print('Results:',counts)\n",
241 | "\n",
242 | "qc_init = QuantumCircuit(cq)\n",
243 | "qc_init.h(cq[0])\n",
244 | "qc_init.cx(cq[0],cq[1])\n",
245 | "(qc_init+qc).draw(output='mpl')\n",
246 | "\n",
247 | "counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()\n",
248 | "print('Results:',counts)\n",
249 | "\n",
250 | "code = RepetitionCode(3,1) #3 qubit, one round of syndrome measurement\n",
251 | "\n",
252 | "for reg in code.circuit['0'].qregs+code.circuit['1'].cregs:\n",
253 | "\treg.name = reg.name.replace('_','\\ ') + '\\ '\n",
254 | "\n",
255 | "code.circuit['0'].draw(output='mpl')\n",
256 | "code.circuit['1'].draw(output='mpl')\n",
257 | "\n",
258 | "def get_raw_results(code,noise_model=None):\n",
259 | "\n",
260 | " circuits = code.get_circuit_list()\n",
261 | " raw_results = {}\n",
262 | " for log in range(2):\n",
263 | " job = execute( circuits[log], Aer.get_backend('qasm_simulator'), noise_model=noise_model)\n",
264 | " raw_results[str(log)] = job.result().get_counts(str(log))\n",
265 | " return raw_results\n",
266 | "\n",
267 | "raw_results = get_raw_results(code)\n",
268 | "for log in raw_results:\n",
269 | " print('Logical',log,':',raw_results[log],'\\n')\n",
270 | "\n",
271 | " \n",
272 | "code = RepetitionCode(3,1)\n",
273 | "\n",
274 | "noise_model = get_noise(0.05,0.05)\n",
275 | "\n",
276 | "raw_results = get_raw_results(code,noise_model)\n",
277 | "for log in raw_results:\n",
278 | "\tprint('Logical',log,':',raw_results[log],'\\n')\n",
279 | " \n",
280 | "circuits = code.get_circuit_list()\n",
281 | "table_results = {}\n",
282 | "for log in range(2):\n",
283 | "\tjob = execute( circuits[log], Aer.get_backend('qasm_simulator'), noise_model=noise_model, shots=10000 )\n",
284 | "\ttable_results[str(log)] = job.result().get_counts(str(log))\n",
285 | " \n",
286 | "P = lookuptable_decoding(raw_results,table_results)\n",
287 | "print('P =',P)\n",
288 | "plt.show()"
289 | ]
290 | },
291 | {
292 | "cell_type": "code",
293 | "execution_count": null,
294 | "metadata": {},
295 | "outputs": [],
296 | "source": [
297 | "#superdence coding\n",
298 | "\n",
299 | " #Import modules\n",
300 | "from qiskit import *\n",
301 | "from qiskit.visualization import plot_histogram\n",
302 | "import matplotlib.pyplot as plt\n",
303 | "import numpy as np\n",
304 | "\n",
305 | "np.random.seed(42) #for reproducibility\n",
306 | "\n",
307 | "#Create the EPR pair for both Alice (a) and Bob (b) for the QuantumCircuit (qc)\n",
308 | "def create_bell_pair(qc, a, b):\n",
309 | "\tqc.h(a)\n",
310 | "\tqc.cx(a,b)\n",
311 | " \n",
312 | "#Encode the message (classical bits) to be sent, on Alice's side. The classical bits are '00', '01', '10', or '11'\n",
313 | "def encode_message(qc, qubit, msg):\n",
314 | " if msg == \"00\":\n",
315 | " pass \n",
316 | " elif msg == \"10\":\n",
317 | " qc.x(qubit) \n",
318 | " elif msg == \"01\":\n",
319 | " qc.z(qubit) \n",
320 | " elif msg == \"11\":\n",
321 | " qc.z(qubit) \n",
322 | " qc.x(qubit) \n",
323 | " else:\n",
324 | " print(\"Invalid Message: Sending '00'\")\n",
325 | "\n",
326 | " \t \n",
327 | "#Decode the message on Bob's side\n",
328 | "def decode_message(qc, a, b):\n",
329 | "\tqc.cx(a,b)\n",
330 | "\tqc.h(a)\n",
331 | " \n",
332 | "#Implement the superdense coding protocol\n",
333 | "qc = QuantumCircuit(2)\n",
334 | "\n",
335 | "create_bell_pair(qc, 0, 1)\n",
336 | "qc.barrier() # This is the barrier (used to improve clarity on the circuit)\n",
337 | "\n",
338 | "message = \"11\" #Alice applies Z gate followed by X gate\n",
339 | "encode_message(qc, 0, message)\n",
340 | "qc.barrier()\n",
341 | "\n",
342 | "decode_message(qc, 0, 1)\n",
343 | "\n",
344 | "qc.measure_all()\n",
345 | "\n",
346 | "qc.draw(output = \"mpl\")\n",
347 | "#plt.show()\n",
348 | "\n",
349 | "#Run the simulation using IBM classical simulator. Then visualize the results using the histogram\n",
350 | "backend = Aer.get_backend('qasm_simulator')\n",
351 | "job_sim = execute(qc, backend, shots=1024)\n",
352 | "sim_result = job_sim.result()\n",
353 | "\n",
354 | "measurement_result = sim_result.get_counts(qc)\n",
355 | "print(measurement_result)\n",
356 | "plot_histogram(measurement_result)\n",
357 | "plt.show()"
358 | ]
359 | }
360 | ],
361 | "metadata": {
362 | "kernelspec": {
363 | "display_name": "Python 3",
364 | "language": "python",
365 | "name": "python3"
366 | },
367 | "language_info": {
368 | "codemirror_mode": {
369 | "name": "ipython",
370 | "version": 3
371 | },
372 | "file_extension": ".py",
373 | "mimetype": "text/x-python",
374 | "name": "python",
375 | "nbconvert_exporter": "python",
376 | "pygments_lexer": "ipython3",
377 | "version": "3.7.6"
378 | }
379 | },
380 | "nbformat": 4,
381 | "nbformat_minor": 4
382 | }
383 |
--------------------------------------------------------------------------------
/Chapter05/ch-5.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 5 stuff"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "From Chapter 5 "
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "Deutsch algorithm"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": null,
27 | "metadata": {},
28 | "outputs": [],
29 | "source": [
30 | "import numpy as np\n",
31 | "import random\n",
32 | "import cirq\n",
33 | "from cirq import H, X, CNOT, measure\n",
34 | "\n",
35 | "q0, q1 = cirq.LineQubit.range(2)\n",
36 | "secret_function = [random.randint(0,1) for _ in range(2)]\n",
37 | "\n",
38 | "def make_oracle(a, b, c):\n",
39 | " if c[0]:\n",
40 | " yield [CNOT(a,b), X(b)]\n",
41 | " if c[1]:\n",
42 | " yield CNOT(a,b)\n",
43 | "\n",
44 | "def make_deutsch_circuit(d,e,f):\n",
45 | " c = cirq.Circuit()\n",
46 | " c.append([H(e), H(e), H(d)])\n",
47 | " c.append(f)\n",
48 | " c.append([H(d), measure(d, key='result')])\n",
49 | " return c\n",
50 | "\n",
51 | "oracle = make_oracle(q0, q1, secret_function)\n",
52 | "circuit = make_deutsch_circuit(q0, q1, oracle)\n",
53 | "print(circuit)\n",
54 | "\n",
55 | "simulator = cirq.Simulator()\n",
56 | "result = simulator.run(circuit)\n",
57 | "print(result)"
58 | ]
59 | },
60 | {
61 | "cell_type": "markdown",
62 | "metadata": {},
63 | "source": [
64 | "Deutsch-Josza"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": null,
70 | "metadata": {},
71 | "outputs": [],
72 | "source": [
73 | "\n",
74 | "'''\n",
75 | "Code adopted from: https://qiskit.org/textbook/ch-algorithms/deutsch-jozsa.html#4.-Qiskit-Implementation-\n",
76 | "'''\n",
77 | "# initialization\n",
78 | "import numpy as np\n",
79 | "\n",
80 | "# importing Qiskit\n",
81 | "from qiskit import BasicAer\n",
82 | "#from qiskit.providers.ibmq import least_busy\n",
83 | "from qiskit import QuantumCircuit, execute\n",
84 | "\n",
85 | "# import basic plot tools\n",
86 | "from qiskit.visualization import plot_histogram\n",
87 | "\n",
88 | "np.random.seed(42)\n",
89 | "\n",
90 | "# set the length of the n-bit input string. \n",
91 | "n = 3\n",
92 | "\n",
93 | "# set the length of the n-bit input string. \n",
94 | "n = 3\n",
95 | "\n",
96 | "%matplotlib inline\n",
97 | "\n",
98 | "#Constant oracle\n",
99 | "const_oracle = QuantumCircuit(n+1)\n",
100 | "\n",
101 | "output = np.random.randint(2)\n",
102 | "if output == 1:\n",
103 | " const_oracle.x(n)\n",
104 | "\n",
105 | "#const_oracle.draw(output='mpl')\n",
106 | "const_oracle.draw()\n",
107 | "\n",
108 | "\n",
109 | "#Balanced oracle\n",
110 | "balanced_oracle = QuantumCircuit(n+1)\n",
111 | "b_str = \"101\"\n",
112 | "\n",
113 | "balanced_oracle = QuantumCircuit(n+1)\n",
114 | "b_str = \"101\"\n",
115 | "\n",
116 | "# Place X-gates\n",
117 | "for qubit in range(len(b_str)):\n",
118 | " if b_str[qubit] == '1':\n",
119 | " balanced_oracle.x(qubit)\n",
120 | "balanced_oracle.draw()\n",
121 | "\n",
122 | "\n",
123 | "\n",
124 | "balanced_oracle = QuantumCircuit(n+1)\n",
125 | "b_str = \"101\"\n",
126 | "\n",
127 | "# Place X-gates\n",
128 | "for qubit in range(len(b_str)):\n",
129 | " if b_str[qubit] == '1':\n",
130 | " balanced_oracle.x(qubit)\n",
131 | "\n",
132 | "# Use barrier as divider\n",
133 | "balanced_oracle.barrier()\n",
134 | "\n",
135 | "# Controlled-NOT gates\n",
136 | "for qubit in range(n):\n",
137 | " balanced_oracle.cx(qubit, n)\n",
138 | "\n",
139 | "balanced_oracle.barrier()\n",
140 | "balanced_oracle.draw()\n",
141 | "\n",
142 | "\n",
143 | "balanced_oracle = QuantumCircuit(n+1)\n",
144 | "b_str = \"101\"\n",
145 | "\n",
146 | "# Place X-gates\n",
147 | "for qubit in range(len(b_str)):\n",
148 | " if b_str[qubit] == '1':\n",
149 | " balanced_oracle.x(qubit)\n",
150 | "\n",
151 | "# Use barrier as divider\n",
152 | "balanced_oracle.barrier()\n",
153 | "\n",
154 | "# Controlled-NOT gates\n",
155 | "for qubit in range(n):\n",
156 | " balanced_oracle.cx(qubit, n)\n",
157 | "\n",
158 | "balanced_oracle.barrier()\n",
159 | "\n",
160 | "# Place X-gates\n",
161 | "for qubit in range(len(b_str)):\n",
162 | " if b_str[qubit] == '1':\n",
163 | " balanced_oracle.x(qubit)\n",
164 | "\n",
165 | "# Show oracle\n",
166 | "balanced_oracle.draw()\n",
167 | "\n",
168 | "\n",
169 | "#implementation of the algo\n",
170 | "dj_circuit = QuantumCircuit(n+1, n)\n",
171 | "\n",
172 | "# Apply H-gates\n",
173 | "for qubit in range(n):\n",
174 | " dj_circuit.h(qubit)\n",
175 | "\n",
176 | "# Put qubit in state |->\n",
177 | "dj_circuit.x(n)\n",
178 | "dj_circuit.h(n)\n",
179 | "dj_circuit.draw()\n",
180 | "\n",
181 | "dj_circuit = QuantumCircuit(n+1, n)\n",
182 | "\n",
183 | "# Apply H-gates\n",
184 | "for qubit in range(n):\n",
185 | " dj_circuit.h(qubit)\n",
186 | "\n",
187 | "# Put qubit in state |->\n",
188 | "dj_circuit.x(n)\n",
189 | "dj_circuit.h(n)\n",
190 | "\n",
191 | "# Add oracle\n",
192 | "dj_circuit += balanced_oracle\n",
193 | "dj_circuit.draw()\n",
194 | "\n",
195 | "dj_circuit = QuantumCircuit(n+1, n)\n",
196 | "\n",
197 | "# Apply H-gates\n",
198 | "for qubit in range(n):\n",
199 | " dj_circuit.h(qubit)\n",
200 | "\n",
201 | "# Put qubit in state |->\n",
202 | "dj_circuit.x(n)\n",
203 | "dj_circuit.h(n)\n",
204 | "\n",
205 | "# Add oracle\n",
206 | "dj_circuit += balanced_oracle\n",
207 | "\n",
208 | "# Repeat H-gates\n",
209 | "for qubit in range(n):\n",
210 | " dj_circuit.h(qubit)\n",
211 | "dj_circuit.barrier()\n",
212 | "\n",
213 | "# Measure\n",
214 | "for i in range(n):\n",
215 | " dj_circuit.measure(i, i)\n",
216 | "\n",
217 | "# Display circuit\n",
218 | "dj_circuit.draw()\n",
219 | "\n",
220 | "\n",
221 | "# use local simulator\n",
222 | "backend = BasicAer.get_backend('qasm_simulator')\n",
223 | "shots = 1024\n",
224 | "results = execute(dj_circuit, backend=backend, shots=shots).result()\n",
225 | "answer = results.get_counts()\n",
226 | "\n",
227 | "plot_histogram(answer)"
228 | ]
229 | },
230 | {
231 | "cell_type": "markdown",
232 | "metadata": {},
233 | "source": [
234 | "Bernstein-vazirani Algorithm"
235 | ]
236 | },
237 | {
238 | "cell_type": "code",
239 | "execution_count": null,
240 | "metadata": {},
241 | "outputs": [],
242 | "source": [
243 | "'''\n",
244 | "This code is adopted from: https://github.com/qiskit-community/qiskit-community-tutorials/blob/master/Coding_With_Qiskit/ep6_Bernstein-Vazirani_Algorithm.ipynb\n",
245 | "'''\n",
246 | "\n",
247 | "#!pip install qiskit\n",
248 | "import numpy as np\n",
249 | "from qiskit import *\n",
250 | "from qiskit.visualization import plot_histogram\n",
251 | "\n",
252 | "np.random.seed(42)\n",
253 | "\n",
254 | "s = input(\"Enter the secret bit string:\\n\")\n",
255 | "\n",
256 | "n = len(s)\n",
257 | "\n",
258 | "circuit = QuantumCircuit(n+1,n)\n",
259 | "\n",
260 | "# Step 0\n",
261 | "\n",
262 | "circuit.x(n) \n",
263 | "circuit.barrier() \n",
264 | "\n",
265 | "# Step 1\n",
266 | "\n",
267 | "circuit.h(range(n+1)) \n",
268 | "\n",
269 | "circuit.barrier() \n",
270 | "\n",
271 | "# Step 2\n",
272 | "\n",
273 | "for ii, yesno in enumerate(reversed(s)):\n",
274 | " if yesno == '1': \n",
275 | " circuit.cx(ii, n)\n",
276 | " \n",
277 | "circuit.barrier()\n",
278 | "\n",
279 | "# Step 3\n",
280 | "\n",
281 | "circuit.h(range(n+1)) \n",
282 | "\n",
283 | "circuit.barrier() \n",
284 | "\n",
285 | "circuit.measure(range(n), range(n))\n",
286 | "\n",
287 | "%matplotlib inline\n",
288 | "#circuit.draw(output='mpl')\n",
289 | "circuit.draw()\n",
290 | "\n",
291 | "#Running the algorithm\n",
292 | "simulator = Aer.get_backend('qasm_simulator')\n",
293 | "result = execute(circuit, backend=simulator, shots=1024).result()\n",
294 | "plot_histogram(result.get_counts(circuit))"
295 | ]
296 | },
297 | {
298 | "cell_type": "markdown",
299 | "metadata": {},
300 | "source": [
301 | "N-qubit QFT using Qiskit"
302 | ]
303 | },
304 | {
305 | "cell_type": "code",
306 | "execution_count": null,
307 | "metadata": {},
308 | "outputs": [],
309 | "source": [
310 | "from qiskit.circuit.library import QFT\n",
311 | "\n",
312 | "n = input(\" Enter the number of qubits: \\n\")\n",
313 | "\n",
314 | "qft_circuit = QFT(num_qubits = n)\n",
315 | "\n",
316 | "qft_circuit.draw()"
317 | ]
318 | },
319 | {
320 | "cell_type": "markdown",
321 | "metadata": {},
322 | "source": [
323 | "Quantum Phase estimation using cirq"
324 | ]
325 | },
326 | {
327 | "cell_type": "code",
328 | "execution_count": null,
329 | "metadata": {},
330 | "outputs": [],
331 | "source": [
332 | "\n",
333 | "\"\"\"Creates and simulates a phase estimator circuit.\n",
334 | "=== EXAMPLE OUTPUT ===\n",
335 | "Testing with 8 qubits.\n",
336 | "target=0.0000, estimate=0.0000=0/256\n",
337 | "target=0.1000, estimate=0.1016=26/256\n",
338 | "target=0.2000, estimate=0.1992=51/256\n",
339 | "target=0.3000, estimate=0.3008=77/256\n",
340 | "target=0.4000, estimate=0.3984=102/256\n",
341 | "target=0.5000, estimate=0.5000=128/256\n",
342 | "target=0.6000, estimate=0.6016=154/256\n",
343 | "target=0.7000, estimate=0.6992=179/256\n",
344 | "target=0.8000, estimate=0.8008=205/256\n",
345 | "target=0.9000, estimate=0.8984=230/256\n",
346 | "RMS Error: 0.0011\n",
347 | "\"\"\"\n",
348 | "\n",
349 | "'''\n",
350 | "This code is adopted from: https://github.com/quantumlib/Cirq/blob/master/examples/phase_estimator.py\n",
351 | "'''\n",
352 | "\n",
353 | "import numpy as np\n",
354 | "import cirq\n",
355 | "\n",
356 | "\n",
357 | "def run_estimate(unknown_gate, qnum, repetitions):\n",
358 | " \n",
359 | "\n",
360 | " ancilla = cirq.LineQubit(-1)\n",
361 | " qubits = cirq.LineQubit.range(qnum)\n",
362 | "\n",
363 | " oracle_raised_to_power = [\n",
364 | " unknown_gate.on(ancilla).controlled_by(qubits[i])**(2**i)\n",
365 | " for i in range(qnum)\n",
366 | " ]\n",
367 | " circuit = cirq.Circuit(cirq.H.on_each(*qubits), oracle_raised_to_power,\n",
368 | " cirq.QFT(*qubits, without_reverse=True)**-1,\n",
369 | " cirq.measure(*qubits, key='phase'))\n",
370 | "\n",
371 | " return cirq.sample(circuit, repetitions=repetitions)\n",
372 | "\n",
373 | "\n",
374 | "def experiment(qnum, repetitions=100):\n",
375 | " \n",
376 | "\n",
377 | " def example_gate(phi):\n",
378 | " \n",
379 | " gate = cirq.MatrixGate(\n",
380 | " matrix=np.array([[np.exp(2 * np.pi * 1.0j * phi), 0], [0, 1]]))\n",
381 | " return gate\n",
382 | "\n",
383 | " print(f'Testing with {qnum} qubits.')\n",
384 | " errors = []\n",
385 | " for target in np.arange(0, 1, 0.1):\n",
386 | " result = run_estimate(example_gate(target), qnum, repetitions)\n",
387 | " mode = result.data['phase'].mode()[0]\n",
388 | " guess = mode / 2**qnum\n",
389 | " print(f'target={target:0.4f}, '\n",
390 | " f'estimate={guess:0.4f}={mode}/{2**qnum}')\n",
391 | " errors.append((target - guess)**2)\n",
392 | " rms = np.sqrt(sum(errors) / len(errors))\n",
393 | " print(f'RMS Error: {rms:0.4f}\\n')\n",
394 | "\n",
395 | "\n",
396 | "def main(qnums = (2, 4, 8), repetitions=100):\n",
397 | " for qnum in qnums:\n",
398 | " experiment(qnum, repetitions=repetitions)\n",
399 | "\n",
400 | "\n",
401 | "if __name__ == '__main__':\n",
402 | " main()"
403 | ]
404 | },
405 | {
406 | "cell_type": "markdown",
407 | "metadata": {},
408 | "source": [
409 | "Simons algorithm using qiskit"
410 | ]
411 | },
412 | {
413 | "cell_type": "code",
414 | "execution_count": null,
415 | "metadata": {},
416 | "outputs": [],
417 | "source": [
418 | "#!pip install 'qiskit==0.19'\n",
419 | "#!pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src\n",
420 | "\n",
421 | "'''\n",
422 | "This is taken from: https://qiskit.org/textbook/ch-algorithms/simon.html\n",
423 | "'''\n",
424 | "# importing Qiskit\n",
425 | "from qiskit import BasicAer\n",
426 | "from qiskit.providers.ibmq import least_busy\n",
427 | "from qiskit import QuantumCircuit, execute\n",
428 | "\n",
429 | "# import basic plot tools\n",
430 | "from qiskit.visualization import plot_histogram\n",
431 | "from qiskit_textbook.tools import simon_oracle\n",
432 | "\n",
433 | "import matplotlib.pyplot as plt\n",
434 | "\n",
435 | "b = '110'\n",
436 | "\n",
437 | "n = len(b)\n",
438 | "simon_circuit = QuantumCircuit(n*2, n)\n",
439 | "\n",
440 | "# Apply Hadamard gates before querying the oracle\n",
441 | "simon_circuit.h(range(n)) \n",
442 | " \n",
443 | "# Apply barrier for visual separation\n",
444 | "simon_circuit.barrier()\n",
445 | "\n",
446 | "simon_circuit += simon_oracle(b)\n",
447 | "\n",
448 | "# Apply barrier for visual separation\n",
449 | "simon_circuit.barrier()\n",
450 | "\n",
451 | "# Apply Hadamard gates to the input register\n",
452 | "simon_circuit.h(range(n))\n",
453 | "\n",
454 | "# Measure qubits\n",
455 | "simon_circuit.measure(range(n), range(n))\n",
456 | "simon_circuit.draw('mpl')\n",
457 | "plt.show()\n",
458 | "\n",
459 | "# use local simulator\n",
460 | "backend = BasicAer.get_backend('qasm_simulator')\n",
461 | "shots = 1024\n",
462 | "results = execute(simon_circuit, backend=backend, shots=shots).result()\n",
463 | "counts = results.get_counts()\n",
464 | "plot_histogram(counts)\n",
465 | "\n",
466 | "# Calculate the dot product of the results\n",
467 | "def bdotz(b, z):\n",
468 | " accum = 0\n",
469 | " for i in range(len(b)):\n",
470 | " accum += int(b[i]) * int(z[i])\n",
471 | " return (accum % 2)\n",
472 | "\n",
473 | "print('b = ' + b)\n",
474 | "for z in counts:\n",
475 | " print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), counts[z]*100/shots))\n"
476 | ]
477 | },
478 | {
479 | "cell_type": "markdown",
480 | "metadata": {},
481 | "source": [
482 | "Shor algorithm"
483 | ]
484 | },
485 | {
486 | "cell_type": "code",
487 | "execution_count": null,
488 | "metadata": {},
489 | "outputs": [],
490 | "source": [
491 | "#!pip install 'qiskit==0.19'\n",
492 | "\n",
493 | "#!pip install 'qiskit==0.19'\n",
494 | "#!pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src\n",
495 | "#!pip install sympy\n",
496 | "\n",
497 | "from qiskit import BasicAer\n",
498 | "from qiskit.aqua import QuantumInstance\n",
499 | "from qiskit.aqua.algorithms import Shor\n",
500 | "\n",
501 | "number = Shor(N=15, a=7)\n",
502 | "simulator = BasicAer.get_backend('qasm_simulator')\n",
503 | "results_dictionary = number.run(QuantumInstance(backend=simulator, shots=5))\n",
504 | "#result = results_dictionary['number']\n",
505 | "print(results_dictionary)"
506 | ]
507 | },
508 | {
509 | "cell_type": "markdown",
510 | "metadata": {},
511 | "source": [
512 | "Grover's algorithm "
513 | ]
514 | },
515 | {
516 | "cell_type": "code",
517 | "execution_count": null,
518 | "metadata": {},
519 | "outputs": [],
520 | "source": [
521 | "#!pip install 'qiskit==0.19'\n",
522 | "\n",
523 | "'''\n",
524 | "Grover's two-qubit search algorithm.\n",
525 | "'''\n",
526 | "from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, BasicAer\n",
527 | "from qiskit.visualization import plot_histogram\n",
528 | "import matplotlib.pyplot as plt\n",
529 | "\n",
530 | "c = ClassicalRegister(2, 'c')\n",
531 | "q = QuantumRegister(2,'q')\n",
532 | "qc = QuantumCircuit(q,c)\n",
533 | "\n",
534 | "qc.h([q[0]])\n",
535 | "qc.h([q[1]])\n",
536 | "\n",
537 | "qc.x([q[0]])\n",
538 | "qc.x([q[1]])\n",
539 | "\n",
540 | "qc.cz(0,1)\n",
541 | "\n",
542 | "qc.x([q[0]])\n",
543 | "qc.x([q[1]])\n",
544 | "\n",
545 | "qc.h([q[0]])\n",
546 | "qc.h([q[1]])\n",
547 | "\n",
548 | "qc.z(q[0])\n",
549 | "qc.z(q[1])\n",
550 | "\n",
551 | "qc.cz(0,1)\n",
552 | "\n",
553 | "qc.h([q[0]])\n",
554 | "qc.h([q[1]])\n",
555 | "\n",
556 | "qc.measure(q[0], c[0])\n",
557 | "qc.measure(q[1], c[1])\n",
558 | "qc.draw('mpl')\n",
559 | "plt.show()\n",
560 | "\n",
561 | "simulator = BasicAer.get_backend('qasm_simulator')\n",
562 | "job = execute(qc, simulator, shots=1024)\n",
563 | "result = job.result()\n",
564 | "count = result.get_counts(qc)\n",
565 | "plot_histogram(count)\n",
566 | "plt.show()"
567 | ]
568 | }
569 | ],
570 | "metadata": {
571 | "kernelspec": {
572 | "display_name": "Python 3",
573 | "language": "python",
574 | "name": "python3"
575 | },
576 | "language_info": {
577 | "codemirror_mode": {
578 | "name": "ipython",
579 | "version": 3
580 | },
581 | "file_extension": ".py",
582 | "mimetype": "text/x-python",
583 | "name": "python",
584 | "nbconvert_exporter": "python",
585 | "pygments_lexer": "ipython3",
586 | "version": "3.7.6"
587 | }
588 | },
589 | "nbformat": 4,
590 | "nbformat_minor": 4
591 | }
592 |
--------------------------------------------------------------------------------
/Chapter06/ch-6.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 6"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "#!pip install nashpy\n",
17 | "\n",
18 | "\n",
19 | "#Prisoner's dilemma using nashpy and numpy\n",
20 | "\n",
21 | "import nashpy as nash\n",
22 | "import numpy as np\n",
23 | "\n",
24 | "Alice = np.array([[3, 1], [4, 2]])\n",
25 | "Bob = np.array([[3, 4], [1, 2]])\n",
26 | "\n",
27 | "prisoner_dilemma = nash.Game(Alice, Bob)\n",
28 | "print(prisoner_dilemma)\n",
29 | "\n",
30 | "\n",
31 | "#calculate utilities\n",
32 | "Alice_sigma = np.array([1, 0])\n",
33 | "Bob_sigma = np.array([1, 0])\n",
34 | "print(prisoner_dilemma[Alice_sigma, Bob_sigma])\n",
35 | "\n",
36 | "# Calculate Nash equilibrium\n",
37 | "for eq in prisoner_dilemma.support_enumeration():\n",
38 | " print(eq)"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": null,
44 | "metadata": {},
45 | "outputs": [],
46 | "source": [
47 | "# !pip install nashpy\n",
48 | "\n",
49 | "# Battle of sexes using nashpy and numpy\n",
50 | "\n",
51 | "import nashpy as nash\n",
52 | "import numpy as np\n",
53 | "\n",
54 | "Alice = np.array([[2, 1], [1, 2]])\n",
55 | "Bob = np.array([[3, 1], [1, 3]])\n",
56 | "\n",
57 | "battle_sexes= nash.Game(Alice, Bob)\n",
58 | "print(battle_sexes)\n",
59 | "\n",
60 | "#calculate utilities\n",
61 | "Alice_sigma = np.array([1, 0])\n",
62 | "Bob_sigma = np.array([1, 0])\n",
63 | "print(battle_sexes[Alice_sigma, Bob_sigma])\n",
64 | "\n",
65 | "# Calculate Nash equilibrium\n",
66 | "for eq in battle_sexes.support_enumeration():\n",
67 | " print(eq)"
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": null,
73 | "metadata": {},
74 | "outputs": [],
75 | "source": [
76 | "# !pip install nashpy\n",
77 | "\n",
78 | "# Matching pennies using nashpy and numpy\n",
79 | "\n",
80 | "import nashpy as nash\n",
81 | "import numpy as np\n",
82 | "\n",
83 | "Alice = np.array([[1, -1], [-1, 1]])\n",
84 | "Bob = np.array([[-1, 1], [1, -1]])\n",
85 | "\n",
86 | "missing_pennies= nash.Game(Alice, Bob)\n",
87 | "print(missing_pennies)\n",
88 | "\n",
89 | "#calculate utilities\n",
90 | "Alice_sigma = np.array([1, 0])\n",
91 | "Bob_sigma = np.array([1, 0])\n",
92 | "print(missing_pennies[Alice_sigma, Bob_sigma])\n",
93 | "\n",
94 | "# Calculate Nash equilibrium\n",
95 | "for eq in missing_pennies.support_enumeration():\n",
96 | " print(eq)"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "metadata": {},
103 | "outputs": [],
104 | "source": [
105 | "# !pip install nashpy \n",
106 | "\n",
107 | "#Rock-paper-scissors game using nashpy and numpy\n",
108 | "\n",
109 | "import nashpy as nash\n",
110 | "import numpy as np\n",
111 | "\n",
112 | "Alice = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]])\n",
113 | "Bob = np.array([[0, 1, -1], [-1, 0, 1], [1, -1, 0]])\n",
114 | "\n",
115 | "rock_paper_scissors = nash.Game(Alice, Bob)\n",
116 | "print(rock_paper_scissors)\n",
117 | "\n",
118 | "#calculate utilities\n",
119 | "Alice_sigma = np.array([0, 0, 1])\n",
120 | "Bob_sigma = np.array([0, 1, 0])\n",
121 | "\n",
122 | "#calculate Nash equilibrium\n",
123 | "for eq in rock_paper_scissors.support_enumeration():\n",
124 | " print(eq) "
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": null,
130 | "metadata": {},
131 | "outputs": [],
132 | "source": [
133 | "#Implementation of the CHSH game \n",
134 | "#!pip install qiskit\n",
135 | "\n",
136 | "from qiskit import *\n",
137 | "#from qiskit.tools.visualization import *\n",
138 | "import numpy as np\n",
139 | "#import matplotlib.pyplot as plt\n",
140 | "\n",
141 | "np.random.seed(42)\n",
142 | "\n",
143 | "def CHSH_circuit(x,y):\n",
144 | " a0=0 \n",
145 | " a1=np.pi/2\n",
146 | " b0=np.pi/4\n",
147 | " b1=-np.pi/4\n",
148 | " \n",
149 | " circ = QuantumCircuit(2,2) \n",
150 | " \n",
151 | " circ.h(0)\n",
152 | " circ.cx(0,1)\n",
153 | " \n",
154 | " if(x==0):\n",
155 | " circ.ry(a0,0)\n",
156 | " else:\n",
157 | " circ.ry(a1,0)\n",
158 | "\n",
159 | " if(y==0):\n",
160 | " circ.ry(b0,1)\n",
161 | " else:\n",
162 | " circ.ry(b1,1)\n",
163 | " \n",
164 | " circ.measure([0,1], [0,1]) \n",
165 | " return circ\n",
166 | "\n",
167 | "def winning_probability(backend, shots):\n",
168 | " a0=0\n",
169 | " a1=np.pi/2 \n",
170 | " b0=np.pi/4\n",
171 | " b1=-np.pi/4\n",
172 | " total = 0\n",
173 | " circuits = [CHSH_circuit(0,0), CHSH_circuit(0,1), CHSH_circuit(1,0), CHSH_circuit(1,1)] \n",
174 | " job = execute(circuits, backend=backend, shots = shots)\n",
175 | " \n",
176 | " for qc in circuits[0:3]:\n",
177 | " counts = job.result().get_counts(qc)\n",
178 | " if('00' in counts):\n",
179 | " total += counts['00']\n",
180 | " if('11' in counts):\n",
181 | " total += counts['11']\n",
182 | " \n",
183 | " counts = job.result().get_counts(circuits[3])\n",
184 | " if('01' in counts):\n",
185 | " total += counts['01']\n",
186 | " if('10' in counts):\n",
187 | " total += counts['10']\n",
188 | " \n",
189 | " return total/(4*shots) \n",
190 | "\n",
191 | "backend = Aer.get_backend('qasm_simulator')\n",
192 | "\n",
193 | "print(winning_probability(backend, shots=1024))"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": null,
199 | "metadata": {},
200 | "outputs": [],
201 | "source": [
202 | "#Implementation of the GHZ game \n",
203 | "#!pip install qiskit\n",
204 | "\n",
205 | "from qiskit import *\n",
206 | "import numpy as np\n",
207 | "\n",
208 | "np.random.seed(42)\n",
209 | "\n",
210 | "def ghz_circuit(x, y, z):\n",
211 | " circ = QuantumCircuit(3,3)\n",
212 | " circ.h(0)\n",
213 | " circ.cx(0,1)\n",
214 | " circ.cx(0,2)\n",
215 | " \n",
216 | " #circ.sdg(0)\n",
217 | " circ.h(0)\n",
218 | " #circ.sdg(1)\n",
219 | " circ.h(1)\n",
220 | " #circ.sdg(2)\n",
221 | " circ.h(2)\n",
222 | "\n",
223 | " if(x == 0):\n",
224 | " circ.z(0)\n",
225 | " if(x== 1): \n",
226 | " circ.x(0)\n",
227 | " if(y == 0):\n",
228 | " circ.z(1)\n",
229 | " if(y== 1): \n",
230 | " circ.x(1)\n",
231 | " if(z == 0):\n",
232 | " circ.z(2)\n",
233 | " if(z== 1):\n",
234 | " circ.x(2)\n",
235 | " circ.measure([0,1,2], [0,1,2])\n",
236 | " return circ\n",
237 | "\n",
238 | "circuits = [ghz_circuit(0,0,0), ghz_circuit(0,1,1), ghz_circuit(1,0,1), ghz_circuit(1,1,0)] \n",
239 | "backend = Aer.get_backend('qasm_simulator')\n",
240 | "job = execute(circuits, backend=backend, shots = 1024)\n",
241 | "result = job.result()\n",
242 | "\n",
243 | "\n",
244 | "\n",
245 | "def winning_probability(backend, shots):\n",
246 | " total = 0\n",
247 | " circuits = [ghz_circuit(0,0,0), ghz_circuit(0,1,1), ghz_circuit(1,0,1), ghz_circuit(1,1,0)] \n",
248 | " job = execute(circuits, backend=backend, shots = shots)\n",
249 | " \n",
250 | " for qc in circuits[0:3]:\n",
251 | " counts = job.result().get_counts(qc)\n",
252 | " if('000' in counts):\n",
253 | " total += counts['000']\n",
254 | " if('110' in counts):\n",
255 | " total += counts['110']\n",
256 | " \n",
257 | " #counts = job.result().get_counts(circuits[3])\n",
258 | " if('011' in counts):\n",
259 | " total += counts['011']\n",
260 | " if('101' in counts):\n",
261 | " total += counts['101']\n",
262 | " \n",
263 | " return total/(4*shots) \n",
264 | "\n",
265 | "backend = Aer.get_backend('qasm_simulator')\n",
266 | "\n",
267 | "print(winning_probability(backend, shots=8000))\n"
268 | ]
269 | },
270 | {
271 | "cell_type": "code",
272 | "execution_count": null,
273 | "metadata": {},
274 | "outputs": [],
275 | "source": [
276 | "#modified GHZ\n",
277 | "\n",
278 | "from qiskit import *\n",
279 | "import numpy as np\n",
280 | "\n",
281 | "np.random.seed(42)\n",
282 | "\n",
283 | "def ghz_circuit(x,y,z):\n",
284 | " circ = QuantumCircuit(3,3)\n",
285 | " circ.h(0)\n",
286 | " circ.cx(0,1)\n",
287 | " circ.cx(0,2)\n",
288 | "\n",
289 | " #circ.h(0)\n",
290 | " #circ.h(1)\n",
291 | " #circ.h(2)\n",
292 | "\n",
293 | " \n",
294 | " if(x,y,z == 0,0,0):\n",
295 | " circ.h(0)\n",
296 | " circ.h(1)\n",
297 | " circ.h(2)\n",
298 | " if(x,y,z == 0,1,1):\n",
299 | " circ.h(0)\n",
300 | " circ.sdg(1)\n",
301 | " circ.h(1)\n",
302 | " if(x,y,z == 1,0,1):\n",
303 | " circ.sdg(0)\n",
304 | " circ.h(0)\n",
305 | " circ.h(1)\n",
306 | " circ.sdg(2)\n",
307 | " circ.h(2)\n",
308 | " if(x,y,z==1,1,0):\n",
309 | " circ.sdg(0)\n",
310 | " circ.h(0)\n",
311 | " circ.sdg(1)\n",
312 | " circ.h(1)\n",
313 | " circ.h(2)\n",
314 | "\n",
315 | " circ.measure([0,1,2], [0,1,2])\n",
316 | " return circ\n",
317 | "\n",
318 | "circuits = [ghz_circuit(0,0,0), ghz_circuit(0,1,1), ghz_circuit(1,0,1), ghz_circuit(1,1,0)] \n",
319 | "backend = Aer.get_backend('qasm_simulator')\n",
320 | "job = execute(circuits, backend=backend, shots = 1024)\n",
321 | "result = job.result()\n",
322 | "\n",
323 | "\n",
324 | "\n",
325 | "def winning_probability(backend, shots):\n",
326 | " total = 0\n",
327 | " circuits = [ghz_circuit(0,0,0), ghz_circuit(0,1,1), ghz_circuit(1,0,1), ghz_circuit(1,1,0)] \n",
328 | " job = execute(circuits, backend=backend, shots = shots)\n",
329 | " \n",
330 | " for qc in circuits[0:3]:\n",
331 | " counts = job.result().get_counts(qc)\n",
332 | " print(counts)\n",
333 | " if('000' in counts):\n",
334 | " total += counts['000']\n",
335 | " if('110' in counts):\n",
336 | " total += counts['110']\n",
337 | " \n",
338 | " #counts = job.result().get_counts(circuits[3])\n",
339 | " if('011' in counts):\n",
340 | " total += counts['011']\n",
341 | " if('101' in counts):\n",
342 | " total += counts['101']\n",
343 | " print(shots)\n",
344 | " print(total)\n",
345 | " return total/(shots) \n",
346 | "\n",
347 | "backend = Aer.get_backend('qasm_simulator')\n",
348 | "\n",
349 | "print(winning_probability(backend, shots=8000))"
350 | ]
351 | },
352 | {
353 | "cell_type": "code",
354 | "execution_count": null,
355 | "metadata": {},
356 | "outputs": [],
357 | "source": [
358 | "#Modified GHZ - 2\n",
359 | "\n",
360 | "from qiskit import *\n",
361 | "from qiskit.visualization import plot_histogram\n",
362 | "import numpy as np\n",
363 | "import matplotlib.pyplot as plt\n",
364 | "\n",
365 | "np.random.seed(42)\n",
366 | "\n",
367 | "circ = QuantumCircuit(3,3)\n",
368 | "circ.h(0)\n",
369 | "circ.cx(0,1)\n",
370 | "circ.cx(0,2)\n",
371 | " \n",
372 | "circ.h(0)\n",
373 | "circ.h(1)\n",
374 | "circ.h(2)\n",
375 | "circ.measure([0,1,2], [0,1,2])\n",
376 | "#circ.draw(output='text')\n",
377 | "#plt.show()\n",
378 | " \n",
379 | "backend = Aer.get_backend('qasm_simulator')\n",
380 | "shots= 1024\n",
381 | "job = execute(circ, backend=backend, shots = shots)\n",
382 | "result = job.result()\n",
383 | "count = result.get_counts(circ)\n",
384 | "plot_histogram(count)\n",
385 | "#print(count)\n",
386 | "\n",
387 | "total = 0\n",
388 | "if('000' in count):\n",
389 | " total += count['000']\n",
390 | "if('011' in count):\n",
391 | " total += count['011']\n",
392 | "if('101' in count):\n",
393 | " total += count['101']\n",
394 | "if('110' in count):\n",
395 | " total += count['110']\n",
396 | "#print(total)\n",
397 | "#print(shots)\n",
398 | "probability_winning = total/shots\n",
399 | "print(\"Probability of winning is:\", probability_winning)\n",
400 | "plt.show()"
401 | ]
402 | }
403 | ],
404 | "metadata": {
405 | "kernelspec": {
406 | "display_name": "Python 3",
407 | "language": "python",
408 | "name": "python3"
409 | },
410 | "language_info": {
411 | "codemirror_mode": {
412 | "name": "ipython",
413 | "version": 3
414 | },
415 | "file_extension": ".py",
416 | "mimetype": "text/x-python",
417 | "name": "python",
418 | "nbconvert_exporter": "python",
419 | "pygments_lexer": "ipython3",
420 | "version": "3.7.6"
421 | }
422 | },
423 | "nbformat": 4,
424 | "nbformat_minor": 4
425 | }
426 |
--------------------------------------------------------------------------------
/Chapter07/ch-7.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 7 Quantum Cryptography"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "#Caesar's cipher \n",
17 | "message = \"YES\"\n",
18 | "\n",
19 | "shift = 3 \n",
20 | "\n",
21 | "encryption = \"\"\n",
22 | "\n",
23 | "for c in message:\n",
24 | "\n",
25 | " # check if character is an uppercase letter\n",
26 | " if c.isupper():\n",
27 | "\n",
28 | " # find the position in 0-25\n",
29 | " c_unicode = ord(c)\n",
30 | "\n",
31 | " c_index = ord(c) - ord(\"A\")\n",
32 | "\n",
33 | " # perform the shift\n",
34 | " new_index = (c_index + shift) % 26\n",
35 | "\n",
36 | " # convert to new character\n",
37 | " new_unicode = new_index + ord(\"A\")\n",
38 | "\n",
39 | " new_character = chr(new_unicode)\n",
40 | "\n",
41 | " # append to encrypted string\n",
42 | " encryption = encryption + new_character\n",
43 | "\n",
44 | " else:\n",
45 | "\n",
46 | " # since character is not uppercase, leave it as it is\n",
47 | " encryption += c\n",
48 | " \n",
49 | "print(\"Plain text:\", message)\n",
50 | "\n",
51 | "print(\"Encrypted text:\", encryption)"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": null,
57 | "metadata": {},
58 | "outputs": [],
59 | "source": [
60 | "# One Time Pad (Vernmam Cipher)\n",
61 | "\n",
62 | "key = 5\n",
63 | "message = \"HELLO\"\n",
64 | "encrypt = \"\"\n",
65 | "\n",
66 | "for i in range(len(message)):\n",
67 | " letter = ord(message[i])-65 # Letters now range 0-25\n",
68 | " letter = (letter + key)%25 # Alphanumeric + key mod 25 = 0-25\n",
69 | " letter +=65\n",
70 | " \n",
71 | "\n",
72 | " encrypt = encrypt + chr(letter)\n",
73 | "\n",
74 | "print(\"Original message is:\", message) \n",
75 | "print(\"Encrypted message is:\", encrypt)"
76 | ]
77 | },
78 | {
79 | "cell_type": "code",
80 | "execution_count": null,
81 | "metadata": {},
82 | "outputs": [],
83 | "source": [
84 | "# A Diffie-Hellman Key Exchange Scheme\n",
85 | "\n",
86 | "import math \n",
87 | "\n",
88 | "p = input(\"Enter the shared prime number: \\n\")\n",
89 | "p = int(p)\n",
90 | "g = input(\"Enter the shared base: \\n\")\n",
91 | "g = int(g)\n",
92 | "\n",
93 | "\n",
94 | "a = input(\"Enter Alice's secret key: \\n\")\n",
95 | "a = int(a)\n",
96 | "b = input(\"Enter Bob's secret key: \\n\")\n",
97 | "b = int(b)\n",
98 | "\n",
99 | "AlicePublicKey = (g ** a ) % p\n",
100 | "BobPublicKey = (g ** b) % p\n",
101 | "\n",
102 | "AliceSecret = (BobPublicKey ** a) % p\n",
103 | "BobSecret = (AlicePublicKey ** b) % p\n",
104 | "\n",
105 | "print(AliceSecret)\n",
106 | "print(BobSecret)"
107 | ]
108 | },
109 | {
110 | "cell_type": "code",
111 | "execution_count": null,
112 | "metadata": {},
113 | "outputs": [],
114 | "source": [
115 | "#A simple pseudorandom number generator.\n",
116 | "\n",
117 | "import random\n",
118 | "\n",
119 | "random.seed(42) \n",
120 | "\n",
121 | "x = []\n",
122 | "y = [] \n",
123 | "\n",
124 | "for i in range(10):\n",
125 | " a = random.random()\n",
126 | " x.append(a)\n",
127 | "\n",
128 | "print(x)\n",
129 | "\n",
130 | "for i in range(5):\n",
131 | " b = random.randint(0,4)\n",
132 | " y.append(b)\n",
133 | "\n",
134 | "print(y)"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": null,
140 | "metadata": {},
141 | "outputs": [],
142 | "source": [
143 | "# MD5 hashing\n",
144 | "\n",
145 | "import hashlib\n",
146 | "\n",
147 | "AliceMessage = hashlib.md5()\n",
148 | "Alice = \"This is Alice\"\n",
149 | "Alice = Alice.encode(encoding='utf-8')\n",
150 | "AliceMessage.update(Alice)\n",
151 | "print(\"Alice's MD5 digest is: \\n\", AliceMessage.hexdigest())\n",
152 | "\n",
153 | "print(\"Alice's digest size is: \\n\", AliceMessage.digest_size)\n",
154 | "print(\"Alice's block size is: \\n\", AliceMessage.block_size)\n",
155 | "\n",
156 | "BobMessage = hashlib.md5()\n",
157 | "Bob = \"This is Bob\"\n",
158 | "Bob = Bob.encode(encoding='utf-8')\n",
159 | "BobMessage.update(Bob)\n",
160 | "print(\"Bob's MD5 digest is: \\n\", BobMessage.hexdigest())\n",
161 | "\n",
162 | "print(\"Bob's digest size is: \\n\", BobMessage.digest_size)\n",
163 | "print(\"Bob's block size is: \\n\", BobMessage.block_size)"
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": null,
169 | "metadata": {},
170 | "outputs": [],
171 | "source": [
172 | "# SHA-512 hashing\n",
173 | "\n",
174 | "import hashlib\n",
175 | "\n",
176 | "AliceMessage = hashlib.sha3_512()\n",
177 | "Alice = \"This is Alice\"\n",
178 | "Alice = Alice.encode(encoding='utf-8')\n",
179 | "AliceMessage.update(Alice)\n",
180 | "print(\"Alice's SHA digest is: \\n\", AliceMessage.hexdigest())\n",
181 | "\n",
182 | "print(\"Alice's digest size is: \\n\", AliceMessage.digest_size)\n",
183 | "print(\"Alice's block size is: \\n\", AliceMessage.block_size)\n",
184 | "\n",
185 | "BobMessage = hashlib.sha3_512()\n",
186 | "Bob = \"This is Bob\"\n",
187 | "Bob = Bob.encode(encoding='utf-8')\n",
188 | "BobMessage.update(Bob)\n",
189 | "print(\"Bob's SHA digest is: \\n\", BobMessage.hexdigest())\n",
190 | "\n",
191 | "print(\"Bob's digest size is: \\n\", BobMessage.digest_size)\n",
192 | "print(\"Bob's block size is: \\n\", BobMessage.block_size)"
193 | ]
194 | },
195 | {
196 | "cell_type": "code",
197 | "execution_count": null,
198 | "metadata": {},
199 | "outputs": [],
200 | "source": [
201 | "# 5-qubit QRNG \n",
202 | "\n",
203 | "#!pip install qiskit \n",
204 | "\n",
205 | "import random\n",
206 | "from qiskit import *\n",
207 | "from qiskit.visualization import plot_histogram\n",
208 | "\n",
209 | "random.seed(42)\n",
210 | "\n",
211 | "circuit = QuantumCircuit(5,5)\n",
212 | "\n",
213 | "circuit.h(0)\n",
214 | "\n",
215 | "circuit.x(1)\n",
216 | "circuit.h(1)\n",
217 | "\n",
218 | "circuit.h(2)\n",
219 | "\n",
220 | "circuit.x(3)\n",
221 | "circuit.h(3)\n",
222 | "\n",
223 | "circuit.h(4)\n",
224 | "\n",
225 | "circuit.measure([0,1,2,3,4], [0,1,2,3,4])\n",
226 | "circuit.draw(output='text')\n",
227 | "\n",
228 | "simulator = Aer.get_backend('qasm_simulator')\n",
229 | "result = execute(circuit, backend=simulator, shots=1024).result()\n",
230 | "plot_histogram(result.get_counts(circuit))"
231 | ]
232 | },
233 | {
234 | "cell_type": "code",
235 | "execution_count": null,
236 | "metadata": {},
237 | "outputs": [],
238 | "source": [
239 | "#Implementation of the BB84 Protocol\n",
240 | "\n",
241 | "from qiskit import QuantumCircuit, execute, Aer \n",
242 | "from qiskit.visualization import *\n",
243 | "#from qiskit.tools.monitor import *\n",
244 | "import matplotlib.pyplot as plt\n",
245 | "import numpy as np\n",
246 | "\n",
247 | "np.random.seed(42)\n",
248 | "\n",
249 | "circ = QuantumCircuit(1,1)\n",
250 | "circ.x(0)\n",
251 | "circ.barrier()\n",
252 | "circ.h(0) \n",
253 | "circ.barrier()\n",
254 | "circ.measure(0,0) \n",
255 | "circ.barrier()\n",
256 | "circ.draw(output='mpl')\n",
257 | "\n",
258 | "\n",
259 | "\n",
260 | "# Alice generates n random bits (some of these bits will form the key)\n",
261 | "backend = Aer.get_backend('qasm_simulator')\n",
262 | "result = execute(circ, backend, shots=128, memory = True).result()\n",
263 | "bits_alice = [int(q) for q in result.get_memory()] \n",
264 | "print(bits_alice)\n",
265 | "\n",
266 | "# Alice randomly chooses the bases in which she is going to measure\n",
267 | "#backend = Aer.get_backend('qasm_simulator')\n",
268 | "result = execute(circ, backend, shots=128, memory = True).result()\n",
269 | "basis_alice = [int(q) for q in result.get_memory()] \n",
270 | "print(basis_alice)\n",
271 | "\n",
272 | "# Bob also chooses at random the bases in which he will measure\n",
273 | "result = execute(circ, backend, shots=128, memory = True).result()\n",
274 | "basis_bob = [int(q) for q in result.get_memory()] \n",
275 | "print(basis_bob)\n",
276 | "\n",
277 | "# Now, Alice codes each bit of her initial string as a qubit and sends it to Bob, who measures in his basis\n",
278 | "\n",
279 | "bits_bob = []\n",
280 | "\n",
281 | "for i in range(128):\n",
282 | " circ_send = QuantumCircuit(1,1)\n",
283 | " if bits_alice[i]: \n",
284 | " circ_send.x(0)\n",
285 | " if basis_alice[i]: \n",
286 | " circ_send.h(0)\n",
287 | " \n",
288 | " # Alice sends the qubit to Bob and he measures\n",
289 | " \n",
290 | " if basis_bob[i]: \n",
291 | " circ_send.h(0) \n",
292 | " \n",
293 | " circ_send.measure(0,0)\n",
294 | " \n",
295 | " result = execute(circ_send, backend, shots = 1, memory = True).result()\n",
296 | " bits_bob.append(int(result.get_memory()[0]))\n",
297 | " \n",
298 | "print(bits_bob)\n",
299 | "\n",
300 | "# Bob tells Alice the basis he used for his measurements \n",
301 | "# Alice confirms which of the basis are correct\n",
302 | "\n",
303 | "key = []\n",
304 | "\n",
305 | "for i in range(128):\n",
306 | " if basis_alice[i] == basis_bob[i]:\n",
307 | " key.append(bits_bob[i])\n",
308 | " \n",
309 | "print(\"Key length\", len(key))\n",
310 | "print(key)"
311 | ]
312 | },
313 | {
314 | "cell_type": "code",
315 | "execution_count": null,
316 | "metadata": {},
317 | "outputs": [],
318 | "source": [
319 | "#The implementation of the B92 protocol\n",
320 | "\n",
321 | "from qiskit import QuantumCircuit, execute, Aer \n",
322 | "from qiskit.visualization import *\n",
323 | "#from qiskit.tools.monitor import *\n",
324 | "import matplotlib.pyplot as plt\n",
325 | "import numpy as np\n",
326 | "\n",
327 | "np.random.seed(42)\n",
328 | "\n",
329 | "circ = QuantumCircuit(1,1)\n",
330 | "circ.x(0)\n",
331 | "circ.barrier()\n",
332 | "circ.h(0) \n",
333 | "circ.barrier()\n",
334 | "circ.measure(0,0) \n",
335 | "circ.barrier()\n",
336 | "circ.draw(output='text')\n",
337 | "\n",
338 | "n = 128\n",
339 | "\n",
340 | "# Alice generates n random bits (some of these bits will form the key)\n",
341 | "backend = Aer.get_backend('qasm_simulator')\n",
342 | "result = execute(circ, backend, shots=n, memory = True).result()\n",
343 | "bits_alice = [int(q) for q in result.get_memory()] \n",
344 | "print(bits_alice)\n",
345 | "\n",
346 | "# Bob also chooses at random the bases in which he will measure\n",
347 | "result = execute(circ, backend, shots=n, memory = True).result()\n",
348 | "basis_bob = [int(q) for q in result.get_memory()] \n",
349 | "print(basis_bob)\n",
350 | "\n",
351 | "bits_bob = []\n",
352 | "for i in range(n):\n",
353 | " circ_send = QuantumCircuit(1,1)\n",
354 | " if bits_alice[i] == 0: #Don't change the basis\n",
355 | " circ_send.id(0)\n",
356 | " if bits_alice[i] == 1: #Change the basis\n",
357 | " circ_send.h(0)\n",
358 | " else:\n",
359 | " circ_send.id(0)\n",
360 | " circ_send.measure(0,0)\n",
361 | " \n",
362 | " result = execute(circ_send, backend, shots = 1, memory = True).result()\n",
363 | " bits_bob.append(int(result.get_memory()[0]))\n",
364 | "\n",
365 | "print(bits_bob)\n",
366 | "\n",
367 | "key = []\n",
368 | "\n",
369 | "for i in range(n):\n",
370 | " if bits_alice[i] == bits_bob[i]:\n",
371 | " key.append(bits_bob[i])\n",
372 | " \n",
373 | "print(\"Key length is:\", len(key))\n",
374 | "print(\"The secret Key is:\", key)"
375 | ]
376 | },
377 | {
378 | "cell_type": "code",
379 | "execution_count": null,
380 | "metadata": {},
381 | "outputs": [],
382 | "source": [
383 | "#Implementation of the E91 protocol\n",
384 | "from qiskit import *\n",
385 | "#from qiskit.visualization import *\n",
386 | "\n",
387 | "import numpy as np\n",
388 | "import matplotlib.pyplot as plt\n",
389 | "\n",
390 | "np.random.seed(42)\n",
391 | "\n",
392 | "A = [0, np.pi/8, np.pi/4] #choice of bases for Alice\n",
393 | "B = [0, np.pi/8, -1*np.pi/8] #choice of bases for Bob\n",
394 | "basesA = []\n",
395 | "basesB = []\n",
396 | "output = []\n",
397 | "\n",
398 | "for i in range(100):\n",
399 | " \n",
400 | " circ = QuantumCircuit(2, 2)\n",
401 | " circ.h(0)\n",
402 | " circ.cx(0,1) \n",
403 | " Ta = np.random.choice(A)\n",
404 | " Tb = np.random.choice(B)\n",
405 | " circ.rz(Ta, 0)\n",
406 | " circ.rz(Tb, 1)\n",
407 | " circ.measure([0, 1], [0, 1])\n",
408 | " #circ.draw(output = 'text')\n",
409 | " \n",
410 | " backend = Aer.get_backend('qasm_simulator')\n",
411 | " result = execute(circ, backend, shots=1, memory=True).result()\n",
412 | " value = result.get_memory()\n",
413 | " output.append(value)\n",
414 | "\n",
415 | "print(\"The output is:\", output)"
416 | ]
417 | },
418 | {
419 | "cell_type": "code",
420 | "execution_count": null,
421 | "metadata": {},
422 | "outputs": [],
423 | "source": [
424 | "#postquantum implementation - NewHope\n",
425 | "\n",
426 | "#!pip install pynewhope \n",
427 | "\n",
428 | "'''\n",
429 | "The code is adopted from: \n",
430 | "https://pypi.org/project/PyNewHope/\n",
431 | "'''\n",
432 | "from pynewhope import newhope\n",
433 | "import numpy as np\n",
434 | "\n",
435 | "np.random.seed(42)\n",
436 | "\n",
437 | "# Step 1: Alice generates random keys and her public msg to Bob\n",
438 | "ka, ma = newhope.keygen()\n",
439 | "\n",
440 | "# Step 2: Bob receives the msg from Alice and responds to Alice with a msg\n",
441 | "skb, mb = newhope.sharedB(ma)\n",
442 | "\n",
443 | "# Step 3: Alice receives the msg from Bob and generates her shared secret\n",
444 | "ska = newhope.sharedA(mb, ka)\n",
445 | "\n",
446 | "if ska == skb:\n",
447 | " print(\"\\nSuccessful key exchange! Keys match.\")\n",
448 | "else:\n",
449 | " print(\"\\nError! Keys do not match.\")\n",
450 | "\n",
451 | "print(\"The shared key is:\", ska)"
452 | ]
453 | },
454 | {
455 | "cell_type": "code",
456 | "execution_count": null,
457 | "metadata": {},
458 | "outputs": [],
459 | "source": [
460 | "#SPHINCS implementation - postquantum technique\n",
461 | "#!pip install pyspx\n",
462 | "\n",
463 | "'''\n",
464 | "This code is adopted from: \n",
465 | "https://cryptobook.nakov.com/quantum-safe-cryptography/quantum-safe-signatures-example\n",
466 | "'''\n",
467 | "\n",
468 | "import pyspx.shake256_128s as sphincs\n",
469 | "import os, binascii\n",
470 | "import numpy as np\n",
471 | "\n",
472 | "np.random.seed(42)\n",
473 | "\n",
474 | "# Key generation: private + public key\n",
475 | "seed = os.urandom(sphincs.crypto_sign_SEEDBYTES)\n",
476 | "public_key, secret_key = sphincs.generate_keypair(seed)\n",
477 | "\n",
478 | "# Sign message and verify signature\n",
479 | "message = b'Hello World'\n",
480 | "signature = sphincs.sign(message, secret_key)\n",
481 | "valid = sphincs.verify(message, signature, public_key)\n",
482 | "\n",
483 | "# Verify tampered message + signature\n",
484 | "message = b'Hello World'\n",
485 | "valid = sphincs.verify(message, signature, public_key)\n",
486 | "print(\"Tampered message:\", message)\n",
487 | "print(\"Tampered signature valid?\", valid)\n",
488 | "\n",
489 | "message = b'Bye World'\n",
490 | "valid = sphincs.verify(message, signature, public_key)\n",
491 | "print(\"Tampered message:\", message)\n",
492 | "print(\"Tampered signature valid?\", valid)"
493 | ]
494 | }
495 | ],
496 | "metadata": {
497 | "kernelspec": {
498 | "display_name": "Python 3",
499 | "language": "python",
500 | "name": "python3"
501 | },
502 | "language_info": {
503 | "codemirror_mode": {
504 | "name": "ipython",
505 | "version": 3
506 | },
507 | "file_extension": ".py",
508 | "mimetype": "text/x-python",
509 | "name": "python",
510 | "nbconvert_exporter": "python",
511 | "pygments_lexer": "ipython3",
512 | "version": "3.7.6"
513 | }
514 | },
515 | "nbformat": 4,
516 | "nbformat_minor": 4
517 | }
518 |
--------------------------------------------------------------------------------
/Chapter08/ch-8.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 8 Code: quantum machine learning "
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "# Implementing MLP using sklearn\n",
17 | "\n",
18 | "import numpy as np\n",
19 | "from sklearn.datasets import load_digits\n",
20 | "from sklearn.model_selection import train_test_split\n",
21 | "from sklearn.neural_network import MLPClassifier\n",
22 | "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
23 | "\n",
24 | "np.random.seed(42)\n",
25 | "\n",
26 | "iris = load_digits()\n",
27 | "X = iris.data\n",
28 | "Y = iris.target\n",
29 | "\n",
30 | "x_train, x_test, y_train, y_test = train_test_split(X,Y, test_size=0.2, random_state=42)\n",
31 | "\n",
32 | "clf = MLPClassifier(alpha=1, max_iter=1000)\n",
33 | "clf.fit(x_train, y_train)\n",
34 | "y_pred = clf.predict(x_test)\n",
35 | "print('Accuracy is:', accuracy_score(y_test, y_pred))\n",
36 | "print('\\nClassification Report is:\\n', classification_report(y_test, y_pred))\n",
37 | "print('\\nConfusion Matrix is:\\n', confusion_matrix(y_test, y_pred))"
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": null,
43 | "metadata": {},
44 | "outputs": [],
45 | "source": [
46 | "#implementing SVM using sklearn\n",
47 | "\n",
48 | "import numpy as np\n",
49 | "import pandas as pd\n",
50 | "import matplotlib.pyplot as plt\n",
51 | "from sklearn.datasets import load_digits\n",
52 | "from sklearn.model_selection import train_test_split\n",
53 | "from sklearn.svm import SVC\n",
54 | "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
55 | "\n",
56 | "np.random.seed(42)\n",
57 | "\n",
58 | "iris = load_digits()\n",
59 | "X = iris.data\n",
60 | "Y = iris.target\n",
61 | "\n",
62 | "x_train, x_test, y_train, y_test = train_test_split(X,Y, test_size=0.2, random_state=42)\n",
63 | "\n",
64 | "clf = SVC(kernel='rbf', gamma = 0.0001, C=1e1)\n",
65 | "clf.fit(x_train, y_train)\n",
66 | "y_pred = clf.predict(x_test)\n",
67 | "print('Accuracy is:', accuracy_score(y_test, y_pred))\n",
68 | "print('\\nClassification Report is:\\n', classification_report(y_test, y_pred))\n",
69 | "print('\\nConfusion Matrix is:\\n', confusion_matrix(y_test, y_pred))"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": null,
75 | "metadata": {},
76 | "outputs": [],
77 | "source": [
78 | "#!pip install qiskit\n",
79 | "\n",
80 | "#QSVM code \n",
81 | "\n",
82 | "#from qsvm_datasets import *\n",
83 | "\n",
84 | "#Chapter 8 - quantum support vector machine\n",
85 | "\n",
86 | "from qiskit import BasicAer\n",
87 | "from qiskit.aqua import QuantumInstance, aqua_globals\n",
88 | "from qiskit.aqua.algorithms import VQC, QSVM\n",
89 | "from qiskit.aqua.components.multiclass_extensions import *\n",
90 | "from qiskit.aqua.components.optimizers import COBYLA\n",
91 | "from qiskit.aqua.components.feature_maps import RawFeatureVector\n",
92 | "#from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_estimator import _QSVM_Estimator\n",
93 | "from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap\n",
94 | "from qiskit.ml.datasets import breast_cancer\n",
95 | "from qiskit.circuit.library import TwoLocal\n",
96 | "\n",
97 | "seed = 42\n",
98 | "aqua_globals.random_seed = seed\n",
99 | "\n",
100 | "feature_dim = 4 # dimension of each data point\n",
101 | "_, training_input, test_input, _ = breast_cancer(training_size=12,\n",
102 | " test_size=4,\n",
103 | " n=feature_dim)\n",
104 | "feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear')\n",
105 | "#feature_map = RawFeatureVector(feature_dimension=feature_dim)\n",
106 | "qsvm = QSVM(feature_map, training_input, test_input)\n",
107 | "\n",
108 | "backend = BasicAer.get_backend('qasm_simulator')\n",
109 | "quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)\n",
110 | "\n",
111 | "result = qsvm.run(quantum_instance)\n",
112 | "\n",
113 | "\n",
114 | "print('Testing accuracy: {:0.2f}'.format(result['testing_accuracy']))"
115 | ]
116 | },
117 | {
118 | "cell_type": "code",
119 | "execution_count": null,
120 | "metadata": {},
121 | "outputs": [],
122 | "source": [
123 | "#!pip install qiskit\n",
124 | "#Chapter 8 - variational quantum classifier \n",
125 | "\n",
126 | "from qiskit import BasicAer\n",
127 | "from qiskit.aqua import QuantumInstance, aqua_globals\n",
128 | "from qiskit.aqua.algorithms import VQC\n",
129 | "from qiskit.aqua.components.optimizers import COBYLA\n",
130 | "from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap\n",
131 | "from qiskit.aqua.components.feature_maps import RawFeatureVector\n",
132 | "from qiskit.ml.datasets import breast_cancer\n",
133 | "from qiskit.circuit.library import TwoLocal\n",
134 | "\n",
135 | "seed = 42\n",
136 | "aqua_globals.random_seed = seed\n",
137 | "\n",
138 | "\n",
139 | "feature_dim = 4 # dimension of each data point\n",
140 | "_, training_input, test_input, _ = breast_cancer(training_size=12,\n",
141 | " test_size=4,\n",
142 | " n=feature_dim)\n",
143 | "\n",
144 | "#feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear')\n",
145 | "feature_map = RawFeatureVector(feature_dimension=feature_dim)\n",
146 | "vqc = VQC(COBYLA(maxiter=1000),\n",
147 | " feature_map,\n",
148 | " TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3),\n",
149 | " training_input,\n",
150 | " test_input)\n",
151 | "\n",
152 | "backend = BasicAer.get_backend('qasm_simulator')\n",
153 | "quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)\n",
154 | "\n",
155 | "result = vqc.run(quantum_instance)\n",
156 | "\n",
157 | "print('Testing accuracy: {:0.2f}'.format(result['testing_accuracy']))"
158 | ]
159 | }
160 | ],
161 | "metadata": {
162 | "kernelspec": {
163 | "display_name": "Python 3",
164 | "language": "python",
165 | "name": "python3"
166 | },
167 | "language_info": {
168 | "codemirror_mode": {
169 | "name": "ipython",
170 | "version": 3
171 | },
172 | "file_extension": ".py",
173 | "mimetype": "text/x-python",
174 | "name": "python",
175 | "nbconvert_exporter": "python",
176 | "pygments_lexer": "ipython3",
177 | "version": "3.7.6"
178 | }
179 | },
180 | "nbformat": 4,
181 | "nbformat_minor": 4
182 | }
183 |
--------------------------------------------------------------------------------
/Chapter09/ch-9.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "Chapter 9 stuff"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "#!pip install strawberryfields\n",
17 | "\n",
18 | "#CV quantum teleportation \n",
19 | "\n",
20 | "# This code is adopted from: https://strawberryfields.ai/photonics/demos/run_teleportation.html\n",
21 | "\n",
22 | "#import modules \n",
23 | "import strawberryfields as sf\n",
24 | "from strawberryfields.ops import *\n",
25 | "import numpy as np\n",
26 | "from numpy import pi, sqrt\n",
27 | "from matplotlib import pyplot as plt\n",
28 | "\n",
29 | "np.random.seed(42) #for reproducibility \n",
30 | "\n",
31 | "prog = sf.Program(3) #initializing the program using three quantum registers\n",
32 | "\n",
33 | "alpha = 1+0.5j\n",
34 | "r = np.abs(alpha)\n",
35 | "phi = np.angle(alpha)\n",
36 | "\n",
37 | "with prog.context as q:\n",
38 | " # prepare initial states\n",
39 | " Coherent(r, phi) | q[0]\n",
40 | " Squeezed(-2) | q[1]\n",
41 | " Squeezed(2) | q[2]\n",
42 | "\n",
43 | " # apply gates\n",
44 | " BS = BSgate(pi/4, pi)\n",
45 | " BS | (q[1], q[2])\n",
46 | " BS | (q[0], q[1])\n",
47 | "\n",
48 | " # Perform homodyne measurements\n",
49 | " MeasureX | q[0]\n",
50 | " MeasureP | q[1]\n",
51 | "\n",
52 | " # Displacement gates conditioned on\n",
53 | " # the measurements\n",
54 | " Xgate(sqrt(2) * q[0].par) | q[2]\n",
55 | " Zgate(sqrt(2) * q[1].par) | q[2]\n",
56 | "\n",
57 | "\n",
58 | "engine = sf.Engine('fock', backend_options={\"cutoff_dim\": 15}) #select backend\n",
59 | "\n",
60 | "result = engine.run(prog, shots=1, modes=None, compile_options={})\n",
61 | "\n",
62 | "# Print results \n",
63 | "print(result.samples)\n",
64 | "print(result.state)\n",
65 | "state = result.state\n",
66 | "\n",
67 | "print(state.dm().shape)\n",
68 | "\n",
69 | "rho2 = np.einsum('kkllij->ij', state.dm())\n",
70 | "print(rho2.shape)\n",
71 | "\n",
72 | "\n",
73 | "probs = np.real_if_close(np.diagonal(rho2))\n",
74 | "print(probs)\n",
75 | "\n",
76 | "\n",
77 | "plt.bar(range(7), probs[:7])\n",
78 | "plt.xlabel('Fock state')\n",
79 | "plt.ylabel('Marginal probability')\n",
80 | "plt.title('Mode 2')\n",
81 | "plt.show()\n",
82 | "\n",
83 | "\n",
84 | "fock_probs = state.all_fock_probs()\n",
85 | "fock_probs.shape\n",
86 | "np.sum(fock_probs, axis=(0,1))"
87 | ]
88 | },
89 | {
90 | "cell_type": "code",
91 | "execution_count": null,
92 | "metadata": {},
93 | "outputs": [],
94 | "source": [
95 | "'''\n",
96 | "This code is adopted from: www.pennylane.ai\n",
97 | "import pennylane as qml\n",
98 | "Continuous-variable qauntum variational algorithm.\n",
99 | "'''\n",
100 | "\n",
101 | "#!pip install pennylane --upgrade\n",
102 | "#!pip install pennylane-qchem\n",
103 | "\n",
104 | "\n",
105 | "import pennylane as qml\n",
106 | "from pennylane import qchem \n",
107 | "from pennylane import numpy as np #use numpy from pennylane instead of the standard numpy\n",
108 | "#from matplotlib import pyplot as plt\n",
109 | "\n",
110 | "np.random.seed(42)\n",
111 | "\n",
112 | "geometry = 'h2.xyz'\n",
113 | "name ='h2'\n",
114 | "charge = 0\n",
115 | "multiplicity=1\n",
116 | "basis= 'sto-3g' \n",
117 | "#h, nr_qubits = qml.qchem.generate_hamiltonian(\n",
118 | "h, nr_qubits = qchem.generate_hamiltonian(\n",
119 | " name,\n",
120 | " geometry,\n",
121 | " charge,\n",
122 | " multiplicity,\n",
123 | " basis,\n",
124 | " mapping='jordan_wigner',\n",
125 | " n_active_orbitals=2,\n",
126 | " n_active_electrons=2,\n",
127 | ")\n",
128 | "\n",
129 | "print(\"Hamiltonian is: \\n\", h)\n",
130 | "print(\"Number of qubits is: \\n\", nr_qubits)\n",
131 | "\n",
132 | "geometry = 'h2.xyz'\n",
133 | "name ='h2'\n",
134 | "charge = 0\n",
135 | "multiplicity=1\n",
136 | "basis= 'sto-3g' \n",
137 | "#h, nr_qubits = qml.qchem.generate_hamiltonian(\n",
138 | "h, nr_qubits = qml.qchem.molecular_hamiltonian(\n",
139 | " name,\n",
140 | " geometry,\n",
141 | " charge,\n",
142 | " multiplicity,\n",
143 | " basis,\n",
144 | " mapping='jordan_wigner',\n",
145 | " n_active_orbitals=2,\n",
146 | " n_active_electrons=2,\n",
147 | ")\n",
148 | "\n",
149 | "print(\"Hamiltonian is: \\n\", h)\n",
150 | "print(\"Number of qubits is: \\n\", nr_qubits)\n",
151 | "\n",
152 | "opt = qml.GradientDescentOptimizer(stepsize=0.4)\n",
153 | "params = np.random.normal(0, np.pi, (nr_qubits, 3))\n",
154 | "\n",
155 | "print(params)\n",
156 | "\n",
157 | "\n",
158 | "max_iterations = 250\n",
159 | "step_size = 0.05\n",
160 | "conv_tol = 1e-06\n",
161 | "\n",
162 | "prev_energy = cost_fn(params)\n",
163 | "for n in range(max_iterations):\n",
164 | " params = opt.step(cost_fn, params)\n",
165 | " energy = cost_fn(params)\n",
166 | " conv = np.abs(energy - prev_energy)\n",
167 | "\n",
168 | "print()\n",
169 | "print('Final convergence parameter = {:.8f} Ha'.format(conv))\n",
170 | "print('Final value of the ground-state energy = {:.8f} Ha'.format(energy))\n",
171 | "print('Accuracy with respect to the FCI energy: {:.8f} Ha ({:.8f} kcal/mol)'.\n",
172 | " format(np.abs(energy - (-1.136189454088)), np.abs(energy - (-1.136189454088))*627.503))\n",
173 | "print()\n",
174 | "print('Final circuit parameters = \\n', params)"
175 | ]
176 | }
177 | ],
178 | "metadata": {
179 | "kernelspec": {
180 | "display_name": "Python 3",
181 | "language": "python",
182 | "name": "python3"
183 | },
184 | "language_info": {
185 | "codemirror_mode": {
186 | "name": "ipython",
187 | "version": 3
188 | },
189 | "file_extension": ".py",
190 | "mimetype": "text/x-python",
191 | "name": "python",
192 | "nbconvert_exporter": "python",
193 | "pygments_lexer": "ipython3",
194 | "version": "3.7.6"
195 | }
196 | },
197 | "nbformat": 4,
198 | "nbformat_minor": 4
199 | }
200 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 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 | # Hands-On Quantum Information Processing with Python
2 |
3 |
4 |
5 | This is the code repository for [Getting Started with Google BERT](https://www.packtpub.com/product/hands-on-quantum-information-processing-with-python/9781800201156?utm_source=github&utm_medium=repository&utm_campaign=9781800201156), published by Packt.
6 |
7 | **Build and train state-of-the-art natural language processing models using BERT**
8 |
9 | ## What is this book about?
10 | Quantum computation is the study of a subclass of computers that exploits the laws of quantum mechanics to perform certain operations that are thought to be difficult to perform on a non-quantum computer.
11 |
12 | Hands-On Quantum Information Processing with Python begins by taking you through the essentials of quantum information processing to help you explore its potential. Next, you’ll get well-versed with the fundamental property of quantum entanglement and find out how to illustrate this using the teleportation protocol. As you advance, you’ll discover how quantum circuits and algorithms such as Simon’s algorithm, Grover’s algorithm, and Shor’s algorithm work, and get to grips with quantum cryptography by implementing important quantum key distribution (QKD) protocols in Python. You will also learn how to implement non-local games such as the CHSH game and GHZ game by using Python. Finally, you’ll cover key quantum machine learning algorithms, and these implementations will give you full rein to really play with and fully understand more complicated ideas.
13 |
14 | By the end of this quantum computing book, you will have gained a deeper understanding and appreciation of quantum information.
15 |
16 | This book covers the following exciting features:
17 | * Discover how quantum circuits and quantum algorithms work
18 | * Familiarize yourself with non-local games and learn how to implement them
19 | * Get to grips with various quantum computing models
20 | * Implement quantum cryptographic protocols such as BB84 and B92 in Python
21 | * Explore entanglement and teleportation in quantum systems
22 | * Find out how to measure and apply operations to qubits
23 | * Delve into quantum computing with the continuous-variable quantum state
24 | * Get acquainted with essential quantum machine learning algorithms
25 |
26 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/180020115X) today!
27 |
28 |
29 |
30 | ## Instructions and Navigations
31 | All of the code is organized into folders.
32 |
33 | The code will look like the following:
34 | ```
35 | from qutip import *
36 |
37 | v_00 = bell_state(state="00")
38 | v_01 = bell_state(state="01")
39 | v_10 = bell_state(state="10")
40 | v_11 = bell_state(state="11")
41 | ```
42 |
43 | **Following is what you need for this book:**
44 | This book is for developers, programmers, or undergraduates in computer science who want to learn about the fundamentals of quantum information processing. A basic understanding of the Python programming language is required, and a good grasp of math and statistics will be useful to get the best out of this book.
45 |
46 | With the following software and hardware list you can run all code files present in the book (Chapters 1 - 9).
47 |
48 | ### Software and Hardware List
49 |
50 | | Chapter | Software required | OS required |
51 | | -------- | ----------------------------------------------------------------------------------------------------| -----------------------------------|
52 | | 1 - 9 | Google Colab / Python 3.x (Qiskit, QuTip, Cirq, PennyLane, Strawberry Fields) | Windows, Mac OS X, and Linux (Any) |
53 |
54 |
55 | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://static.packt-cdn.com/downloads/9781800201156_ColorImages.pdf).
56 |
57 |
58 | ### Related products
59 | * Quantum Computing and Blockchain in Business [[Packt]](https://www.packtpub.com/product/quantum-computing-and-blockchain-in-business/9781838647766) [[Amazon]](https://www.amazon.com/dp/1838647767)
60 |
61 | * Quantum Computing in Practice with Qiskit® and IBM Quantum Experience® [[Packt]](https://www.packtpub.com/product/quantum-computing-in-practice-with-qiskit-and-ibm-quantum-experience/9781838828448) [[Amazon]](https://www.amazon.com/dp/1838828443)
62 |
63 | ## Get to Know the Author
64 | **Dr. Makhamisa Senekane** is a Lecturer at the National University of Lesotho. He comes aboard with a vast experience in the field of Quantum cryptography, Quantum information processing, Quantum computing, Machine learning and more.
65 |
--------------------------------------------------------------------------------