<jupyter_start><jupyter_text>Coin toss quantum circuitIn this exercise we create a quantum circuit that simulates the probabilistic nature of a single qubit in superposition. The one qubit circuit initializes the qubit in the ground state $|0\rangle$ and then uses a Hadamard gate to put the qubit in superposition $|\psi\rangle = \left(|0\rangle+|1\rangle\right)/\sqrt{2}.$  Measuring the qubit causes it to collapse into one of the states $|0\rangle$ or $|1\rangle$ with a 50% probability, i.e. a coin toss.   In this exercise we introduce the Hadamard gate, which puts a qubit in superposition.  ![Hadamard circuit](data:image/png;base64,iVBORw0KG<KEY>g==)<jupyter_code>from qiskit import QuantumCircuit, execute, Aer

# Import visualization
from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere<jupyter_output><empty_output><jupyter_text>As we will be using the Bloch sphere visualization (`plot_bloch_multivector`) a bit, here's a quick function that calculates the state vector ($|\psi\rangle$) for the circuit to let you display the Bloch vector for any given state.<jupyter_code>def get_psi(circuit): 
    global psi
    backend = Aer.get_backend('statevector_simulator') 
    psi = execute(circuit, backend).result().get_statevector(circuit)
    display(plot_bloch_multivector(psi))<jupyter_output><empty_output><jupyter_text>Create an empty quantum circuit. We start out with the qubit in the $|0\rangle$ state.<jupyter_code>qc = QuantumCircuit(1,1)

# Print out the circuit
display(qc.draw(output="mpl"))

# Display the Bloch sphere
get_psi(qc)<jupyter_output><empty_output><jupyter_text>Add a Hadamard (super position) gate to the quantum circuit. This puts the qubit in a superposition: $|\psi\rangle = \left(|0\rangle+|1\rangle\right)/\sqrt{2}.$<jupyter_code>qc.h(0)

# Print out the circuit
display(qc.draw(output="mpl"))

# Display the Bloch sphere
get_psi(qc)<jupyter_output><empty_output><jupyter_text>Finally, add a measurement gate to complete the circuit.<jupyter_code># Add measure gate
qc.measure(0,0)
display(qc.draw(output="mpl"))<jupyter_output><empty_output><jupyter_text>Set the backend to a local simulator.<jupyter_code>backend = Aer.get_backend('qasm_simulator')<jupyter_output><empty_output><jupyter_text>Create a quantum job that runs just one shot to simulate a coin toss. Then run the job and display the result; either 0 for up (base) or 1 for down (excited). Display the result as a histogram.<jupyter_code>job = execute(qc, backend, shots=1)
counts  = job.result().get_counts()
print(counts)
plot_histogram(counts)<jupyter_output>{'1': 1}<jupyter_text>Adding some statistics**Now, it is your turn!** Just running the circuit once gives you a single quantum outcome, 0 or 1. But generally that cingle result might not be useful, and you want to see some statistics of the potential outcome space. Lets run a thousand coin tosses in a row, print the outcome and display it in a histogram. With what probability do you expect to get 0 and 1? Do the results match your expectation? **Tip:** You can modify the previous commands, or create a new execution by adding code in the next window.<jupyter_code># Add your code here 

job_2 = execute(qc, backend, shots=1000)
counts2  = job_2.result().get_counts()
print(counts2)
plot_histogram(counts2)<jupyter_output>{'0': 520, '1': 480}<jupyter_text>Tossing with heads or tails up**Some more work for you!** We can also do our coin flip with the qubit starting in the $|1\rangle$ state by first flipping the qubit by using the X gate. The Hadamard gate still flips the qubit to the equator, but now on the -X side. Would you expect any difference in the outcome. For this exercise we introduce the X gate that flips the qubit from $|0\rangle$ to $|1\rangle$ and vice versa.![NOT circuit](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJEAAAB7CAYAAAB0B2LHAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAFOElEQVR4nO3dT2gUZxyH8e/sJiY2EpIYgqCiaERIcAMKHtoG8dB2i6ke0iRV9KAQU6uHgLT10j/UNrFJWntoD+lNaJWNYcNeXKShmEZzMEH8l4p7MEUFQQQjColtdqeHUotY<KEY>)**Tip:** You can modify the previous commands, or create and execute a new circuit, adding the gates, and then running the circuit and displaying the results by adding code in the next window.<jupyter_code># Add your code here 

qc2 = QuantumCircuit(1,1)
qc2.x(0)

get_psi(qc2)

qc2.h(0)
get_psi(qc2)

qc2.measure(0,0)
display(qc2.draw(output="mpl"))

job2 = execute(qc2, backend, shots=1000)
counts2  = job2.result().get_counts()
print(counts2)
plot_histogram(counts2)<jupyter_output><empty_output><jupyter_text>Cheating coin toss quantum circuitSo, the X gate didn't make much of a difference; our coin toss is pretty fair. So, what can we do about this? Can we tweak the probabilistic nature of a single qubit in superposition? Can we cheat in coin tossing?Like before we put the qubit in superposition $|\psi\rangle = \left(|0\rangle+|1\rangle\right)/\sqrt{2}.$  We then add an additional Ry (rotation around the Y axis) gate, which pushes the Bloch vector $\pi/8$ closer to $|1\rangle$. we tweak the odds in favor of $|1\rangle$. The expected outcome is now $|0\rangle$ ~ 33% and $|1\rangle$ with a 66% probability.In this exercise we introduce the Ry gate, which rotates a qubit around the y-axis.![Hadamard circuit](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJEAAAB7CAYAAAB0B2LHAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAHtUlEQVR4nO3dfUxV9x3H8TeXWlDwioCIgsKQB4Xqneh0mjqqXTMSzZhx1cg0ZmbK2tpEo8lMyR4SV+2UzmQP7VhnFrfOBWZ0uEW02inRmU2wyoQpVwXGBVFwgoKilof9sY2MWgX3u7e/e5vPK+EPzgXOl+TN75x7LnCC+vr6+hAx4LA9gAQ+RSTGFJEYU0RiTBGJMUUkxhSRGFNEYkwRiTFFJMYUkRhTRGJMEYkxRSTGFJEYU0RiTBGJMUUkxhSRGFNEYkwRiTFFJMYUkRhTRGJMEYkxRSTGFJEYe8r2AIHgaIGd/X5xk539PimtRGJMEYkxRSTGFJEY04m1Fy3bMp7Ou204HME4HMGkT5zDhhffISZigu3RfEorkZfcuNXEzdvNvLX+A/7weie/3lxL+50Wdh3cbHs0n1NEXlLjKWdEqJOJMZMBcIZFkRyXSVvHdcuT+Z4i8pIaTzlp8Z8jKCiInp5uyi8eoqyyiAXTc22P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AASUVORK5CYII=) Add a Hadamard (super position) gate to the quantum circuit. This puts the qubit in a superposition: $|\psi\rangle = \left(|0\rangle+|1\rangle\right)/\sqrt{2}.$<jupyter_code>qc3 = QuantumCircuit(1,1)
qc3.h(0)

display(qc3.draw(output="mpl"))

# Display the Bloch sphere
get_psi(qc3)<jupyter_output><empty_output><jupyter_text>Now, let's rotate the Bloch vector vector $\pi$/8 radians closer to $|1\rangle$ by adding a Y rotation gate.For the rotation gate we need to use $\pi$, which we import from Python math.<jupyter_code>from math import pi

qc3.ry(pi/8,0) 
#Move the Bloch vector pi/8 radians closer to |1>. 
display(qc3.draw(output="mpl"))

# Display the Bloch sphere
get_psi(qc3)<jupyter_output><empty_output><jupyter_text>Add measurement and then run the circuit on a local simulator like before.<jupyter_code>qc3.measure(0,0)
display(qc3.draw(output="mpl"))

backend = Aer.get_backend('qasm_simulator')

job3 = execute(qc3, backend, shots=1000)
result3 = job3.result()
counts3  = result3.get_counts(qc3)
print(counts3)
plot_histogram(counts3)<jupyter_output><empty_output><jupyter_text>Notice the change inprobability for getting 0 and 1. The slight tweak of the Bloch vector towards |1> turns out to have a massive result in that ~70% of the coin tosses are now |1>.  Retweak your quantum coin to your advantage**Your turn again!** Now go ahead and change the probability for your coin toss to be ~75% chance to get the result 0.**Tip:** You can modify the previous commands, or create and execute a new circuit, adding the gates, and then running the circuit and displaying the results by adding code in the next window. **Challenge:** Can you get the same results *without* using the Hadamard gate?<jupyter_code># Your code goes here

qc4 = QuantumCircuit(1,1)
qc4.h(0)
qc4.ry(33*-pi/200,0) 

# Or without H gate...

#qc4.ry(67*pi/200,0) 


# Display the Bloch sphere
get_psi(qc4)

qc4.measure(0,0)

display(qc4.draw(output="mpl"))

backend = Aer.get_backend('qasm_simulator')

job4 = execute(qc4, backend, shots=1000)
result4 = job4.result()
counts4  = result4.get_counts(qc4)
print(counts4)
plot_histogram(counts4)<jupyter_output><empty_output><jupyter_text>Congratulations, you now know how to cheat in coin tossing. Next stop Las Vegas! As you have seen, you are not *required* to use the Hadamard gate to put your qubit in a superposition, any rotational gate along the X or Y axis will do. The Hadamard gate is just a very handy gate to initialize your qubit for further computing.  Tossing your coin on an IBM quantum computerIn this exercise we run our simple coin toss circuit on a real IBM Q quantum computer. For a local Qiskit installation we need to store our IBM Q credentials locally to be able to access the IBM Q backends.We use the `least_busy` method to find the backend with the smallest queue.<jupyter_code># Import IBMQ and the job monitoring tool
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor<jupyter_output><empty_output><jupyter_text>**Time for some work!** Before you can run your program on IBM Q you must load your API key. If you are running this notebook in an IBM Qx environment, your API key is already stored in the system, but if you are running on your own machine you [must first store the key](https://qiskit.org/documentation/install.htmlaccess-ibm-q-systems).<jupyter_code>#Save and store API key locally.
from qiskit import IBMQ
#IBMQ.save_account('MY_API_TOKEN') <- Uncomment this line if you need to store your API key

#Load account information 
IBMQ.load_account()
provider = IBMQ.get_provider()<jupyter_output><empty_output><jupyter_text>Set the backend to the least busy IBM quantum computer. We filter out simulators. We also want to know how long the quque is.<jupyter_code>backend = least_busy(provider.backends(operational=True, simulator=False))
print(backend.configuration().backend_name)
print(backend.status().pending_jobs)<jupyter_output>ibmqx2
1<jupyter_text>Create a quantum job for your circuit and the selected backend that runs 1,000 shots to simulate a series of coin tosses. Run the job and monitor the progress. Get and display the results.<jupyter_code>job_ibmq = execute(qc4, backend, shots=1000)
job_monitor(job_ibmq)

counts_ibmq  = job_ibmq.result().get_counts(qc4)

print(counts_ibmq)  
plot_histogram(counts_ibmq)<jupyter_output>Job Status: job has successfully run
{'0': 695, '1': 305}
{'fraction_non_alphanumeric': 0.07876685326815422, 'fraction_numerical': 0.04872664196168099, 'mean_word_length': 7.411140583554377, 'pattern_counts': {'":': 0, '<': 68, '<?xml version=': 0, '>': 70, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '398137', 'license': 'Apache-2.0', 'n_tokens_mistral': 5673, 'n_tokens_neox': 5223, 'n_words': 1149, 'path': 'qiskit_advocates/meetups/11_04_19-Hassi_Norlen-McLean/exercise_1_single_qubits_and_superposition.ipynb', 'repo_name': 'ordmoj/qiskit-community-tutorials', 'size': '16345'}