# ops¶

The operations collection consists of various default gates and is a work-in-progress, as users start to work with ProjectQ.

## Module contents¶

projectq.ops.All

alias of Tensor

class projectq.ops.AllocateDirtyQubitGate

Dirty qubit allocation gate class

class projectq.ops.AllocateQubitGate

Qubit allocation gate class

class projectq.ops.BasicGate

Base class of all gates.

__init__()

Initialize a basic gate.

Note

Set interchangeable qubit indices! (gate.interchangeable_qubit_indices)

As an example, consider

ExampleGate | (a,b,c,d,e)


where a and b are interchangeable. Then, call this function as follows

self.set_interchangeable_qubit_indices([[0,1]])


As another example, consider

ExampleGate2 | (a,b,c,d,e)


where a and b are interchangeable and, in addition, c, d, and e are interchangeable among themselves. Then, call this function as

self.set_interchangeable_qubit_indices([[0,1],[2,3,4]])

generate_command(qubits)

Return a Command object which represents the gate acting on qubits.

Parameters: qubits – see BasicGate.make_tuple_of_qureg(qubits) A Command object which represents the gate acting on qubits.
get_inverse()

Return the inverse gate.

Standard implementation of get_inverse:

Raises: NotInvertible – inverse is not implemented
get_merged(other)

Return this gate merged with another gate.

Standard implementation of get_merged:

Raises: NotMergeable – merging is not implemented
static make_tuple_of_qureg(qubits)

Convert quantum input of “gate | quantum input” to internal formatting.

A Command object only accepts tuples of Quregs (list of Qubit objects) as qubits input parameter. However, with this function we allow the user to use a more flexible syntax:

1. Gate | qubit
2. Gate | [qubit0, qubit1]
3. Gate | qureg
4. Gate | (qubit, )
5. Gate | (qureg, qubit)

where qubit is a Qubit object and qureg is a Qureg object. This function takes the right hand side of | and transforms it to the correct input parameter of a Command object which is:

1. -> Gate | ([qubit], )
2. -> Gate | ([qubit0, qubit1], )
3. -> Gate | (qureg, )
4. -> Gate | ([qubit], )
5. -> Gate | (qureg, [qubit])
Parameters: qubits – a Qubit object, a list of Qubit objects, a Qureg object, or a tuple of Qubit or Qureg objects (can be mixed). A tuple containing Qureg (or list of Qubits) objects. Canonical representation (tuple)
class projectq.ops.BasicMathGate(math_fun)

Base class for all math gates.

It allows efficient emulation by providing a mathematical representation which is given by the concrete gate which derives from this base class. The AddConstant gate, for example, registers a function of the form

def add(x):
return (x+a,)


upon initialization. More generally, the function takes integers as parameters and returns a tuple / list of outputs, each entry corresponding to the function input. As an example, consider out-of-place multiplication, which takes two input registers and adds the result into a third, i.e., (a,b,c) -> (a,b,c+a*b). The corresponding function then is

def multiply(a,b,c)
return (a,b,c+a*b)

__init__(math_fun)

Initialize a BasicMathGate by providing the mathematical function that it implements.

Parameters: math_fun (function) – Function which takes as many int values as input, as the gate takes registers. For each of these values, it then returns the output (i.e., it returns a list/tuple of output values).

Example

def add(a,b):
return (a,a+b)
BasicMathGate.__init__(self, add)


If the gate acts on, e.g., fixed point numbers, the number of bits per register is also required in order to describe the action of such a mathematical gate. For this reason, there is

BasicMathGate.get_math_function(qubits)


which can be overwritten by the gate deriving from BasicMathGate.

Example

def get_math_function(self, qubits):
n = len(qubits[0])
scal = 2.**n
def math_fun(a):
return (int(scal * (math.sin(math.pi * a / scal))),)
return math_fun

class projectq.ops.BasicRotationGate(angle)

Defines a base class of a rotation gate.

A rotation gate has a continuous parameter (the angle), labeled ‘angle’ / self._angle. Its inverse is the same gate with the negated argument. Rotation gates of the same class can be merged by adding the angles. The continuous parameter is modulo 4 * pi, self._angle is in the interval [0, 4 * pi).

__init__(angle)

Initialize a basic rotation gate.

Parameters: angle (float) – Angle of rotation (saved modulo 4 * pi)
get_inverse()

Return the inverse of this rotation gate (negate the angle, return new object).

get_merged(other)

Return self merged with another gate.

Default implementation handles rotation gate of the same type, where angles are simply added.

Parameters: other – Rotation gate of same type. NotMergeable – For non-rotation gates or rotation gates of different type. New object representing the merged gates.
tex_str()

Return the Latex string representation of a BasicRotationGate.

Returns the class name and the angle as a subscript, i.e.

[CLASSNAME]$_[ANGLE]$

projectq.ops.C(gate, n=1)

Return n-controlled version of the provided gate.

Parameters: gate – Gate to turn into its controlled version n – Number of controls (default: 1)

Example

C(NOT) | (c, q) # equivalent to CNOT | (c, q)

class projectq.ops.ClassicalInstructionGate

Classical instruction gate.

Base class for all gates which are not quantum gates in the typical sense, e.g., measurement, allocation/deallocation, ...

class projectq.ops.Command(engine, gate, qubits)

Class used as a container to store commands. If a gate is applied to qubits, then the gate and qubits are saved in a command object. Qubits are copied into WeakQubitRefs in order to allow early deallocation (would be kept alive otherwise). WeakQubitRef qubits don’t send deallocate gate when destructed.

gate

The gate to execute

qubits

Tuple of qubit lists (e.g. Quregs). Interchangeable qubits are stored in a unique order

control_qubits

The Qureg of control qubits in a unique order

engine

The engine (usually: MainEngine)

tags

The list of tag objects associated with this command (e.g., ComputeTag, UncomputeTag, LoopTag, ...). tag objects need to support ==, != (__eq__ and __ne__) for comparison as used in e.g. TagRemover. New tags should always be added to the end of the list. This means that if there are e.g. two LoopTags in a command, tag[0] is from the inner scope while tag[1] is from the other scope as the other scope receives the command after the inner scope LoopEngine and hence adds its LoopTag to the end.

all_qubits

A tuple of control_qubits + qubits

__init__(engine, gate, qubits)

Initialize a Command object.

Note

control qubits (Command.control_qubits) are stored as a list of qubits, and command tags (Command.tags) as a list of tag- objects. All functions within this class also work if WeakQubitRefs are supplied instead of normal Qubit objects (see WeakQubitRef).

Parameters: engine – engine which created the qubit (mostly the MainEngine) gate – Gate to be executed qubits – Tuple of quantum registers (to which the gate is applied)
add_control_qubits(qubits)

Add (additional) control qubits to this command object.

They are sorted to ensure a canonical order. Also Qubit objects are converted to WeakQubitRef objects to allow garbage collection and thus early deallocation of qubits.

Parameters: qubits (list of Qubit objects) – List of qubits which control this i.e., the gate is only executed if all qubits are in state 1. (gate,) –
all_qubits

Get all qubits (gate and control qubits).

Returns a tuple T where T[0] is a quantum register (a list of WeakQubitRef objects) containing the control qubits and T[1:] contains the quantum registers to which the gate is applied.

control_qubits

Returns Qureg of control qubits.

engine

Return engine to which the qubits belong / on which the gates are executed.

get_inverse()

Get the command object corresponding to the inverse of this command.

Inverts the gate (if possible) and creates a new command object from the result.

Raises: NotInvertible – If the gate does not provide an inverse (see BasicGate.get_inverse)
get_merged(other)

Merge this command with another one and return the merged command object.

Parameters: other – Other command to merge with this one (self) NotMergeable – if the gates don’t supply a get_merged()-function or can’t be merged for other reasons.
interchangeable_qubit_indices

Return nested list of qubit indices which are interchangeable.

Certain qubits can be interchanged (e.g., the qubit order for a Swap gate). To ensure that only those are sorted when determining the ordering (see _order_qubits), self.interchangeable_qubit_indices is used. .. rubric:: Example

If we can interchange qubits 0,1 and qubits 3,4,5, then this function returns [[0,1],[3,4,5]]

class projectq.ops.ControlledGate(gate, n=1)

Controlled version of a gate.

Note

Use the meta function C() to create a controlled gate

A wrapper class which enables (multi-) controlled gates. It overloads the __or__-operator, using the first qubits provided as control qubits. The n control-qubits need to be the first n qubits. They can be in separate quregs.

Example

ControlledGate(gate, 2) | (qb0, qb2, qb3) # qb0 and qb2 are controls
C(gate, 2) | (qb0, qb2, qb3) # This is much nicer.
C(gate, 2) | ([qb0,qb2], qb3) # Is equivalent


Note

Use C() rather than ControlledGate, i.e.,

C(X, 2) == Toffoli

__init__(gate, n=1)

Initialize a ControlledGate object.

Parameters: gate – Gate to wrap. n (int) – Number of control qubits.
get_inverse()

Return inverse of a controlled gate, which is the controlled inverse gate.

class projectq.ops.DaggeredGate(gate)

Wrapper class allowing to execute the inverse of a gate, even when it does not define one.

If there is a replacement available, then there is also one for the inverse, namely the replacement function run in reverse, while inverting all gates. This class enables using this emulation automatically.

A DaggeredGate is returned automatically when employing the get_inverse- function on a gate which does not provide a get_inverse() member function.

Example

with Dagger(eng):
MySpecialGate | qubits


will create a DaggeredGate if MySpecialGate does not implement get_inverse. If there is a decomposition function available, an auto-replacer engine can automatically replace the inverted gate by a call to the decomposition function inside a “with Dagger”-statement.

__init__(gate)

Initialize a DaggeredGate representing the inverse of the gate ‘gate’.

Parameters: gate – Any gate object of which to represent the inverse.
get_inverse()

Return the inverse gate (the inverse of the inverse of a gate is the gate itself).

class projectq.ops.DeallocateQubitGate

Qubit deallocation gate class

class projectq.ops.EntangleGate

Entangle gate (Hadamard on first qubit, followed by CNOTs applied to all other qubits).

class projectq.ops.FastForwardingGate

Base class for classical instruction gates which require a fast-forward through compiler engines that cache / buffer gates. Examples include Measure and Deallocate, which both should be executed asap, such that Measurement results are available and resources are freed, respectively.

Note

The only requirement is that FlushGate commands run the entire circuit. FastForwardingGate objects can be used but the user cannot expect a measurement result to be available for all back-ends when calling only Measure. E.g., for the IBM Quantum Experience back-end, sending the circuit for each Measure-gate would be too inefficient, which is way a final

is required before the circuit gets sent through the API.

class projectq.ops.FlushGate

Flush gate (denotes the end of the circuit).

Note

All compiler engines (cengines) which cache/buffer gates are obligated to flush and send all gates to the next compiler engine (followed by the flush command).

Note

This gate is sent when calling

eng.flush()


on the MainEngine eng.

class projectq.ops.HGate

Hadamard gate class

class projectq.ops.MeasureGate

Measurement gate class

exception projectq.ops.NotInvertible

Exception thrown when trying to invert a gate which is not invertable (or where the inverse is not implemented (yet)).

exception projectq.ops.NotMergeable

Exception thrown when trying to merge two gates which are not mergeable (or where it is not implemented (yet)).

class projectq.ops.Ph(angle)

Phase gate (global phase)

class projectq.ops.R(angle)

Phase-shift gate (equivalent to Rz up to a global phase)

class projectq.ops.Rx(angle)

RotationX gate class

class projectq.ops.Ry(angle)

RotationX gate class

class projectq.ops.Rz(angle)

RotationZ gate class

class projectq.ops.SGate

S gate class

class projectq.ops.SelfInverseGate

Self-inverse basic gate class.

Automatic implementation of the get_inverse-member function for self-inverse gates.

Example

get_inverse(H) | qubit # get_inverse(H) == H; it is a self-inverse gate

class projectq.ops.SwapGate

Swap gate class (swaps 2 qubits)

class projectq.ops.TGate

T gate class

class projectq.ops.Tensor(gate)

Wrapper class allowing to apply a (single-qubit) gate to every qubit in a quantum register. Allowed syntax is to supply either a qureg or a tuple which contains only one qureg.

Example

Tensor(H) | x # applies H to every qubit in the list of qubits x
Tensor(H) | (x,) # alternative to be consistent with other syntax

__init__(gate)

Initialize a Tensor object for the gate.

get_inverse()

Return the inverse of this tensored gate (which is the tensored inverse of the gate).

class projectq.ops.XGate

Pauli-X gate class

class projectq.ops.YGate

Pauli-Y gate class

class projectq.ops.ZGate

Pauli-Z gate class

projectq.ops.apply_command(cmd)

Apply a command.

Extracts the qubits-owning (target) engine from the Command object and sends the Command to it.

Parameters: cmd (Command) – Command to apply
projectq.ops.get_inverse(gate)

Return the inverse of a gate.

Tries to call gate.get_inverse and, upon failure, creates a DaggeredGate instead.

Parameters: gate – Gate of which to get the inverse

Example

get_inverse(H) # returns a Hadamard gate (HGate object)