The post quantum-viz.js: a quantum circuits visualization library appeared first on Q# Blog.

]]>|Entangle circuit|

Quantum circuits are a commonly used representation of quantum programs, so we’ve been looking for ways to incorporate them into Q# and the QDK. We first considered using existing tools like qpic or qcircuit, but typically they must be invoked from the command line or a Python script, and one key requirement for us was the ability to integrate the visualizer with IQ#, our Jupyter kernel for Q#, which is built on top of .NET Core. Also, these tools generate a static representation of the circuit in the form of a jpeg, LaTeX or pdf file, but we had some interactivity components in mind that we wanted to expose through the tool, so instead we took a bit of inspiration from Bono and built a stand-alone tool based on core HTML technologies like svg, css and javascript.

An example of the interactivity we wanted to build is the ability to expand the definition of an operation. Q# is a high-level programming language for quantum programs; thus, it is possible and common to group operations to reuse them and to convey intention. Take for example the following implementation of the common Teleport algorithm:

|Teleport Circuit|

From the diagram you can quickly get a high-level view of the different elements of the program: there is an operation that entangles a pair of qubits, another that prepares a message on another qubit, a process that encodes the message using one of the entangled qubits and finally another operation that decodes the message on the other entangled qubit. But notice this circuit is interactive: if you move your mouse over an operation block, you’ll see a ‘plus’ sign appear. Clicking on the plus sign shows a detailed view of that operation so you can see the actual gates. Try it now!

Another interesting interactive feature we built is the way we represent classically controlled operations. Take the following circuit:

|Classically controlled circuit|

When the first qubit is measured, if the result of measurement is `1`

the program will apply a `Z`

and `X`

operations to the second bit; otherwise, if the measurement is `0`

it applies just a `Y`

. The visualization represents the unknown state of the circuit before measuring with a transparent block of gates: when you click the circle with question mark once, the circuit shows the gates that are executed when the measurement is `1`

; if you click on the circle again it shows the gates that are executed when the measurement result is `0`

.

This tool is currently available on IQ# using the `%trace`

magic which we discussed previously in this blog post. Since Q# can mix classical and quantum operations with high level constructs like arrays and loops, there is not a single circuit associated with a Q# program, so this command simulates the corresponding operation and traces the quantum gates that are executed to visualize the corresponding circuit:

Because the tool is built using core HTML technologies, integrating it with Jupyter was fairly simple. We now took the extra step of packaging as a stand-alone tool so it can be easily integrated into other web applications, like Observable or even this blog post!

We are excited about the potential of this tool and we already have some new features in mind, such as the ability to show how the state of the qubits evolve as the program executes. If you have other ideas that you would like to contribute or would like to incorporate the tool into your projects let us know as we would be excited to collaborate.

The post quantum-viz.js: a quantum circuits visualization library appeared first on Q# Blog.

]]>The post Quantum software development using the QDK appeared first on Q# Blog.

]]>Here is a diagram that shows the steps of quantum software development in one picture.

Let’s look at each step in more detail.

The most recognizable part of the QDK is probably Q# – the domain-specific programming language we created to express quantum programs. (Check out the blog in which we discuss why we decided to create Q# for a bit of background.)

QDK includes extensions for Visual Studio and VS Code. Though they are not required to write and run Q# programs, they make the experience much smoother, offering nice features such as syntax highlighting and IntelliSense.

QDK also includes the Q# version of Jupyter Notebooks – an interactive development environment that offers, among other convenient features, a rich set of program visualization tools.

The quantum libraries that are part of the Quantum Development Kit help you keep your code high-level, doing a lot of the heavy lifting in implementation for you so that you can focus on the logic of your algorithms.

They include both “standard” libraries that implement patterns common for a lot of quantum algorithms, and domain-specific libraries such as Microsoft.Quantum.Numerics and Microsoft.Quantum.Chemistry that drill down into more specific applications.

Quantum programs don’t exist in a vacuum; they are typically parts of hybrid workflows that combine classical libraries and tools with using quantum computers to accelerate solving specific sub-problems that are well suited for quantum computing. For example, quantum development tools for chemistry rely heavily on classical chemistry simulation packages such as NWChem to compute the inputs to the quantum part of the program.

The Quantum Development Kit allows you to integrate Q# programs with Python and .NET, enabling a quantum software developer to take advantage of a lot of the advances made in classical computing in the past 70 years.

The previous steps look pretty similar to the classical software development workflow, but there are some steps that are very specific for quantum computing. Once you’ve written your program, you’ll want to use simulators – classical programs that simulate the behavior of a quantum system, so that you can run a small instance of your program and see what it does without actual hardware access.

QDK includes a variety of simulators, from the full-state simulator that imitates a quantum system perfectly to the new experimental simulators designed to simulate noisy systems.

The simulators are limited in the size and/or the capabilities of the programs they can simulate. However, they are very helpful for testing your quantum programs and experimenting with things such as error correction.

Of course, eventually you’re going to need to run your quantum programs on quantum hardware to enjoy the benefits of quantum computing. Before you do that, though, you’ll need to figure out whether your program can run on existing hardware. You can use QDK resource estimators to tell you how many qubits you need and how long your program will take.

You can use resources estimation in a slightly different manner as well: when applied to algorithms we know are not suitable for NISQ devices, it informs us about the viability of these algorithms in the long run, allowing to validate and optimize them years before sufficiently powerful quantum hardware becomes available.

Finally, you’ve validated the correctness of your program and estimated that it is fit to run on the hardware you have access to. The last step is using Azure Quantum to run your program on quantum hardware!

Most importantly, you use the same Q# code for all steps of the workflow. In the short term you might have to tweak some portions of the code to account for the current hardware limitations. You can think of it as rewriting portions of high-level code in Assembly to speed up a part of a classical program. But in the long run you’ll be able to switch between various simulators and hardware providers without any code modifications.

Curious to see this workflow in action? Check out the recent Azure Friday episode in which I show all the steps of quantum software development in a live demo, culminating in running Q# code on Azure Quantum!

The post Quantum software development using the QDK appeared first on Q# Blog.

]]>The post The AutoSubstitution rewrite step appeared first on Q# Blog.

]]>`Microsoft.Quantum.AutoSubstitution`

which provides a rewrite step that allows you to substitute some Q# operations with alternatives dynamically depending on which simulator you use to execute them. This feature has been requested by users through feedback in Github.
This is best explained with a small example. Assume you have an implementation that swaps two qubits, in which all the `CNOT`

operations have the target on the same qubit. Such an operation can be useful in an architecture that constrains the direction in which `CNOT`

operations can be executed. This can be achieved in the following way:

operation ApplySingleDirectionSWAP(a : Qubit, b : Qubit) : Unit is Adj + Ctl { within { CNOT(a, b); H(a); H(b); } apply { CNOT(a, b); } }

The operation is functionally equivalent to `Microsoft.Quantum.Intrinsic.SWAP`

, however, the Toffoli simulator cannot execute it due to the non-classical Hadamard operation, whereas it can execute the `SWAP`

operation. That means that we also cannot execute other classical operations (e.g., arithmetic operations) with the Toffoli simulator, if they make use of the `ApplySingleDirectionSWAP`

operation.

In these situations, `Microsoft.Quantum.AutoSubstitution`

can help by allowing us to instruct the Q# compiler to use the original SWAP operation as an alternative for our custom `ApplySingleDirectionSWAP`

operation, whenever we execute the program with the Toffoli simulator. We simply need to add this information using an annotation:

open Microsoft.Quantum.Targeting; @SubstitutableOnTarget("Microsoft.Quantum.Intrinsic.SWAP", "ToffoliSimulator") operation ApplySingleDirectionSWAP(a : Qubit, b : Qubit) : Unit is Adj + Ctl { // ... }

You need to add the dependency to `Microsoft.Quantum.AutoSubstitution`

into your project file as a Q# reference

<PackageReference Include="Microsoft.Quantum.AutoSubstitution" Version="0.18.2106148911" IsQscReference="true" />

and open the `Microsoft.Quantum.Targeting`

, which contains the `SubstitutableOnTarget`

attribute. Note that for now, you must ensure that the alternative operation is referenced somewhere in the code. To be sure, you could add

let _ = Microsoft.Quantum.Intrinsic.SWAP;

as the first line of your operation `ApplySingleDirectionSWAP`

. (This limitation will be resolved in our next release.) You can find a sample project that uses the new rewrite step in our samples repository.

Of course, this attribute is not limited to Toffoli simulator, but can be used with the other simulators from the QDK or using custom simulators. (Make sure to address custom simulators with their fully classified names.) Replacing operations with alternatives is also referred to as emulation. The new rewrite step makes this scenario much more accessible.

The package makes use of custom compilation steps, a technique that you can use to extend the compiler. If you are interested in the underlying techniques that support this new NuGet package, you find more information on extending the Q# compiler in this blog post.

The post The AutoSubstitution rewrite step appeared first on Q# Blog.

]]>The post Visualizing quantum programs using the QDK appeared first on Q# Blog.

]]>In this blog post we’ll look at the tools offered by Microsoft Quantum Development Kit to visualize various elements of quantum programs.

Recall that the state of an *N*-qubit quantum system at any point of time is a superposition – a linear combination of 2* ^{N}* basis states |

If this program runs on a physical quantum system, there is no way to get all the information about the values of *x _{k}* at a certain point of the program execution from a single observation – quantum mechanics just doesn’t allow this.

However, at the early stages of quantum program development the program typically runs on a simulator – a classical program which simulates the behavior of a small quantum system while having complete information about its internal state. You can take advantage of this to do some non-physical things, such as peeking at the internals of the quantum system to observe its exact state without disturbing it!

The functions DumpMachine and DumpRegister from the Microsoft.Quantum.Diagnostics namespace allow you to do exactly that: print the state of the quantum system or its part when the program is executed on a simulator.

For example, let’s define the following operation that allocates two qubits and prepares an uneven superposition state on them.

open Microsoft.Quantum.Diagnostics; operation MultiQubitDumpMachineDemo() : Unit { use qs = Qubit[2]; H(qs[0]); Controlled Ry([qs[0]], (1.57075, qs[1])); DumpMachine(); ResetAll(qs); }

Now, let’s run this operation in a Q# Jupyter Notebook on a full state quantum simulator using the `%simulate`

magic. DumpMachine call will print the information about the quantum state of the program after the Controlled Ry gate as a set of lines, one per basis state, showing their complex amplitudes, phases, and measurement probabilities:

Note that the Q# code doesn’t have access to the output of DumpMachine, so you don’t need to resist the temptation to write any non-physical code, such as making decisions based on the amplitude of a certain basis state!

Similarly, DumpRegister allows you to print the quantum state of one part of the quantum system, as long as it’s not entangled with the rest of the system.

Finally, you can use %config magic command (available only in Q# Jupyter Notebooks) to tweak the format of DumpMachine output. It offers a lot of settings convenient in different scenarios. For example, by default DumpMachine uses little-endian integers to denote the basis states (the first column of the output); if you find raw bit strings easier to read, you can use `%config dump.basisStateLabelingConvention="Bitstring"`

to switch.

Let’s say you’re working on a unitary synthesis task, implementing a quantum gate described by a matrix. You’ve written a Q# operation and want to check that it implements exactly the unitary matrix you’re looking for.

The DumpOperation library operation offers you a short and elegant way to do this. It takes an operation that acts on an array of qubits as a parameter (if your operation acts on a single qubit, like most intrinsic gates, or on a mix of individual qubits and qubit arrays, you’ll need to write a wrapper for it to use DumpOperation on it), and prints a matrix implemented by this operation. For example, `DumpOperation(2, ApplyToFirstTwoQubitsCA(CNOT, _));`

will print the matrix of the CNOT gate.

Note that this matrix might differ from the one you are used to seeing in quantum computing resources. DumpOperation uses the little-endian encoding for converting basis states to the indices of matrix elements. Thus, the second column of the CNOT matrix corresponds to the input state |1⟩ _{LE} = |10⟩, which the CNOT gate converts to |11⟩ = |3⟩_{LE}, meaning that the last element of this column is going to be 1, and the rest of the elements will be 0s.

On the other hand, a lot of resources on quantum computing use big-endian encoding, in which the second column of the CNOT matrix corresponds to the input state |1⟩_{BE} = |01⟩, which should be left unchanged by the CNOT gate, meaning that the 2^{nd} element of this column will be 1, and the rest of the elements will be 0s. This convention will produce the familiar CNOT matrix:

Quantum circuits are a very common way of visualizing the execution of quantum programs; you’ll see them in a lot of tutorials, papers, and books on quantum computing. Quantum circuits are a less powerful way of expressing the quantum computation compared to a quantum program. They don’t offer a good way to show the values of classical variables and their evolution, the decisions made based on the classical parameters or the measurement results, or even flow control structures such as loops or conditional statements. At the same time, they can be convenient to get a quick idea of what the program did, or to compare your implementation to the one offered in a book as a circuit.

%trace magic command (available only in Q# Jupyter Notebooks) offers a way to trace one run of the Q# program and to build a circuit based on that execution. Note that these circuits include only the quantum gates executed by the program during one run. They might differ in different runs of the same program, if that program takes parameters, has conditional branching or other behaviors that can change the sequence of gates applied by the program.

Here, for example, is the circuit printed using %trace for Q# program that implements Deutsch-Jozsa algorithm.

You see that initially the circuit focuses on high-level operations used in the root operation, showing them as blocks. The visualization is interactive, allowing you to click on each block to drill down to the intrinsic gates:

The final tool in the list is the %debug magic command (available only in Q# Jupyter Notebooks) which allows you to combine tracing the program execution (as a circuit) and observing the program state as it evolves at the same time.

Here is a brief video of the %debug results for the same Deutsch-Jozsa algorithm operation for 2-qubit function. We switch to observing real and imaginary components of the amplitudes instead of measurement probabilities in the beginning of the program. For Deutsch-Jozsa algorithm, the probabilities of measuring each basis state during the program execution remain pretty much the same, it’s the signs of the amplitudes we want to watch for. For other algorithms, such as Grover’s search algorithm or quantum Fourier transform, observing measurement probabilities or the phases of the states can be more interesting.

Note that the %debug session requires the user to click through each of the steps and does not end until the program run is complete.

We hope you’ll find these tools useful in your work with the QDK, regardless of whether you are at the beginning of your quantum computing journey and seeking to confirm your understanding of the basics, or an experienced quantum software developer looking for that bug that’s been driving you crazy.

And if you want to practice using these tools and interpreting their output before using them for your work, check out our new VisualizationTools tutorial! As usual for the Quantum Katas tutorials, it offers detailed descriptions of the various tools listed here, demos, and hands-on exercises.

The post Visualizing quantum programs using the QDK appeared first on Q# Blog.

]]>Quantum computers will be able to reveal the exact quantum nature of chemical systems exponentially faster than classical computers. That’s why one of the most impactful future applications of quantum computing is chemistry simulation.

The post Quantum developer tools for chemistry appeared first on Q# Blog.

]]>

Quantum computers will be able to reveal the exact quantum nature of chemical systems exponentially faster than classical computers. That’s why one of the most impactful future applications of quantum computing is chemistry simulation. Quantum mechanics plays a dominant role in the behavior of molecular systems at the fundamental scales. However, the complex nature of quantum effects make them computationally expensive to simulate. For instance, a simple, approximate quantum chemistry calculation could take many hours to run on a large computational cluster. While exact calculations may even be intractable for these classical systems, quantum computers can reveal the exact quantum nature of chemical systems. Such advantage can unlock the ability to study molecules and chemical phenomena we were not able to study before. If you are interested in what chemical systems can benefit most from quantum computers, please take a look at our latest work: Prospects of Quantum Computing for Molecular Sciences.

To get started with quantum development of chemistry algorithms, you can either run quantum algorithms on a simulator or on near-term hardware. Simulators can be a great way to get started with quantum programming, and they also offer a way to understand the hardware requirements of a specific algorithm. The Microsoft Quantum Development Kit (QDK) offers multiple simulator back-ends that can be targeted by the Q# compiler and runtime. In addition, we offer Python-based tools that easily let you plug in your favorite libraries to analyze and plot the results. Many of the chemistry tools in the QDK have resulted from work done by our research team in collaboration with the Advanced Computing, Mathematics, and Data Division at Pacific Northwest National Laboratory (PNNL). Some of our tools include interacting with the Microsoft Quantum Editor on EMSL Arrows, a computational chemistry tool built and maintained by the PNNL team. In this post we will show examples of chemistry algorithms that you can run with the QDK and the Q# Chemistry library.

Energy is one of the most important properties of a molecule from the computational perspective. It can be directly translated to metrics and design principles to guide real-world application, for instance the design of catalysts or photovoltaic materials. As most of the time molecules are in their ground state, i.e. lowest energy state, the evaluation of ground state energy thus becomes the most fundamental step to understand the molecule. A scalable and powerful algorithm that can be used to calculate the ground state is called Quantum Phase Estimation (QPE). QPE projects the quantum state onto an eigen state of the Hamiltonian of the molecule, such that it always produces exact energies. Here we will demonstrate how to run Robust Phase Estimation, a version of Quantum Phase Estimation algorithm that uses fewer qubits, using the QDK developer tools for chemistry. This calculation consists roughly of the following steps:

- Compute the electron interactions (i.e. Hamiltonian terms) using chemistry simulation packages such as NWChem.
- From the results in (1), generate the coefficients for generating a good guess of the ground state, also known as a
*trial state*, to encode in qubits. Optionally, it is possible here to perform further calculations in chemistry packages to get an elaborate trial state if higher accuracy is required in the estimation. - Apply Robust Phase Estimation algorithm to estimate the phase of the trial state. This prepares the trial state generated in (2) and projects the state onto a possible ground state of the Hamiltonian.
- Repeat (3) and post-select to find the solution that provides the lowest energy.

In the example below, we will run a Q# program that runs Robust Phase Estimation on a simulator, in particular, the Q# full state simulator. The Q# program is defined in a Q# file and contains an operation that we can import and run from a Q# entry point, the IQ# kernel, a host program in C# or Python, or directly from a Jupyter notebook, as we will do in this blog post.

namespace Microsoft.Quantum.Chemistry.Trotterization { open Microsoft.Quantum.Core; open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Canon; open Microsoft.Quantum.Chemistry; open Microsoft.Quantum.Chemistry.JordanWigner; open Microsoft.Quantum.Simulation; open Microsoft.Quantum.Characterization; open Microsoft.Quantum.Convert; open Microsoft.Quantum.Math; operation GetEnergyRPE ( JWEncodedData: JordanWignerEncodingData, nBitsPrecision : Int, trotterStepSize : Double, trotterOrder : Int ) : (Double, Double) { let (nSpinOrbitals, fermionTermData, inputState, energyOffset) = JWEncodedData!; let (nQubits, (rescaleFactor, oracle)) = TrotterStepOracle(JWEncodedData, trotterStepSize, trotterOrder); let statePrep = PrepareTrialState(inputState, _); let phaseEstAlgorithm = RobustPhaseEstimation(nBitsPrecision, _, _); let estPhase = EstimateEnergy(nQubits, statePrep, oracle, phaseEstAlgorithm); let estEnergy = estPhase * rescaleFactor + energyOffset; return (estPhase, estEnergy); } }

This operation makes use of the Q# Libraries, in particular the Quantum Chemistry Library, and will return a tuple of the estimated phase and energy of the ground state of the molecule. For more information on the above libraries and operations used in this sample, please take a look at the extensive Q# user guide.

To start off calculating the ground state, we need to first load the molecule such that we can construct its electronic model. Here, we will use an XYZ file, which specifies the spatial coordinates of the atoms in the molecule. To inspect the molecule, we can use the qdk Python package and visualize it in Jupyter notebook. To install the qdk package and its dependencies, we recommend installing conda and running:

$ conda install -c rdkit rdkit $ pip install qdk

If you don’t have it already, make sure to also install the qsharp package:

$ conda install –c quantum-engineering qsharp

Now, start a Jupyter notebook by running:

$ jupyter notebook

This opens a new browser window with a Jupyter server, from which you can start a new notebook with a Python kernel. To load the molecule inside the notebook, simply import the Molecule class and use the from_xyz class method to create an instance:

In: from qdk.chemistry import Molecule caffeine = Molecule.from_xyz("data/xyz/caffeine.xyz") caffeine Out:

This returns an interactive JSMol widget in the notebook.

For a static image of the molecule generated by RDKit, run:

In: caffeine.mol Out:

We can then inspect how many electrons this molecule has:

In: caffeine.num_electrons Out: 102

And the atomic number of its atoms:

In: caffeine.atoms Out: [1, 6, 7, 8]

To evaluate the energy of a molecule, we need to choose a set of one-electron basis functions (often known as orbitals) to represent the electronic wave functions. Here, we use one of the most elementary basis sets, STO-3G, to represent the caffeine molecule:

In: caffeine.num_orbitals(basis="STO-3G") Out: 80

In total, there are 80 spatial orbitals. The state of an orbital, which can contain up to two electrons, can be represented by 2 qubits. One can easily see that the classical simulation of many orbitals is very costly due to the exponential complexity of simulating qubits. Luckily, only a couple of frontier orbitals (in many cases, the highest-occupied-molecular-orbital, HOMOs; and lowest-unoccupied-molecular-orbital, LUMOs) dominate the chemical properties of the molecule. We only need to probe the molecule’s quantum properties within those chemically most relevant orbitals, also known as *active space*, and use approximations to estimate the energy contribution of rest of the orbitals. This largely reduces the number of orbitals we need to map to the qubits.

For this problem, we can start off with four active orbitals, which means we will need 8 qubits to encode the problem. RPE also requires one auxiliary qubit, which would bring us to 9 qubits in total, which is a number we can comfortably simulate on a laptop. To do that, we need to calculate the electronic properties using a computation chemistry tool such as NWChem or OpenMolcas. To use NWChem in the browser and generate a Broombridge file directly, use the Microsoft Quantum Editor on EMSL Arrows.

To encode the electronic properties, also known as the electrionic Hamiltonian, we need to store them in a file format using the Broombridge Quantum Chemistry Schema. You can use the following Python code to load it via the QDK Python package:

In: from qdk.chemistry.broombridge import load_and_encode encoded_data_caffeine = load_and_encode("data/broombridge/caffeine.yaml")

Then we can import and call the Q# operation from Python:

In: from Microsoft.Quantum.Chemistry.RPE import GetEnergyRPE GetEnergyRPE.simulate( JWEncodedData=encoded_data_caffeine, nBitsPrecision=10, trotterStepSize=0.2, trotterOrder=1 ) Out: (-0.3383813350711708, -627.6309264967134)

By classical simulations we found the exact ground state energy to be `-627.63095945558848 Ha`

. Given that we are using 10 bits of precision with a step size of 0.2, we expect an error of (1/2^{10})/0.2=4*10^{-3}, which is 4 mHa accuracy, so our result from RPE is within the expected error range.

To see how resource intensive this calculation was, we can use the `estimate_resources`

method:

In: GetEnergyRPE.estimate_resources( JWEncodedData=encoded_data_caffeine, nBitsPrecision=10, trotterStepSize=0.2, trotterOrder=1 )

This will calculate the resources and return a Python dictionary:

Out: { 'CNOT': 42913920, 'QubitClifford': 24522844, 'R': 9196140, 'Measure': 609, 'T': 0, 'Depth': 0, 'Width': 9, 'QubitCount': 9, 'BorrowedWidth': 0 }

Here, the values in the dictionary return the estimates of numbers of different gates and circuit depth required to run this algorithm. To learn more about what each of these metrics represent, please visit the “Metrics reported” section of the docs of the Q# resources estimator simulator back-end.

Based on the resource metrics, it looks like simulating the ground state of caffeine using RPE requires quite a lot of resources. We need many millions of CNOT gates! Obviously, this is not yet realistic on near-term hardware, such as the systems available on Azure Quantum. So how are we going to simulate a chemistry molecule on a near-term machine? For this purpose, variational methods might come in handy.

While Quantum Phase Estimation algorithms such as the RPE sample mentioned above provide an exact solution, there are variational methods in chemistry that are used to iteratively get to an approximate solution. We can do exactly that using small and shallow quantum algorithms such as the Variational Quantum Eigensolver. The VQE algorithm starts with a *parameterized trial state*, and optimizes the parameters to approximate the ground state energy. The protocol is as follows:

- Compute the electron interactions (i.e. Hamiltonian terms) using a chemistry simulation package.
- From the results in (1), generat a good guess of the ground state
*(trial**state*), and encode it in qubits. - Estimate the energy of the trial state by doing a projective measurement for each term in the Hamiltonian.
- Modify the trial state using its parametric definition.
- Repeat steps 2 to 4 until the energy of the molecule is minimized.

The algorithm requires many evaluations on quantum hardware, but this will give us an approximation of the ground state. The Q# program that implements VQE uses the EstimateEnergy operation which uses EstimateFrequencyA to estimate the fraction of samples of a projected measurement that are in the Zero state. This operation is run using a built-in emulation feature in the simulator that uses binomial sampling to simulate running multiple shots on quantum hardware without directly inspecting the quantum state, which allows us to run the VQE algorithm on millions of shots without any significant added run time. Note that on real hardware, this emulation is not possible, so it would take a significantly longer time to run.

The Q# program is shown below. The operation takes the Hamiltonian information, then encodes the wave function ansatz as a linear combination of the Hartree-Fock state, two singly excited states, and a doubly excited state. VQE modifies the input state with the given parameters `theta1`

, `theta2`

and `theta3`

, and returns the estimated ground state energy for that given input state, in order to determine the variational bound of energy.

namespace Microsoft.Quantum.Chemistry.VQE { open Microsoft.Quantum.Core; open Microsoft.Quantum.Chemistry; open Microsoft.Quantum.Chemistry.JordanWigner; open Microsoft.Quantum.Chemistry.JordanWigner.VQE; open Microsoft.Quantum.Intrinsic; operation GetEnergyVQE (JWEncodedData: JordanWignerEncodingData, theta1: Double, theta2: Double, theta3: Double, nSamples: Int) : Double { let (nSpinOrbitals, fermionTermData, inputState, energyOffset) = JWEncodedData!; let (stateType, JWInputStates) = inputState; let inputStateParam = ( stateType, [ JordanWignerInputState((theta1, 0.0), [2, 0]), // singly-excited state JordanWignerInputState((theta2, 0.0), [3, 1]), // singly-excited state JordanWignerInputState((theta3, 0.0), [2, 3, 1, 0]), // doubly-excited state JWInputStates[0] // Hartree-Fock state from Broombridge file ] ); let JWEncodedDataParam = JordanWignerEncodingData( nSpinOrbitals, fermionTermData, inputState, energyOffset ); return EstimateEnergy( JWEncodedDataParam, nSamples ); } }

To compare this approach to the previous calculation of caffeine using RPE, we can estimate how many resources it will take to run this algorithm. Because it’s variational, let’s look at just the cost for one iteration (`nSamples=1`

):

In: from Microsoft.Quantum.Chemistry.VQE import GetEnergyVQE GetEnergyVQE.estimate_resources( JWEncodedData=encoded_data_caffeine, theta1=0.001, theta2=-0.001, theta3=0.001, nSamples=1 ) Out: { 'CNOT': 0, 'QubitClifford': 1440, 'R': 0, 'Measure': 3240, 'T': 0, 'Depth': 0, 'Width': 8, 'QubitCount': 8, 'BorrowedWidth': 0 }

Note that while the resources for a single run are much lower compared to RPE, this algorithm has a much higher total cost because we still need to multiply the numbers for gates and measurements above by the number of samples and optimization steps, as discussed in our recent prospects.

Let’s try out calculating the energy for a given trial state of the ground state of caffeine for a given initial set of parameters `theta1`

, `theta2`

and `theta3`

:

In: GetEnergyVQE.simulate( JWEncodedData=encoded_data_caffeine, theta1=0.001, theta2=-0.001, theta3=0.001, nSamples=10000000 ) Out: -627.6287520087537

To find the ground state energy, we need find the optimal values of `theta1`

, `theta2`

and `theta3`

at which the energy is minimized. Instead of doing a large scan over the entire parameter space, we run this quantum simulation using an optimizer. For that, we can use any optimization function that can minimize a cost function given a set of input parameters. Here, we will use `scipy.optimize`

:

from scipy.optimize import minimize def run_program(var_params, num_samples) -> float: # run parameterized quantum program for VQE algorithm theta1, theta2, theta3 = var_params return GetEnergyVQE.simulate( JWEncodedData=encoded_data_caffeine, theta1=theta1, theta2=theta2, theta3=theta3, nSamples=num_samples ) def VQE(initial_var_params, num_samples): """ Run VQE Optimization to find the optimal energy and the associated variational parameters """ opt_result = minimize( run_program, initial_var_params, args=(num_samples,), method="COBYLA", tol=0.000001, options={'disp': True, 'maxiter': 200,'rhobeg' : 0.05} ) if opt_result.success: print(opt_result.message) print(f"Result: {opt_result.fun} Ha") print(f"Number of evaluations: {opt_result.nfev}") print(f"Optimal parameters found: {opt_result.x}") return opt_result

We can then run this to find the ground state energy. To get an accurate result, let’s use 10 million samples:

In: VQE([0.001, -0.001, 0.001], 10000000) Optimization terminated successfully. Result: -627.6287829908172 Ha Number of evaluations: 39 Optimal parameters found: [ 0.05093427 -0.00092959 0.05098581]

This prints the and returns the optimization result returned by the optimizer. For a more detailed overview of the parameters that are returned by the minimize function, see the scipy.optimize documentation page.

Important to note here is that the energy estimate by VQE is not going to be as close to the exact energy that we simulated earlier with the RPE sample. This is mainly because we chose a fairly simple trial state. By choosing a more elaborate trial state we will be able to get a better estimate, but this would require us to use more qubits and gate operations in order to run the algorithm.

If this blog post has inspired you to develop quantum algorithms in Q#, we encourage you to get started with our MS Learn modules to get your machine set up to run quantum simulations on your own machine:

Create your first Q# program by using the Quantum Development Kit – Learn | Microsoft Docs

To get a refresher of the fundamental concepts of quantum computing, this MS Learn learning path might help you get started as well:

Quantum computing foundations – Learn | Microsoft Docs

If you prefer to get started with some hands-on samples that you can run directly including the one covered in this blog post, we recommend cloning our Quantum repo which contains more chemistry examples than the ones just mentioned in this blog post:

microsoft/Quantum: Microsoft Quantum Development Kit Samples (github.com)

Alternatively, launch the repo in Binder to can get started running algorithms via IQ# right away:

The Broombridge files and example code that were used in this blog post are part of the `qdk-python`

repo:

microsoft/qdk-python: Python packages for the Microsoft Quantum Development Kit (QDK) (github.com)

If you have any questions, please don’t hesitate to get in touch with us and other quantum developers using the comments to this blog post or the Q# community. Happy quantum developing!

The post Quantum developer tools for chemistry appeared first on Q# Blog.

]]>The post Inside the Quantum Katas, part 2: testing quantum programs appeared first on Q# Blog.

]]>In this blog post we will continue the deep dive into testing different types of quantum programming tasks.

Tasks that ask the learner to implement a given unitary transformation – an operation on qubits that changes their state – are frequently seen in the katas. Quantum oracles and more complicated operations such as quantum Fourier transform or quantum arithmetic are just a few examples that justify their popularity.

Verifying that the learner’s solution is correct can be done by comparing it to the reference implementation using the AssertOperationsEqualReferenced library operation. This operation relies on the Choi–Jamiołkowski isomorphism to reduce the comparison of two unitaries to a comparison of a quantum state to the all-zeros state. Let’s take a quick look at how it works for the small case of single-qubit unitaries (for unitaries acting on multiple qubits the principle is the same but the math is bulkier).

- We will start by preparing an entangled state |Φ⁺⟩ = 1/√2 (|00⟩ + |11⟩).
- Apply the learner’s solution that implements the unitary U to the second qubit:
1/√2 (|0⟩ ⊗ U|0⟩ + |1⟩ ⊗ U|1⟩) This state carries all information about the effects of the unitary on all basis states, and thus, all the information about the unitary itself (up to a global phase). - Now apply the adjoint of the reference implementation R to the second qubit:
1/√2 (|0⟩ ⊗ R†U|0⟩ + |1⟩ ⊗ R†U|1⟩) The trick turns out to be similar to the one we’ve seen when testing the state preparation tasks. If the unitaries R and U are the same, their effects on the state are going to cancel out, and we’ll get the state |Φ⁺⟩ with which we started. If the unitaries are different, their effects either on the |0⟩ state or on the |1⟩ state will not cancel out, and we’ll end up with a different state. - To check whether we ended up with the original state |Φ⁺⟩, we can use the same trick again: apply the adjoint of the routine used to prepare it from the |0⟩ state and compare the result to the |0⟩ state.

With all these steps hidden away in the library operation, the actual test code ends up very short. Here is the testing harness from the first task of the MultiQubitGates tutorial:

@Test("QuantumSimulator") operation TestCompoundGate () : Unit { AssertOperationsEqualReferenced(3, CompoundGate, CompoundGate_Reference); }

In the previous examples we’ve covered tasks that focused on practicing using quantum gates; now let’s learn more about the tasks that offer measurements practice.

The Measurements kata offers tasks which give the learner qubits in one of two or more possible orthogonal states (for example, |0⟩ or |1⟩) and ask to figure out which state it was. This type of task can be tested as follows:

- Pick one of the possible input states randomly.
- Prepare the qubits in this state and pass them to the solution.
- Compare the solution’s answer with the state we picked to see if it’s a match.
- Repeat the steps 1-3 several times to reduce the probability that the solution guessed the state accidentally. This also allows us to gather statistics on the incorrect guesses to help the learner identify their mistakes, such as confusing the indices of states returned or making randomized guesses instead of deterministic.

The testing harness complete with error tracking can get somewhat lengthy; you can find the complete example from the Measurements kata here.

This testing approach can be used for other types of tasks as well. The second part of the Measurements kata offers tasks in which the solution has to identify the state with a certain probability or without errors but with some “unknown state” verdicts allowed. A more recent DistinguishUnitaries kata asks the learner to figure out which of the two unitaries they are given by designing the right experiment.

Sometimes we care not only about the results produced by the solution but also about the operations used by it. Here are several examples of such tasks:

- The Deutsch-Jozsa algorithm example from part 1, in which we want to ascertain that the learner uses the quantum algorithm rather than the classical one, and the most reliable way to do this is to limit the number of times they can use the oracle.
- The random numbers generation tutorial prohibits the use of classical random number generation routines to make sure the learner uses the quantum approach to generating randomness.
- The task that asks the user to implement CNOT using joint measurements restricts the use of two-qubit gates, since otherwise calling CNOT or Controlled X would achieve the formal goal without making the point.

Some of these needs can be addressed by the library operation AllowAtMostNCallsCA. However, the Quantum Katas use a more sophisticated and more flexible approach: the CounterSimulator. It is a custom simulator built as an extension to the full state simulator provided with the QDK, and it counts various resources used during the “normal” program simulation. Developing a simulator with resource counting capabilities is out of scope for this blog post, but since it exists (and is shipped as part of the Microsoft.Quantum.Katas NuGet package), the testing harnesses can use its methods to get the necessary resource counts.

Here is the testing harness for the Deutsch-Jozsa algorithm which runs the algorithm on the given oracle, checks that its result is correct and then checks that the solution doesn’t overuse the oracle calls:

operation TestDJAlgorithm (N : Int, oracle : (Qubit[], Qubit) => Unit, expected : Bool, msg : String) : Unit { EqualityFactB(DJ_Algorithm(N, oracle), expected, msg); let nu = GetOracleCallsCount(oracle); Fact(nu <= 1, $"You are allowed to call the oracle at most once, and you called it {nu} times"); }

Similarly, sometimes we care about the number of auxiliary qubits allocated by the solution. The simplest examples are tasks that ask the learner to implement a phase oracle for a certain function. If the task aims to teach phase manipulation, it might prohibit the solution allocating extra qubits to render implementing a marking oracle and then using the phase kickback trick impossible.

What will the testing harness look like in this case? We can validate that the solution implements the right unitary using the AssertOperationsEqualReferenced operation from the example 1. On top of that, we can use another library operation, AllowAtMostNQubits, to check that AssertOperationsEqualReferenced allocates exactly 2N qubits, where N is the number of qubits on which the oracle acts. (Why 2N? Remember that AssertOperationsEqualReferenced uses 2N qubits to compare the unitaries that act on N qubits. If the reference solution does not allocate extra qubits, any qubits allocated on top of 2N must come from the learner’s solution!)

Here is the testing harness used for the task:

@Test("QuantumSimulator") operation TestPhaseOracle () : Unit { let N = 3; within { AllowAtMostNQubits(2*N, "You are not allowed to allocate extra qubits"); } apply { AssertOperationsEqualReferenced(N, PhaseOracle, PhaseOracle_Reference); } }

These testing patterns are the ones most frequently used in the Quantum Katas. There are plenty of one-off tasks that require more elaborate testing logic (the whole counting multi-qubit gates functionality of the CounterSimulator is only used in one task!), but these should help you get started with testing your own quantum code.

If you’re looking for more advanced scenarios of code verification, see the paper “A Resource Estimation and Verification Workflow in Q#” by Mathias Soeken et al.

The post Inside the Quantum Katas, part 2: testing quantum programs appeared first on Q# Blog.

]]>You can see all of the release notes for the year here.

Thinking of You

2020 was a year like no other.

Life was dominated by the COVID-19 virus and the measures taken around the world to try and control its spread.

The post Three Years of Q# appeared first on Q# Blog.

]]>You can see all of the release notes for the year here.

2020 was a year like no other. Life was dominated by the COVID-19 virus and the measures taken around the world to try and control its spread.

I, and the entire Microsoft Quantum team, hope that you and those close to you have weathered the pandemic safely, and wish you continued health and safety in the coming year.

Perhaps our primary theme for this past year has been opening up Q# to more community involvement.

Our first release of Year 3 added support for compiler extensions, which make it easier for anyone to add new functionality to the Q# compiler. We are very excited about this feature; we really want to make it as easy as possible for the community to experiment with Q#.

In September we launched the Q# Language Design GitHub repository. This site provides a forum for discussing proposed language features and defines a process for proposing new features and for evaluating and approving proposals. It serves a similar purpose for the Q# standard library APIs. We have already collected several issues from the community that will help guide the future evolution of the language. We hope to continue to get this sort of feedback both as new issues and also as feedback on proposed features while they’re being discussed.

Also in September, we launched QIR, our quantum intermediate representation. QIR is language- and platform-independent; it supports Q#, but it is completely general. QIR is based on the popular LLVM open source compiler framework, so it is immediately compatible with the many LLVM-based tools available, such as the clang compiler. There are already teams in several national laboratories using QIR to bridge Q# to classical and quantum platforms.

This past year saw continued growth in community contribution to Q# development, which we greatly appreciate. We added our first team-external maintainer to one of our core repositories, the Quantum Katas. Our Hacktoberfest participation generated about 30 contributions to our repositories, among a total of about 175 community contributions for the full year.

We are very proud to announce that the Unitary Fund made grants to two Q#-based projects: QRAM and QAOA.

Finally, we ran our third Q# coding contest this past summer. It attracted 657 participants, 591 of whom solved at least one problem.

We added a lot of library functionality in 2020. Perhaps the most exciting addition was the quantum machine learning library we rolled out in February. You can see it in use in this tutorial.

Machine learning, of course, is one of the hottest topics in modern computer science. Every large software company is investing heavily in machine learning and artificial intelligence, and many people expect that quantum computing will lead to better machine learning algorithms. While there haven’t been any demonstrations yet of quantum machine learning algorithms that significantly outperform classical ones, this is a very active area of research. We’re happy to provide a “starter kit” to help advance this field.

Based on user feedback we’ve been working on overall performance. Recent releases have made significant improvements to the compiler and simulator performance. We continue to work in this area, and there should be continued improvement over the coming year.

Our last, but far from least, theme for 2020 was improved usability. We made a number of usability improvements to the Q# standard libraries, added new samples, and added some new testing and debugging features. We added the ability to create stand-alone Q# projects that don’t require a driver in another language.

One particular focus was on making our Jupyter notebook integration easier to use and more powerful. We added multiple new features there, especially around visualization. We also made it easier to use IQ# with other Python tools such as NumPy.

This post is part of the Q# Advent Calendar 2020. Follow the calendar for other great posts!

The post Three Years of Q# appeared first on Q# Blog.

]]>The post Emulation in Q# appeared first on Q# Blog.

]]>The first technique employs intrinsic functions. It can be used to implement a Q# function using a .NET language, for example C#. This is particularly useful when the required library functionality is not available in Q#. Let’s consider the following example, typical for this season. We often find ourselves in need of the number of the remaining days until Christmas as a value in our Q# operation. This value can be used as the secret shift in the hidden shift algorithm or as the special element in a Grover search. We cannot retrieve the current date in Q#, and therefore we have to provide this function as an intrinsic:

function DaysUntilChristmas() : Int { body intrinsic; }

This Q# code gets translated into a partial C# class called `DaysUntilChristmas`

.
We can add the implementation by creating a nested class called `Native`

that
derives from `DaysUntilChristmas`

. In its constructor this class accepts an instance `m`

of type `IOperationFactory`

, which is the base class to
all simulators. Therefore, `m`

holds the simulator object for which the
function is called. This will enable us to perform simulator-dependent code.
We’ll use this variable when describing the second technique, however, in this
example we compute the same function independent of the simulator.

public partial class DaysUntilChristmas { public class Native : DaysUntilChristmas { public Native(IOperationFactory m) : base(m) {} // can be adjusted (e.g., 1/7, 1/6, 1/19, ...) private static int ChristmasMonth => 12; private static int ChristmasDay => 25; // C# function with matching signature private long DaysUntilChristmasFunction(QVoid input) { var today = DateTime.Today; var christmas = new DateTime(today.Year, ChristmasMonth, ChristmasDay); // make sure the next Christmas is today or in the future if (christmas < today) christmas = christmas.AddYears(1); // return difference in days return (christmas - today).Days; } // Override __Body__ property to use C# function public override Func__Body__ => DaysUntilChristmasFunction; } }

The function implementation is provided in terms of the `__Body__`

property,
which is of type `Func<__In__, __Out__>`

, where `__In__`

is the type of the input
argument tuple in the Q# function and `__Out__`

is the type of the output
argument tuple. In this case, there are no input arguments,
represented by the empty tuple type `QVoid`

, and there is a single output
argument of Q# type `Int`

, which corresponds to the C# type `long`

(= `Int64`

).

We can use a similar technique to replace an existing function with an
alternative one. It would be nice to make Q#’s `Message`

outputs a little more
festive this month. For this purpose, we implement an intrinsic function called
`ChristmasMessage`

:

function ChristmasMessage(msg : String) : Unit { body intrinsic; }

The implementation is provided in C# and it prefixes each message with Santa’s way of expressing his happiness and joy.

public partial class ChristmasMessage { public class Native : ChristmasMessage { private readonly IOperationFactory simulator; public Native(IOperationFactory m) : base(m) { simulator = m; } private QVoid ChristmasMessageFunction(string message) { if (simulator is ToffoliSimulator) { WriteLine(message); } else { WriteLine($"Ho ho ho: {message}"); } return QVoid.Instance; } public override Func__Body__ => ChristmasMessageFunction; } }

Note that we do not override the behavior when using the `ToffoliSimulator`

,
since the Toffoli simulator does not support the `H`

in *Ho ho ho*.

Instead of replacing all occurrences of `Message`

in our Q# programs by hand, we
wish to do this automatically and hide the existence of the `ChristmasMessage`

from our users. When constructing a simulator instance in a C# host program, we
can use the `Register`

method to replace an existing function with an
alternative one.

var simulator = new QuantumSimulator(); simulator.Register(typeof(Message), typeof(ChristmasMessage), typeof(ICallable));

The first parameter is the type of the existing function, in this case
`Message`

, the second parameter is the type of the replacement, in this case
`ChristmasMessage`

, and the third parameter is the type of either `ICallable`

,
`IAdjointable`

, `IControllable`

, or `IUnitary`

. For functions and operations
that are neither adjoint nor controlled, use `ICallable`

. For operations that
are marked `Adj`

but not `Ctl`

, use `IAdjointable`

, for those marked `Ctl`

but
not `Adj`

, use `IControllable`

, and if they have both, use `IUnitary`

.

It’s worth to note that we couldn’t just have implemented `ChristmasMessage`

by
calling `Message`

inside and then use `Register`

for the replacement. This
would have lead to an infinite recursive loop, since the `Message`

call inside
`ChristmasMessage`

would also be replaced.

The same technique can be used to replace one Q# operation by another Q# operation, the replacement operation doesn’t need to be implemented in C#. Consider the following operation that swaps two qubits using three CNOTs:

operation SwapWithCNOTs(a : Qubit, b : Qubit) is Adj+Ctl { CNOT(a, b); CNOT(b, a); CNOT(a, b); }

To replace the `SWAP`

operation in the `Microsoft.Quantum.Intrinsic`

namespace,
we can simply call `Register`

on the simulator like this:

simulator.Register(typeof(SWAP), typeof(SwapWithCNOTs), typeof(IUnitary));

The emulation technique was demonstrated for Q# functions in this post, but it
applies similarly to Q# operations as well. However, depending on the supported
functors (such as `Adj`

and `Ctl`

), operations for `__AdjointBody__`

,
`__ControlledBody__`

, and `__AdjointControlledBody__`

might also need to be implemented.

The technique is used in several places in the Q# and QDK code base. Some examples include:

- Many functions in the
`Microsoft.Quantum.Math`

namespace. - Speeding up full state simulation for quantum oracles by applying the permutation directly to the state vector.
- A custom gate counting simulator in the Quantum Katas that keeps track of gate and qubit resources to power the testing harnesses used to validate the learner’s solutions.
- Replacing
`ApplyAnd`

and`ApplyLowDepthAnd`

with`CCNOT`

when used with the Toffoli simulator.

The complete code for the project can be found in this gist.

It’s `DaysUntilChristmas()`

days until Christmas, ```
ChristmasMessage("Happy
holidays!")
```

.

The post Emulation in Q# appeared first on Q# Blog.

]]>If you’re reading this blog post, you probably have heard of the Quantum Katas – our collection of tutorials and programming exercises that help one learn quantum computing via quantum programming.

The post Inside the Quantum Katas, part 1 appeared first on Q# Blog.

]]>If you’re reading this blog post, you probably have heard of the Quantum Katas – our collection of tutorials and programming exercises that help one learn quantum computing via quantum programming. (If you haven’t, check them out – I’ve heard great feedback about them )

The Katas are about two and a half years old, and I’ve written about them before once or twice – from the first overview of the project and the summary of its first year in public to its part in this year’s Hacktoberfest celebration (we got 23 pull requests from 11 different folks, 8 of them first-time contributors!)

Oddly enough, I’ve never written about the internal workings of the katas or their most important component – the testing harnesses that provide the learner immediate feedback on their solutions. Testing quantum programs is an interesting topic, very different from testing classical code in some respects and quite similar to it in others. Let’s see how we build the Quantum Katas and how we test them.

Each kata is a sequence of individual tasks, and each task consists of several pieces working in concert.

- The task.

This is the “frontend” of the task, the part where the user spends most of their time. It includes the description of the task (what needs to be accomplished, the format of inputs and outputs, examples and any restrictions imposed on the solution) and the signature of the Q# operation that the learner needs to implement.

A typical kata will have two “frontends” – in the`Tasks.qs`

file (used when solving the kata in Visual Studio or VS Code) and in the Jupyter Notebook. The task description and, most importantly, the operation signature of the task should always match in both cases, though the Jupyter Notebook “frontend” certainly looks much fancier! - The reference solution.

`ReferenceImplementation.qs`

file contains the “reference” solutions to all tasks – correct solutions to the tasks that will pass the tests. Sometimes these solutions play a significant role in the testing of the learner’s code, and one can always turn to them to get an idea about the expected approach to the task. That last goal, though, is often better served by the workbooks – the worked-out explanations of the tasks and their implementation in code that are included in many katas. - The testing harness.

Finally,`Tests.qs`

file contains the code that verifies whether the learner’s code is correct. It is implemented as a collection of unit tests, one per task, that pass if the learner filled in the right code to solve the task and fail otherwise. (This means that when you start solving the kata in VS or VS Code, all tests are failing – a somewhat scary set up!)

The Jupyter Notebook “frontend” doesn’t support unit tests, so the testing harness is invoked using the`%kata`

magic command included in the code cell that contains the task operation.

The most important part of developing a new task is creating the testing harness for it. When we consider the ways to test a solution, we follow one main principle:

In other words, we test whether the solution accomplishes the given task, not the exact path it takes to do that.

Consider, for example, the following task: given a pair of qubits in the |00⟩ state, prepare one of the Bell states |Φ⁻⟩ = 1/√2 (|00⟩ – |11⟩). There are a lot of ways to do this – start by preparing a different Bell state |Φ⁺⟩ = 1/√2 (|00⟩ + |11⟩) and then adjust the relative phase of the second term by applying the Z gate to one of the qubits, or apply an X gate to one of the qubits before applying the Hadamard gate to it and using it as a control in CNOT gate – the possibilities are endless! At the same time we don’t really care which path to the solution the learner takes – the idea of the task is to practice using Pauli gates and the CNOT gate to prepare entangled states, and if the end result is the right superposition state, the task achieved its goal.

Of course, sometimes the goals of the task are more sophisticated than this. The first time we hosted a workshop using the prototype of the DeutschJozsaAlgorithm kata, one of the attendees went ahead and implemented the classical solution to the problem solved by the Deutsch-Jozsa algorithm (figuring out whether the given function is constant or balanced), applying the quantum oracle to basis states to evaluate the classical function. This is a valid classical approach (and later we added it as a separate task to the ExploringDeutschJozsaAlgorithm tutorial), but not the quantum algorithm we’re looking for! We had to add an extra check to count the number of times the given oracle is applied in the learner’s solution, and if it is more than once, fail the test.

Over the years we have accumulated quite a box of tricks for testing different kinds of programming tasks, and I’ll share some of them in the second part of this post. For now, let’s take a look at the simplest example (that is also historically the first type of tasks developed for the Katas) – testing a state preparation task.

Let’s use our Bell state preparation task again: given a pair of qubits in the |00⟩ state, prepare the state |Φ⁻⟩ = 1/√2 (|00⟩ – |11⟩).

First, how does the task signature look like? We want the task to take a pair of qubits as a parameter and have no return – the result of the task is the change in the qubits’ state. The Q# signature that matches this is

operation PrepareBellStatePhiMinus (qs : Qubit[]) : Unit { // ... }

This is it! In the task we leave the operation body blank and mark the part that needs to be filled by the learner with a `// ...`

comment.

To get the reference solution, we just copy the task signature, rename the operation and fill in the code that solves the task.

operation PrepareBellStatePhiMinus_Reference (qs : Qubit[]) : Unit { H(qs[0]); CNOT(qs[0], qs[1]); Z(qs[0]); }

Now, how can we test this kind of a task?

Remember that Q# doesn’t give us direct programmatic access to the amplitudes of the quantum state vector, since that doesn’t match the physical reality of a quantum-mechanical system. Instead, it offers a variety of operations in the Microsoft.Quantum.Diagnostics namespace that can only be applied when running the code on a simulator – which is the case for the Katas – and allow to provide diagnostics on the simulator and to check various assertions about its state. In our case we’ll run the test on the full state simulator and use AssertAllZero operation which passes if all qubits of the given array are in the |0⟩ state and fails otherwise.

At this point an attentive reader should ask “Wait, we are given the |00⟩ state, we’re not trying to prepare it, are we?” We’ll need to do one more step before we can use this assertion to implement our test, and this step involves the reference solution for the task and the very convenient ability of Q# compiler to generate adjoints of quantum operations automatically.

More specifically, we have the learner’s solution that implements a transformation U, and we need to check whether it transforms the initial |00⟩ state to the required state |Φ⁻⟩:

We also know that our reference solution R performs this transformation correctly:

Let’s apply adjoint of our reference solution R† to both parts of the check we want to do:

We see that if we start with the |00⟩ state and apply first the learner’s solution and then the adjoint of the reference solution, we’ll end up with the |00⟩ state again if and only if the learner’s solution did indeed prepare the |Φ⁻⟩ state. Importantly, the results of this check don’t depend on the path the solution took to arrive to the required state.

The code implementation of this test ends up being shorter than the explanation of the logic behind it: once we add “is Adj” to the signature of the reference implementation to enable automatic adjoint generation,

@Test("QuantumSimulator") operation TestPrepareBellStatePhiMinus () : Unit { use qs = Qubit[2]; PrepareBellStatePhiMinus(qs); Adjoint PrepareBellStatePhiMinus_Reference(qs); AssertAllZero(qs); }

This testing harness can be improved further. For example, the error message it produces, “Qubit in invalid state.”, is not very helpful for the learner. The Superposition kata makes an extra effort to output the desired superposition state and the state prepared by the learner’s solution (using another convenient diagnostic operation DumpMachine) before comparing these states.

In part 2 of this blog post we’ll take a look at other types of programming tasks offered in the Quantum Katas and the tools we use to test them. Stay tuned!

The post Inside the Quantum Katas, part 1 appeared first on Q# Blog.

]]>The post Q# Advent Calendar 2020 appeared first on Q# Blog.

]]>The rules are simple:

- Reserve a slot by leaving a comment on this post. (You can also tweet about it, but you’ll have to mention @tcNickolas to make sure we’ve seen it!) The slots are assigned on the first come, first serve basis. You do not have to announce the topic of your blog post until you’re ready to publish it, but we’d really love to hear it beforehand. (This also helps other bloggers to pick a topic that is not too close to the ones already covered.)
- Prepare a blog post (in English) about Q#, cool project you’ve done in Q#, learning Q#, teaching Q#, using Q# for research, tools for working with Q#… You got the idea.* Don’t forget to check out the previous calendars for inspiration!
- Publish your blog post on your assigned date. Don’t forget to link back to the Q# Advent Calendar from your post, so that your readers can find the entire advent.
- Leave the link to your blog post in a comment to this post, and we’ll add it to the calendar. If you share a link to your post on Twitter, use hashtags #qsharp and #QsAdvent.

**Q# Advent Calendar accepts only original content.*

Looking forward to reading your Q# stories!

The post Q# Advent Calendar 2020 appeared first on Q# Blog.

]]>