QuECT: A New Quantum Programming Paradigm
Quantum computation constitutes a rapidly expanding subfield of computer science. Development quantum algorithms is facilitated by the availability of efficient quantum programming languages, and a plethora of approaches has been already suggested in the literature, ranging from GUI-based simple tools to elaborate standalone programming languages. In this paper we propose a novel paradigm called Quantum Embeddable Circuit Technique (QuECT) that allows a programmer to embed a circuit diagram in a classical “host” language. The paradigm can be implemented in any modern classical language. A prototype has been developed by the author using Java.
Quantum computation is a rapidly developing field, and even though actual quantum computers are yet to be constructed in a large scale, many quantum computing algorithms have already appeared in the literature. One needs some quantum programming language to present these algorithms to a quantum computer (or a simulator). A variety of approaches have been suggested in the literature to this end. These range from drag-and-drop graphical interfaces to quantum assembly languages. Most textbooks like to present quantum algorithms in the form of “circuit diagrams.” All the graphical approaches to quantum programming rely on these circuit diagrams. Its intuitive nature notwithstanding, this ubiquitous technique is not easily amenable to standard programming constructs like conditional jumps and loops. In this paper we propose a new quantum programming paradigm called Quantum Embeddable Circuit Technique (QuECT) that combines the power of circuit diagram and yet allows the traditional control structures. It enhances an existing classical language to handle quantum circuit diagram embedded in it. The author’s implementation uses Java as the classical “host” language, but the same idea carries over directly to any other language (compiled/byte code compiled/interpreted). The QuECT paradigm is equally applicable for a real quantum computer (when one is constructed) as it is for a simulator. It is expected that this paradigm will help traditional programmers to pick up quantum computing more easily.
At this point the reader may like to take a look at a simple example of the QuECT approach given in section 4. The layout of the paper is as follows. Section 2 gives a concise summary of the basic notions of quantum computing. Our exposition loosely follows that of . In section 3 we review the quantum programming paradigms in existence. The section after that is devoted to the details of the QuECT paradigm. Section 5 shows the paradigm in action, where we demonstrate QuECT implementation of some standard quantum algorithms. Some practical issues about compiling a QuECT program may be found section 7.
2 Basic ideas
The most fundamental building block of quantum computing is a qubit, which is often considered as the quantum analog of a bit, and hence its name. This analogy, however, has its pitfalls, and for a rigorous understanding one should better remember a qubit as a nonzero element of identified up to multiples. Thus, is a qubit, and is another. The qubit is actually the same as since these are multiples of each other. The two qubits and are special, and have the names and respectively.
By a -qubit register we shall understand a nonzero element of A -qubit register is the same as a single qubit. However, for general a -qubit register is not the same as a collection of qubits. Two -qubit registers are considered the same if they are (nonzero) multiples of each other.
Since we are working with vectors and matrices of size it is obvious that the sizes are going to explode pretty soon even for a modest While it is not supposed to pose a problem to a computer with quantum hardware, it is nevertheless difficult for a human programmer to keep track of such large vectors and matrices. The concept of factorization helps us here by expressing a large vector as tensor product (also known as Kronecker product) of shorter vectors. This allows us to work with the shorter vectors separately, combining the results at the very end, if necessary. For example, it may be possible to express a -qubit register (consisting of complex numbers) may be expressed as a tensor product of registers of sizes (where requiring a total of only complex numbers).
However, not all quantum registers admit a factorization. If a -qubit register cannot be factored, then we say that the qubits are entangled. Entangled qubits give the main power to quantum programming, and also stand as the main hurdle for a classical programmer aspiring to write a quantum program.
2.2 Quantum gates
The second most important concept in quantum computing is that of quantum gates, which are unitary matrices with complex entries. We shall think of a -qubit register as a column vector of length and a quantum gate as a unitary matrix of size multiplying it from the left. From the viewpoint of a quantum programmer these are of two types. First, there are some commonly used operators (e.g., Hadamard, Pauli’s etc). Then there are the operators specially crafted for some specific algorithm. The most prominent example of the later type is a “quantum wrapper” that packages a classical function into a unitary matrix of order as follows.
To find the -th entry of we first express and in binary using bits. Then we split each of them into two parts: the -part consisting of the most significant bits, and the -part consisting of the least significant bits. Let these be denoted by and Then
It is not difficult to see that each row and each column of has exactly a single 1, and so is unitary.
The third important concept in quantum computing is that of measurement. While it is standard to treat measurement as a Hermitian operator, we shall restrict ourselves to the most frequently used form, viz., measurement of one or more qubits in a multi-qubit register. If we measure given qubits in a -qubit register then we shall observe a random variable which takes values (or, equivalently, the corresponding bit patterns of length ). Quantum physics dictates that the probability of observing a given bit pattern is
where the numerator sum is for those ’s only whose binary representations have the pattern in the positions of the qubits being measured. For example, if we measure qubits at positions 0 and 2 in a 3-qubit register containing the value we shall observe 0 or 1 or 2 or 3 with the probabilities
Here means means and so on. Also the bits at positions 0 and 2 are underlined in the right hand sides for ease of comparison. The process of measurment also changes the contents of the multi-qubit register. If the output is the bit pattern then the contents of the multi-qubit register changes from to where
The fact that a quantum measurement potentially changes the underlying quantum register is a main distinguishing feature of quantum systems over classical ones. However, in a typical quantum algorithm the measurement comes at the very end. So we do not care about the fate of the register once the measurement is over. However the way a measurement affects the contents of a quantum register has the following theoretical implication which indirectly helps a quantum programmer.
Suppose that we are working with a -qubit register. Let be two disjoint, nonempty subsets of Then all the following measurement operations will produce identically distributed outputs:
First measure the qubits at positions then measure those at positions
Measure the qubits at positions
This observation allows us to combine all the measurements at the end of an algorithm into a single mesaurement.
2.4 Quantum circuits
A quantum algorithm, in its barest form, consists of
a multi-qubit register with some given classical initial value, (i.e., a tensor product of ’s and ’s),
an ordered list of quantum gates that act on the register in that order,
measurements of some qubits at the very end.
Usually the quantum gates are complicated, huge matrices, made by taking tensor products of smaller matrices. An actual quantum computer will have no problem in computing the effect of applying such gates, but a human programmer always finds it easier to specify a huge gate in terms of the constituent smaller gates. The quantum circuit diagram is the most popular way to achieve this.
The evolution of a -qubit register is shown in a quantum circuit as parallel lines. Roughly speaking, these lines are like wires each carrying a single qubit111This analogy is not entirely correct in presence of possible entanglement, as we shall see soon.. The left hand circuit diagram in Fig LABEL:im:ckt1.eps, for example, represents a 1-qubit register initially storing and being acted upon by a quantum gate (which is a unitary matrix).
Fig 1: Two simple quantum circuits
The right hand circuit diagram represents a 2-qubit register starting with the value
and being acted upon by a quantum gate which must be a unitary matrix. The result may not be factorizable as a tensor product of two qubits, in which case it is meaningless to talk about the values of the individual output lines.
The following circuit shows a 3-qubit register starting with the content
Fig 2: An example of entanglement
Then it is acted upon by the unitary matrix
The lower 2 qubits are possibly entangled together, however they are not entangled with the top qubit. This is shown using a broken ellipse (which is not part of a standard circuit diagram).
Fig LABEL:im:ckt3.eps presents a more complicated example that also demonstrates a pitfall.
Fig 3: A more complicated circuit
It would be wrong to think that the quantum gate acts upon the top two qubits. This is because the middle qubit actually does not exist separately after stage 1, thanks to the possible entanglement introduced by Thus the naive interpretation that each line is like a wire carrying a single qubit does not hold any more. The unitary matrix that is depicted by this diagram is actually
where denotes identity matrix of order 2 (corresponding to the bottom line “passing through” stage 2). This circuit also has some measurement symbols. Here we are measuring the two extreme qubits. The overall circuit denotes a quantum function from to
The usefulness of circuit diagrams to represent quantum algorithms stems from the following reasons.
It allows one to work with just lines even when the underlying system has dimension
The quantum gates can be constructed easily out of component gates suppressing cumbersome expressions like (* ‣ 2.4) involving tensor products and identity matrices.
The chief drawbacks of a circuit diagram are as follows.
Before talking about the contents of a subset of the lines one has to make sure that none of these are entangled with lines outside the subset.
Control structures like conditional jumps and loops are not easily represented in a circuit diagram.
3 Review of existing techniques
Representing quantum algorithms in a way suitable for classical programmers has been an area of considerable interest. In this section we discuss some of the techniques currently proposed. Many of these approaches are implemented with a simulator back end.
The different approaches fall into two categories, those that rely on a graphical user interface (GUI), and those that rely on text-based programming.
All the graphical representations
A slew of graphical applications built upon the idea of circuit diagrams have been proposed. Most of these allow the user to construct a quantum circuit by dragging and dropping out-of-the-box components on a panel. The simulators of this genre mainly differ from one another in terms of the following points.
The number of available components,
The ease with which a new component can be created by the user,
The way the measurements are presented (e.g., as colour bars, or as floating point numbers or using symbolic expressions).
Unfortunately we have not seen any GUI based quantum programming tool that allows the programmer to implement the “quantum wrapper” mentioned earlier. Nor do these tools allows loops. These two serious drawbacks restrict the uses of these tools to introductory didactic purposes only.
The second category of quantum programming tools consist of text-based programming. One conspicuous example is QCL  which is a standalone quantum programming language. Other examples are Q proposed by  and LanQ by . A quantum functional programming language QFC has been suggested by . Excellent (though somewhat antiquated) surveys are provided in [6, 9].
A third approach suggested in  consists of buiding a quantum assembly language that can be emebedded in a classical program. Some typical quantum assembler directives could be
INITIALIZE X 1 U TENSOR H I2 APPLY U X
The quantum (assembly) languages belonging to the second and third categories above, while superficially akin to their classical brethren, nevertheless deprives the programmer of the intuitive feel of a quantum circuit. The state of a classical program is typically stored in a collection of variables, and the programmer processes the different variables differently. This, unfortunately, is not possible in presence of entanglement, because we cannot store entangled qubits separately. In the circuit of Fig LABEL:im:ckt3.eps, for example, we cannot really store the outcome of the first stage into 3 qubits and feed the top two qubits to
Our QuECT approach detailed below aims to rectify these flaws.
4 The QuECT paradigm
The QuECT paradigm is a hybrid approach where we embed a quantum circuit diagram in a classical “host” program to get the best of both worlds. We use the classical programming constructs for the classical part, and seamlessly integrate it with circuit diagrams for the quantum parts. Before we delve into the details let us take a look at a simple example.
4.1 An example
Consider the quantum circuit shown in Fig LABEL:im:ckt4.eps.
Fig 4: A circuit to demonstrate QuECT
Here is the quantum wrapper around the classical function given by
The QuECT version of this quantum algorithm is given below using Java as the classical “host” language. The embedded circuit is shown in bold.
%#] public class QTester
public static void main(String args) QMachine qm = new QMachine(2); H = MatUnitary.HADAMARD; Classical c = new Classical(1,1) //domain dim=1=range dim, public f(int x) return 1-x; ; Uf = new WrapUnitary(c);
int measVal = qm.getObsDist(); System.err.println(”measured value = ”+measVal);
- Line 4
A new quantum machine is created to handle a 2-qubit register.
- Lines 5
A new Hadamard gate is created. This gate is one of the standard gates used in quantum computation.
- Lines 6–8
The classical function is defined.
- Line 9
A quantum wrapper is put around this
- Line 10–13
The circuit diagram is embedded as an ASCII art between the
%#] QBEGIN(qm) … QEND
delimiters. The name of the target quantum machine (qm, here) is provided as an argument. The syntax of the ASCII art (self-evident in this example) will be explained shortly. The ‘’ symbol at the end of line 12 marks that qubit for measurement.
- Line 15
The method getObs() extracts the measured value.
4.2 QuECT syntax
A quantum algorithm is embedded in a QuECT program as one or more chunks of the form the
%#] QBEGIN(… QEND
Just like classical statements, a chunk can be inserted anywhere inside a program (e.g., in the body of the for-loop). The syntactic elements of QuECT come in two flavours—those for use inside a quantum chunk, and those that are used outside. We start our description with the first category.
The syntax for use inside a chunk is designed to mimic a quantum circuit diagram as closely as possible with ASCII art. Certain features are added to avoid ambiguity during parsing. A walk-through follows.
Each qubit line is shown with a sequence of dashes (the length is immaterial). Multiple lines can be abbreviated as shown in Fig LABEL:im:ckt5.eps.
Fig 5: QuECT syntax for single and multi-qubit lines
We can also use
where n is some integer variable defined in the classical part of the QuECT program.
Initialization is done as in Fig LABEL:im:ckt6.eps.
Fig 6: QuECT syntax for initialization
The quantum gates spanning only a single line are shown inside square brackets (Fig LABEL:im:ckt6.eps).
Fig 7: QuECT syntax for single line gates
Gates spanning multiple lines are delimited by vertical bars (Fig LABEL:im:ckt7.eps).
Fig 8: QuECT syntax for multiline gates
They must be vertically aligned (otherwise a syntax error will be generated).
Care must be exercised to distinguish the two situations depicted in Fig LABEL:im:ckt8.eps.
Fig 9: Two similar but different circuits
Notice the need of two different identifiers A1 and A2 in the latter case. We could use any other identifiers also, as long as they are both associated with the same gate in the classical part of the algorithm.
Sometime we need to feed two or more nonadjacent qubits into a gate. This often messes up the circuit diagram. Some simulators employ a (pseudo-)gate called swap to bring the qubit lines to adjacent positions before feeding them into the gate. But this is easy to achieve in QuECT as in Fig LABEL:im:cktadj.eps.
Fig 10: QuECT syntax for gates spanning nonadjacent lines
Here the gate takes the two extreme qubits as input, letting the middle qubit “pass through”.
Swap (pseudo-) gates are somewhat like goto-statements, and should be generally avoided in a circuit diagram, as they reduce readability of the diagram. A judicious layout of the lines can avoid the need of swap gates in many situations. Also the “pass through” syntax of QuECT as discussed above reduces the need of swapping lines. But still there may be situations where swapping is needed. QuECT provides the syntax shown in Fig LABEL:im:cktswap.eps for such rare occasions.
Fig 11: QuECT syntax for swapping lines
The two X’s must be vertically aligned. Also each column allows either zero or exactly 2 X’s. Attempt to swap lines with different repeat counts generates syntax error.
All measurements are done at the very end. A qubit to be measured is marked with a ‘’ at the end of the line (Fig LABEL:im:ckt9.eps).
Fig 12: QuECT syntax for measurement
Next we come to the QuECT syntax for use outside the quantum chunks. The actual quantum computation is encapsulated inside a class called QMachine. In a real quantum computer this class will be responsible for interfacing the underlying quantum hardware. Alternatively, this class may just run a simulator. Multiple instances of QMachine may exist in parallel. We interact with the quantum machine at the three levels discussed below.
We pass the number of qubits via its constructor.
- Creating quantum gates:
The quantum gates can be created in two ways. Either they are out-of-the-box standard gates (e.g., Hadamard), or they are classical functions in a quantum wrapper. The class MatUnitary deals with the out-of-the-box gates. The WrapUnitary class provides a quantum wrapper for a classical function Such a function is specified by and which are encapsulated inside the class Classical. Lines 6–8 of the example QuECT code show an example with and
All measurements are read back into the classical part via the two methods getObsDist() and getObs(). The first method returns the probability distribution as an array of length where is the number of qubits being measured. The second method returns an actual output. A simulator may use randomization to generate one output from the output distribution. In an actual quantum computer, only the second method will be available. Explicitly computing the probability distribution of the measurement is a luxury that we can afford only in a simulator.
5 Some standard algorithms
In this section we show the implementation of some well known quantum algorithms using QuECT. The aim is not to acquaint the readers with the details of the algorithms, rather to demonstrate different applications of the new paradigm. Interested readers will find a very readable account of the algorithms in .
5.1 Deutsch algorithm
The simplest possible quantum algorithm is the Deutsch algorithm which checks if a given classical “blackbox” function
is 1-1 or not.
%#] QMachine qm = new QMachine(2,1);
Classical c = new Classical(1,1) public f(int x) return 1-x; ; Unitary Uf = new WrapUnitary(c));
if(qm.getObs()==1) System.out.println(”1-1”); else System.out.println(”not 1-1”);
5.2 Deutsch Jozsa algorithm
This is a multidimensional generalization of Deutsch algorithm from the last section. Here we start with a classical “blackbox” function which is known to be either a constant function or a “balanced” function , i.e., exactly half of the binary -tuples are mapped to 0, the other half being mapped to 1.
The aim of the algorithm is to detect which is the case.
%#] int n = 4; QMachine qm = new QMachine(n+1);
Classical c = new Classical(n,1) public f(int x) return x & 1; //A sample balanced function ; Uf = new WrapUnitary(c);
5.3 Simon’s periodicity algorithm
Here we are given a classical “blackbox” function which is known to be periodic, i.e.,
We are told that such a exists, but we do not know what actually is. Simon’s algorithm is a way to find this The algorithm starts with some quantum computation followed by a classical linear equation solver. We present only the quantum part here.
%#] int n = 5, orthog; QMachine qm = new QMachine(2*n);
Classical c = new Classical(n,n) public f(int x) //f is defined here ; Uf = new WrapUnitary(c); for(int i=0;i¡100;i++) orthog[i]=qm.getObs();
Notice how we have put a quantum chunk inside a for-loop.
5.4 Grover’s search algorithm
Grover’s search algorithm is for searching a linear list of size
%#] int n = 6; QMachine qm = new QMachine(n+1);
Classical c = new Classical(1,1) public f(int x) return (x = 7? 1 : 0); //We are searching //for 7 in 0,…,63. ;
Uf = new WrapUnitary(c);
Here we have used multiple quantum chunks. The quantum gate performs an operation called inversion around mean, whose details need not concern us here.
5.5 Shor’s algorithm and QFT
This algorithm factorizes a given integer in polynomial time. Its quantum part is structurally quite similar to the algorithms already discussed, except for a Quantum Fourier Transform (QFT) block. The definition of is recursive. If we denote the -qubit QFT gate by then it is defined recursively in terms of A typical step (for is shown in Fig LABEL:im:qft.eps.
Fig 13: Definition of in terms of
Two points set this circuit aside from the ones already discussed earlier: recursion and the gate which has a parameter (shown in the subscript). We shall not go into the details of the gate. We shall just treat it as a blackbox and show the implementation of the circuit in QuECT.
We notice that the basic building blocks are
Let us construct using these. There are recursive steps. In the -th step we define in terms of This requires applications of the first block, followed by one application of the second block. It is not difficult to see that this is achieved by the following hybrid code.
%#] for(int r=0;r¡n;r++) int p = n-(r+1); for(int k=1;k¡r;k++) int m = r-(k+1); Unitary R = new Rgate(Math.PI/(2 ¡¡ k)); QBEGIN(qm) –/p/——- ———— –/k/——- ——[R]— –/m/——- QEND
int q = r-1; QBEGIN(qm) –/p/——- ——-[H]– –/q/——- QEND
Notice how we are performing both classical as well as quantum computation in the same pass of a for-loop.
In this section we briefly touch upon the issue of compiling a QuECT program. As QuECT is not a programming language, but a paradigm, it does not make strict sense to compile a QuECT program. The details will depend on the classical host language. But certain host-independent suggestions can be given, and this is our aim here.
Typically the compilation of any computer program proceeds in two stages: the front end reduces the program to some abstract intermediate representation, while the back end converts this representation to hardware specific code.
For a QuECT program we suggest that the back end should produce code in the host language with the QMachine class encapsulating all the quantum hardware details. The following describes one approach for the front end.
The information contained inside a single quantum chunk can be represented as follows.
The number of lines. Here a multi-qubit line counts as a single line.
A list of repeat counts, one for each line.
A list of Stages, where each Stage consists of a list of gates (including swap pseudo-gates), each with its list of lines.
A list of lines to be measured.
An example will make this clear.
Suppose that we have
%#] QBEGIN -/n/–—A——-—Uf—— ——–[B]–—Uf——¿ ———A————- QEND
Here we have 3 lines, the repeat counts are and 1. There are two stages. The first stage consists of two gates, (spanning lines 0 and 2) and (spanning line 2). Measurement is done only on line 1.
It is now easy to embed this information to a suitable method in the QMachine class, producing an ordinary Java program. The advantage of producing the output as a high level host program is that we can borrow the symbol table of the host language, and use the identifiers declared in the classical part.
In this paper we have proposed a new paradigm called Quantum Embedded Circuit Technique (QuECT) for programming a quantum computer. Our approach seeks to combine the advantage of classical programming constructs as well as the visual benefits of a quantum circuit diagram. The paradigm can be easily implemented in any high level language, preferably with object-oriented facilities. At present this can be used as a powerful and versatile front end to simulators. The same approach can be easily applied to harness the power of the real quantum computers when they are built.
-  List of qc simulators. Available at http://www.quantiki.org/wiki/List_of_QC_simulators. Part of a publicly editable online encyclopedia on quantum computing.
-  Lanq – a quantum imperative programming language. Available at http://lanq.sourceforge.net/, 2007.
-  S. Bettelli, T. Calarco, and L. Serafini. Toward and architecture for quantum programming. CoRR. Available at http://arxiv.org/abs/cs.PL/0103009, 2001.
-  Andreas de Vries. jquantum—quantum computer simulator. Available at http://jquantum.sourceforge.net, 2010.
-  D. Deutsch and R. Jozsa. Rapid solution of problems by quantum computation. In Proceedings of the Royal Soceity of London, A, pages 439:553–558, 1992.
-  S.J. Gay. Quantum programming languages: Survey and bibliography. Bulletin of the EATCS, 86:176–196, 2005. Available at http://dblp.uni-trier.de.db/journals/eatcs/eatcs86.html#Gay05.
-  L.K. Grover. Quantum mechanics helps in searching a needle in a haystack. Physical Review Letters, 79(2):325–328, 1997.
-  B. Ömer. Quantum programming qcl. Available at http://tph.tuwien.ac.at/oemer/doc/quprog.pdf, 2000.
-  R. Rüdiger. Quantum programming languages. The Computer Journal, 50(2):134–150, 2007. Available at http://comjnl.oxford-journals.org/cgi/content/abstract/50/2/134.
-  P. Selinger. Towards a quantum programming language. Mathematical Structures in Computer Science, 14(4):527–586, 2004. Available at http://www.mathstat.dal.ca/selinger/papers/qpl.pdf.
-  S. Shary and M. Cahay. Bloch sphere simulation. Available at http://www.ece.uc.edu/~mcahay/blochsphere/.
-  P.W. Shor. Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum comouter. SIAM Journal Computing, 26(5):1484–1509, 1997.
-  D.R. Simon. On the power of quantum computation. SIAM Journal Computing, 26(5):1474–1483, 1997.
-  N.S. Yanofsky and M.A. Mannucci. Quantum Computing for Computer Scientists. Cambridge University Press, 2008.