Skip to content

Instantly share code, notes, and snippets.

@maxfischer2781
Last active October 14, 2021 07:43
Show Gist options
  • Save maxfischer2781/61c5e6e7709c199bebc9a72f25dd403a to your computer and use it in GitHub Desktop.
Save maxfischer2781/61c5e6e7709c199bebc9a72f25dd403a to your computer and use it in GitHub Desktop.
Simple Physics Notation to Quantum Circuit example
# Measuring < 00 | X | 00 >, < 01 | X | 00 >, < 10 | X | 00 >, < 11 | X_0 | 00 >
from qiskit import QuantumCircuit
from qiskit.providers.aer import QasmSimulator
import time
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Circuit setup
circuit = QuantumCircuit(2) # |00>
# vvv change/expand this to prepare other states
circuit.x(0) # |ψ> = |01> = X_0 |00>
circuit.measure_all() # <00|ψ>, <01|ψ>, ...
# Display the circuit to see what it looks like
print(circuit.draw())
# Evaluate the circuit on a quantum device
pre = time.time()
job = simulator.run(circuit, shots=1000)
post = time.time()
print("Elapsed:", post - pre)
# Unpack results into human readable format
result = job.result()
counts = result.get_counts(circuit)
print("Measured the following states:", counts)

Setup

You need python3 and its venv module – if you don't have it, your package manager (apt-get, yum, ...) should be of help.

Create a separate Python environment. This is where the dependencies live; you can just delete it when you don't need it anymore.

$ # run this in your terminal
$ PLAYGROUND_PATH="~/qc_playground"    # you can change this to another folder if you want
$ mkdir -p $PLAYGROUND_PATH
$ python3 -m venv $PLAYGROUND_PATH/venv
$ source $PLAYGROUND_PATH/venv/bin/activate
$ pip install qiskit

Download the base_playground.py above. Ideally put it into PLAYGROUND_PATH, but any other path works as well. For example:

$ # pick either one as available
$ wget https://gist.githubusercontent.com/maxfischer2781/61c5e6e7709c199bebc9a72f25dd403a/raw/329c304ebbe2be22971aabd7325998e2292c6398/base_playground.py -P $PLAYGROUND_PATH/
$ curl https://gist.githubusercontent.com/maxfischer2781/61c5e6e7709c199bebc9a72f25dd403a/raw/329c304ebbe2be22971aabd7325998e2292c6398/base_playground.py -o $PLAYGROUND_PATH/base_playground.py

Whenever you want to play around with qiskit, run source $PLAYGROUND_PATH/venv activate in the shell. This changes the python command to point to your Qiskit Python environment.

To run the example, execute it after activating the environment:

python $PLAYGROUND_PATH/base_playground.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment