{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Simulating noise on Amazon Braket" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Use Braket SDK Cost Tracking to estimate the cost to run this example\n", "from braket.tracking import Tracker\n", "t = Tracker().start()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook gives a detailed overview of noise simulations on Amazon Braket. Amazon Braket provides two noise simulators: a local noise simulator that you can use for free as part of the Braket SDK and an on-demand, high-performing noise simulator, DM1. Both simulators are based on the density matrix formalism. After this tutorial, you will be able to define noise channels, apply noise to new or existing circuits, and run those circuits on the Braket noise simulators. \n", "\n", "### Table of contents:\n", "* [Background](#Background)\n", " * [Noise simulation based on the density matrix formalism](#density_matrix)\n", " * [Quantum channel and Kraus representation](#quantum_channel)\n", "* [General imports](#imports)\n", "* [Quick start](#start)\n", "* [Defining noise channels](#noise_channels)\n", " * [Pre-defined noise channels](#pre-defined)\n", " * [Defining custom noise channels](#self-defined)\n", "* [Adding noise to a circuit](#apply_noise)\n", " * [Build noisy circuits bottom-up](#apply_noise_directly)\n", " * [Applying noise to existing circuits with global methods](#apply_noise_globally)\n", " * [Applying gate noise to the circuit](#gate-noise)\n", " * [Applying initialization noise to the circuit](#initialization-noise)\n", " * [Applying readout noise to the circuit](#readout-noise)\n", " * [Using both the direct and global methods to apply noise](#both)\n", "* [Running a noisy circuit](#run)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Background \n", "\n", "### Noise simulation based on the density matrix formalism \n", "In an ideal case, a quantum state prepared by a noise-free circuit can be described by a state vector $|\\psi\\rangle$ -- we call it a 'pure state'. However, the presence of noise in realistic quantum devices will introduce classical uncertainty to the quantum state. For example, a bit flip error with 50% probability acting on a qubit flips the $|0\\rangle$ state into either $|0\\rangle$ or $|1\\rangle$ with a 50-50 chance. Note that this is different from an Hadamard-gate acting on $|0\\rangle$: The latter results in a coherent superposition of $|0\\rangle$ and $|1\\rangle$, whereas the former is a classical, so-called mixture of $|0\\rangle$ and $|1\\rangle$. The most general way of describing a quantum state in the presence of noise is through the so-called density matrix: $\\rho = \\sum_i p_i|\\psi_i\\rangle\\langle\\psi_i|$. It can be understood as a classical mixture of a series of pure states $|\\psi_i\\rangle$ (each of which could be highly entangled), where $p_i$ is the probability of the state being in $|\\psi_i\\rangle$. Because the $p_i$ are classical probabilities they have to sum up to 1: $\\sum_i p_i = 1$. The density matrix of a pure state is simply $\\rho = |\\psi\\rangle\\langle\\psi|$ and, in the bit-flip example from above, the density matrix would be $\\rho = 0.5|0\\rangle\\langle 0| + 0.5|1\\rangle\\langle 1|$. \n", "\n", "The density matrix formalism is a very useful way to describe a noisy system with probabilistic outcomes. It gives an exact description of a quantum system going through a quantum channel with noise. Besides, the expectation value of an observable $\\langle O\\rangle$ can be easily calculated by $\\rm{Tr}(O\\rho)$, where \"$\\rm{Tr}$\" is the trace operator. \n", "\n", "### Quantum channel and Kraus representation \n", "\n", "A [quantum channel](https://en.wikipedia.org/wiki/Quantum_channel) describes the time evolution of a quantum state which is expressed as a density matrix. For instance, to understand what a series of noisy gates does to the state of a quantum computer, you can apply a quantum channel corresponding to the different gate and noise operations. \n", "Mathematically speaking, a quantum channel is a completely positive and trace-preserving (CPTP) linear map acting on a density matrix. Completely positive means the channel maps positive operators into positive operators (even if the operator is applied to part of a larger system) to make sure the density matrix describes a proper quantum state after the map. Trace-preserving means the trace of the density matrix remains unchanged during the mapping process (this is so that after the map the classical probabilities $p_i$ still sum to 1). \n", "\n", "The so-called _Kraus representation_ is a commonly used representation for CPTP maps. [Kraus's theorem](https://en.wikipedia.org/wiki/Quantum_operation#Kraus_operators) states that any quantum operation acting on a quantum state $\\rho$ can be expressed as a map $\\varepsilon(\\rho) = \\sum_i K_i\\rho K_i^{\\dagger}$, and it satisfies: $\\sum_i K_i^{\\dagger}K_i = \\mathbb{1}$, where $\\mathbb{1}$ is the Identity operator.\n", "\n", "Let's get started and have a look how you can define and simulate noisy circuits on Amazon Braket." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## General imports " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's begin with the usual imports." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from braket.circuits import Circuit, Observable, Gate, Noise, FreeParameter\n", "from braket.devices import LocalSimulator\n", "from braket.aws import AwsDevice\n", "import numpy as np\n", "from scipy.stats import unitary_group" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Quick start \n", "\n", "Let's start with a simple example of running a noisy circuit on Amazon Braket. " ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "measurement results: Counter({'11': 441, '00': 381, '01': 94, '10': 84})\n" ] } ], "source": [ "# build a simple circuit\n", "circ = Circuit().h(0).cnot(0,1)\n", "\n", "# define a noise channel\n", "noise = Noise.BitFlip(probability=0.1)\n", "\n", "# add noise to every gate in the circuit\n", "circ.apply_gate_noise(noise)\n", "\n", "# select the local noise simulator\n", "device = LocalSimulator('braket_dm')\n", "\n", "# run the circuit on the local simulator\n", "task = device.run(circ, shots = 1000)\n", "\n", "# visualize the results\n", "result = task.result()\n", "measurement = result.measurement_counts\n", "print('measurement results:', measurement)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ideally, in the noise-free case, the circuit we defined prepares a Bell-state, and we would expect to measure only '00' and '11' outcomes. However, the presence of noise, in our case a bit flip error, means that sometimes we find the state in '01' and '10' instead.\n", "\n", "The local simulator is suitable for fast prototyping on small circuits. If you want to run a noisy circuit with more than 10~12 qubits, we recommend using the on-demand simulator DM1. Using DM1, you can run circuits with up to 17 qubits, and benefit from parallel execution for a group of circuits. The code below shows an example of preparing a 13-qubit GHZ state in the presence of noise." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "measurement results: Counter({'0000000000000': 2, '1100111111111': 1, '0000000000001': 1, '1000001111100': 1, '1111100000000': 1, '0000000010000': 1, '1111111111111': 1, '1000010000001': 1, '0011111111111': 1})\n" ] } ], "source": [ "def ghz_circuit(n_qubits: int) -> Circuit:\n", " \"\"\"\n", " Function to return simple GHZ circuit ansatz. Assumes all qubits in range(0, n_qubits-1)\n", " are entangled.\n", " \"\"\"\n", " circuit = Circuit().h(0) \n", "\n", " for ii in range(0, n_qubits-1):\n", " circuit.cnot(control=ii, target=ii+1) \n", " return circuit\n", "\n", "# build a 13-qubit GHZ circuit\n", "circ = ghz_circuit(13)\n", "\n", "# define a noise channel\n", "noise = Noise.Depolarizing(probability=0.1)\n", "\n", "# add noise to every gate in the circuit\n", "circ.apply_gate_noise(noise)\n", "\n", "# select the on-demand density matrix simulator DM1\n", "device = AwsDevice(\"arn:aws:braket:::device/quantum-simulator/amazon/dm1\")\n", "\n", "# run the circuit on DM1\n", "task = device.run(circ, shots = 10)\n", "\n", "# visualize the results\n", "result = task.result()\n", "measurement = result.measurement_counts\n", "print('measurement results:', measurement)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We now start exploring the detailed instructions and use cases of each step in the following sections." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Defining noise channels \n", "\n", "To apply noise to a quantum circuit, first, you need to define the noise channel, which is defined in Kraus representation. We offer many commonly-used noise channels in the `Noise` class of the [Amazon Braket SDK](https://amazon-braket-sdk-python.readthedocs.io/en/latest/_apidoc/braket.circuits.html). In addition, you can also define your own custom noise channel as a list of Kraus operators.\n", "\n", "### Pre-defined noise channels \n", "\n", "The pre-defined single-qubit noise channels include `BitFlip`, `PhaseFlip`, `Depolarizing`, `AmplitudeDamping`, `GeneralizedAmplitudeDamping`, `PhaseDamping` and `PauliChannel`. \n", "The pre-defined two-qubit noise channels include `TwoQubitDepolarizing` and `TwoQubitDephasing`. The Kraus representations for all of the pre-defined channels are summarized in the following table.\n", "\n", "__single-qubit noise channels__\n", "\n", "| Noise channel |
Kraus representation
| Parameter |\n", "|:-------------- |:-------------------------------------------------- |:------------|\n", "| `BitFlip` | $(1-p)\\rho$ + $pX\\rho X$| $p$ is the probability of the bit flip noise. |\n", "| `PhaseFlip` | $(1-p)\\rho$ + $pZ\\rho Z$| $p$ is the probability of the phase flip noise. |\n", "| `Depolarizing` |$(1-p)\\rho$ + $p/3(X\\rho X$ + $Y\\rho Y$ + $Z\\rho Z)$|$p$ is the probability of the depolarizing noise (the three possible error cases share the same probability of $p/3$).|\n", "|`AmplitudeDamping`|$K_0\\rho K_0^\\dagger$ + $K_1\\rho K_1^\\dagger$|$K_0=[1,0;0,\\sqrt{1-\\gamma}]$, $K_1=[0,\\sqrt{\\gamma};0,0]$, where $\\gamma$ is the rate of amplitude damping.|\n", "|`GeneralizedAmplitudeDamping`|$K_0\\rho K_0^\\dagger$ + $K_1\\rho K_1^\\dagger$ + $K_2\\rho K_2^\\dagger$ + $K_3 \\rho K_3^\\dagger$|$K_0=\\sqrt{p}[1,0;0,\\sqrt{1-\\gamma}]$, $K_1=\\sqrt{p}[0,\\sqrt{\\gamma};0,0]$, $K_2=\\sqrt{1-p}[\\sqrt{1-\\gamma},0;0,1]$, $K_3=\\sqrt{1-p}[0,0;\\sqrt{\\gamma},0]$, where $\\gamma$ is the rate of amplitude damping, and $p$ is the probability of the system been excited by the environment [1].|\n", "|`PhaseDamping`|$K_0\\rho K_0^\\dagger$ + $K_1 \\rho K_1^\\dagger$|$K_0=[1,0;0,\\sqrt{1-\\gamma}]$, $K_1=[0,0;0,\\sqrt{\\gamma}]$, where $\\gamma$ is the rate of phase damping.|\n", "|`PauliChannel`|$(1-p_x-p_y-p_z)\\rho$ + $p_xX\\rho X$ + $p_yY\\rho Y$ + $p_zZ\\rho Z$|$p_x$, $p_y$ and $p_z$ are probabilities for the Pauli X, Y, Z noise respectively.|\n", "\n", "\n", "__two-qubit noise channels__\n", "\n", "|
Noise channel
|
Kraus representation
| Parameter |\n", "|:----------------------- |:-------------------------------------------------- |:------------|\n", "| `TwoQubitDepolarizing`| $(1-p)\\rho$ + $p/15(IX\\rho IX$ + $IY\\rho IY$ + $IZ\\rho IZ$ + $XI\\rho XI$ +....+ $ZZ\\rho ZZ)$| $p$ is the probability of the two-qubit depolarizing noise (the 15 possible error combinations share the same probability of $p/15$).|\n", "| `TwoQubitDephasing` | $(1-p)\\rho$ + $p/3(IZ\\rho IZ$ + $ZI\\rho ZI$ + $ZZ\\rho ZZ)$| $p$ is the probability of the two-qubit dephasing noise (the three possible error combinations share the same probability of $p/3$). |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following code block takes the example of the bit flip noise channel: $\\rho\\rightarrow(1-p)\\rho$ + $pX\\rho X$, where $p$ corresponds to the `probability` parameter when defining the noise. This noise channel is equivalent to applying a bit flip error (applying an X gate) with probability $p$ and doing nothing with probability $1-p$. You can check the target qubit count and the Kraus operators of the noise channel defined." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name: BitFlip\n", "qubit count: 1\n", "Kraus operators: \n", "[[0.9486833+0.j 0. +0.j]\n", " [0. +0.j 0.9486833+0.j]] \n", "\n", "[[0. +0.j 0.31622777+0.j]\n", " [0.31622777+0.j 0. +0.j]] \n", "\n" ] } ], "source": [ "# define a bit flip noise channel with probability = 0.1\n", "noise = Noise.BitFlip(probability=0.1)\n", "\n", "print('name: ', noise.name)\n", "print('qubit count: ', noise.qubit_count)\n", "print('Kraus operators: ')\n", "for matrix in noise.to_matrix():\n", " print(matrix, '\\n')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other pre-defined noise channels can be used in a similar way:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# define a phase flip noise channel\n", "noise = Noise.PhaseFlip(probability=0.1)\n", "# define a single-qubit depolarizing noise channel\n", "noise = Noise.Depolarizing(probability=0.1)\n", "# define a two-qubit depolarizing noise channel\n", "noise = Noise.TwoQubitDepolarizing(probability=0.1)\n", "# define a two-qubit dephasing noise channel\n", "noise = Noise.TwoQubitDephasing(probability=0.1)\n", "# define an amplitude damping noise channel\n", "noise = Noise.AmplitudeDamping(gamma=0.1)\n", "# define a generalized amplitude damping noise, where gamma is the amplitude damping rate, and\n", "# probability is the probability of the system being excited by the environment.\n", "noise = Noise.GeneralizedAmplitudeDamping(gamma=0.1, probability=0.1)\n", "# define a phase damping noise channel\n", "noise = Noise.PhaseDamping(gamma=0.1)\n", "# define a Pauli noise channel\n", "noise = Noise.PauliChannel(probX=0.1, probY=0.2, probZ=0.3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Defining custom noise channels \n", "Apart from the pre-defined noise models, you can also define your own noise model by specifying a list of Kraus operators. The following code shows an example of defining a two-qubit Kraus channel with randomly generated unitary operators." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# create an arbitrary 2-qubit Kraus matrix\n", "E0 = unitary_group.rvs(4) * np.sqrt(0.2) \n", "E1 = unitary_group.rvs(4) * np.sqrt(0.8)\n", "K = [E0, E1] \n", "\n", "# define a two-qubit noise channel with Kraus operators\n", "noise = Noise.Kraus(K) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the noise channel you define needs to form a CPTP map. If the input matrices do not define a CPTP map, an error will be raised." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The input matrices do not define a completely-positive trace-preserving map.\n" ] } ], "source": [ "K_invalid = [np.random.randn(2,2), np.random.randn(2,2)] \n", "\n", "try:\n", " noise = Noise.Kraus(K_invalid)\n", " pass\n", "except ValueError as err:\n", " print(err)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding noise to a circuit \n", "\n", "There are two methods to build a 'noisy' circuit. First, you can add noise to the circuit 'bottom-up', by using the noise operations in the same way as you would add a gate to the circuit. Second, you can use the methods `apply_gate_noise()`, `apply_initialization_noise()` and `apply_readout_noise()` to apply gate error, qubit initialization error and measurement error globally to existing circuits. \n", "\n", "The direct method is more flexible as you can apply noise to any place in a circuit. But for an existing large circuit with lots of gates, you may want to use the global methods to conveniently apply noise to the circuit.\n", "\n", "\n", "### Build noisy circuits bottom-up \n", "Noise channels can be applied to the circuit the same way as gates. The following example shows how to apply single- and two-qubit noise channels directly to a circuit. The noise applied can be visualized in the circuit diagram with the `print()` method." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T : |0| 1 | 2 |\n", " \n", "q0 : -X-C-----------X-DEPH(0.1)-\n", " | | \n", "q1 : -X-X-DEPO(0.2)---DEPH(0.1)-\n", "\n", "T : |0| 1 | 2 |\n" ] } ], "source": [ "# apply depolarizing noise\n", "circ = Circuit().x(0).x(1).cnot(0,1).depolarizing(1, probability=0.2).x(0).two_qubit_dephasing(target1=0, target2=1, probability=0.1)\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Applying noise to existing circuits with global methods\n", "\n", "We offer three methods to apply noise globally to the circuit: `apply_gate_noise()`, `apply_initialization_noise()` and `apply_readout_noise()`. In the following, we explain in detail the usage of these three methods.\n", "\n", "#### Applying gate noise to the circuit \n", "\n", "`apply_gate_noise()` is the method to conveniently apply gate-noise to the circuit. It accepts the following input parameters:\n", "\n", "- __noise__: A single or a list of noise channel in `Noise` type.\n", "- __target_unitary__: A single unitary gate in the form of a matrix in `numpy.ndarray` type. The noise will be applied to that unitary gate. \n", "- __target_gates__: A single or a list of gates in `Gate` type. Note that `target_gates` and `target_unitary` can not be provided at the same time. If none of `target_gates` and `target_unitary` is given, noise will be applied to all the gates in the circuit. \n", "- __target_qubits__: A single or a list of qubit indexes. If not given, noise will be applied to all the qubits in the circuit.\n", "\n", "When calling the method, the noise channel(s) will be applied right after all `target_gates` in `target_qubits`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Note When you call this method, noise will be inserted right after the gate. If you like to apply more than one noise operation, be aware of the order. Alternatively, you can provide a list of noise operations in one call, and the noise will be applied in forward order. \n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code below is an example of applying phase damping noise to all gates in the circuit." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise is applied to every gate in the circuit:\n", "\n", "T : | 0 | 1 |\n", " \n", "q0 : -X-PD(0.1)-BF(0.1)-C-PD(0.1)-\n", " | \n", "q1 : -------------------X-PD(0.1)-\n", "\n", "T : | 0 | 1 |\n" ] } ], "source": [ "noise = Noise.PhaseDamping(gamma=0.1)\n", "\n", "# the noise channel is applied to every gate in the circuit\n", "circ = Circuit().x(0).bit_flip(0,0.1).cnot(0,1)\n", "circ.apply_gate_noise(noise)\n", "print('Noise is applied to every gate in the circuit:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to apply noise to some particular gates in the circuit, you can specify them as `target_gates`. Below is an example in which noise is applied to all X gates in the circuit." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Note The target_gates must be a Gate type. You can find all available gates with the following commands:\n", " \n", "\n", "from braket.circuits import Gate\n", "gate_set = [attr for attr in dir(Gate) if attr[0] in string.ascii_uppercase]\n", "print(gate_set)\n", "\n", "
" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise is applied to every X gate:\n", "\n", "T : | 0 | 1 |2|\n", " \n", "q0 : -X-PD(0.1)-C-------------\n", " | \n", "q1 : -Y---------|-X-PD(0.1)---\n", " | \n", "q2 : -----------X-----------Z-\n", "\n", "T : | 0 | 1 |2|\n" ] } ], "source": [ "# the noise channel is applied to all the X gates in the circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_gate_noise(noise, target_gates = Gate.X)\n", "print('Noise is applied to every X gate:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you define custom unitary gates as part of your circuit, and you want to apply noise to them, you can use the `target_unitary` criterion." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise is applied to U2:\n", "\n", "T : |0|1| 2 |3| 4 |\n", " \n", "q0 : -X-U-C---------------\n", " | | \n", "q1 : -Y-U-|-X---U-PD(0.1)-\n", " | | \n", "q2 : -----X---Z-U-PD(0.1)-\n", "\n", "T : |0|1| 2 |3| 4 |\n" ] } ], "source": [ "U1=unitary_group.rvs(4)\n", "U2=unitary_group.rvs(4)\n", "circ = Circuit().x(0).y(1).unitary((0,1),U1).cnot(0,2).x(1).z(2).unitary((1,2),U2)\n", "circ.apply_gate_noise(noise, target_unitary = U2)\n", "print('Noise is applied to U2:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to apply noise to some particular qubits in the circuit, you can specify them as `target_qubits`. Below is an example to apply noise to all gates in qubits 0 and 2 in the circuit." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise is applied to every gate in qubits 0 and 2:\n", "\n", "T : | 0 | 1 | 2 |\n", " \n", "q0 : -X-PD(0.1)-C-PD(0.1)-----------\n", " | \n", "q1 : -Y---------|-X-----------------\n", " | \n", "q2 : -----------X-PD(0.1)-Z-PD(0.1)-\n", "\n", "T : | 0 | 1 | 2 |\n" ] } ], "source": [ "# the noise channel is applied to every gate on qubits 0 and 2\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_gate_noise(noise, target_qubits = [0,2])\n", "print('Noise is applied to every gate in qubits 0 and 2:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `target_qubits` and `target_gates` criteria can be used at the same time. The code block below applies the gate noise to all X gates in qubit 0." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise is applied to X gates in qubits 0:\n", "\n", "T : | 0 | 1 | 2 |\n", " \n", "q0 : -X-PD(0.1)-C---X-PD(0.1)-\n", " | \n", "q1 : -Y---------|-X-----------\n", " | \n", "q2 : -----------X---Z---------\n", "\n", "T : | 0 | 1 | 2 |\n" ] } ], "source": [ "# the noise channel is applied to X gate on qubits 0\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(0).x(1).z(2)\n", "circ.apply_gate_noise(noise, target_gates = Gate.X, target_qubits = 0)\n", "print('Noise is applied to X gates in qubits 0:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a list of noise channels is provided, the first noise channel in the list will be applied first, then the second. " ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise channels are applied to every gate in qubits 0 and 1:\n", "\n", "T : | 0 | 1 |2|\n", " \n", "q0 : -X-DEPO(0.1)-BF(0.2)-C-DEPO(0.1)-BF(0.2)-------------\n", " | \n", "q1 : -Y-DEPO(0.1)-BF(0.2)-|-X---------DEPO(0.1)-BF(0.2)---\n", " | \n", "q2 : ---------------------X-----------------------------Z-\n", "\n", "T : | 0 | 1 |2|\n" ] } ], "source": [ "# define two noise channels\n", "noise1 = Noise.Depolarizing(probability=0.1)\n", "noise2 = Noise.BitFlip(probability=0.2)\n", "\n", "# apply a list of noise channels \n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_gate_noise([noise1, noise2], target_qubits = [0,1])\n", "print('Noise channels are applied to every gate in qubits 0 and 1:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to apply multi-qubit noise channels to a gate, the number of qubits associated with the gate must equal to the number of qubits defined by the noise channel, or otherwise the noise will not be applied. Below shows an example." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The two-qubit noise channel is applied to all the two-qubit gates in the circuit:\n", "\n", "T : |0| 1 | 2 |\n", " \n", "q0 : -X-C-DEPH(0.1)---SWAP-DEPH(0.1)-\n", " | | | | \n", "q1 : -Y-|-|---------X-SWAP-DEPH(0.1)-\n", " | | \n", "q2 : ---X-DEPH(0.1)---Z--------------\n", "\n", "T : |0| 1 | 2 |\n" ] } ], "source": [ "# define a two-qubit noise channel\n", "noise = Noise.TwoQubitDephasing(probability=0.1)\n", "\n", "# apply the noise to the circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2).swap(1,0)\n", "circ.apply_gate_noise(noise)\n", "print('The two-qubit noise channel is applied to all the two-qubit gates in the circuit:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Applying initialization noise to the circuit \n", "\n", "`apply_initialization_noise()` is the method to apply initialization noise to the circuit. By using the method, the noise will be applied to every qubit at the beginning of a circuit. It accepts the following input parameters:\n", "\n", "- __noise__: a single or a list of noise channel in `Noise` type.\n", "- __target_qubits__: a single or a list of qubit indexes. If not given, noise will be applied to all the qubits in the circuit.\n", "\n", "If you want to apply the initialization noise to an empty circuit, you need to provide `target_qubits` to the method. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Note When you call this method, noise will be inserted at the very beginning of the circuit. If you like to apply more than one noise operation, be aware of the order. Alternatively, you can provide a list of noise operations in one call, and the noise will be applied in forward order. \n", "
" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialization noise is applied to the circuit:\n", "\n", "T : | 0 | 1 |2|\n", " \n", "q0 : -DEPO(0.1)-X-C-----\n", " | \n", "q1 : -DEPO(0.1)-Y-|-X---\n", " | \n", "q2 : -DEPO(0.1)---X---Z-\n", "\n", "T : | 0 | 1 |2|\n" ] } ], "source": [ "# define a noise channel\n", "noise = Noise.Depolarizing(probability=0.1)\n", "\n", "# the noise channel is applied as the initialization noise to the circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_initialization_noise(noise)\n", "print('Initialization noise is applied to the circuit:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to apply a multi-qubit noise channel as the initialization noise to a circuit and if the number of the qubits in the existing circuit doesn't match the number of qubits as defined by the noise channel, you need to provide `target_qubits` with the number of qubits matching the noise channel. " ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialization noise is applied to the circuit:\n", "\n", "T : | 0 |1|2|\n", " \n", "q0 : -DEPH(0.1)-X-C-Z-\n", " | | \n", "q1 : -DEPH(0.1)-Y-X-X-\n", "\n", "T : | 0 |1|2|\n" ] } ], "source": [ "# define a two-qubit noise channel\n", "noise = Noise.TwoQubitDephasing(probability=0.1)\n", "\n", "# the noise channel is applied as the initialization noise to the circuit\n", "circ = Circuit().x(0).y(1).cnot(0,1).x(1).z(0)\n", "circ.apply_initialization_noise(noise)\n", "print('Initialization noise is applied to the circuit:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Applying readout noise to the circuit \n", "\n", "The method of `apply_readout_noise()` is very similar to the method to apply initialization noise, except that the noise channel is applied to every qubit in the end of a circuit. It accepts the following input parameters:\n", "\n", "- __noise__: a single or a list of noise channel in `Noise` type.\n", "- __target_qubits__: a single or a list of qubit indexes. If not given, noise will be applied to all the qubits in the circuit.\n", "\n", "If you want to apply the readout noise to an empty circuit, you need to provide `target_qubits` to the method. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Note When you call this method, noise will be inserted at the very end of the circuit. If you like to apply more than one noise operation, be aware of the order. You can also provide a list of noise operations in the one call, and the noise will be applied in forward order. \n", "
" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Read-out noise is applied to the circuit:\n", "\n", "T : |0| 1 | 2 |\n", " \n", "q0 : -X-C---DEPO(0.1)-----------\n", " | \n", "q1 : -Y-|-X-DEPO(0.1)-----------\n", " | \n", "q2 : ---X---Z---------DEPO(0.1)-\n", "\n", "T : |0| 1 | 2 |\n" ] } ], "source": [ "# define a noise channel\n", "noise = Noise.Depolarizing(probability=0.1)\n", "\n", "# the noise channel is applied as the readout noise to the circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_readout_noise(noise)\n", "print('Read-out noise is applied to the circuit:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to apply a multi-qubit noise channel as the readout noise to a circuit and if the number of the qubits in the existing circuit doesn't match the number of qubits as defined by the noise channel, you need to provide `target_qubits` with the number of qubits matching the noise channel. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using both the direct and global methods to apply noise \n", "You can apply noise to the circuit using both the direct and global methods. " ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Noise channels are applied to the circuit:\n", "\n", "T : | 0 | 1 |2|\n", " \n", "q0 : -X-PF(0.2)-BF(0.1)---------------\n", " \n", "q1 : -Y-----------------C-DEPO(0.1)---\n", " | | \n", "q2 : -------------------X-DEPO(0.1)-Z-\n", "\n", "T : | 0 | 1 |2|\n" ] } ], "source": [ "# define a noise channel\n", "noise = Noise.PhaseFlip(probability=0.2)\n", "\n", "# create a circuit and add noise directly to the circuit\n", "circ = Circuit().x(0).y(1).bit_flip(0,0.1).cnot(1,2).two_qubit_depolarizing(1, 2, probability=0.1).z(2)\n", "circ.apply_gate_noise(noise, target_qubits=0)\n", "print('Noise channels are applied to the circuit:\\n')\n", "print(circ)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Running a noisy circuit \n", "\n", "Running a noisy circuit is like running any other task on Amazon Braket. In the example below we will pick the local simulator to run our circuit. \n", "\n", "With shots = 0, you can obtain the exact values of probability, density matrix and expectation values of the mixed state by attaching the corresponding result type. The reduced density matrix is also available if providing the targets qubits. If no target qubit is provided, the full density matrix will be returned. \n", "\n", "An example is shown in the code block below." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T : | 0 | 1 | 2 | Result Types |\n", " \n", "q0 : -X-AD(0.1)-C-AD(0.1)-----------Probability-Expectation(Z)-DensityMatrix-\n", " | | | \n", "q1 : -Y---------|-X-----------------Probability----------------DensityMatrix-\n", " | | \n", "q2 : -----------X-AD(0.1)-Z-AD(0.1)-Probability------------------------------\n", "\n", "T : | 0 | 1 | 2 | Result Types |\n", "- Probability is: \n", "[0.1171 0.0729 0. 0. 0.1539 0.6561 0. 0. ]\n", "- Expectation value is: \n", "-0.6199999999999997\n", "- The reduced Density Matrix is: \n", "[[0.19+0.j 0. +0.j 0. +0.j 0. +0.j]\n", " [0. +0.j 0. +0.j 0. +0.j 0. +0.j]\n", " [0. +0.j 0. +0.j 0.81+0.j 0. +0.j]\n", " [0. +0.j 0. +0.j 0. +0.j 0. +0.j]]\n" ] } ], "source": [ "# define the noise channel\n", "noise = Noise.AmplitudeDamping(gamma=0.1)\n", "# create a circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "# apply the noise to qubits 0 and 2 in the circuit \n", "circ.apply_gate_noise(noise, target_qubits = [0,2])\n", "\n", "# attach the result types\n", "circ.probability()\n", "circ.expectation(observable = Observable.Z(),target=0)\n", "# attach the density matrix with target=[0,1], and the reduced density matrix of qubits 0,1 will be returned\n", "circ.density_matrix(target=[0,1])\n", "print(circ)\n", "\n", "# choose the noise simulator, which is called \"braket_dm\"\n", "device = LocalSimulator(\"braket_dm\")\n", "# run the circuit\n", "task = device.run(circ, shots=0)\n", "result = task.result()\n", "\n", "\n", "print('- Probability is: ')\n", "print(result.values[0])\n", "print('- Expectation value is: ')\n", "print(result.values[1])\n", "print('- The reduced Density Matrix is: ')\n", "print(result.values[2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With shots > 0, the results are sampled from the probability distributions. The result type `density_matrix` is not available for shots > 0. \n", "\n", "The code below shows the expectation value $\\langle Z_0\\rangle$ and the probability that the mixed state collapsing into different states. We see those values here are different from the exact values obtained in the shots = 0 case." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T : | 0 | 1 | 2 | Result Types |\n", " \n", "q0 : -X-AD(0.1)-C-AD(0.1)-----------Probability-Expectation(Z)-\n", " | | \n", "q1 : -Y---------|-X-----------------Probability----------------\n", " | | \n", "q2 : -----------X-AD(0.1)-Z-AD(0.1)-Probability----------------\n", "\n", "T : | 0 | 1 | 2 | Result Types |\n", "- Probability is: \n", "[0.12 0.11 0. 0. 0.22 0.55 0. 0. ]\n", "- Expectation value is: \n", "-0.54\n" ] } ], "source": [ "# create a circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_gate_noise(noise, target_qubits = [0,2])\n", "\n", "circ.probability()\n", "circ.expectation(observable = Observable.Z(),target=0)\n", "print(circ)\n", "\n", "# run the circuit\n", "task = device.run(circ, shots=100)\n", "result = task.result()\n", "\n", "print('- Probability is: ')\n", "print(result.values[0])\n", "print('- Expectation value is: ')\n", "print(result.values[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also create circuits with parametrized noise operations and specify the parameter values later:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T : | 0 | 1 | 2 | Result Types |\n", " \n", "q0 : -X-AD(gamma)-C-AD(gamma)-------------Probability-Expectation(Z)-\n", " | | \n", "q1 : -Y-----------|-X---------------------Probability----------------\n", " | | \n", "q2 : -------------X-AD(gamma)-Z-AD(gamma)-Probability----------------\n", "\n", "T : | 0 | 1 | 2 | Result Types |\n", "- Probability when gamma=0.1 is: \n", "[0.12 0.18 0. 0. 0.09 0.61 0. 0. ]\n", "- Expectation value when gamma=0.1 is: \n", "-0.4\n", "- Probability when gamma=0.3 is: \n", "[0.42 0.1 0. 0. 0.21 0.27 0. 0. ]\n", "- Expectation value when gamma=0.3 is: \n", "0.04\n" ] } ], "source": [ "# define the free parameter\n", "gamma = FreeParameter('gamma')\n", "# define the noise channel\n", "noise = Noise.AmplitudeDamping(gamma=gamma)\n", "# create a circuit\n", "circ = Circuit().x(0).y(1).cnot(0,2).x(1).z(2)\n", "circ.apply_gate_noise(noise, target_qubits = [0,2])\n", "\n", "circ.probability()\n", "circ.expectation(observable = Observable.Z(),target=0)\n", "print(circ)\n", "\n", "# run the circuit with gamma = 0.1\n", "task = device.run(circ(gamma=0.1), shots=100)\n", "result = task.result()\n", "\n", "print('- Probability when gamma=0.1 is: ')\n", "print(result.values[0])\n", "print('- Expectation value when gamma=0.1 is: ')\n", "print(result.values[1])\n", "\n", "# run the circuit with gamma = 0.3\n", "task = device.run(circ(gamma=0.3), shots=100)\n", "result = task.result()\n", "\n", "print('- Probability when gamma=0.3 is: ')\n", "print(result.values[0])\n", "print('- Expectation value when gamma=0.3 is: ')\n", "print(result.values[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reference\n", "[1] Srikanth R, Banerjee S. \"Squeezed generalized amplitude damping channel\", Physical Review A, 2008, 77(1): 012318." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Task Summary\n", "{'arn:aws:braket:::device/quantum-simulator/amazon/dm1': {'shots': 10, 'tasks': {'COMPLETED': 1}, 'execution_duration': datetime.timedelta(microseconds=639000), 'billed_execution_duration': datetime.timedelta(seconds=3)}}\n", "Note: Charges shown are estimates based on your Amazon Braket simulator and quantum processing unit (QPU) task usage. Estimated charges shown may differ from your actual charges. Estimated charges do not factor in any discounts or credits, and you may experience additional charges based on your use of other services such as Amazon Elastic Compute Cloud (Amazon EC2).\n", "Estimated cost to run this example: 0.004 USD\n" ] } ], "source": [ "print(\"Task Summary\")\n", "print(t.quantum_tasks_statistics())\n", "print('Note: Charges shown are estimates based on your Amazon Braket simulator and quantum processing unit (QPU) task usage. Estimated charges shown may differ from your actual charges. Estimated charges do not factor in any discounts or credits, and you may experience additional charges based on your use of other services such as Amazon Elastic Compute Cloud (Amazon EC2).')\n", "print(f\"Estimated cost to run this example: {t.qpu_tasks_cost() + t.simulator_tasks_cost():.3f} USD\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.8.15" }, "vscode": { "interpreter": { "hash": "590fab68195cf107911461461f81d5c472d3d6127f579badfcfad30f03e5cab2" } } }, "nbformat": 4, "nbformat_minor": 4 }