%%capture

# First, we install the essential libraries to our current Python runtime.
# "%%capture" (above) captures and in this case, hides the output of this 
# cell, so you can comment it out if you need help debugging this step.

%pip install cirq cirq_ionq matplotlib

import cirq, cirq_ionq, matplotlib.pyplot as plt, os
from getpass import getpass

# Before you begin, get your API key from https://cloud.ionq.com/settings/keys

# If your API key is stored as "IONQ_API_KEY" in your local environment, this
# should find it. Otherwise you'll be prompted to enter your API key manually.

api_key = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ')

service = cirq_ionq.Service(api_key=api_key, default_target='simulator')

# Now we set up our circuit. In this case, we're creating a circuit with two
# qubits, applying an H gate to qubit-0, a CXGate to both, then measuring.

q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit(
    cirq.H(q0),           # H
    cirq.CX(q0, q1),      # CNOT
    cirq.measure(q0, q1)  # Measure both qubits
)

# Before submitting the job, we can visualize the circuit using print().

print(circuit)

result = service.run(circuit, name="Cirq example", repetitions=100)
_ = cirq.plot_state_histogram(result, plt.subplot())
plt.show()