Experiment basic usage#
Setup and imports#
%matplotlib inline
import numpy as np
import exa.core as ec
from exa.core.provider import provider
from exa.core import TimeBox
from dataclasses import dataclass
#provider.init_loggers() # Optionally specify path to loggers conf file: `provider.init_loggers("loggers.yml.example")`
provider.init_iqm_server_runtime(
iqm_server_url="https://example.qc.com/",
quantum_computer="<quantum-computer-name>",
username="<username>",
token="<api-token>", # or set the IQM_TOKEN environment variable instead
# experiment_configuration_path="experiment.yml", # optional
)
obs_stash = ec.set_global_observation_stash([ec.GetCalibrationSet('default')])
Simple example: recreate T2 Ramsey experiment#
Creating an Experiment object with no init arguments inits the class with the default options and the
default circuit generation function. The available gates are taken from configuration.
By default, the readout_mode is “complex”.
The subscribed_components (i.e. the components that are read) default to all qubits found in the QPU.
exp = ec.Experiment()
print("Gates available:\n ", list(exp.gate_definitions.keys()))
print("Gates with calibration:\n ", list(exp.gates.keys()))
print("The options:\n ", exp.options)
print("The circuit generation function:\n ", exp.circuit_generation_function)
By default, this experiment generates a single circuit without gates and measures all qubits.
exp.run().last_run
To do something more useful, we should define circuit(s) to run. One way is to create a new Experiment class, and define the default circuit generator in the class, as explained later. We can also proceed without defining an Experiment class by passing circuit generation function to the constructor.
As an example, let’s create a circuit generation function that executes the T2 Ramsey experiment on all qubits. In this case, the given pulse sequences simply consists of pi/2 - wait - pi/2 pulses. The latter pi/2 pulse can be applied either around X or Y axis.
The pulse sequence generation functions are in principle free form, but the first two parameters are fixed:
components: The logical chip components, i.e. qubits and computational resonators.builder: A ScheduleBuilder object which will realize the gates.
def ramsey(
components,
builder: ec.ScheduleBuilder,
pulse_delay = 1e-6,
use_XY: bool = True
) -> list[TimeBox]:
timeboxes_for_qubits = []
for qubit in components:
prx = builder.prx([qubit])
first_pi2 = prx.rx(np.pi/2)
wait = builder.wait([qubit], pulse_delay, rounding=True)
if use_XY:
second_pi2 = prx.ry(np.pi/2)
else:
second_pi2 = prx.rx(np.pi/2)
timeboxes_for_qubits.append(TimeBox.composite(first_pi2 + wait + second_pi2))
return [TimeBox.composite(timeboxes_for_qubits)]
We can now use the function to execute the pulse schedule with the default circuit values.
exp = ec.Experiment(
circuit_generation_function=ramsey,
)
exp.run().last_run
Setting circuit parameters#
Circuit parameter values that are not part of a sweep can be set through settings.stages.circuit_generation.circuit.
If not set manually, the circuit parameters will be created from the parameter names of the circuit generation function.
It is possible to sweep any of the circuit parameters. Let’s sweep both the pulse_delay and use_XY parameters and then run the experiment.
settings = exp.get_settings()
settings.stages.circuit_generation.circuit.print_tree()
p_XY = settings.stages.circuit_generation.circuit.use_XY # This is a circuit setting
p_delay = settings.stages.circuit_generation.circuit.pulse_delay # This is a circuit setting
exp.run(
settings=settings,
sweeps=[
p_delay.sweep(np.linspace(1e-6, 20e-6, 21)),
p_XY.sweep([False, True]),
]
)
analyze_result = exp.analyze()
analyze_result.plot_all()
analyze_result.run_result.dataset
By default, the experiment does not know the units or datatypes of the circuit parameters, so we have to add them here if we want to display them.
p_delay = ec.Parameter('pulse_delay', 'Pulse Delay', unit='s')
p_XY = ec.Parameter('use_XY', 'Y gate', data_type=ec.DataType.BOOLEAN)
settings = exp.get_settings()
settings.stages.circuit_generation.circuit.use_XY = ec.Setting(p_XY, True)
settings.stages.circuit_generation.circuit.pulse_delay = ec.Setting(p_delay, 1e-6)
settings.stages.circuit_generation.circuit.print_tree()
Different readout modes#
Experiment supports five readout modes:
“complex” (the default)
“threshold”
“single_shot”
“single_shot_threshold”
“counter”
See the docstrings in ExperimentOptions and experiment_definitions.ReadoutMode for more
info on the readout modes.
Now, let’s change the readout_mode to “single_shot” and run the same T2 Ramsey experiment:
exp_ss = ec.Experiment(circuit_generation_function=ramsey)
exp_ss.options.readout_mode = "single_shot"
exp_ss.options.repetitions = 64
Note how the dataset now contains the “repetitions” dimension, which corresponds to the non-averaged single shots. The averaged results are computed as well.
exp_ss.run(
sweeps=[settings.stages.circuit_generation.circuit.pulse_delay.sweep(np.linspace(1e-6, 20e-6, 7))]
)
analyze_result = exp_ss.analyze()
analyze_result.plot_all()
analyze_result.run_result.dataset
A bit more complicated sequence#
Let’s use Native Instructions for specifying the single qubit gates this time, and do some CZ gates between two qubits. Let’s run the experiment in the “counter” readout mode.
from iqm.pulse.gates.enums import XYGate
def N_CZ(components, builder, CZ_count = 1):
"""Applies X180 on all qubits, then `CZ_count` number of CZ's to the first pair."""
flips = [
builder.prx([qubit]).clifford(XYGate.X_180)
for qubit in components
]
cz_on_first_pair = builder.cz(components[0:2])
czs = [cz_on_first_pair()] * CZ_count
return [TimeBox.composite(flips + czs)]
exp_cz = ec.Experiment(circuit_generation_function=N_CZ)
exp_cz.options.readout_mode = "counter"
sweep = ec.Parameter('CZ_count').set(0).sweep([0, 1, 2])
exp_cz.run(
components=["QB2", "QB3"],
sweeps=[sweep]
)
exp_cz.last_run.dataset
Deriving from Experiment#
Simple example of deriving a new experiment from Experiment.
The idea is not to override core functions like _run and get_settings,
but instead just define the minimal changes needed for the experiment to function.
Below, we need to only define the circuit generation function, the default sweeps and the default options.
One could also add extra arguments to the circuit function and get them to the settings tree
via Experiment.get_default_circuit_settings, do additional default changes to the settings tree
via Experiment.update_settings, and modify the default observation loading rules,
or use a custom connection graph via Experiment.setup_additional_init_properties.
# 1. Define the circuit.
def parallel_rabi_circuit(components, builder):
return [
TimeBox.composite(
[builder.prx([q]).rx(np.pi) for q in components]
).set_alap()
]
# 2. Define the new experiment
class RabiMQ(ec.Experiment):
default_options = ec.ExperimentOptions(readout_mode="complex")
# Here you pick the default circuit
def get_default_circuit_generation_function(self):
return parallel_rabi_circuit
# Define the default sweeps here. The ranges defined here are the lowest priority and are overridden by
# 1. default sweeps from the configuration (if they exist)
# 2. User provided ranges
def get_default_sweeps(self, components, settings):
pi_sweep = []
for qubit in components:
pi_sweep.append(settings.gates.prx.drag_gaussian[qubit].amplitude_i.sweep(np.linspace(-1, 1, 50)))
return [tuple(pi_sweep)]
#If you want the analysis to use parameters that are derived from the originally measured ones, define them here.
#For Rabi, we want to use contrast. Default data parameters will be updated.
def get_target_data_parameters(self, subscribed_components, components, settings):
return [ec.Parameter(f'{qubit}_contrast') for qubit in components]
rabi_mq = RabiMQ()
rabi_mq.run()
rabi_mq.analyze().plot_all()
Parallel Framework#
Writing parallelized 1QB experiments in the aforementioned way is easy, but when we want to create an experiment where the parallel elements are not single components but groups of components, e.g. connected qubit-pairs, it would result in a lot of boilerplate code. For this reason, Experiment provides functionalities that allow one to write the relevant experiment functions in terms of the quantities that actually matter. Also, now that we (hopefully) understand what Experiment does, we can actually skip writing most of the typical Experiment methods and instead define them as just functions.
# let's first define the circuit, sweep and analysis functions in terms of a single connected qubit-pair
def n_cphases_subschedule(group, builder, n_cphases = 1):
"""You don't need to write the circuit for the whole chip, but just for the given unit of
parallelisation, ``group``, which here is the connected qubit-pair."""
target_qubit, control_qubit = group
x_target = builder.prx([target_qubit]).clifford(XYGate.X_180)
x_control = builder.prx([control_qubit]).clifford(XYGate.X_180)
cz = builder.cz([target_qubit, control_qubit])()
flips = TimeBox.composite([x_target, x_control])
czs = TimeBox.composite([cz] * n_cphases)
return TimeBox.composite([flips, czs])
def n_cphases_sweep(group, chip_topology, settings):
"""We simply sweep the ``n_cphases``circuit param."""
return [ec.Parameter("n_cphases").set(0).sweep([0, 1, 2])]
def dummy_analyze_for_pair(group, chip_topology, run_result, data_color, settings, circuit_index):
"""The analyze function can also be written for just the pair."""
ec.AnalyzeResult(run_result=run_result, observations=[], plots={})
# Then writing the actual experiment class becomes just a couple of lines of "fitting the functions in their slots"
class NCPhaseTest(ec.Experiment):
name = "n cphase test"
parallel_group = ec.ParallelGroup.CONNECTED_PAIRS
default_circuit_generation_function = staticmethod(n_cphases_subschedule)
default_sweep_generation_function = staticmethod(n_cphases_sweep)
default_analyze_function = staticmethod(dummy_analyze_for_pair)
n_cphase = NCPhaseTest()
# let's run the experiment. Note that even though we defined everything in terms of just a single-pair, this will
# now run it for the whole chip, dividing the components to sets of parallelly runnable pairs (so called colors)
n_cphase.run()
n_cphase.last_run.dataset
Developing new gates & gate implementations#
Creating new GateImplementations#
iqm.pulse allows users to define their own gates and implementations and registering them for ad-hoc usage in a notebook/script without having to touch any of the underlying libraries. In the simplest case, this means changing some detail in one of the generic gate implementations, for example the pulse waveforms. However, it is also possible to write the gate implementation from scratch.
from exa.core.provider import ExaRuntime
# let's define a new PRX implementation by defining the I and Q waveforms via the PRX_CustomWaveforms base class:
from iqm.models.playlist.waveforms import Waveform
from iqm.pulse.gates.prx import PRX_CustomWaveforms
from iqm.pulse.gate_implementation import CompositeGate
@dataclass(frozen=True)
class RaisedCosine(Waveform):
r"""Raised cosine pulse.
.. math::
f(t) = \frac{1}{2} (1 + \cos((t - c) \pi / w)) \quad \text{when} \: |t - c| \le w, 0 \: \text{otherwise}
where :math:`c` is :attr:`center_offset`, and :math:`w` is :attr:`width`.
The raised cosine has a finite support.
Args:
width: half-width of the support
center_offset: center offset
"""
width: float
center_offset: float = 0.0
def _sample(self, sample_coords: np.ndarray) -> np.ndarray:
offset_coords = sample_coords - self.center_offset
return np.where(
np.abs(offset_coords) <= self.width,
0.5 * (1 + np.cos(offset_coords * np.pi / self.width)),
0.0,
)
@dataclass(frozen=True)
class RaisedCosineDerivative(Waveform):
r"""Scaled derivative of the RaisedCosine pulse.
.. math::
f(t) = -\sin((t - c) \pi / w) \quad \text{when} \: |t - c| \le w, 0 \: \text{otherwise}
where :math:`c` is :attr:`center_offset`, and :math:`w` is :attr:`width`.
Args:
width: half-width of the support
center_offset: center offset
"""
width: float
center_offset: float = 0.0
def _sample(self, sample_coords: np.ndarray) -> np.ndarray:
offset_coords = sample_coords - self.center_offset
return np.where(
np.abs(offset_coords) <= self.width,
-0.5 * np.sin(offset_coords * np.pi / self.width),
0.0,
)
class RaisedCosinePRX(PRX_CustomWaveforms, wave_i=RaisedCosine, wave_q=RaisedCosineDerivative):
"""Implementation of PRX using a raised cosine pulse instead of a gaussian."""
# Now that we have defined the gate implementation, we must register it for the gate prx.
# Let's do this for the whole of the current session such that all experiments can use the new implementation:
config = ExaRuntime.experiment_configuration()
config.register_gate_implementation(
gate_name="prx",
impl_name="raised_cosine",
impl_class=RaisedCosinePRX,
)
# Set some default values for the gate parameters:
config.set_calibration_data_for_gate_implementation(
"prx",
"raised_cosine",
{(): { # empty locus () denotes default values. You can set values for specific locus, like ("QB1",) similarly
"duration": 4e-8,
"amplitude_i": 0.0,
"amplitude_q": 0.0,
"i": {"width": 3e-8, "center_offset": 0.0},
"q": {"width": 3e-8, "center_offset": 0.0}
}}
)
# Or alternatively only for a specific experiment instance (using the same method):
my_exp = ec.Experiment()
my_exp.register_gate_implementation(
gate_name="prx",
impl_name="raised_cosine",
impl_class=RaisedCosinePRX,
)
my_exp.set_calibration_data_for_gate_implementation(
"prx",
"raised_cosine",
{(): {
"duration": 4e-8,
"amplitude_i": 0.0,
"amplitude_q": 0.0,
"i": {"width": 3e-8, "center_offset": 0.0},
"q": {"width": 3e-8, "center_offset": 0.0}
}}
)
# Most experiments are written such that they will always use the currently defined default implementation.
# Let's create a Rabi experiment but change the default PRX into RaisedCosinePRX.
# NOTE: we could also set the default for the whole session, similarly to the registering above.
from exa.public_experiments import Rabi
rabi = Rabi()
rabi.set_gate_implementation_as_default("prx", "raised_cosine")
# Observe that the default has now been changed into RaisedCosinePRX
rabi_settings = rabi.get_settings()
rabi_settings.gates.prx.print_tree(6)
# Let's run it and see the results. We can also save the observations and have amplitude calibration
# for our RaisedCosinePRX. We could then continue with the full calibration sequence if we wanted.
rabi.run()
analyze_result = rabi.analyze()
analyze_result.render_report()
analyze_result.run_result.observations.validate().tag(tags=tags).stash(obs_stash)
Registering new gates (operations) using CompositeGate#
iqm.pulse also allows for creating a completely new gate/operation in one’s notebook/script and then registering it similarly to the GateImplementation above. The user may of course write the logic for any implementations of this new gate from the scratch, but there is also a useful base class CompositeGate, which can be used to create GateImplementations in terms of other already existing gates.
# Let's define a Hadamard gate implementation in terms of PRX gate:
from iqm.pulse.quantum_ops import QuantumOp
class CompositeHadamard(CompositeGate):
"""Hadamard gate."""
registered_gates = ("prx",)
def _call(self) -> TimeBox:
return self.build("prx", self.locus).ry(np.pi / 2) + self.build("prx", self.locus).rx(np.pi)
# Let's further define a CNot gate implementation in terms of Hadamard and CZ gates:
class CompositeCNot(CompositeGate):
"""CNot gate."""
registered_gates = ("hadamard", "cz")
def _call(self) -> TimeBox:
target_hadamard = self.build("hadamard", (self.locus[0],))()
return target_hadamard + self.build("cz", self.locus)() + target_hadamard
# Let's register both gates and their composite implementations. Since there are no prior implementations for either,
# gate, the above implementations will be defaults automatically
# NOTE: as these are composite gate implementations, we don't necessarily need to add any calibration data for them.
# They will use the normal CZ and PRX calibrations unless otherwise specified (see the below cells)
config = ExaRuntime.experiment_configuration()
config.register_gate_implementation(
gate_name="hadamard",
impl_name="composite_hadamard",
impl_class=CompositeHadamard,
quantum_op=QuantumOp( # here we define the new quantum operation, i.e. "gate" for which to add the implementation
name="hadamard",
arity=1, # how many locus components the operation has
symmetric=True, # does not matter for arity=1
)
)
config.register_gate_implementation(
gate_name="cnot",
impl_name="composite_cnot",
impl_class=CompositeCNot,
quantum_op=QuantumOp(
name="cnot",
arity=2,
symmetric=False, # cnot is asymmetric
)
)
# CNot is a 2-qubit gate that flips the target qubit if and only if the control qubit is in the excited state.
# Let's write a quick (inconclusive) experiment that verifies this
def verify_cnot_circuit(components, builder):
"""Circuit where the first element corresponds to CNot * |00>, the second element to CNot * |01>,
the third to CNot * |10>, and the fourth to |11>"""
pair, target, control = components[0], components[0][0], components[0][1]
idn = builder.wait(control, 0.0)
flip_t = builder.prx((target,)).rx(np.pi)
flip_c = builder.prx((control,)).ry(np.pi)
flips = [idn, flip_c, flip_t, flip_t + flip_c]
boxes = []
for flip in flips:
boxes.append(flip + builder.get_implementation("cnot", pair)())
return boxes
cnot_exp = ec.Experiment(circuit_generation_function=verify_cnot_circuit)
cnot_exp.options.readout_mode = "counter"
cnot_settings = cnot_exp.get_settings()
# The settings tree structure for CNot contains its component gates recursively
# You may set different values for CZ inside the CNOT or further a PRX inside the Hadamard inside the CNot.
# The values set like this will override the default values of CZ, PRX etc.
cnot_settings.gates.cnot.composite_cnot.QB2__QB3.gates.cz.tgss.QB2__QB3.duration = 4e-8
cnot_settings.gates.cnot.print_tree(15)
# Let's run it and compare with ideal CNot operation:
cnot_exp.run(components=[("QB3", "QB1")])
cnot_00 = list(cnot_exp.last_run.dataset["counter.result"][:,0].data)
cnot_01 = list(cnot_exp.last_run.dataset["counter.result"][:,1].data)
cnot_10 = list(cnot_exp.last_run.dataset["counter.result"][:,2].data)
cnot_11 = list(cnot_exp.last_run.dataset["counter.result"][:,3].data)
print("\n")
print("Ideally we expect CNot to map |00> to |00>, i.e. in counter readout: [1,0,0,0]")
print(f"The measured counter readout was: {cnot_00}")
print("\n")
print("Ideally we expect CNot to map |01> to |11>, i.e. in counter readout: [0,0,0,1]")
print(f"The measured counter readout was: {cnot_01}")
print("\n")
print("Ideally we expect CNot to map |10> to |10>, i.e. in counter readout: [0,0,1,0]")
print(f"The measured counter readout was: {cnot_10}")
print("\n")
print("Ideally we expect CNot to map |11> to |01>, i.e. in counter readout: [0,1,0,0]")
print(f"The measured counter readout was: {cnot_11}")
Programmable readout#
By default Experiment appends each segment in a circuit with a multiplexed measurement operation that reads all the readout components simultaneously. When this behaviour is enough, the user does not need to add any measurement operations in the circuit function itself. However, in case a more complicated measurement scheme is needed, the readouts can also be included in schedule itself. There can be any number of measurements in a circuit (also different numbers between different components). Currently the number of measurements for a given component must be constant between different segments of the circuit, and the measurements must happen at same times in each segment, however.
def circuit_with_readouts(components, builder: ec.ScheduleBuilder):
"""Simple circuit that runs X180 + measurement for all qubits twice, and then does one more X180 and
adds a third measurement for just the first qubit."""
prxs = TimeBox.composite([builder.prx((c,)).rx(np.pi) for c in components])
measure_all = builder.measure(tuple(components))()
measure1 = builder.measure((components[0],))()
return [prxs + measure_all + prxs + measure_all + prxs + measure1]
readout_exp = ec.Experiment(circuit_generation_function=circuit_with_readouts)
# CUSTOM programming mode does not add any extra readouts, they must be included in the schedule itself.
readout_exp.options.readout_programming_mode = "custom"
# All readout_modes are supported, but the "counter" mode has a caveat that it does not currently support
# different number of measurements per component due to xarray limitations.
readout_exp.options.readout_mode = "threshold"
readout_settings = readout_exp.get_settings()
# Let's print the settings and observe the calibration data for the measure operation:
readout_settings.gates.measure.print_tree()
# Let's run the experiment and display the resulting dataset. We see there is a data dimension <qubit>_readout_slot
# that defines the index of the measurement for that qubit. For all the other qubits, the dimensionality is 2 but
# for the first qubit, it is 3. We also observe from the measured data that the consecutive X180 gates flip
# qubits between |0> and |1>, as expected.
readout_exp.run(settings=readout_settings)
readout_exp.last_run.dataset