{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Writing Custom Noise Sources\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example will demonstrate how to write a custom noise source for the simulator.\nSee also :doc:`this guide<../../guides/run/simulator>` for more general information.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nimport trueq as tq\nimport trueq.simulation as tqs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A custom noise source can be implemented by subclassing\n:py:class:`~trueq.simulation.noise_source.NoiseSource` and overriding its\n:py:meth:`~trueq.simulation.noise_source.NoiseSource.apply` method.\n\nThe :py:meth:`~trueq.simulation.noise_source.NoiseSource.apply` method will be passed\nthree arguments: ``cycle_wrapper``, ``state``, and ``circuit_cache``. The job of apply\nis to mutate ``state`` based on the contents of ``cycle_wrapper``. The ``state``\nrefers to \"the state of simulation\" and can either be a\n:py:class:`~trueq.math.tensor.StateTensor` (which can store either a pure state or a\nmixed state), or a :py:class:`~trueq.math.tensor.OperatorTensor` (which can store\neither a unitary or a superoperator). Each of these four possibilities share the\nmethod :py:meth:`~trueq.math.tensor.Tensor.apply_matrix` which can always accept a\nunitary or superoperator as input, and for example upgrades pure states to mixed\nstates when necessary, and so the distinction between these various types of states\nbecomes irrelevant to the implementation of a noise source.\n\nNote that ``cycle_wrapper`` is not a :py:class:`~trueq.Cycle` instance as one\nmight expect, but instead a thin wrapper called\n:py:class:`~trueq.simulation.match.CycleWrapper` which in turn wraps each cycle\noperation as :py:class:`~trueq.simulation.match.OpWrapper`.\n\nThese wrapper types are required to store metadata on each operation (also discussed\nfurther below). However, noise sources will rarely need to deal with these wrapper\nobjects directly. This is because noise sources (by strongly encouraged convention,\nthough not by contract) own a :py:class:`~trueq.simulation.match.Match` instance which\ntakes ownership of the mechanics of these wrappers. This is seen in the example below,\nwhere the :py:class:`~trueq.simulation.match.Match.iter_gates` method is used to yield\ngate objects with their corresponding gate labels.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# predefine noise matrices to be applied to qubits following ideal gates\n# note that rowstack_subsys is the superoperator convention required by the simulator\np = 0.01\ns = tq.math.Superop.from_kraus([np.sqrt(1 - p) * np.eye(2), np.sqrt(p) * tq.Gate.x.mat])\ns1 = s.rowstack_subsys()\n\np = 0.02\ns = tq.math.Superop.from_kraus(\n [np.sqrt(1 - p) * np.eye(4), np.sqrt(p) * tq.math.random_unitary(4)]\n)\ns2 = s.rowstack_subsys()\n\n\nclass ExampleNoise(tqs.NoiseSource):\n def __init__(self, match=None):\n # this simulator hardcodes the subsystem dimension to 2\n super().__init__(dim=2, match=match)\n\n def make_circuit_cache(self, circuit):\n # this return will be made available to apply() as circuit_cache for every\n # cycle in the circuit\n return set(circuit.labels)\n\n def apply(self, cycle_wrapper, state, circuit_cache):\n # in this method we need to mutate state by inspecting cycle_wrapper\n\n used_labels = set()\n # loop through the gates in the cycle and mutate the state\n # note that we must set noise_only=False since we are simulating each gate\n for labels, gate in self.match.iter_gates(cycle_wrapper, noise_only=False):\n used_labels.update(labels)\n # first do ideal simulation of this gate\n state.apply_matrix(labels, gate.mat)\n\n # now add some noise to each qubit the gate acts on\n if len(labels) == 1:\n state.apply_matrix(labels, s1)\n elif len(labels) == 2:\n state.apply_matrix(labels, s2)\n\n # apply a 20 degree Z rotation to every qubit without a gate in this cycle\n for label in circuit_cache.difference(used_labels):\n state.apply_matrix((label,), tq.Gate.rp(\"Z\", 20))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can instantiate a simulator that uses this noise source and do any simulator\ncalculation. Here, we use the simulator to predict the output of a hypothetical\nKNR experiment.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sim = tq.Simulator().append_noise_source(ExampleNoise())\n\ncycle = {(0, 1): tq.Gate.cnot, 2: tq.Gate.x}\nfit = sim.predict_knr(cycle, twirl=tq.Twirl(\"P\", range(5)))\nfit.plot.knr_heatmap()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Caching\n\nThere are two distinct caches available to a noise source. The first is a private\nnoise source attribute that is called ``_cache`` (by convention, not by contract) in\nbuilt-in noise models which persists throughout the lifetime of the noise source. For\nexample, a gate-dependent noise model may consider caching gate noise if it is\nexpensive to recompute everytime the same gate is encountered.\n\nThe second cache comes as the third argument to the apply\nmethod. This cache is instantiated by\n:py:meth:`~trueq.simulation.noise_source.NoiseSource.make_circuit_cache` just before a\nnew circuit is simulated and is presented as the third argument to the apply method\nfor every cycle within that circuit. It typically stores information about the\ncircuit that is not available in every cycle, such as all of the labels the circuit\nacts on, or which measurements it performs at the end.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Wrappers and metadata\n\nThe variable ``cycle_wrapper`` in the example above has type\n:py:class:`~trueq.simulation.match.CycleWrapper` which is a thin wrapper for a cycle\nand also wraps every cycle operation with\n:py:class:`~trueq.simulation.match.OpWrapper`\\. During simulation, everytime a new\ncycle is encountered it is wrapped once, and the same wrapped cycle instance is passed\nto all noise sources. The cycle wrapper exists to enable efficient looping logic used\nby :py:class:`~trueq.simulation.match.Match` and to persist operation wrappers for\nmultiple noise sources\\. The operation wrapper exists to store\ntwo important pieces of information:\n\n 1. Whether some noise source has previously simulated the same operation of the\n cycle. This is stored as a boolean called ``has_been_simulated`` and is set to\n true whenever a match method is called with the argument ``noise_only=False``, as\n it is in the above example.\n 2. Whether no noise sources (except the ideal final simulation if relevant) should\n touch the operation again. This is stored as a boolean called ``no_more_noise``\n and is set to true whenever it is yielded by a match method whose ``exclusive``\n value is true.\n\n" ] } ], "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.6.8" } }, "nbformat": 4, "nbformat_minor": 0 }