Q|SI〉: A Quantum Programming Environment

10/26/2017 ∙ by Shusen Liu, et al. ∙ University of Technology Sydney 0

This paper describes a quantum programming environment, named Q|SI〉. It is a platform embedded in the .Net language that supports quantum programming using a quantum extension of the while-language. The framework of the platform includes a compiler of the quantum while-language and a suite of tools for simulating quantum computation, optimizing quantum circuits, and analyzing and verifying quantum programs. Throughout the paper, using Q|SI〉 to simulate quantum behaviors on classical platforms with a combination of components is demonstrated. The scalable framework allows the user to program customized functions on the platform. The compiler works as the core of Q|SI〉 bridging the gap from quantum hardware to quantum software. The built-in decomposition algorithms enable the universal quantum computation on the present quantum hardware.



There are no comments yet.


page 1

page 2

page 3

page 4

This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.

I Introduction

It is well-known that quantum computers can solve certain categories of problems much more efficiently than classical computers; for example, Shor’s factoring algorithm Shor1997 , Grover’s search algorithm grover1996fast and more recently Harrow, Hassidim and Lloyd’s algorithm for systems of linear equations harrow2009 . In recent years, governments and industries around the globe have been racing to build quantum computers. As happened in the history of classical computing, once quantum computers are commercialized, programmers will certainly need a modern platform that can express and implement quantum algorithms without considering the trivialities of their circuits. Such a platform will be even more helpful for quantum programming than in classical computing because physically implement quantum algorithms in a quantum system is somewhat counterintuitive. Using a platform like  could help programmers understand some of these features, which may help to (partially) avoid some of the errors.

Several quantum programming platforms have been developed in the last two decades. The first quantum programming language, QCL, was proposed by Ömer qcl1 ; qcl2 in 1998. It was implemented in C++. A very similar quantum programming language, Q language, was defined by Bettelli et al. qlanguage in 2003, which was implemented as a C++ library. In 2000, qGCL was introduced by Sanders and Zuliani Sanders2000 as a quantum extension of GCL (Dijkstra’s Guarded-Command Language) and pGCL (a probabilistic extension of GCL). Over the last few years, some more scalable and robust quantum programming platforms have emerged: A scalable functional programming language Quipper for quantum computing was proposed by Green et al. Green2013 in 2013. This was implemented using Haskell as its host language. LIQUwas developed in 2014 by Wecker and Svore from QuArc (the Microsoft Research Quantum Architecture and Computation team) Liquid as a modern tool-set and is embedded in another functional programming language F#. In the same year, the quantum programming language Scafford was defined by JavadiAbhari et al. Scafford . Its compilation system ScaffCC was developed in the article scaffCC . Smelyanskiy et al. intel at Intel built a parallel quantum computing simulator qHiPSTER that can simulate up to qubits on a supercomputer with very high performance.

Contributions of this paper: This paper presents a powerful and flexible new quantum programming environment called 222http://www.qcompiler.com, named after our research center333http://www.qsi.uts.edu.au. The core of  is a quantum programming language and its compiler. This language is a quantum extension of the -language. It was first defined in ying2011floyd along with a careful study of its operational and denotational semantics (see also Ying2016 , Chapter 3). The language includes a measurement-based case statement and a measurement-based -loop. These two program constructs are extremely convenient for describing large-scale quantum algorithms, e.g., quantum random walk-based algorithms.

For operations with quantum hardware, we have defined a new assembly language called f-QASM (Quantum Assembly Language with feedback) as an interactive command set. f-QASM is an extension of the instruction set QASM (Quantum Assembly Language) introduced in svore2006layered . A feedback instruction has been added that allows the efficient implementation of measurement-based case and loop statements. A compiler then transforms the quantum -program into a sequence of f-QASM instructions and further generates a corresponding quantum circuit equivalent to the program (i.e., a sequence of executable quantum gates).  also has a module for optimizing the quantum circuits as well as a module to simulate its quantum programs on a classical computer. Two novel features set  apart from other existing quantum programming environments:

  • A quantum program analyzer. Several algorithms for termination analysis and for computing the average running time of quantum programs were developed by one of the authors in ying2010quantum ; ying2013verification . In addition, a semi-definite programming (SDP) algorithm generates invariants of quantum -loops was developed by one of the authors in ying2017invariants . These algorithms have been implemented in  for the static analysis of quantum programs. In turn, this program analyzer helps the compiler to optimize the implementation of quantum programs.

  • A quantum program verifier. A logic in the Floyd-Hoare style was established in ying2011floyd (see also Ying2016 , Chapter 4). This logic, which reasons about the correctness of quantum programs, has been written in the quantum -language. Recently, a theorem prover was implemented by Liu et al. liu2016theorem for quantum Floyd-Hoare logic based on Isabelle/HOL. We plan to link  with the quantum theorem prover presented in liu2016theorem and provide this facility in our platform for the verification of quantum programs.

Ii Quantum -Language

For convenience, a brief review of the quantum -language follows. The quantum -language is a pure quantum language without classical variables. It assumes only a set of quantum variables denoted by the symbols . However, in practice, almost all existing quantum algorithms involve elements of both classical and quantum computation. Therefore,  has been designed such that the quantum -language can be embedded into C#, which brings a significant level of convenience to program design. Some explanations of the quantum program constructs follow; For more detailed descriptions and examples, see ying2011floyd and Chapter 3 of Ying2016 . The quantum -language is generated using the following simple syntax:


As in the classical -language, the statement does nothing and terminates immediately.


The initialization statement “” sets the quantum variable to the basis state .

Unitary transformation

The statement “” means that a unitary transformation (quantum gate) is performed on quantum register leaving the other variables unchanged.

Sequential composition

As in a classical programming language, in the composition , program is executed first. Once terminates, is executed.

Case statement

In the case statement , is a quantum measurement with representing its possible outcomes. To execute this statement, is first performed on the quantum register and a measurement outcome

is obtained with a certain probability. Then, the subprogram

is selected according to the outcome and executed. The difference between a classical case statement and a quantum case statement is that the state of the quantum program variable is changed after performing the measurement.


In the loop , is a “yes-no” measurement with only two possible outcomes: and . During execution, is performed on the quantum register to check the loop guard. If the outcome is , the program terminates. If the outcome is the program executes the loop body and continues. Note that here the state of the program variable is also changed after measuring .

Iii The Structure of

This section provides an introduction to the basic structure of  , leaving the details to be described in subsequent sections.  is designed to offer a unified general-purpose programming environment to support the quantum -language. It includes a compiler for quantum -programs, a quantum computation simulator, and a module for the analysis and verification of quantum programs. We have implemented  as a deeply embedded domain-specific platform for quantum programming using the host language C#.

 ’s framework is shown in the Fig. 1.

Figure 1: Framework of

iii.1 Basic features of

The main features of  are explained as follows:

Language supporting

 is the first platform to support the quantum -language. In particular, it allows users to program with measurement-based case statements and -loops. The two program constructs provide more efficient and clearer descriptions of some quantum algorithms, such as quantum walks and Grover’s search algorithm.

Quantum type enriched

Compared to other simulators and analysis tools,  supports quantum types beyond pure qubit states, such as density operators, mixed states, etc. These types have unified operations and can be used in different scenarios. This feature provides high flexible usability and facilitates the programming process.

Dual mode

 has two executable modes. “Running-time execution” mode simulates quantum behaviors in one-shot experiments. “Static execution” mode is mainly designed for quantum compilation, analysis, and verification.

f-QASM instruction set

Defined as an extension of Quantum Assembly Language (QASM) svore2006layered , f-QASM is essentially a quantum circuit description language that can be adapted for a variety purpose. In this language, every line has only one command. f-QASM’s ‘goto’ structure contains more information than the original QASM svore2006layered or space efficient QASM-HL scaffCC . f-QASM can also be used for further optimization and analysis.

Quantum circuits generation

Similar to modern digital circuits in classical computing, quantum circuits provide a low-level representation of quantum algorithms svore2006layered . Our compiler can produce a quantum circuit from a program written in the high-level quantum -language.

Arbitrary unitary operator implementation

The  platform includes the Solovay-Kitaev algorithm dawson2005solovay together with two-level matrix decomposition algorithm Nielsen2000 and a quantum multiplexor (QMUX) algorithm ShendeBullockMarkov2006 . Therefore, an arbitrary unitary operator could be transferred into a quantum circuit consisting of quantum gates from a small pre-defined set of basic gates once these are available from quantum chip manufactures.

Gate-by-gate description

Similar to other quantum simulators,  has a gate-by-gate description feature. Some basic quantum gates are provided inherently in our platform. Users can use them to build their desired quantum circuits gate-by-gate. We have also provided a decomposition function to generate arbitrary two-dimensional controlled-unitary gates for emulation feasibility.

iii.2 Main components of

The  platform mainly consists of four parts.

Quantum Simulation Engine

This component includes some support assemblies, a quantum mechanics library and a quantum simulator engine. The support assemblies provide supporting for the quantum types and quantum language. More specifically, they provide a series of quantum objects, and reentrant encapsulated functions to play the role of the quantum program constructs and . The quantum mechanics library provides the behaviors for quantum objects such as unitary transformation and measurement including the result and post-state. The quantum simulator engine is designed as an execution engine. It accepts quantum objects and their rules from the quantum mechanics library and converts them into probability programming which can be executed on a classical computer.

Quantum Program (QP) Analysis Module

This module currently contributes two sub-modules to static analysis mode: the “QTerminator” and the “QAverage Running-Timer”. The former provides the terminating information, and the latter evaluates the running time of the given program. Their outputs are sent to the quantum compiler at the next stage for further usage.

QP Verification Module

This module is a tool for verifying the correctness of quantum programs. It is based on quantum Hoare logic, which was introduced by one of the authors in ying2011floyd and is still under development. One possibility for its future advancement is to link  to the quantum theorem prover developed by Liu et al liu2016theorem .

Quantum Compiler

The compiler consists of a series of tools to map a high-level source program representing a quantum algorithm into a quantum device related language svore2006layered , e.g., f-QASM and further into a quantum circuit. Our target is to be able to implement any source code without considering the details of the devices. It will ultimately run on, i.e., to automatically construct a quantum circuit based on the source code. A tool to optimize the quantum circuits will be added to the compiler in the future.

iii.3 Implementation of

One of the basic problems during implementation is how to use probabilistic and classical algorithms to simulate quantum behaviors. To support quantum operations,  has been enriched with data structures from a quantum simulation engine. Fig. 2 shows the procedure for simulating a quantum engine.

Figure 2:   Pre-parser

Three types of languages are supported: pure quantum -language, classical -language and a mixed language. The engine starts a support flow path when it detects the quantum part of a program. Then, the engine checks the quantum type for each variable and operator and executes the corresponding support assembly. As mentioned, one of the main features of  is that it supports programming in the quantum -language. This feature is provided by the quantum -language support assemblies. All of the quantum behaviors are explained by probabilistic algorithms on a classical computer. The outputs are extended C# languages which can be run on a .Net framework or can be explained in f-QASM and quantum circuits by the compiler.

The quantum simulation engine involves numerous matrix computations and operations. In  , Math.net is used for matrix computation. Math.NET is an open-source initiative to build and maintain toolkits that cover fundamental mathematics. It targets both the everyday and the advanced needs of .Net developers444https://www.mathdotnet.com. It includes numerical computing, computer algebra, signal processing and geometry. Math.net is also able to accelerate matrix calculations when the simulation includes a MIC (Many Integrated Core Architecture) device.

In static analysis mode, Roslyn is our chosen auxiliary code analysis tool. Roslyn is a set of open-source compilers and code analysis APIs for C# and Basic languages. Since our platform is embedded in the .Net framework for the C# language, Roslyn is used as a parser to produce an abstract syntax tree (AST) for further analysis.

Iv The Quantum Compiler

A compiler works as a connection between different devices and data structures and serves several different functions. It produces f-QASM code, which can be used to emulate a real or virtual quantum processor. It provides quantum circuits for quantum chip design. It also optimizes quantum circuits.

The  compiler is heavily dependent on other modules. It collects data structures from the quantum simulation engine and splits the program into several parts: variables, quantum gates, quantum measurements, entry and exit points for each clause with their positions. It constructs an AST (Abstract Syntax Tree) from the program, then reconstructs the program as a sequence of f-QASM instructions for further use. Based on f-QASM, the compiler provides a method for decomposing the unitary operators. It can decompose an arbitrary unitary operator into a sequence of basic quantum gates from a pre-defined set where (qubit gate). This corresponds to a scenario in quantum device development: people need universal computation in spite of only a few of gates, which can be produced by the manufacturers. Further, the quantum -language delivers the power of loops, but it also increases the complexity of compilation. A quantum program with a loop structure is much harder to trace than the one without loops. The QP Analysis module provides static analysis tools including a “QTerminator” for termination checking and a “QAverage Running-Timer” for computing the expected running time. In addition, the QP Verification module, still in development, is being designed to verify quantum programs. Once complete, programmers will be able to insert to debug program behaviors.

iv.1 f-QASM

QASM (Quantum Assembly Language) is widely used in modern quantum simulators. It was first introduced in svore2006layered and is defined as a technology-independent reduced-instruction-set computing assembly language extended by a set of quantum instructions based on the quantum circuit model. The article ying2011flowchart carefully characterizes its theoretical properties. In 2014, A.JavadiAbhari et al. scaffCC defined a space-consuming flat description and denser hierarchical description QASM, called QASM-HL. Recently, Smith et al. Quil proposed a hybrid QASM for classical-quantum algorithms and applied it in Quil. Quil is the front-end of Forest which is a tool for quantum programming and simulation that works in the cloud.

We propose a specific QASM format, called f-QASM (Quantum Assembly Language with feedback). The most significant motivation behind our variation is to translate the inherent logic of quantum program written in a high-level programming language into a simple command set, i.e., so there is only one command in every line or period. However, a further motivation is to solve an issue raised by the IBM QASM 2.0 list and provide the ability to have conditional operations to implement feedback based on measurement outcomes.

iv.2 Basic definition of f-QASM

Let us first define the registers:

  • Define as the finite classical registers.

  • Define as the finite quantum registers.

  • Define as the finite flag registers. These are a special kind of classical registers that are often used to illustrate partial results of the code segment. In most cases, the flag registers can not be operated directly by any users code.

Then we define two kinds of basic operations:

  • Define the command “” as , where is a unitary operator and is a quantum register.

  • Define the command “” as , where is a set of measurement operators, is a quantum register, and a is classical register.

After defining registers and operations, we can define some assembly functions:

  • Define “” as , where is a quantum register. The value of is assigned into .

  • Define “”, where is a quantum register, and is an operator, in another functional form of . When is , it means the unitary operator belongs to the pre-defined set of basic quantum gates which can be prepared by the manufacturer or the user. Otherwise, can only be used after being decomposed into basic gates, or be ignored.

  • Define “”, and are the classical registers. This function assigns the value of the register to the register and empties .

  • Define “” as or as , where are two classical registers, is the function comparing whether is equal to : if is equal to then ; otherwise .

  • Define as the current command goes to the line indexed by .

  • Define as indexing the value of and jumping. If is equal to then the compiler executes , otherwise it does nothing.

iv.3 f-QASM examples

Some simple examples to help readers understand f-QASM follow,

iv.3.1 Initialization

means the program initializes the quantum register in the state . In f-QASM, initializing two quantum registers and in the state would be written as


iv.3.2 Unitary transformation

means the program performs a unitary transformation on the register

. The compiler will check whether the unitary matrix is a basic gate. An example program segment of unitary transformation follows:


Here we support hGate is a Hadamard gate performed on single qubit, i.e., To transform this into an f-QASM instruction, it is written as

hGate(q1, 0);

iv.3.3 Case statement

The following program segment is written as a case statement in quantum -language:

() =>
() =>

where hGate is a Hadamard gate performed on single qubit, xGate is a bit-flip gate performing on single qubit , and zGate is a phase-flip gate . Here we assume that all the gates can be provided. is a user-defined measurement. The compiler interprets this segment as the following f-QASM instructions:

JE L1;
JE L2;

iv.3.4 Loop

A loop construct is provided using , where is a key word, is a measurement and is a quantum register. An example program segment with quantum -loop follows:

() =>

Both hGate and xGate are basic gates which have been described above. It could be transformed into f-QASM as follows:

JE L2;

iv.4 Decomposition of a general unitary transformation

Given a set of basic gates. If any unitary operator can be approximated to arbitrary accuracy by a sequence of gates from this set, then the set is said to be universal Nielsen2000 .

In the compiler, there are two kinds of built-in decomposition algorithms. One is the QR method given in barenco1995elementary ; Nielsen2000 . It consists of the following steps:

  1. An arbitrary unitary operator is decomposed exactly into (the composition of) a sequence of unitary operators that act non-trivially only on a subspace spanned by two computational basis states;

  2. Each unitary operator, which only acts non-trivially on a subspace spanned by two computational basis states are further expressed using single qubit gates () and the CNOT gate;

  3. Each single qubit gate can be decomposed into a sequence of gates from a given small set of basic (single qubit) gates using the Solovay-Kitaev theorem dawson2005solovay .

The other is the QSD method presented in ShendeBullockMarkov2006 , consisting of the following steps:

  1. An arbitrary operator is decomposed into three multiplexed rotations and four generic operators, where is the number of qubits;

  2. Repeatedly execute step 1 until is generated;

  3. The operator is decomposed into operators with two extra CNOT gates;

  4. Each single qubit gate in is decomposed into gates from a given small set of basic (single qubit) gates using the Solovay-Kitaev theorem dawson2005solovay .

V The Quantum Simulator

v.1 Quantum types

Data types can be extended from classical computing to quantum computing. For example, quantum generalizations of boolean and integer variables were introduced in ying2011floyd . The state space of a quantum boolean variable is the -dimensional Hilbert space , and the state space of a quantum integer variable is the infinite-dimensional Hilbert space . In  , every kind of quantum variable has its own initialization method and operation. Currently,  contains only finite-dimensional quantum variables, but infinite-dimensional variables will be added in the future. The quantum types used in  are presented in Fig. 3.

Figure 3:   Quantum types layer

The entire quantum types are defined as subclasses of one virtual base class called . The introduction of the virtual base class is only for the purpose of indicating that all of the derived subclasses are quantum objects. From the virtual base class , two extended virtual base classes inherit:

, which represents a class of quantum variables which share some vector rules, and

, which represents a class of quantum operators that share some operator rules.

Quantum variables come in two basic types: Ket is used to denote a quantum variable of arbitrary dimension, and type Bra is the conjugate transpose of Ket. Two specialized (sub)types QBit and QBitBra are provided for two-dimension quantum variable. Note that they are compatible when we consider the boolean type as a subtype of an integer. Also, these types must accept a few rules:

Normalized states

For example, a qubit can be written as . We get either the result with a probability of or the result with a probability of when it is measured on a computational basis. Since these probabilities must sum to , it obeys . Thus, the length of a vector should be normalized to during initialization and computation. For convenience,  provides a function to keep the norm of the variable types QBit and Ket.

Hidden states

It is well-known that the information of a QBit or a Ket cannot be extracted unless the state is measured. However, as indicated by Nielsen and Chuang in Nielsen2000 , “Nature evolves a closed quantum system of qubits, not performing any ‘measurements’, she apparently does keep track of all the continuous variables describing the state, like and ”. In our platform

 , we use the following trick to simulate quantum computing: a quantum state is a black box- each part in the box cooperates with others, but an external viewer knows nothing. Functions and other object methods including unitary transformation or a quantum channel know the quantum state exactly, but a viewer gets nothing about this hidden information unless it is measured. Thus, we classify the state of information storage as a “

Protect” class, which means that the information of a quantum state cannot be touched easily.

The matrix form is widely used in (the semantics of) the quantum -language. There are three categorized of matrix: DensityOperator, MeasureMatrixSet and SuperOperator. DensityOperator is also a virtual basic class with two sub-classes: PureDensityOperator and MixDensityOperator. In fact, the difference between PureDensityOperator and MixDensityOperator is that only MixDensityOperator accepts an ensemble, namely a set of probabilities and their corresponding states, which can be expressed by a PureDensityOperator or a . The object quantum variable of satisfies the following two conditions: (1) has trace ; (2) is a positive operator. Every operation of objects is set to trigger the verification of these conditions in order to ensure the object is a real density operator. MeasureMatrixSet is a measurement containing an array of matrix satisfying a completeness condition . It is very flexible to define a quantum measurement in such a way. Specifically, a plus-minus basis and a computation basis are two built-in measurements, and a user can easily use their designed measurement. A SuperOperator can be used to simulate an open quantum system. It uses an array of Kraus operators satisfying as a representation.

v.1.1 Simulation of quantum behaviors

The basis of simulating quantum computation is to simulate the quantum behaviors defined by the four basic postulates of quantum mechanics Nielsen2000 :

  • Postulate 1: Associated to any isolated physical system is a complex vector space with an inner product (Hilbert space) known as the state space of the system. The system is completely described by its state vector, which is a unit vector in the system’s state space.

    In the platform  , a function in Math.net called

    double ConjugateDotProduct(Vector other)

    is used to support the inner product.

  • Postulate 2: The evolution of a closed quantum system is described by a unitary transformation. That is, the state of the system at time is related to the state of the system at time by a unitary operator which depends only on the time and . .

    To simulate this feature in  , we have added the function to some of our quantum types such as QBit, Ket and DensityOperator in a closed quantum system. In addition, the static global function SuperMatrixTrans is provided to describe the dynamics of an open quantum system as a super-operator .

  • Postulate 3: Quantum measurements are described by a collection of measurement operators. These are operators acting on the state space of the system being measured. The index refers to the measurement outcomes that may occur in the experiment. If the state of the quantum system is before the measurement, then the probability that the result occurs is given by and the state of the system after the measurement is .

    Quantum measurements are simulated with a modified Monte Carlo method. A detailed description is postponed to the next subsection.

  • Postulate 4

    : The state space of a composite physical system is the tensor product of the state spaces of the component physical systems. Moreover, if we have systems numbered

    through , and system number is prepared in the state , then the joint state of the total system is

    The function void KroneckerProduct (Matrix other, Matrix result) is used in the tensor product method, which is embedded in Math.net.

v.1.2 Simulating measurement with pseudo-random number sampling


 , a pseudo-random number sampling method is employed to simulate quantum measurement. It is the numerical experiment generating pseudo-random numbers are distributed according to a given probability distribution 

devroye1986sample .

Let a quantum measurement be described by a collection of bounded linear operators that satisfy a completeness condition . is used to describe the measurement results and the corresponding probability set is denoted as , where . The indexed variable set is denoted as where can be settled to the value . The current system state is assumed to be the quantum state , the indexed variables are and the probabilities are where ,

. A uniform distribution


 is used to simulate a random variable


provides a random variable called which is uniformly distributed on . Then the interval is divided into intervals as . The width of interval equals the probability .

Finally, measurement triggers the strategy in following steps:

  1. Given a measurement and the current quantum state ,  computes the set , where . This step provides the probability distribution : .

  2.  checks the elements of . If there exists any , discard the index in the next step. If there exists any , return the index as the final result and skip the following steps.

  3. Assuming is a set having the same quantity as ,  accumulates the distribution to with the rules: for each in , .

  4. Draw a number which is a uniformly pseudo-random number distributed between .

  5. Find , such that and and return the index . It should be noted that in the case of and in the case of .

The distribution of the variable where is the simulated distribution using the uniform distribution variable . This method of pseudo-random number sampling was developed for Monte-Carlo simulations and its quality is determined by the quality of the pseudo-number.

After is randomly chosen with the distribution , the function returns the value of and the quantum state is modified as an atom operation. According to quantum mechanics, the state would be changed into .

v.1.3 Simulating operational semantics of quantum while-language

Simulating the computation of a program written in the quantum while-language is based on simulating the operational semantics of the language. To clearly delineate coding in mixed classic-quantum programs, quantum -clause are denoted as and quantum -clause are denoted as in quantum simulation engine. To simulate these two functions, the related function methods are encapsulated in Quantum Mechanics Library.

The execution of a quantum program can be conveniently described in terms of transitions between configurations.

Definition V.1.

A quantum configuration is a pair , where:

  • is a quantum program or the empty program (termination);

  • is a partial density operator used to indicate the (global) state of quantum variables.

With the preparations in the previous subsections, we are able to simulate the transition rules that define the operational semantics of the quantum while-language:


The statement does nothing and terminates immediately. Both -identity operation and the null clause satisfy this procedure requirement for simulation in  .



The initialization statement “” sets the quantum variable to the basis state .

In  , initialization has two forms. When the variable is a QBit, it is explained as ; otherwise, it is explained as , where is the dimension of the quantum variable . Moreover, a more flexible initialization method is provided with the help of unitary transformation.

Unitary revolution

The statement “” means that the unitary gate is performed on the quantum register leaving other variables unchanged.

A corresponding method called QuantumTypes .UnitaryTrans(Matrix other) has been designed for objects to perform this function. This function accepts a unitary operator and performs the operator on the variable with null returns. We have also provided a global function called

UnitaryGlobalTrans(QuantumType, Matrix)

that perform an arbitrary unitary matrix on quantum variables.

The quantum -languages do not include any assignment claim for a pure state because a unitary operator exists for any pure state satisfies . Therefore, any pure state can be produced from a combination of an initialization clause and a unitary transformation clause. However, for convenience,  provides a flexible state claim to initialize a QBit, or a Ket using a vector, and to initialize a using a positive matrix.

Sequential composition

The current version of the quantum -language is not designed for concurrent programming. Thus sequential composition is spontaneous.

Case statement

for each possible outcome of measurement

The first step in executing of the case statement is performing a measurement on the quantum variable and observing the output result index. The corresponding subprogram is then chosen according to the index.

Case statements in  use an encapsulated function with the prototype


By default, the sequence is a subprogram corresponding to a measurement output index, i.e., the th corresponds to the th measurement output index. We have also considered cases where the user has not provided a subprogram corresponding to every measurement output index. In these situations,  ’s strategy is to automatically skip that clause if the outcome index exceeds number. In fact, nothing to be done on variables excepted a measurement in this case.

Another difference between a classical and a quantum case statement is that quantum case statement variables must be modified into the state corresponding the measurement output index after performing a measurement. We call the function

to return the measurement result and go to the correct subprogram, then it would call the inherently, which changes the variable to the corresponding state after the measurement.

Loop statement

To implement this loop statement in  , we use an encapsulated function with the prototype

This function accepts quantum types, a measurement, and an integer. Then, it compares the measurement result with the given integer in the guard. If the guard has a value of ‘’, it enters into the loop body, otherwise it terminates. In addition, the state will have been changed after being measured in the guard. The function

is called to return the guard index and go to the correct subprogram, then it calls the inherently as per the case statement.

Vi Experiments

Here, we present three experiments to show the power of our quantum programming environment: Qloop, BB84 and Grover’s search algorithm. Readers can find more details in the Appendices.


Qloop case is a “Hello world” example that includes a quantum channel, a quantum measurement, a quantum -clause and some quantum variables. Basically, it can be regarded as a simplified quantum walk. This test illustrates three main features of the  platform, super-operators, unitary transformations and quantum measurement.

The basic idea of a Qloop is to perform a super-operator on a quantum state and leave the state changed. A counter is used to record the number of times the state enters into different branches. A measurement is taken in every shots and the counter should show the predicted probability for the state.


BB84 is a quantum key distribution (QKD) protocol developed by Bennett and Brassard in 1984 bennett2014quantum . The protocol is an already-proven security protocol shor2000simple that relies on the no-cloning theorem. Using this protocol Alice and Bob reach an agreement about a classical key string that can be used to encrypt classical bits.

Several different scenarios are considered in this experiment. The simple BB84 case outlines the basic communication procedure between two clients: Alice and Bob. The multi-client BB84 case illustrates a more practical example where one Alice generates the raw keys, and many Bobs make an agreement key with Alice. The most interesting case is the BB84 protocol in a channel with quantum noise. Because no real quantum systems are ever perfectly closed, super-operators can serve as a key tool for describing the dynamics of open quantum systems. In this case, influencing factors for QKD are explored. The package length and sampling percentages are crucial to real QKD protocol under quantum noise. With  , different parameters are tested in different channels which can be adjusted for practical use of this protocol.

Grover’s search algorithm

Grover’s search algorithm is an impressive algorithm in the quantum domain. It solves search task in disorderly databases consisting of elements, indexed by number with an oracle. The oracle returns it answers according to position and can find solutions with a high probability within error and steps.

A more general multi-object Grover’s search is also considered that supposes there is more than one answer (position) for the oracle to find. In this case, we use a blind box strategy that reverses the proper position of the answer. This experiment reveals that Grover’s algorithm leads to an avalanche of errors in a multi-object setting, indicating that the algorithm needs be modified in some way.

Vii Conclusions

This paper presents a new software platform,  , for programming quantum computers.  includes an embedded quantum -language, a quantum simulator, and quantum program analysis and verification toolkits. The platform can be used to simulate quantum algorithms, analyze the termination and average running time of quantum programs, and verify program correctness.

Throughout the paper, we demonstrate how to use  to simulate quantum behaviors on classical platforms using a combination of components. We discuss simulating measurement with pseudo-random number sampling, and how to generate the syntax and semantics of the quantum -language.

Active development of  is ongoing. The tensor product is a clumsy way of emulating quantum circuits. We may need to consider timing and entanglement analysis inspired by scaffCC to extend  ’s quantum computing power. The Termination and Average Running Time modules need to be unified into one format for syntax, and we are considering how to split classical and quantum coding for verification purposes.

Interfaces for different quantum computation programs, such as LIQU, ScaffCC and even the real quantum computation platform from IBM’s quantum experiment also need to be considered. These diversified platforms often can provide different views of one quantum program.


We were grateful to Michael Blumenstein, Ian Burnett, Yuan Feng, and Glenn Wightwick for their helpful discussions and support to this project.


  • [1] Peter W Shor. Polynomial-Time Algorithms for Prime Factorization and Discrete Logarithms on a Quantum Computer. SIAM Journal on Computing, 26(5):1484, 1997.
  • [2] Lov K Grover. A fast quantum mechanical algorithm for database search. In

    Proceedings of the twenty-eighth annual ACM symposium on Theory of computing

    , pages 212–219. ACM, 1996.
  • [3] Aram W Harrow, Avinatan Hassidim, and Seth Lloyd. Quantum algorithm for linear systems of equations. Physical Review Letters, 103(15):150502, 2009.
  • [4] Bernhard Ömer. A procedural formalism for quantum computing. 1998.
  • [5] Peter Selinger. A brief survey of quantum programming languages. In

    International Symposium on Functional and Logic Programming

    , pages 1–6. Springer, 2004.
  • [6] Stefano Bettelli, Tommaso Calarco, and Luciano Serafini. Toward an architecture for quantum programming. The European Physical Journal D-Atomic, Molecular, Optical and Plasma Physics, 25(2):181–200, 2003.
  • [7] Jeff W Sanders and Paolo Zuliani. Quantum programming. In International Conference on Mathematics of Program Construction, pages 80–99. Springer, 2000.
  • [8] Alexander S Green, Peter LeFanu Lumsdaine, Neil J Ross, Peter Selinger, and Benoît Valiron. Quipper: a scalable quantum programming language. In ACM SIGPLAN Notices, volume 48, pages 333–342. ACM, 2013.
  • [9] Dave Wecker and Krysta M Svore. Liquid: A software design architecture and domain-specific language for quantum computing. arXiv preprint arXiv:1402.4467, 2014.
  • [10] Ali JavadiAbhari, Shruti Patil, Daniel Kudrow, Jeff Heckey, Alexey Lvov, Frederic T Chong, and Margaret Martonosi. Scaffcc: Scalable compilation and analysis of quantum programs. Parallel Computing, 45:2–17, 2015.
  • [11] Ali JavadiAbhari, Shruti Patil, Daniel Kudrow, Jeff Heckey, Alexey Lvov, Frederic T Chong, and Margaret Martonosi. Scaffcc: a framework for compilation and analysis of quantum computing programs. Proceedings of the 11th ACM Conference on Computing Frontiers, page 1, 2014.
  • [12] Mikhail Smelyanskiy, Nicolas PD Sawaya, and Alán Aspuru-Guzik. qhipster: the quantum high performance software testing environment. arXiv preprint arXiv:1601.07195, 2016.
  • [13] Mingsheng Ying. Floyd–hoare logic for quantum programs. ACM Transactions on Programming Languages and Systems (TOPLAS), 33(6):19, 2011.
  • [14] Mingsheng Ying. Foundations of Quantum Programming. Morgan Kaufmann, 2016.
  • [15] Krysta Marie Svore, Alfred V Aho, Andrew W Cross, Isaac Chuang, and Igor L Markov. A layered software architecture for quantum computing design tools. IEEE Computer, 39(1):74–83, 2006.
  • [16] Mingsheng Ying and Yuan Feng. A flowchart language for quantum programming. IEEE Transactions on Software Engineering, 37(4):466–485, 2011.
  • [17] Mingsheng Ying, Nengkun Yu, Yuan Feng, and Runyao Duan. Verification of quantum programs. Science of Computer Programming, 78(9):1679–1700, 2013.
  • [18] Mingsheng Ying, Shenggang Ying, and Xiaodi Wu. Invariants of quantum programs: characterisations and generation. In Proceedings of the 44th ACM SIGPLAN Symposium on Principles of Programming Languages, pages 818–832. ACM, 2017.
  • [19] Tao Liu, Yangjia Li, Shuling Wang, Mingsheng Ying, and Naijun Zhan. A theorem prover for quantum hoare logic and its applications. arXiv preprint arXiv:1601.03835, 2016.
  • [20] Christopher M Dawson and Michael A Nielsen. The solovay-kitaev algorithm. arXiv preprint quant-ph/0505030, 2005.
  • [21] Michael A Nielsen and Isaac L Chuang. Quantum computation and quantum information. Cambridge University Press, 2010.
  • [22] V.V. Shende, S.S. Bullock, and I.L. Markov. Synthesis of quantum-logic circuits. IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems, 25(6):1000–1010, jun 2006.
  • [23] Adriano Barenco, Charles H Bennett, Richard Cleve, David P DiVincenzo, Norman Margolus, Peter Shor, Tycho Sleator, John A Smolin, and Harald Weinfurter. Elementary gates for quantum computation. Physical Review A, 52(5):3457, 1995.
  • [24] Luc Devroye. Sample-based non-uniform random variate generation. Proceedings of the 18th conference on Winter simulation, pages 260–265, 1986.
  • [25] Robert S Smith, Michael J Curtis, and William J Zeng. A practical quantum instruction set architecture. arXiv preprint arXiv:1608.03355, 2016.
  • [26] Mingsheng Ying and Yuan Feng. Quantum loop programs. Acta Informatica, 47(4):221–250, 2010.
  • [27] Charles H Bennett and Gilles Brassard. Quantum cryptography: Public key distribution and coin tossing. Theoretical computer science, 560:7–11, 2014.

Appendix A Setup and configuration of

 mainly relies on IDE (Visual Studio) to provide the details of the program. After completing a program using  , the programmer needs to build and compile it. This feature is considered to be an essential component because a smarter IDE is a basic way of ensuring the syntax is correct as programs grow in size and complexity. This feature is unlike IScasMC or QPAT which are not able to execute a program.

NuGet is a part of the .Net development platform and it is used in  to manage the packages. All packages used to provide functions, such as matrix computation, random number generation, and Roslyn, etc., can be automatically controlled by NuGet. To add all the essential packages, a user needs only add the NuGet feed v3 “https://api.nuget.org/v3/index.json” to the Visual Studio 2017 configuration. This will provide the package resources and automatically configure them for the platform.

 is compatible with any version of Visual Studio 2015 and later. However, we recommend the Enterprise version of Visual Studio 2017 because of some of its premium features, such as the ability to draw quantum circuits with the DGML tools, the most up-to-date Math.net, etc. Examples are stored in the sub-folder UnitTest. All entry-level examples can be found in the ‘Program.cs’ file in UnitTest.

Appendix B Experiment-Qloop case

The first example showcases the Qloop case. It uses quantum channels, measurement, quantum -clause and quantum variables. The Qloop case can also be treated as a simplified quantum walk. The flow path is shown in Fig. 4.

Figure 4: Qloop

b.1 Input and output


  • ;

  • ;

  • ;

  • ;

  • .


  • : the number of circles is .

b.2 Results

The Qloop experiment is executed about 100000 shots and the results are shown in the Fig. 5.

Figure 5: Qloop data

b.3 Features and analysis

After calculation, it is clear that , , and .

The three main features of this experiment include super-operators, unitary transformation, and measurement operation. In addition, processes that consider a qubit’s collapse and measurement probability are involved as part of quantum mechanics.

  • Super-operator operation. The initial state passes through a quantum channel and becomes . Let be performed on the state in each shot. There is a probability that the state would change to and then terminate. Likewise, there is a probability of moving in a circle and having the process recorded by the counter. So if the program is executed many times, such as in a shot experiment, the counter should show the state enters the circle about times.

  • Measurement operation and unitary transformation. After the first measurement, would change to and continue or it would change to and terminates. If the state becomes , after a Hadamard operator which is a unitary transformation, it becomes and counter records the circle once. When a measurement is performed on the state, we can assert that almost half the time becomes and half the time it becomes . If the result is , it will enter into the loop body again and is recorded by our counter. In total, the counter number shows how many circles the state enters into. Obviously, this decreases at almost half the rate of a geometric progression, as in say , , ,

Appendix C BB84 case

BB84 is a basic quantum key distribution (QKD) protocol developed by Bennett and Brassard in 1984 [27].

c.1 Simple BB84 case

In this case, a client-server model is used as a prototype for a multi-user communication protocol. A “quantum type converter” is used to convert a ‘’ into a density operator. For simplicity and clarity, this example only ‘’ quantum types is considered, not quantum channels or Eves. The flow path is shown in Fig. 6.

Figure 6: Simple BB84 protocol

The entire flow path follows,

  1. Alice randomly generates a sequence of classical bits called a rawKeyArray. Candidates from this raw key sequence are chosen to construct the final agreement key. The sequence length is determined by user input.

  2. Alice also randomly generates a sequence of classical bits called basisRawArray. This sequence indicates the chosen basis to be used in next step. Alice and Bob share a rule before the protocol:

    • They use or to encode the information.

    • A classical bit 0 indicates a basis while a classical bit 1 indicates . This rule is used to generate Alice’s qubits and to check Bob’s basis.

  3. Alice generates a sequence of quantum bits called KetEncArray, one by one according to the rules below,

    • If the basisRawArray[i] in position [i] is and the rawKeyArray[i] in position [i] is , KetEncArray[i] would be .

    • If the basisRawArray[i] in position [i] is and the rawKeyArray[i] in position [i] is , KetEncArray[i] would be .

    • If the basisRawArray[i] in position [i] is and the rawKeyArray[i] in position [i] is , KetEncArray[i] would be .

    • If the basisRawArray[i] in position [i] is and the rawKeyArray[i] in position [i] is , KetEncArray[i] would be .

  4. Alice sends the KetEncArray through a quantum channel. In this case, she sends it through the channel.

  5. Bob receives the KetEncArray through the quantum channel.

  6. Bob randomly generates a sequence of classical bits called measureRawArray. This sequence indicates the chosen basis to be used in next step.

  7. Bob generates a sequence of classical bits called tempResult, using quantum measurement according to the rules:

    • If the measureRawArray[i] in [i] position is a classical bit 0, Bob uses a basis to measure the KetEncArray[i] while a classical bit 1 indicates using a basis.

  8. Bob broadcasts the measureRawArray to Alice using a classical channel.

  9. Alice generates a sequence of classical bits called correctBroadArray, by comparing Bob’s basis measureRawArray and her basis basisRawArray. If the position [i] is correct, the correctBroadArray[i] would be , otherwise would be .

  10. Alice sends the sequence correctBroadArray to Bob.

  11. Alice generates a sequence of classical bits called using the rule:

    • If position [i] in correctBroadArray[i] is 1, she keeps rawKeyArray[i] and copies it to FinalALiceKey , else she discards rawKeyArray[i].

  12. Bob generates a sequence of classical bits called using the rule:

    • If position [i] in correctBroadArray[i] is 1, he keeps tempResult[i] and copies it to FinalBobKey[i], else he discards tempResult[i].

  13. GlobalView: We use a function compare whether every position [i] in FinalALiceKey and FinalBobKey[i] are the same.

This case shows some useful features,

  • Client-server mode. The process uses a client-server model to simulate the BB84 protocol. The model includes many implicit features, such as waiting threads and concurrent communications which are also used in the next example.

  • Measurement. According to theory, choosing a random measurement basis may arrive at half of the correct result. As a result, the agreement of classical shared bits should be almost half the length of the raw keys.

c.2 BB84 case, multi-client

The multi-client BB84 model offers a more attractive and practical example. In this model, there is one Alice to generate the raw keys and many Bobs to construct an agreement key with Alice.

In this case, users can specify the number of clients. Also, a typical BB84 flow path would occur for every client-server pair of this model.

  • Threads Model. Many clients are generated and communicate with Alice. Each of them finally reaches an agreement.

  • Measurement threads. In this case, Alice generates raw keys, and Bob measures the quantum bits. However, this raises a serious question that when a client is considered to generate a raw key while the server measure, how can we ensure the server correctly and fairly conducts the measurement for the server.

c.3 BB84 case with noise

A practical topic for the  is to consider the BB84 model with noisy quantum channels. Noisy quantum operations are the key tools for the description of the dynamics of open quantum systems.

In this example, different channels such as bit flip, depolarizing, amplitude damping and -identity channels are described by quantum operations performing as the evolution of quantum systems in a wide variety of circumstances. Alice and Bob use these quantum channels to communicate with each other via the BB84 protocol as Fig. 6 shows. During communication, verification steps also need to be considered.

c.3.1 Input and output

In this example, the basic quantum channels are defined as follows:

deplarizing channel with noise parameter ,

amplitude damping channel with noise parameter ,

bit flip channel with noise parameter ,

bit flip channel with noise parameter ,

bit flip channel with noise parameter ,

The flow path follows the simple BB84 protocol shown in Fig. 6. The only differences are in Step 4 and a sampling step is added.

  • Alice sends the KetEncArray through a quantum channel. In this case, it is one of the channels mentioned above.

  • Sampling check step: Alice randomly publishes some sampling positions randomly with the bits against these positions in her own key string. Bob checks these bits against his own key strings. If all the bits in these sampling strings are the same, he believes the key distribution is a success; Otherwise, the connection fails.

For a statistical quantity characterizing success in a channel with the BB84 protocol, we executed a 100-shot experiment for each channel. In every shot for every channel, different sampling percentages and package lengths were considered. The tables and figures are provided in Fig. 7 that show the trade-off between success times, different sampling proportions and package lengths in each of the quantum channels.

c.3.2 Results

Success times for different sampling percentages in different channels in 100 shots are provided by Fig. 7.

(a) Bit Flip Channel, , (b) Bit Flip Channel, , (c) Bit Flip Channel, , (d) Depolarizing Channel, , (e) -channel, (f) Amplitude Damping Channel, ,
Figure 7: Statistics of success communication via BB84 with channels

c.3.3 Features and Analysis

The example generates some ‘erroneous’ bits during communication due to the quantum channels. These bits cause a connection failure. Meanwhile, not all error bits can be found in the sampling step because, in theory, almost half the bits are invalid in the measurement step. Additionally, the sampling step is also a probability verification step which means it does not use all the agreed bits to verify the communication procedure.

Subfigures (a),(b) and (c) in Fig. 7 are bit flip channels with different probabilities. Overall, successful shots increase as increases and the raw key length shortens. This is because is a reflection of the percentage of information that remains in bit flip channel and an increase in means fewer errors in communication. A shorter raw key length ensures fewer bits are sampled. Sub-figure (d),(e) and (f) illustrate the communication capacity of the BB84 protocol in the other three channels. Note that the -identity channel has a 100% success rate, which means it is a noiseless channel and can keep information intact during the transfer procedure.

Appendix D Grover’s search algorithm

Grover’s search algorithm is a well-known quantum algorithm. It solves searching problems in databases consisting of elements, indexed by number with an oracle provides the answer as a position. This algorithm can find solutions with a probability of within steps.

d.1 A Simple Grover’s search algorithm

In this example, we assume there is only one answer to the question, i.e., the oracle will only reverse one position at a time. Further, the oracle is assumed to be working as a black box and can reverse the correct position of the answer. After querying the oracle times with the corresponding phase rotations, the quantum state includes the correct information to answer the question.

d.1.1 Input and output


  • The total number of space . For convenience, we restrict .

  • The correct position of the search. That is used to construct oracle.


  • The final position of the measurement result.

  • Oracle time .

d.1.2 Results

The simple Grover’s search algorithm has only one result, and the final measurement result shows the correct answer to the searching problem.

d.1.3 Features and analysis

Suppose is not the solution but rather is the solution where indicates the sum of all the solutions. The initial state may be expressed as

Every rotation makes the to the solution where

When is larger, the gap between the measurement result and the real position number is less than . Therefore, it is almost impossible to have a wrong answer within times.

d.2 Multi-object Grover’s search algorithm

A more general Grover’s search algorithm is considered: a multi-object Grover’s search algorithm. This case supposes that there may be more than one correct answer (position) for the oracle to find. We use a strategy that adds a blind box to reverse the proper position of the answer. This experiment reveals that Grover’s algorithm leads to an avalanche of error in a multi-object setting, indicating that algorithm needs to be modified in some way.

A new blind box (a unitary gate) is added, which reverses the proper position of the answer. In short, the oracle is a matrix where all the diagonal elements are , but all the answer positions are . Thus, the blind box is a diagonal matrix where all elements are , and all the answer position that have been found are . When these two boxes are combined, we create a new oracle with the answers to all the questions except ones were found in previous rounds.

d.2.1 Input and output

The input is

  • The total number of spaces . For convenience, we restrict .

  • All correct positions of the search.

The output is

  • The final position of the measurement result.

  • Oracle time .

d.2.2 Results

The measurement shows different probabilities of the final result. The theory holds that if we have multiple-answers, the state after times oracles and phase gates become the state near both of them. For example, if the answers are , the state before the measurement is expected to be almost . We should get or the first time and the other one the next time. However, we get results other than and with high probability, which indicates that the multi-object search algorithm is not very good.

d.2.3 Features and analysis

It worth noting that due to multi-objects, the real state after using Grover’s search algorithm becomes where and . However, cannot be ignored even it is very small. An interesting issue occurs when the wrong position index is found. If the wrong index is measured, the algorithm creates an incorrect blind box and reverses the wrong position of the oracle, i.e., it adds a new answer to the questions. In next round, the proportion of correct answers is further reduced. In the last example, we would have gotten a wrong answer by measurement, say . After new procedure, the state would become: . It becomes harder and harder to find the correct answer with this state.