Passing input arguments to your QiskitPattern¶
In this document, we will learn how to pass arguments to our pattern.
Let’s create another file with our pattern ./source_files/pattern_with_arguments.py.
Instead of having the circuit defined inside the pattern (like we did in first example), we will pass it as an argument. We will also save the results, so we can access them later by calling save_result.
Here is the pattern:
# source_files/pattern_with_arguments.py
from qiskit_serverless import get_arguments, save_result
from qiskit.primitives import Sampler
# get all arguments passed to this pattern
arguments = get_arguments()
# get specific argument that we are interested in
circuit = arguments.get("circuit")
sampler = Sampler()
quasi_dists = sampler.run(circuit).result().quasi_dists
print(f"Quasi distribution: {quasi_dists[0]}")
# saving results of a pattern
save_result({
"quasi_dists": quasi_dists[0]
})
As you can see, the circuit construction is not inside the pattern anymore. Instead, we parse the arguments by calling the get_arguments function.
First, we will create circuit that we want to pass as an argument to the pattern.
[1]:
from qiskit import QuantumCircuit
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
circuit.draw()
[1]:
┌───┐ ░ ┌─┐ q_0: ┤ H ├──■───░─┤M├─── └───┘┌─┴─┐ ░ └╥┘┌─┐ q_1: ─────┤ X ├─░──╫─┤M├ └───┘ ░ ║ └╥┘ meas: 2/══════════════╩══╩═ 0 1
Now let’s create and configure our client
⚠ This provider is set up with default credentials to a test cluster intended to run on your machine. For information on setting up infrastructure on your local machine, check out the guide on local infrastructure setup.
[4]:
from qiskit_serverless import ServerlessClient
import os
client = ServerlessClient(
token=os.environ.get("GATEWAY_TOKEN", "awesome_token"),
host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"),
)
client
[4]:
<gateway-client>
[5]:
from qiskit_serverless import QiskitFunction
function = QiskitFunction(
title="pattern-with-arguments",
entrypoint="pattern_with_arguments.py",
working_dir="./source_files/",
)
client.upload(function)
[5]:
'pattern-with-arguments'
Run the function using the run
method and by passing arguments.
[6]:
my_function = client.get("pattern-with-arguments")
my_function
[6]:
QiskitFunction(pattern-with-arguments)
[7]:
job = my_function.run(circuit=circuit)
job
[7]:
<Job | c937663c-b722-43a8-b14d-5ee843f63b7c>
Retrieve the results from the client
[11]:
job.result()
[11]:
{'quasi_dists': {'0': 0.4999999999999999, '3': 0.4999999999999999}}