{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Design robust single-qubit gates using computational graphs\n",
"**Generate and test robust controls in Boulder Opal**\n",
"\n",
"In this tutorial you will find optimal pulses to implement a quantum gate for a single qubit, and test them against a scan of noise amplitude values.\n",
"\n",
"You will achieve that by creating a graph representing your control optimization problem, and using the highly flexible optimization engine in Boulder Opal to obtain high fidelity pulses robust to noise processes.\n",
"You will then test these pulses by calculating the infidelity of your gate for a range of values of the noise amplitude with another graph.\n",
"If you want to learn more about graphs and their use in Boulder Opal, we recommend that you read our [related topic](https://docs.q-ctrl.com/boulder-opal/topics/understanding-graphs-in-boulder-opal)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Design robust controls for a single qubit\n",
"\n",
"Your first task will be to obtain robust controls which implement a Y gate in a noisy single-qubit system.\n",
"In particular, the system is described by a Hamiltonian of the form\n",
"$$\n",
"H(t) = \\alpha(t) \\sigma_{z} + \\frac{1}{2}\\left(\\gamma(t)\\sigma_{-} + \\gamma^*(t)\\sigma_{+}\\right) + \\delta \\sigma_{z} + \\beta(t) \\sigma_{z} , \n",
"$$\n",
"where\n",
"$\\sigma_{z}$ is the Pauli Z operator,\n",
"$\\sigma_{\\pm}$ are the qubit ladder operators,\n",
"$\\alpha(t)$ and $\\gamma(t)$ are, respectively, real and complex time-dependent controls that you can manipulate, \n",
"$\\delta$ is the qubit detuning, and\n",
"$\\beta(t)$ is a dephasing noise process.\n",
"The dephasing amplitude $\\beta(t)$ is slowly varying so that you can assume that it is constant at each different realization.\n",
"\n",
"To generate the robust controls, you will create a computational graph that solves the Schrödinger equation for the system's Hamiltonian with optimizable controls $\\alpha(t)$ and $\\gamma(t)$ and calculates the infidelity with respect to your target gate.\n",
"By using the optimization engine in Boulder Opal, you will then find the controls that minimize that infidelity."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. Import libraries and start a Boulder Opal session\n",
"\n",
"Before doing any calculation with Boulder Opal, you always need to import the necessary libraries and start a session.\n",
"\n",
"In this case, import the `numpy`, `matplotlib.pyplot`, `qctrlvisualizer`, and `qctrl` packages.\n",
"To learn more about installing Boulder Opal and starting a session, see the [Get started](https://docs.q-ctrl.com/boulder-opal/get-started) guide."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# Import packages.\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import qctrlvisualizer\n",
"from qctrl import Qctrl\n",
"\n",
"# Apply Q-CTRL style to plots created in pyplot.\n",
"plt.style.use(qctrlvisualizer.get_qctrl_style())\n",
"\n",
"# Start a Boulder Opal session.\n",
"qctrl = Qctrl()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. Create the graph defining the optimization\n",
"\n",
"The relationships between inputs and outputs of a quantum system calculation in Boulder Opal are represented by a graph.\n",
"\n",
"#### Create the graph object\n",
"\n",
"Start by creating the graph object that will define the calculation.\n",
"You can do this by calling the `qctrl.create_graph` function."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"graph = qctrl.create_graph()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create optimizable signals for the Hamiltonian terms\n",
"\n",
"Control optimizations in Boulder Opal start by defining the time-dependent coefficients for the different Hamiltonian terms you want to optimize over, in this case, $\\alpha(t)$ and $\\gamma(t)$.\n",
"\n",
"\n",
"Start by creating an optimizable PWC in the graph representing $\\alpha(t)$, using the `graph.utils.real_optimizable_pwc_signal` operation.\n",
"Assign a name to this node with the `name` parameter so that you can retrieve its value after the optimization.\n",
"\n",
"***\n",
"_**`graph.utils` is part of the [Boulder Opal Toolkits](https://docs.q-ctrl.com/boulder-opal/references/qctrl/Toolkits.html) which are currently in beta phase of development. Breaking changes may be introduced.**_\n",
"\n",
"***"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# Pulse parameters.\n",
"segment_count = 50\n",
"duration = 10e-6 # s\n",
"\n",
"# Maximum value for |α(t)|.\n",
"alpha_max = 2 * np.pi * 0.25e6 # rad/s\n",
"\n",
"# Real PWC signal representing α(t).\n",
"alpha = graph.utils.real_optimizable_pwc_signal(\n",
" segment_count=segment_count,\n",
" duration=duration,\n",
" minimum=-alpha_max,\n",
" maximum=alpha_max,\n",
" name=\"$\\\\alpha$\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Following the same steps as you have just done for $\\alpha(t)$, create an optimizable PWC in the graph representing $\\gamma(t)$, using `graph.utils.complex_optimizable_pwc_signal`, and assign a name to it."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# Maximum value for |γ(t)|.\n",
"gamma_max = 2 * np.pi * 0.5e6 # rad/s\n",
"\n",
"# Complex PWC signal representing γ(t)\n",
"gamma = graph.utils.complex_optimizable_pwc_signal(\n",
" segment_count=segment_count, duration=duration, maximum=gamma_max, name=\"$\\\\gamma$\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Construct the Hamiltonian\n",
"\n",
"You have just defined the signals you want to find optimal values for.\n",
"The next step is to construct the system's Hamiltonian (so you can define the target of the optimization: the infidelity of the gate realized by these pulses).\n",
"\n",
"You can construct it by multiplying each signal (or constant) by its corresponding operator and adding the different terms.\n",
"You can use `graph.hermitian_part` to obtain the Hermitian part of $\\gamma(t) \\sigma_-$."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# Detuning δ.\n",
"delta = 2 * np.pi * 0.25e6 # rad/s\n",
"\n",
"# Total Hamiltonian.\n",
"hamiltonian = (\n",
" alpha * graph.pauli_matrix(\"Z\")\n",
" + graph.hermitian_part(gamma * graph.pauli_matrix(\"M\"))\n",
" + delta * graph.pauli_matrix(\"Z\")\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Define the target operation you want to achieve\n",
"\n",
"Now the graph contains a representation of your system's Hamiltonian with optimizable controls. \n",
"Next, use the `graph.target` operation to define the target operation that the Hamiltonian is meant to realize.\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# Target operation node.\n",
"target = graph.target(operator=graph.pauli_matrix(\"Y\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Define the noise processes in the system\n",
"\n",
"With the system Hamiltonian and the target gate, you now have all the ingredients needed to calculate the gate infidelity.\n",
"However, as you want your controls to be robust against dephasing, you need to create operators representing that noise process.\n",
"\n",
"In this case, as the noise amplitude $\\beta(t)$ is slowly varying, you can consider it to be constant but with a different amplitude at each experiment realization.\n",
"Thus, give it an amplitude representing the order of magnitude of the expected dephasing values."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# Dephasing noise amplitude.\n",
"beta = 2 * np.pi * 20e3 # rad/s\n",
"\n",
"# (Constant) dephasing noise term.\n",
"dephasing = beta * graph.pauli_matrix(\"Z\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create the cost node for a gate infidelity\n",
"\n",
"You can now create a node with the robust infidelity of the gate realized by your pulses with the `graph.infidelity_pwc` operation with the PWC `hamiltonian` and your `target` operation.\n",
"This convenient node takes care of solving the Schrödinger equation with your time-dependent PWC Hamiltonian, and calculating the infidelity with respect to the target operation.\n",
"\n",
"Pass it also the `dephasing` noise operator so that the infidelity includes its associated filter function values, making it robust against this type of noise.\n",
"Assign a name to it so you can tell the optimizer this is the (cost) node whose value should be minimized."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"# Robust infidelity.\n",
"robust_infidelity = graph.infidelity_pwc(\n",
" hamiltonian=hamiltonian,\n",
" noise_operators=[dephasing],\n",
" target=target,\n",
" name=\"robust_infidelity\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now you have defined a full graph describing the relationship between the optimizable signals and the robust gate infidelity."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3. Optimize the graph\n",
"\n",
"You can optimize the graph using the `qctrl.functions.calculate_optimization` function.\n",
"It will attempt to minimize the node whose `cost_node_name` you provide (in this case, the robust infidelity).\n",
"You need to also provide it with the `output_node_names` of the nodes that you want to retrieve, in this case the PWC signals $\\alpha(t)$ and $\\gamma(t)$."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/100 [00:00"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"qctrlvisualizer.plot_controls(controls=optimization_result.output)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Although the structure of these controls is not obvious at first glace, they work in such a way that they end up implementing a Y gate, and canceling the effects of the dephasing in the system.\n",
"Their jagged look is due to the PWC representation you have used, but Boulder Opal can also produce [continuous pulses by adding smoothing or band limits to them](https://docs.q-ctrl.com/boulder-opal/user-guides/how-to-add-smoothing-and-band-limits-to-optimized-controls)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test the robust controls\n",
"\n",
"Your next task will be to study how the controls you have just obtained behave for a range of dephasing values.\n",
"From the low optimization cost, you would expect that the pulses should yield low infidelities for a range of dephasing values.\n",
"\n",
"You will now set up another graph to calculate the gate infidelity of the robust controls for different values of the dephasing.\n",
"Instead of looping over the different values of the dephasing we are interested in, you will create a batch of dephasing terms, so that the graph calculation only has to be run once.\n",
"You can learn more about batching from our [Batching and broadcasting in Boulder Opal](https://docs.q-ctrl.com/boulder-opal/topics/batching-and-broadcasting-in-boulder-opal) topic."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. Extract the robust control values from the optimization\n",
"\n",
"Create arrays from the values of the robust PWC controls from the optimization in `optimization_result.output`.\n",
"Remember that `optimization_result.output[\"$\\\\alpha$\"]` is a list of dictionaries, one for each segment in the control, with `\"duration\"` and `\"value\"` keys.\n",
"You can easily extract these values with `qctrl.utils.pwc_pairs_to_arrays`."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"# Retrieve values of the robust PWC controls α(t) and γ(t).\n",
"_, alpha_values, _ = qctrl.utils.pwc_pairs_to_arrays(\n",
" optimization_result.output[\"$\\\\alpha$\"]\n",
")\n",
"_, gamma_values, _ = qctrl.utils.pwc_pairs_to_arrays(\n",
" optimization_result.output[\"$\\\\gamma$\"]\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that you have the values of the pulses that you want to simulate, you can create a graph very similar to the optimization one you defined above, but using these values instead of optimizable ones."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. Create the graph defining the scan\n",
"\n",
"#### Create the graph object\n",
"\n",
"Start by creating a new graph to define the infidelity scan."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"# Create a new Boulder Opal graph.\n",
"graph = qctrl.create_graph()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create PWC signals with the robust controls\n",
"\n",
"Similarly to how you created the optimizable PWC signals in the optimization graph with the `graph.pwc_signal` operation, define PWC signals for $\\alpha(t)$ and $\\gamma(t)$, but this time use the values you have just retrieved from the optimization."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"# Create a real PWC signal representing α(t).\n",
"alpha = graph.pwc_signal(values=alpha_values, duration=duration)\n",
"\n",
"# Create a complex PWC signal representing γ(t).\n",
"gamma = graph.pwc_signal(values=gamma_values, duration=duration)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a batch of dephasing operators\n",
"\n",
"As you want to analyze what happens for a range of values of the dephasing amplitude $\\beta$, create a batch of dephasing operators terms.\n",
"Create a 1D array with the values of $\\beta$ that you would like to scan over.\n",
"Pass those to `graph.constant_pwc`, along with the pulse `duration` and a `batch_dimension_count` of 1 (as the scan you're performing is over a single axis)."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"# Values of β to scan over.\n",
"beta_scan = np.linspace(-beta, beta, 100)\n",
"\n",
"# 1D batch of constant PWC\n",
"dephasing_amplitude = graph.constant_pwc(\n",
" beta_scan, duration=duration, batch_dimension_count=1\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This creates a batch of constant (scalar) PWCs, each element in it representing a different value of $\\beta$.\n",
"Using this to build your Hamiltonian will create a batch of Hamiltonians for each of the values of $\\beta$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Construct the Hamiltonian\n",
"\n",
"Construct the full Hamiltonian of the system in the same way you did in the optimization graph, but this time also include the dephasing term."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"# Total Hamiltonian.\n",
"hamiltonian = (\n",
" alpha * graph.pauli_matrix(\"Z\")\n",
" + graph.hermitian_part(gamma * graph.pauli_matrix(\"M\"))\n",
" + delta * graph.pauli_matrix(\"Z\")\n",
" + dephasing_amplitude * graph.pauli_matrix(\"Z\")\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Calculate the gate infidelity\n",
"\n",
"Define the infidelity of the Hamiltonian with `graph.infidelity_pwc` and a target defined with `graph.target`.\n",
"Note that this time you don't need to pass `noise_operators` as you are interested in the actual operational infidelity (without the filter function values).\n",
"Assign a node to it so you can retrieve it when the graph is executed."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"# Target operation node.\n",
"target = graph.target(operator=graph.pauli_matrix(\"Y\"))\n",
"\n",
"# Quasi-static scan infidelity.\n",
"infidelity = graph.infidelity_pwc(\n",
" hamiltonian=hamiltonian, target=target, name=\"infidelity\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As the `hamiltonian` is a batch of Hamiltonians for different values of $\\beta$, this infidelity node will contain the infidelity for each value of $\\beta$ you selected."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3. Execute the graph\n",
"\n",
"You now have a graph representing the dephasing scan calculation.\n",
"You can execute it with `qctrl.functions.calculate_graph` to evaluate the graph and get the outputs.\n",
"Pass to it the `output_node_names` of the nodes you want to retrieve, the `\"infidelity\"` for all dephasing values."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/100 [00:00"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Create plot with the infidelity scan.\n",
"fig, ax = plt.subplots()\n",
"ax.plot(beta_scan / 1e6 / 2 / np.pi, infidelities)\n",
"ax.set_xlabel(r\"$\\beta$ (MHz)\")\n",
"ax.set_ylabel(\"Infidelity\")\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that the infidelity is very low for a wide range of $\\beta$ values around zero, and particularly flat in the central region, showing the robustness of the pulse."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This concludes the tutorial. Congratulations on designing and testing your first robust pulses!\n",
"\n",
"You can now try optimizing controls for different quantum systems or robust to different types of noise by changing the optimization graph you have defined.\n",
"Our [user guides](https://docs.q-ctrl.com/boulder-opal/user-guides/) can also help you extend this powerful control optimization tool to other quantum problems.\n",
"If you want to generate smooth control pulses, please refer to our [How to add smoothing and band-limits to optimized controls](https://docs.q-ctrl.com/boulder-opal/user-guides/how-to-add-smoothing-and-band-limits-to-optimized-controls) user guide.\n",
"You might also be interested in reading about [Hamiltonians with nonlinear dependences](https://docs.q-ctrl.com/boulder-opal/user-guides/how-to-optimize-controls-with-nonlinear-dependences) or [dealing with systems in large Hilbert spaces](https://docs.q-ctrl.com/boulder-opal/user-guides/how-to-optimize-controls-on-large-sparse-hamiltonians).\n",
"You can also read more about [evaluating control susceptibility to quasi-static noise](https://docs.q-ctrl.com/boulder-opal/user-guides/how-to-evaluate-control-susceptibility-to-quasistatic-noise).\n",
"\n",
"If you want to learn more about graphs, you can read our [Understanding graphs in Boulder Opal](https://docs.q-ctrl.com/boulder-opal/topics/understanding-graphs-in-boulder-opal) topic.\n",
"You can also learn how to use graphs to simulate and visualize quantum dynamics in our [tutorial about simulation](https://docs.q-ctrl.com/boulder-opal/tutorials/simulate-the-dynamics-of-a-single-qubit-using-computational-graphs)."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"| Package | Version |\n",
"| ---------------- | ------- |\n",
"| Python | 3.9.12 |\n",
"| matplotlib | 3.5.1 |\n",
"| numpy | 1.23.3 |\n",
"| scipy | 1.9.1 |\n",
"| qctrl | 19.5.0 |\n",
"| qctrl-commons | 17.3.0 |\n",
"| qctrl-toolkit | 1.9.0 |\n",
"| qctrl-visualizer | 4.0.0 |\n"
]
}
],
"source": [
"from qctrl.utils import print_environment_related_packages\n",
"\n",
"print_environment_related_packages()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}