{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Contextual optimisation\n", "\n", "**Download this notebook - {nb-download}`contextual_optimisation.ipynb`**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook will illustrate the techniques of \"contextual optimisation\" available in TKET." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See the user manual for an introduction to the concept and methods. Here we will present an example showing how we can save some gates at the beginning and end of a circuit, making no assumptions about the structure of the circuit." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will take as an example an ansatz circuit consisting of alternating layers of Ry and CX gates, where some proportion of the Ry angles are zero. This is a typical ansatz for variational algorithms, used for solving diagonal Hamiltonians for combinatorial optimisation." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from pytket.circuit import Circuit\n", "from random import random, randrange, seed\n", "\n", "def random_sparse_ansatz(n_qubits, n_layers, p, rng_seed=None):\n", " seed(rng_seed)\n", " circ = Circuit(n_qubits)\n", " for q in range(n_qubits):\n", " if random() < p:\n", " circ.Ry(0.1 * randrange(20), q)\n", " for l in range(n_layers):\n", " for q in range(0, n_qubits - 1, 2):\n", " circ.CX(q, q + 1)\n", " for q in range(2 * (n_qubits // 2)):\n", " if random() < p:\n", " circ.Ry(0.1 * randrange(20), q)\n", " for q in range(1, n_qubits - 1, 2):\n", " circ.CX(q, q + 1)\n", " for q in range(2 * ((n_qubits - 1) // 2)):\n", " if random() < p:\n", " circ.Ry(0.1 * randrange(20), q + 1)\n", " circ.measure_all()\n", " return circ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's examine a smallish example:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "