Merge remote-tracking branch 'origin/Dev' into Dev

# Conflicts:
This commit is contained in:
ismael faro 2017-05-11 02:03:49 -04:00
parent 5db9593449
commit 1f2d18ca26
24 changed files with 909 additions and 1453 deletions

View File

@ -13,6 +13,8 @@ gate u1(lambda) q { U(0,0,lambda) q; }
gate cx c,t { CX c,t; }
// idle gate (identity)
gate id a { U(0,0,0) a; }
// idle gate (identity) with length gamma*sqglen
gate u0(gamma) q { U(0,0,0) q; }
// --- QE Standard Gates ---

View File

@ -13,6 +13,8 @@ gate u1(lambda) q { U(0,0,lambda) q; }
gate cx c,t { CX c,t; }
// idle gate (identity)
gate id a { U(0,0,0) a; }
// idle gate (identity) with length gamma*sqglen
gate u0(gamma) q { U(0,0,0) q; }
// --- QE Standard Gates ---

View File

@ -13,6 +13,8 @@ gate u1(lambda) q { U(0,0,lambda) q; }
gate cx c,t { CX c,t; }
// idle gate (identity)
gate id a { U(0,0,0) a; }
// idle gate (identity) with length gamma*sqglen
gate u0(gamma) q { U(0,0,0) q; }
// --- QE Standard Gates ---

View File

@ -41,7 +41,7 @@ from . import qasm
from . import mapper
# from .qasm import QasmException
from .extensions.standard import barrier, h, cx, u3, x, z
from .extensions.standard import barrier, h, cx, u3, x, z, s, ry
class QuantumProgram(object):
""" Quantum Program Class
@ -98,7 +98,7 @@ class QuantumProgram(object):
self.__classical_registers = {}
self.__scope = scope
self.__name = name
# self.__qasm_compile = {}
# self.__API = {}
self.mapper = mapper
@ -137,11 +137,13 @@ class QuantumProgram(object):
return self.__API.req.credential.config
def _setup_api(self, token, url):
self.__API = IBMQuantumExperience.IBMQuantumExperience(token, {"url":url})
try:
self.__API = IBMQuantumExperience.IBMQuantumExperience(token, {"url":url})
return True
except:
print('Exception connect to servers')
print('---- Error: Exception connect to servers ----')
return False
def set_api(self, token=None, url=None):
@ -154,7 +156,8 @@ class QuantumProgram(object):
url = self.__API_config["url"]
else:
self.__API_config["url"] = {"url":url}
return self._setup_api(token, url)
api = self._setup_api(token, url)
return api
def set_api_token(self, token):
""" Set the API Token """
@ -184,12 +187,14 @@ class QuantumProgram(object):
try:
qasm_file = open(qasm_file, 'r')
qasm_source = qasm_file.read()
circuit = unroll.Unroller(qasm_source,
qasm_file.close()
circuit = unroll.Unroller(qasm.Qasm(data=qasm_source).parse(),
unroll.CircuitBackend(basis_gates.split(",")))
# print(circuit.qasm())
self.__circuits[qasm_file] = circuit
return circuit
except:
print('Error: Load qasm file = ', qasm_file)
print('---- Error: Load qasm file = ', qasm_file)
def unroller_code(self, circuit, basis_gates=None):
""" Unroller the code
@ -271,7 +276,7 @@ class QuantumProgram(object):
return self.__qasm_compile
def run_circuits(self, circuits, device, shots, max_credits=3, basis_gates=None):
def run_circuits(self, circuits, device, shots, max_credits=3, basis_gates=None, wait=5, timeout=60):
"""Run a circuit.
circuit is a circuit name
api the api for the device
@ -285,7 +290,12 @@ class QuantumProgram(object):
qasm_source, circuit = self.unroller_code(circuit, basis_gates)
jobs.append({'qasm': qasm_source})
output = self.__API.run_job(jobs, device, shots, max_credits)
return output
if 'error' in output:
return {"status":"Error", "result":output['error']}
job_result = self.wait_for_job(output['id'], wait=wait, timeout=timeout)
return job_result
def run_circuit(self, circuit, device, shots, max_credits=3, basis_gates=None):
"""Run a circuit.
@ -378,6 +388,8 @@ class QuantumProgram(object):
t += wait
print("status = %s (%d seconds)" % (job['status'], t))
job = self.__API.get_job(jobid)
if job['status'] == 'ERROR_CREATING_JOB' or job['status'] == 'ERROR_RUNNING_JOB':
return {"status":"Error", "result": job['status'] }
# Get the results
if timeout_over:
@ -414,6 +426,17 @@ class QuantumProgram(object):
results.append(self.__API.get_job(i))
return results
def flat_results(self, results):
""" Flat the results
results array of results
"""
flattened = []
for sublist in results:
for val in sublist:
flattened.append(val)
return {'qasms': flattened}
def combine_jobs(self, jobids, wait=5, timeout=60):
"""Like wait_for_jobs but with a different return format.
jobids is a list of id strings.
@ -425,13 +448,7 @@ class QuantumProgram(object):
results = list(map(lambda x: x['qasms'],
self.wait_for_jobs(jobids, wait, timeout)))
flattened = []
for sublist in results:
for val in sublist:
flattened.append(val)
# Are there other parts from the dictionary that we want to add,
# such as shots?
return {'qasms': flattened}
return self.flat_result(results)
def average_data(self, data, observable):
@ -467,11 +484,11 @@ class QuantumProgram(object):
cregisters=classicalr)
else:
if "quantum_registers" in specs:
print("quantum_registers created")
print(">> quantum_registers created")
quantumr = specs["quantum_registers"]
self.create_quantum_registers(quantumr["name"], quantumr["size"])
if "classical_registers" in specs:
print("quantum_registers created")
print(">> quantum_registers created")
classicalr = specs["classical_registers"]
self.create_classical_registers(classicalr["name"], classicalr["size"])
if quantumr and classicalr:

View File

@ -2,4 +2,5 @@ IBMQuantumExperience
requests
networkx
ply
numpy
numpy
scipy

View File

@ -1,113 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"A = np.random.choice([0, 0.5], size=(20,20), p=[1./3, 2./3])\n",
"for i in range(20):\n",
" for j in range(i):\n",
" A[j,i]=A[i,j]\n",
"for i in range(20):\n",
" A[i,i]=0;"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0. , 0.5, 0.5, 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0.5, 0. ,\n",
" 0.5, 0.5, 0.5, 0.5, 0. , 0.5, 0. , 0. , 0.5],\n",
" [ 0.5, 0. , 0. , 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0. , 0.5,\n",
" 0.5, 0.5, 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0.5],\n",
" [ 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5, 0.5, 0.5, 0.5,\n",
" 0.5, 0. , 0. , 0.5, 0.5, 0. , 0. , 0. , 0.5],\n",
" [ 0.5, 0.5, 0.5, 0. , 0. , 0. , 0.5, 0. , 0. , 0. , 0.5,\n",
" 0.5, 0.5, 0. , 0.5, 0.5, 0. , 0.5, 0.5, 0.5],\n",
" [ 0.5, 0.5, 0. , 0. , 0. , 0. , 0.5, 0. , 0. , 0. , 0.5,\n",
" 0. , 0.5, 0.5, 0. , 0.5, 0.5, 0. , 0. , 0.5],\n",
" [ 0. , 0.5, 0.5, 0. , 0. , 0. , 0.5, 0.5, 0.5, 0. , 0.5,\n",
" 0. , 0.5, 0. , 0.5, 0.5, 0.5, 0. , 0.5, 0.5],\n",
" [ 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0.5, 0.5,\n",
" 0.5, 0. , 0.5, 0.5, 0.5, 0.5, 0. , 0.5, 0.5],\n",
" [ 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0. , 0. , 0.5, 0.5, 0.5,\n",
" 0.5, 0.5, 0. , 0.5, 0.5, 0. , 0. , 0.5, 0.5],\n",
" [ 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0.5, 0.5, 0. , 0.5, 0.5,\n",
" 0. , 0.5, 0.5, 0. , 0.5, 0. , 0.5, 0.5, 0.5],\n",
" [ 0.5, 0. , 0.5, 0. , 0. , 0. , 0.5, 0.5, 0.5, 0. , 0.5,\n",
" 0.5, 0.5, 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0. ],\n",
" [ 0. , 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0. ,\n",
" 0. , 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5, 0. ],\n",
" [ 0.5, 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0.5, 0. , 0.5, 0. ,\n",
" 0. , 0. , 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0. ],\n",
" [ 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0. ,\n",
" 0. , 0. , 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0. ],\n",
" [ 0.5, 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5, 0.5, 0. ,\n",
" 0.5, 0.5, 0. , 0. , 0.5, 0.5, 0. , 0.5, 0.5],\n",
" [ 0.5, 0.5, 0.5, 0.5, 0. , 0.5, 0.5, 0.5, 0. , 0.5, 0.5,\n",
" 0.5, 0.5, 0. , 0. , 0. , 0.5, 0. , 0.5, 0.5],\n",
" [ 0. , 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0. , 0. ,\n",
" 0. , 0.5, 0.5, 0. , 0. , 0.5, 0.5, 0.5, 0. ],\n",
" [ 0.5, 0. , 0. , 0. , 0.5, 0.5, 0.5, 0. , 0. , 0.5, 0.5,\n",
" 0.5, 0. , 0.5, 0.5, 0.5, 0. , 0.5, 0.5, 0.5],\n",
" [ 0. , 0. , 0. , 0.5, 0. , 0. , 0. , 0. , 0.5, 0.5, 0. ,\n",
" 0.5, 0. , 0. , 0. , 0.5, 0.5, 0. , 0.5, 0.5],\n",
" [ 0. , 0.5, 0. , 0.5, 0. , 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,\n",
" 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0. , 0. ],\n",
" [ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0. , 0. ,\n",
" 0. , 0. , 0.5, 0.5, 0. , 0.5, 0.5, 0. , 0. ]])"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [default]",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

View File

@ -13,6 +13,8 @@ gate u1(lambda) q { U(0,0,lambda) q; }
gate cx c,t { CX c,t; }
// idle gate (identity)
gate id a { U(0,0,0) a; }
// idle gate (identity) with length gamma*sqglen
gate u0(gamma) q { U(0,0,0) q; }
// --- QE Standard Gates ---

View File

@ -13,6 +13,8 @@ gate u1(lambda) q { U(0,0,lambda) q; }
gate cx c,t { CX c,t; }
// idle gate (identity)
gate id a { U(0,0,0) a; }
// idle gate (identity) with length gamma*sqglen
gate u0(gamma) q { U(0,0,0) q; }
// --- QE Standard Gates ---

File diff suppressed because one or more lines are too long

View File

@ -4,7 +4,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"./scripts/images/QISKit-c.gif\" alt=\"Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook\" width=\"250 px\" align=\"left\">"
"<img src=\"./images/QISKit-c.gif\" alt=\"Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook\" width=\"250 px\" align=\"left\">"
]
},
{
@ -44,7 +44,7 @@
"## Introducing the tools\n",
"\n",
"These notebooks give an introduction to using the QISKit tools\n",
"* [Getting Started with the Quantum Experience Web API](scripts/getting_started_with_the_qx_api.ipynb) shows how to use the API to run your own quantum program on the QX. "
"* [Getting Started with the Quantum Experience Web API](sections/getting_started_with_the_qx_api.ipynb) shows how to use the API to run your own quantum program on the QX. "
]
},
{
@ -57,6 +57,8 @@
"\n",
"* [Superposition and entanglement](scripts/superposition_and_entanglement.ipynb) - illustrates how to make simple quantum states on one and two qubits and shows concepts such as a quantum superpositions and entanglement. \n",
"* [Single qubit states: amplitude and phase](scripts/single_qubit_states_amplitude_and_phase.ipynb) illustrates more complicated single qubit states. \n",
"* [Superposition and entanglement](sections/superposition_and_entanglement.ipynb) - illustrates how to make simple quantum states on one and two qubits and shows concepts such as a quantum superpositions and entanglement. \n",
"* [Single qubit states: amplitude and phase](scripts/single_qubit_states_amplitude_and_phase.ipynb) TODO WITH JAY\n",
"* [Entanglement revisited](scripts/entanglement_revisited.ipynb) - illustrates the CHSH inequality and extensions for three qubits (Mermin). \n",
"* Quantum sphere TODO WITH JAY\n",
"* Quantum teleportation TODO WITH JAY\n",

View File

@ -0,0 +1,830 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"./images/QISKit-c.gif\" alt=\"Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook\" width=\"250 px\" align=\"left\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## _*Entanglement revisited*_ \n",
"\n",
"The latest version of this notebook is available on https://github.com/IBM/qiskit-sdk-py/tree/master/scripts.\n",
"\n",
"For more information about how to use the Quantum Experience consult the [Quantum Experience tutorials](https://quantumexperience.ng.bluemix.net/qstage/#/tutorial?sectionId=c59b3710b928891a1420190148a72cce&pageIndex=0) or check-out the [community](https://quantumexperience.ng.bluemix.net/qstage/#/community).\n",
"\n",
"***\n",
"### Contributors\n",
"Jay Gambetta, Antonio Córcoles"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Entanglement\n",
"\n",
"In [superposition and entanglement](scripts/superposition_and_entanglement.ipynb) we introduced you to the concept of entanglement. We made the quantum state $|\\psi\\rangle= (|00\\rangle+|11\\rangle)/\\sqrt{2}$ and showed that (up to experimental noise) the system has perfect correlations in both the computation basis and the superpostion basis. This means that if $q_0$ is measured in state $|0\\rangle$ then we know $q_1$ is in this state, and furthermore if $q_0$ is measured in state $|+\\rangle$ then we know $q_1$ is in this state.\n",
"\n",
"To understand the implications of this in a little bit more detail lets introduce the concept of an observable. An observable is a Hermitian matrix where the real eigenvalues represent the outcome of the experiment and the eigenvectors are the states the system is projected in under measurement. That is $ A$ is given by\n",
" \n",
"\n",
"$$ A = \\sum_j a_j|a_j\\rangle\\langle a_j|$$ \n",
"\n",
"where $|a_j\\rangle$ is the eigenvector of the observable with result $a_j$. This expectation value of this observable is given by \n",
"\n",
"$$\\langle A \\rangle = \\sum_j a_j |\\langle \\psi |a_j\\rangle|^2 = \\sum_j a_j \\mathrm{Pr}(a_j|\\psi)$$\n",
"\n",
"and we see there is the standard relationship between average (expectation value) and probability. \n",
"\n",
"For a two qubit system the following important two-outcome ($\\pm1$) single qubit observables are \n",
"\n",
"$$ Z= |0\\rangle\\langle 0| - |1\\rangle\\langle 1|$$ \n",
"$$ X= |+\\rangle\\langle +| - |-\\rangle\\langle -|$$ \n",
"\n",
"which can be extended to the two-qubit space to give \n",
"\n",
"$$\\langle I\\otimes Z\\rangle =\\mathrm{Pr}(00|\\psi) - \\mathrm{Pr}(01|\\psi) + \\mathrm{Pr}(10|\\psi)- \\mathrm{Pr}(11|\\psi)$$ \n",
"$$\\langle Z\\otimes I\\rangle =\\mathrm{Pr}(00|\\psi) + \\mathrm{Pr}(01|\\psi) - \\mathrm{Pr}(10|\\psi)- \\mathrm{Pr}(11|\\psi)$$ \n",
"$$\\langle Z\\otimes Z\\rangle =\\mathrm{Pr}(00|\\psi) - \\mathrm{Pr}(01|\\psi) - \\mathrm{Pr}(10|\\psi)+ \\mathrm{Pr}(11|\\psi)$$ \n",
"\n",
"$$\\langle I\\otimes X\\rangle =\\mathrm{Pr}(++|\\psi) - \\mathrm{Pr}(+-|\\psi) + \\mathrm{Pr}(-+|\\psi)- \\mathrm{Pr}(--|\\psi)$$ \n",
"$$\\langle X\\otimes I\\rangle =\\mathrm{Pr}(++|\\psi) + \\mathrm{Pr}(+-|\\psi) - \\mathrm{Pr}(-+|\\psi)- \\mathrm{Pr}(--|\\psi)$$ \n",
"$$\\langle X\\otimes X\\rangle =\\mathrm{Pr}(++|\\psi) - \\mathrm{Pr}(+-|\\psi) - \\mathrm{Pr}(-+|\\psi)+ \\mathrm{Pr}(--|\\psi)$$ \n",
"\n",
"\n",
"$$\\langle Z\\otimes X\\rangle =\\mathrm{Pr}(0+|\\psi) - \\mathrm{Pr}(0-|\\psi) - \\mathrm{Pr}(1+|\\psi)+ \\mathrm{Pr}(1-|\\psi)$$ \n",
"$$\\langle X\\otimes Z\\rangle =\\mathrm{Pr}(+0|\\psi) - \\mathrm{Pr}(+1|\\psi) - \\mathrm{Pr}(-0|\\psi)+ \\mathrm{Pr}(-1|\\psi)$$ "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#Checking the version of PYTHON we only support 3 at the moment\n",
"import sys\n",
"if sys.version_info < (3,0):\n",
" raise Exception(\"Please use Python version 3 or greater.\")\n",
" \n",
"#usefull additional packages \n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import scipy as sp\n",
"import scipy.linalg\n",
"%matplotlib inline\n",
"import time\n",
"\n",
"import sys\n",
"sys.path.append(\"..\")\n",
"\n",
"#some usefull functions for running a program, plotting, and getting the data\n",
"from qhelpers.misc import run_program\n",
"from qhelpers.misc import program_to_text\n",
"from qhelpers.misc import combine_jobs\n",
"from qhelpers.misc import get_data\n",
"from qhelpers.basicplotter import plot_histogram\n",
"from qhelpers.misc import average_data\n",
"\n",
"#importing the QISKit\n",
"from qiskit import QuantumProgram\n",
"import Qconfig"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recall to make the Bell state $|\\psi\\rangle= (|00\\rangle+|11\\rangle)/\\sqrt{2}$ from the initial state $|00\\rangle$, the quantum circuit first applies a Hadmard on $q_0$ and then a CNOT from $q_0$ to $q_1$. On the Quantum Experience this is done by using the script for measurement of the above expectation values we have to run four different experiments with measurements in the standard basis, superposition basis, and a combination of both."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"device = 'qx5q' # the device to run on\n",
"shots = 1024 #the number of shots in the experiment. \n",
"# device = 'simulator' # the device test purpose \n",
"\n",
"QPSpecs = {\n",
" \"name\": \"Entanglement\",\n",
" \"circuits\": [{\n",
" \"name\": \"bell\",\n",
" \"quantum_registers\": [{\n",
" \"name\":\"q\",\n",
" \"size\":2\n",
" }],\n",
" \"classical_registers\": [{\n",
" \"name\":\"c\",\n",
" \"size\":2\n",
" }]}],\n",
"}\n",
"\n",
"Q_program = QuantumProgram(specs=QPSpecs)\n",
"Q_program.set_api(Qconfig.APItoken, Qconfig.config[\"url\"])\n",
"\n",
"#quantum circuit to make bell state \n",
"bell = Q_program.circuit(\"bell\")\n",
"q = Q_program.quantum_registers(\"q\")\n",
"c = Q_program.classical_registers('c')\n",
"\n",
"bell.h(q[0])\n",
"bell.cx(q[0],q[1])\n",
"\n",
"# quantum circuit to measure q in standard basis \n",
"measureZZ = Q_program.create_circuit(\"measureZZ\", \"q\", \"c\")\n",
"measureZZ.measure(q[0], c[0])\n",
"measureZZ.measure(q[1], c[1])\n",
"\n",
"# quantum circuit to measure q in superposition basis \n",
"measureXX = Q_program.create_circuit(\"measureXX\", \"q\", \"c\")\n",
"measureXX.h(q[0])\n",
"measureXX.h(q[1])\n",
"measureXX.measure(q[0], c[0])\n",
"measureXX.measure(q[1], c[1])\n",
"\n",
"# quantum circuit to measure ZX\n",
"measureZX = Q_program.create_circuit(\"measureZX\", \"q\", \"c\")\n",
"measureZX.h(q[0])\n",
"measureZX.measure(q[0], c[0])\n",
"measureZX.measure(q[1], c[1])\n",
"\n",
"# quantum circuit to measure XZ\n",
"measureXZ = Q_program.create_circuit(\"measureXZ\", \"q\", \"c\")\n",
"measureXZ.h(q[1])\n",
"measureXZ.measure(q[0], c[0])\n",
"measureXZ.measure(q[1], c[1])\n",
"\n",
"circuits = [bell+measureZZ, bell+measureZX, bell+measureXX, bell+measureXZ]\n",
"\n",
"print(Q_program.program_to_text(circuits))\n",
"\n",
"results = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=10, timeout=240)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"obsevableIZ ={'00000': 1, '00001': -1, '00010': 1, '00011': -1}\n",
"obsevableZI ={'00000': 1, '00001': 1, '00010': -1, '00011': -1}\n",
"obsevableZZ ={'00000': 1, '00001': -1, '00010': -1, '00011': 1}\n",
"\n",
"obsevableIZ_ideal ={'00': 1, '01': -1, '10': 1, '11': -1}\n",
"obsevableZI_ideal ={'00': 1, '01': 1, '10': -1, '11': -1}\n",
"obsevableZZ_ideal ={'00': 1, '01': -1, '10': -1, '11': 1}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(\"IZ = \" + str(average_data(get_data(results,0),obsevableIZ)))\n",
"print(\"ZI = \" + str(average_data(get_data(results,0),obsevableZI)))\n",
"print(\"ZZ = \" + str(average_data(get_data(results,0),obsevableZZ)))\n",
"\n",
"print(\"IX = \" + str(average_data(get_data(results,2),obsevableIZ)))\n",
"print(\"XI = \" + str(average_data(get_data(results,2),obsevableZI)))\n",
"print(\"XX = \" + str(average_data(get_data(results,2),obsevableZZ)))\n",
"\n",
"print(\"ZX = \" + str(average_data(get_data(results,1),obsevableZZ)))\n",
"print(\"XZ = \" + str(average_data(get_data(results,3),obsevableZZ)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we see that for the state $|\\psi\\rangle= (|00\\rangle+|11\\rangle)/\\sqrt{2}$ that within experimental error expectation values are\n",
"\n",
"\n",
"Observable | Expected value |Observable | Expected value|Observable | Expected value\n",
"------------- | ------------- | ------------- | ------------- | ------------- | -------------\n",
"ZZ | 1 |XX | 1 | ZX | 0 \n",
"ZI | 0 |XI | 0 | XZ | 0\n",
"IZ | 0 |IX | 0 | |\n",
"\n",
"If we assume there is a hidden variable $\\lambda$ and the follow assumptions \n",
"\n",
"* _Locality_: No information can travel faster than the speed of light. There is a hidden variable $\\lambda$ that defines all the correlations so that $$\\langle A\\otimes B\\rangle = \\sum_\\lambda P(\\lambda) A(\\lambda) B(\\lambda)$$ \n",
" \n",
"* _Realism_: All observables have a definite value independent of the measurement ($A(\\lambda)=\\pm1$ etc).\n",
"\n",
"can we describe these observations. --- The answer is yes! \n",
"\n",
"Lets assume $\\lambda$ has two bits each occurring randomly with probably 1/4 then the following predefined table would explain all the above observables\n",
"\n",
"$\\lambda$ | Z (qubit 1) |Z (qubit 2) | X (qubit 1)| X (qubit 2) \n",
"------------- | ------------- | ------------- | ------------- | ------------- \n",
"00 | 1 | 1 | 1 | 1 \n",
"01 | 1 | 1 |-1 |-1 \n",
"10 |-1 |-1 |-1 |-1 \n",
"11 |-1 |-1 | 1 | 1 \n",
"\n",
"however there are some states where this is not true. This was first observed by John Stewart Bell in 1964. He proposed a theorem that suggests that there are no hidden variables in quantum mechanics. At the core of Bell's theorem is the famous Bell inequality. Here, we'll use a refined version of this inequality (known as the CHSH inequality, derived by John Clauser, Michael Horne, Abner Shimony, and Richard Holt in 1969) to demonstrate Bell's proposal "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CHSH inequality \n",
"\n",
"\n",
"In the CHSH inequality we measure the correlator of the four observables: $A$ and $A'$ on $q_0$ and $B$ and $B'$ on $q_1$ which have eigenvalues $\\pm 1$. The CHSH inequality says that no local hidden variable theory can have \n",
"\n",
"$$|C|>2$$ \n",
"\n",
"where \n",
"\n",
"$$C = \\langle B\\otimes A\\rangle + \\langle B\\otimes A'\\rangle+\\langle B'\\otimes A'\\rangle-\\langle B'\\otimes A\\rangle$$\n",
"\n",
"Under the locality and realism assumtion above $C$ becomes \n",
"\n",
"$$C = \\sum_\\lambda P(\\lambda) \\{ B(\\lambda) [ A(\\lambda)+A'(\\lambda)] + B'(\\lambda) [ A'(\\lambda)-A(\\lambda)]$$\n",
" \n",
"and $[A(\\lambda)+A'(\\lambda)]=2$ (or 0) while $[A'(\\lambda)-A(\\lambda)]=0$ (or 2) respectively. That is, $|C|=2$, and noise will only make this smaller. \n",
" \n",
"If we measure a number greater than 2 then the above assumptions can not be valid, and this is one of those astonishing counterintuitive ideas one must accept in the quantum world.\n",
"\n",
"For simplicity we choose these observables to be \n",
"\n",
" $$C = \\langle Z\\otimes Z\\rangle + \\langle Z\\otimes X\\rangle+\\langle X\\otimes X\\rangle-\\langle X\\otimes Z\\rangle$$\n",
"\n",
"Z is measured in the computational basis and X in the superposition basis ($H$ is applied before measurement) and the input state $$|\\psi(\\theta)\\rangle = I\\otimes Y(\\theta)\\frac{|00\\rangle + |11\\rangle}{\\sqrt(2)} = \\frac{\\cos(\\theta/2)|00\\rangle + \\cos(\\theta/2)|11\\rangle+\\sin(\\theta/2)|01\\rangle-\\sin(\\theta/2)|10\\rangle}{\\sqrt{2}}$$ is swept vs $\\theta$. \n",
" \n",
"Note that the following demonstration of CHSH is not loophole-free. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"CHSH = lambda x : x[0]+x[1]+x[2]-x[3]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"program = []\n",
"xdata=[]\n",
"\n",
"program_end = [measureZZ, measureZX, measureXX, measureXZ]\n",
"\n",
"for jj in range(30):\n",
" theta = 2.0*np.pi*jj/30\n",
" bell_middle = Q_program.create_circuit(\"circuit\"+str(jj),\"q\", \"c\")\n",
" bell_middle.ry(theta,q[0])\n",
" for i in range(4):\n",
" program.append(bell+bell_middle+program_end[i])\n",
" xdata.append(theta)\n",
" \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(program_to_text(program[0:8]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"device = 'simulator'\n",
"shots = 1024\n",
"\n",
"program_list=[program[0:40],program[40:80],program[80:120]]\n",
"\n",
"r = {'qasms':[]}\n",
"for circuits in program_list:\n",
" output = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=1, timeout=240)\n",
" print(output)\n",
" r['qasms'] += output['qasms']\n",
"\n",
"CHSH_data_sim = []\n",
"for j in range(0,len(r['qasms']),4):\n",
" temp=[]\n",
" temp.append(average_data(get_data(r,j+0),obsevableZZ_ideal))\n",
" temp.append(average_data(get_data(r,j+1),obsevableZZ_ideal))\n",
" temp.append(average_data(get_data(r,j+2),obsevableZZ_ideal))\n",
" temp.append(average_data(get_data(r,j+3),obsevableZZ_ideal))\n",
" CHSH_data_sim.append(CHSH(temp))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"device = 'qx5q'\n",
"shots = 1024\n",
"# device = 'simulator' # the device test purpose \n",
"\n",
"program = []\n",
"xdata2=[]\n",
"\n",
"for jj in range(10):\n",
" theta = 2.0*np.pi*jj/10\n",
" bell_middle = Q_program.create_circuit(\"circuit_real_\"+str(jj),\"q\", \"c\")\n",
" bell_middle.ry(theta,q[0])\n",
" for i in range(4):\n",
" program.append(bell+bell_middle+program_end[i])\n",
" xdata2.append(theta)\n",
"\n",
"r = Q_program.run_circuits(program, device, shots, max_credits=3, wait=10, timeout=240)\n",
"\n",
"CHSH_data_real = []\n",
"for j in range(0, len(r['qasms']), 4):\n",
" temp=[]\n",
" temp.append(average_data(get_data(r,j+0),obsevableZZ))\n",
" temp.append(average_data(get_data(r,j+1),obsevableZZ))\n",
" temp.append(average_data(get_data(r,j+2),obsevableZZ))\n",
" temp.append(average_data(get_data(r,j+3),obsevableZZ))\n",
" CHSH_data_real.append(CHSH(temp))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plt.plot(xdata, CHSH_data_sim, 'r-', xdata2, CHSH_data_real, 'bo')\n",
"plt.plot([0, 2*np.pi], [2, 2], 'b-')\n",
"plt.plot([0, 2*np.pi], [-2, -2], 'b-')\n",
"plt.grid()\n",
"plt.ylabel('CHSH', fontsize=20)\n",
"plt.xlabel(r'$Y(\\theta)$', fontsize=20)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The graph created by running the next cell compares the simulated data (sinusoidal line) and the data from the real experiment. The graph also gives lines at $\\pm 2$ for reference."
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"Here is the saved CHSH data. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(CHSH_data_real)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Despite the presence of loopholes in our demonstration, we can see that this experiment is compatible with quantum mechanics as a theory with no local hidden variables."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## GHZ state\n",
"\n",
"An important set of quantum states are the GHZ states. These are the states of the form \n",
"$|\\psi\\rangle = \\left (|0...0\\rangle+|1...1\\rangle\\right)/\\sqrt{2}$. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# 2 - qubits \n",
"shots = 8192\n",
"device = 'qx5q'\n",
"# device = 'simulator' # the device test purpose \n",
"\n",
"#quantum circuit to make GHZ state\n",
"q = Q_program.create_quantum_registers(\"q\", 2)\n",
"c = Q_program.create_classical_registers(\"c\", 2)\n",
"ghz = Q_program.create_circuit(\"ghz\", \"q\", \"c\")\n",
"ghz.h(q[0])\n",
"ghz.cx(q[0],q[1])\n",
"\n",
"# quantum circuit to measure q in standard basis \n",
"measureZZ = Q_program.create_circuit(\"measureZZ\", \"q\", \"c\")\n",
"measureZZ.measure(q[0], c[0])\n",
"measureZZ.measure(q[1], c[1])\n",
"\n",
"measureXX = Q_program.create_circuit(\"measureXX\", \"q\", \"c\")\n",
"measureXX.h(q[0])\n",
"measureXX.h(q[1])\n",
"measureXX.measure(q[0], c[0])\n",
"measureXX.measure(q[1], c[1])\n",
"\n",
"circuits = [ghz+measureZZ, ghz+measureXX]\n",
"\n",
"print(program_to_text(circuits))\n",
"\n",
"results = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=10, timeout=240) \n",
"\n",
"data=get_data(results,0)\n",
"plot_histogram(data)\n",
"data=get_data(results,1)\n",
"plot_histogram(data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# 3 - qubits \n",
"shots = 8192\n",
"#quantum circuit to make GHZ state \n",
"q = Q_program.create_quantum_registers(\"q\", 3)\n",
"c = Q_program.create_classical_registers(\"c\", 3)\n",
"ghz = Q_program.create_circuit(\"ghz\", \"q\", \"c\")\n",
"ghz.h(q[0])\n",
"ghz.cx(q[0],q[1])\n",
"ghz.cx(q[1],q[2])\n",
"\n",
"# quantum circuit to measure q in standard basis \n",
"measureZZZ = Q_program.create_circuit(\"measureZZZ\", \"q\", \"c\")\n",
"measureZZZ.measure(q[0], c[0])\n",
"measureZZZ.measure(q[1], c[1])\n",
"measureZZZ.measure(q[2], c[2])\n",
"\n",
"measureXXX = Q_program.create_circuit(\"measureXXX\", \"q\", \"c\")\n",
"measureXXX.h(q[0])\n",
"measureXXX.h(q[1])\n",
"measureXXX.h(q[2])\n",
"measureXXX.measure(q[0], c[0])\n",
"measureXXX.measure(q[1], c[1])\n",
"measureXXX.measure(q[2], c[2])\n",
"\n",
"circuits = [ghz+measureZZZ, ghz+measureXXX]\n",
"\n",
"print(program_to_text(circuits))\n",
"\n",
"results = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=10, timeout=240)\n",
"\n",
"data=get_data(results,0)\n",
"plot_histogram(data)\n",
"data=get_data(results,1)\n",
"plot_histogram(data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# 4 - qubits \n",
"shots = 8192\n",
"#quantum circuit to make GHZ state \n",
"q = Q_program.create_quantum_registers(\"q\", 4)\n",
"c = Q_program.create_classical_registers(\"c\", 4)\n",
"ghz = Q_program.create_circuit(\"ghz\", \"q\", \"c\")\n",
"ghz.h(q[0])\n",
"ghz.cx(q[0],q[1])\n",
"ghz.cx(q[1],q[2])\n",
"ghz.h(q[3])\n",
"ghz.h(q[2])\n",
"ghz.cx(q[3],q[2])\n",
"ghz.h(q[3])\n",
"ghz.h(q[2])\n",
"\n",
"# quantum circuit to measure q in standard basis \n",
"measureZZZZ = Q_program.create_circuit(\"measureZZZZ\", \"q\", \"c\")\n",
"measureZZZZ.measure(q[0], c[0])\n",
"measureZZZZ.measure(q[1], c[1])\n",
"measureZZZZ.measure(q[2], c[2])\n",
"measureZZZZ.measure(q[3], c[3])\n",
"\n",
"measureXXXX = Q_program.create_circuit(\"measureXXXX\", \"q\", \"c\")\n",
"measureXXXX.h(q[0])\n",
"measureXXXX.h(q[1])\n",
"measureXXXX.h(q[2])\n",
"measureXXXX.h(q[3])\n",
"measureXXXX.measure(q[0], c[0])\n",
"measureXXXX.measure(q[1], c[1])\n",
"measureXXXX.measure(q[2], c[2])\n",
"measureXXXX.measure(q[3], c[3])\n",
"\n",
"circuits = [ghz+measureZZZZ, ghz+measureXXXX]\n",
"\n",
"print(program_to_text(circuits))\n",
"\n",
"results = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=10, timeout=240)\n",
"\n",
"data=get_data(results,0)\n",
"plot_histogram(data)\n",
"data=get_data(results,1)\n",
"plot_histogram(data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mermin's test\n",
"In case the violation of Bell's inequality (CHSH) by two qubits is not enough for you to believe in quantum mechanics, we can generalize to a more stringent set of tests with three qubits which can a single shot violation (rather than average). We can explore beyond two-qubit entanglement and generate Greenberger-Horne-Zeilinger states. A well-known three-qubit case is Mermin's inequality, and here in this notebook we work through such a test."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An example of a three-qubit GHZ state is $|\\psi\\rangle = \\left (|000\\rangle+|111\\rangle\\right)/\\sqrt{2}$. You can see this is a further generalization of a Bell-state and if measured, should give $|000\\rangle$ half the time and $|111 \\rangle$ the other half of the time."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#quantum circuit to make GHZ state \n",
"q = Q_program.create_quantum_registers(\"q\", 3)\n",
"c = Q_program.create_classical_registers(\"c\", 3)\n",
"ghz = Q_program.create_circuit(\"ghz\", \"q\", \"c\")\n",
"ghz.h(q[0])\n",
"ghz.cx(q[0],q[1])\n",
"ghz.cx(q[0],q[2])\n",
"\n",
"# quantum circuit to measure q in standard basis \n",
"measureZZZ = Q_program.create_circuit(\"measureZZZ\", \"q\", \"c\")\n",
"measureZZZ.measure(q[0], c[0])\n",
"measureZZZ.measure(q[1], c[1])\n",
"measureZZZ.measure(q[2], c[2])\n",
"\n",
"circuits = [ghz+measureZZZ]\n",
"\n",
"print(program_to_text(circuits))\n",
"\n",
"results = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=10, timeout=240) \n",
"\n",
"data=get_data(results,0)\n",
"plot_histogram(data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Three-box game\n",
"\n",
"Now suppose we have three independent systems,$\\{A,B,C\\}$, for which we can query two particular questions $X$ and $Y$. In each case, either query can give $+1$ or $-1$. Is it possible to choose some state of the three boxes such that we can satisfy the following four conditions, $X_A Y_B Y_C = 1$, $Y_A X_B Y_C =1$, $Y_A Y_B X_C = 1$, and $X_A X_B X_C = -1$. Choosing classical states, this can be shown to be impossible. Yet a 3-qubit GHZ state can satsify all four conditions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"MerminM = lambda x : x[0]*x[1]*x[2]*x[3]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"observable ={'00000': 1, '00001': -1, '00010': -1, '00011': 1, '00100': -1, '00101': 1, '00110': 1, '00111': -1}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# quantum circuit to measure q XXX \n",
"measureXXX = Q_program.create_circuit(\"measureXXX\", \"q\", \"c\")\n",
"measureXXX.h(q[0])\n",
"measureXXX.h(q[1])\n",
"measureXXX.h(q[2])\n",
"measureXXX.measure(q[0], c[0])\n",
"measureXXX.measure(q[1], c[1])\n",
"measureXXX.measure(q[2], c[2])\n",
"\n",
"# quantum circuit to measure q XYY\n",
"measureXYY = Q_program.create_circuit(\"measureXYY\", \"q\", \"c\")\n",
"measureXYY.s(q[1]).inverse()\n",
"measureXYY.s(q[2]).inverse()\n",
"measureXYY.h(q[0])\n",
"measureXYY.h(q[1])\n",
"measureXYY.h(q[2])\n",
"measureXYY.measure(q[0], c[0])\n",
"measureXYY.measure(q[1], c[1])\n",
"measureXYY.measure(q[2], c[2])\n",
"\n",
"# quantum circuit to measure q YXY\n",
"measureYXY = Q_program.create_circuit(\"measureYXY\", \"q\", \"c\")\n",
"measureYXY.s(q[0]).inverse()\n",
"measureYXY.s(q[2]).inverse()\n",
"measureYXY.h(q[0])\n",
"measureYXY.h(q[1])\n",
"measureYXY.h(q[2])\n",
"measureYXY.measure(q[0], c[0])\n",
"measureYXY.measure(q[1], c[1])\n",
"measureYXY.measure(q[2], c[2])\n",
"\n",
"# quantum circuit to measure q YYX\n",
"measureYYX = Q_program.create_circuit(\"measureYYX\", \"q\", \"c\")\n",
"measureYYX.s(q[0]).inverse()\n",
"measureYYX.s(q[1]).inverse()\n",
"measureYYX.h(q[0])\n",
"measureYYX.h(q[1])\n",
"measureYYX.h(q[2])\n",
"measureYYX.measure(q[0], c[0])\n",
"measureYYX.measure(q[1], c[1])\n",
"measureYYX.measure(q[2], c[2])\n",
"\n",
"circuits = [ghz+measureXXX,ghz+measureYYX,ghz+measureYXY,ghz+measureXYY]\n",
"\n",
"results = Q_program.run_circuits(circuits, device, shots, max_credits=3, wait=10, timeout=240) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"temp=[]\n",
"temp.append(average_data(get_data(results,0),observable))\n",
"temp.append(average_data(get_data(results,1),observable))\n",
"temp.append(average_data(get_data(results,2),observable))\n",
"temp.append(average_data(get_data(results,3),observable))\n",
"print(temp)\n",
"print(MerminM(temp))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above shows that the average statistics are not consistent with a local hidden variable theory. To show it with single shots below we run 50 single experiments with each experiement is chosen randomly and the outcome is saved. If there was a local hidden variable theory all of these outcomes would be $+1$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"device = 'qx5q'\n",
"shots = 1\n",
"\n",
"program_singleshot=[]\n",
"for j in range(0, 50):\n",
" r=np.random.randint(4)\n",
" program_singleshot.append(circuits[r])\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"results = Q_program.run_circuits(program_singleshot, device, shots, max_credits=3, wait=10, timeout=240)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"temp=[]\n",
"for j in range(0, 50):\n",
" temp.append(average_data(get_data(results,j),observable))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"outcomes = np.histogram(temp,bins=2)\n",
"outcomes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}