ops¶
The operations collection consists of various default gates and is a workinprogress, as users start to work with ProjectQ.
projectq.ops.BasicGate () 
Base class of all gates. 
projectq.ops.MatrixGate ([matrix]) 
Defines a gate class whose instances are defined by a matrix. 
projectq.ops.SelfInverseGate () 
Selfinverse basic gate class. 
projectq.ops.BasicRotationGate (angle) 
Defines a base class of a rotation gate. 
projectq.ops.BasicPhaseGate (angle) 
Defines a base class of a phase gate. 
projectq.ops.ClassicalInstructionGate () 
Classical instruction gate. 
projectq.ops.FastForwardingGate () 
Base class for classical instruction gates which require a fastforward through compiler engines that cache / buffer gates. 
projectq.ops.BasicMathGate (math_fun) 
Base class for all math gates. 
projectq.ops.apply_command (cmd) 
Apply a command. 
projectq.ops.Command (engine, gate, qubits[, …]) 
Class used as a container to store commands. 
projectq.ops.H 
Shortcut (instance of) projectq.ops.HGate 
projectq.ops.X 
Shortcut (instance of) projectq.ops.XGate 
projectq.ops.Y 
Shortcut (instance of) projectq.ops.YGate 
projectq.ops.Z 
Shortcut (instance of) projectq.ops.ZGate 
projectq.ops.S 
Shortcut (instance of) projectq.ops.SGate 
projectq.ops.Sdag 
Wrapper class allowing to execute the inverse of a gate, even when it does not define one. 
projectq.ops.T 
Shortcut (instance of) projectq.ops.TGate 
projectq.ops.Tdag 
Wrapper class allowing to execute the inverse of a gate, even when it does not define one. 
projectq.ops.SqrtX 
Shortcut (instance of) projectq.ops.SqrtXGate 
projectq.ops.Swap 
Shortcut (instance of) projectq.ops.SwapGate 
projectq.ops.SqrtSwap 
Shortcut (instance of) projectq.ops.SqrtSwapGate 
projectq.ops.Entangle 
Shortcut (instance of) projectq.ops.EntangleGate 
projectq.ops.Ph (angle) 
Phase gate (global phase) 
projectq.ops.Rx (angle) 
RotationX gate class 
projectq.ops.Ry (angle) 
RotationX gate class 
projectq.ops.Rz (angle) 
RotationZ gate class 
projectq.ops.R (angle) 
Phaseshift gate (equivalent to Rz up to a global phase) 
projectq.ops.FlushGate () 
Flush gate (denotes the end of the circuit). 
projectq.ops.MeasureGate () 
Measurement gate class (for single qubits). 
projectq.ops.Allocate 
Shortcut (instance of) projectq.ops.AllocateQubitGate 
projectq.ops.Deallocate 
Shortcut (instance of) projectq.ops.DeallocateQubitGate 
projectq.ops.AllocateDirty 
Shortcut (instance of) projectq.ops.AllocateDirtyQubitGate 
projectq.ops.Barrier 
Shortcut (instance of) projectq.ops.BarrierGate 
projectq.ops.DaggeredGate (gate) 
Wrapper class allowing to execute the inverse of a gate, even when it does not define one. 
projectq.ops.ControlledGate (gate[, n]) 
Controlled version of a gate. 
projectq.ops.C (gate[, n]) 
Return ncontrolled version of the provided gate. 
projectq.ops.All 
Shortcut (instance of) projectq.ops.Tensor 
projectq.ops.Tensor (gate) 
Wrapper class allowing to apply a (singlequbit) gate to every qubit in a quantum register. 
projectq.ops.QFT 
Shortcut (instance of) projectq.ops.QFTGate 
projectq.ops.QubitOperator ([term, coefficient]) 
A sum of terms acting on qubits, e.g., 0.5 * ‘X0 X5’ + 0.3 * ‘Z1 Z2’. 
projectq.ops.CRz (angle) 
Shortcut for C(Rz(angle), n=1). 
projectq.ops.CNOT 
Controlled version of a gate. 
projectq.ops.CZ 
Controlled version of a gate. 
projectq.ops.Toffoli 
Controlled version of a gate. 
projectq.ops.TimeEvolution (time, hamiltonian) 
Gate for time evolution under a Hamiltonian (QubitOperator object). 
projectq.ops.UniformlyControlledRy (angles) 
Uniformly controlled Ry gate as introduced in arXiv:quantph/0312218. 
projectq.ops.UniformlyControlledRz (angles) 
Uniformly controlled Rz gate as introduced in arXiv:quantph/0312218. 
projectq.ops.StatePreparation (final_state) 
Gate for transforming qubits in state 0> to any desired quantum state. 
projectq.ops.FlipBits (bits_to_flip) 
Gate for flipping qubits by means of XGates 
Module contents¶

projectq.ops.
All
[source]¶ Shortcut (instance of)
projectq.ops.Tensor
alias of
projectq.ops._metagates.Tensor

class
projectq.ops.
AllocateDirtyQubitGate
[source]¶ Dirty qubit allocation gate class

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented


class
projectq.ops.
AllocateQubitGate
[source]¶ Qubit allocation gate class

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented


class
projectq.ops.
BarrierGate
[source]¶ Barrier gate class

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented


class
projectq.ops.
BasicGate
[source]¶ Base class of all gates. (Don’t use it directly but derive from it)

__init__
()[source]¶ 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]])

__or__
(qubits)[source]¶ Operator overload which enables the syntax Gate  qubits.
Example
 Gate  qubit
 Gate  [qubit0, qubit1]
 Gate  qureg
 Gate  (qubit, )
 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).

generate_command
(qubits)[source]¶ Helper function to generate a command consisting of the gate and the qubits being acted upon.
Parameters: qubits – see BasicGate.make_tuple_of_qureg(qubits) Returns: A Command object containing the gate and the qubits.

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented

get_merged
(other)[source]¶ Return this gate merged with another gate.
Standard implementation of get_merged:
Raises: NotMergeable
– merging is not implemented

static
make_tuple_of_qureg
(qubits)[source]¶ 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:
 Gate  qubit
 Gate  [qubit0, qubit1]
 Gate  qureg
 Gate  (qubit, )
 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:
 > Gate  ([qubit], )
 > Gate  ([qubit0, qubit1], )
 > Gate  (qureg, )
 > Gate  ([qubit], )
 > 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). Returns: A tuple containing Qureg (or list of Qubits) objects. Return type: Canonical representation (tuple<qureg>)


class
projectq.ops.
BasicMathGate
(math_fun)[source]¶ 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 outofplace 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)[source]¶ 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

get_math_function
(qubits)[source]¶ Return the math function which corresponds to the action of this math gate, given the input to the gate (a tuple of quantum registers).
Parameters: qubits (tuple<Qureg>) – Qubits to which the math gate is being applied. Returns: Python function describing the action of this gate. (See BasicMathGate.__init__ for an example). Return type: math_fun (function)


class
projectq.ops.
BasicPhaseGate
(angle)[source]¶ Defines a base class of a phase gate.
A phase gate has a continuous parameter (the angle), labeled ‘angle’ / self.angle. Its inverse is the same gate with the negated argument. Phase gates of the same class can be merged by adding the angles. The continuous parameter is modulo 2 * pi, self.angle is in the interval [0, 2 * pi).

__init__
(angle)[source]¶ Initialize a basic rotation gate.
Parameters: angle (float) – Angle of rotation (saved modulo 2 * pi)

get_inverse
()[source]¶ Return the inverse of this rotation gate (negate the angle, return new object).

get_merged
(other)[source]¶ 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. Raises: NotMergeable
– For nonrotation gates or rotation gates of different type.Returns: New object representing the merged gates.


class
projectq.ops.
BasicRotationGate
(angle)[source]¶ 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)[source]¶ Initialize a basic rotation gate.
Parameters: angle (float) – Angle of rotation (saved modulo 4 * pi)

get_inverse
()[source]¶ Return the inverse of this rotation gate (negate the angle, return new object).

get_merged
(other)[source]¶ 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. Raises: NotMergeable
– For nonrotation gates or rotation gates of different type.Returns: New object representing the merged gates.


projectq.ops.
C
(gate, n=1)[source]¶ Return ncontrolled 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
[source]¶ 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, controls=(), tags=())[source]¶ 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
[source]¶ Tuple of qubit lists (e.g. Quregs). Interchangeable qubits are stored in a unique order
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.

__init__
(engine, gate, qubits, controls=(), tags=())[source]¶ 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 (projectq.cengines.BasicEngine) – engine which created the qubit (mostly the MainEngine)
 gate (projectq.ops.Gate) – Gate to be executed
 qubits (tuple[Qureg]) – Tuple of quantum registers (to which the gate is applied)
 controls (Qureglist[Qubit]) – Qubits that condition the command.
 tags (list[object]) – Tags associated with the command.

add_control_qubits
(qubits)[source]¶ 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 gate, i.e., the gate is only executed if all qubits are in state 1.

all_qubits
[source] 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
[source] Returns Qureg of control qubits.

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

get_inverse
()[source]¶ 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)[source]¶ Merge this command with another one and return the merged command object.
Parameters: other – Other command to merge with this one (self) Raises: NotMergeable
– if the gates don’t supply a get_merged()function or can’t be merged for other reasons.

interchangeable_qubit_indices
[source]¶ 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)[source]¶ Controlled version of a gate.
Note
Use the meta function
C()
to create a controlled gateA wrapper class which enables (multi) controlled gates. It overloads the __or__operator, using the first qubits provided as control qubits. The n controlqubits need to be the first n qubits. They can be in separate quregs.
Example
ControlledGate(gate, 2)  (qb0, qb2, qb3) # qb0 & qb2 are controls C(gate, 2)  (qb0, qb2, qb3) # This is much nicer. C(gate, 2)  ([qb0,qb2], qb3) # Is equivalent

__init__
(gate, n=1)[source]¶ Initialize a ControlledGate object.
Parameters:  gate – Gate to wrap.
 n (int) – Number of control qubits.

__or__
(qubits)[source]¶ Apply the controlled gate to qubits, using the first n qubits as controls.
 Note: The control qubits can be split across the first quregs.
 However, the nth control qubit needs to be the last qubit in a qureg. The following quregs belong to the gate.
Parameters: qubits (tuple of lists of Qubit objects) – qubits to which to apply the gate.


class
projectq.ops.
DaggeredGate
(gate)[source]¶ 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)[source]¶ Initialize a DaggeredGate representing the inverse of the gate ‘gate’.
Parameters: gate – Any gate object of which to represent the inverse.


class
projectq.ops.
DeallocateQubitGate
[source]¶ Qubit deallocation gate class

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented


class
projectq.ops.
EntangleGate
[source]¶ Entangle gate (Hadamard on first qubit, followed by CNOTs applied to all other qubits).

class
projectq.ops.
FastForwardingGate
[source]¶ Base class for classical instruction gates which require a fastforward 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 backends when calling only Measure. E.g., for the IBM Quantum Experience backend, sending the circuit for each Measuregate would be too inefficient, which is why a final
is required before the circuit gets sent through the API.

class
projectq.ops.
FlipBits
(bits_to_flip)[source]¶ Gate for flipping qubits by means of XGates

__init__
(bits_to_flip)[source]¶ Initialize FlipBits gate.
Example
qureg = eng.allocate_qureg(2) FlipBits([0, 1])  qureg
Parameters: bits_to_flip (list[int]list[bool]strint) – int or array of 0/1, True/False, or string of 0/1 identifying the qubits to flip. In case of int, the bits to flip are determined from the binary digits, with the least significant bit corresponding to qureg[0]. If bits_to_flip is negative, exactly all qubits which would not be flipped for the input bits_to_flip1 are flipped, i.e., bits_to_flip=1 flips all qubits.

__or__
(qubits)[source]¶ Operator overload which enables the syntax Gate  qubits.
Example
 Gate  qubit
 Gate  [qubit0, qubit1]
 Gate  qureg
 Gate  (qubit, )
 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).


class
projectq.ops.
FlushGate
[source]¶ 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.
MatrixGate
(matrix=None)[source]¶ Defines a gate class whose instances are defined by a matrix.
Note
Use this gate class only for gates acting on a small numbers of qubits. In general, consider instead using one of the provided ProjectQ gates or define a new class as this allows the compiler to work symbolically.
Example
gate = MatrixGate([[0, 1], [1, 0]]) gate  qubit

__init__
(matrix=None)[source]¶ Initialize MatrixGate
Parameters: matrix (numpy.matrix) – matrix which defines the gate. Default: None

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented


exception
projectq.ops.
NotInvertible
[source]¶ Exception thrown when trying to invert a gate which is not invertable (or where the inverse is not implemented (yet)).

exception
projectq.ops.
NotMergeable
[source]¶ Exception thrown when trying to merge two gates which are not mergeable (or where it is not implemented (yet)).

class
projectq.ops.
QubitOperator
(term=None, coefficient=1.0)[source]¶ A sum of terms acting on qubits, e.g., 0.5 * ‘X0 X5’ + 0.3 * ‘Z1 Z2’.
A term is an operator acting on n qubits and can be represented as:
coefficent * local_operator[0] x … x local_operator[n1]
where x is the tensor product. A local operator is a Pauli operator (‘I’, ‘X’, ‘Y’, or ‘Z’) which acts on one qubit. In math notation a term is, for example, 0.5 * ‘X0 X5’, which means that a Pauli X operator acts on qubit 0 and 5, while the identity operator acts on all other qubits.
A QubitOperator represents a sum of terms acting on qubits and overloads operations for easy manipulation of these objects by the user.
Note for a QubitOperator to be a Hamiltonian which is a hermitian operator, the coefficients of all terms must be real.
hamiltonian = 0.5 * QubitOperator('X0 X5') + 0.3 * QubitOperator('Z0')
Our Simulator takes a hermitian QubitOperator to directly calculate the expectation value (see Simulator.get_expectation_value) of this observable.
A hermitian QubitOperator can also be used as input for the TimeEvolution gate.
If the QubitOperator is unitary, i.e., it contains only one term with a coefficient, whose absolute value is 1, then one can apply it directly to qubits:
eng = projectq.MainEngine() qureg = eng.allocate_qureg(6) QubitOperator('X0 X5', 1.j)  qureg # Applies X to qubit 0 and 5 # with an additional global phase # of 1.j

terms
¶ dict – key: A term represented by a tuple containing all nontrivial local Pauli operators (‘X’, ‘Y’, or ‘Z’). A nontrivial local Pauli operator is specified by a tuple with the first element being an integer indicating the qubit on which a nontrivial local operator acts and the second element being a string, either ‘X’, ‘Y’, or ‘Z’, indicating which nontrivial Pauli operator acts on that qubit. Examples: ((1, ‘X’),) or ((1, ‘X’), (4,’Z’)) or the identity (). The tuples representing the nontrivial local terms are sorted according to the qubit number they act on, starting from 0. value: Coefficient of this term as a (complex) float

__init__
(term=None, coefficient=1.0)[source]¶ Inits a QubitOperator.
The init function only allows to initialize one term. Additional terms have to be added using += (which is fast) or using + of two QubitOperator objects:
Example
ham = ((QubitOperator('X0 Y3', 0.5) + 0.6 * QubitOperator('X0 Y3'))) # Equivalently ham2 = QubitOperator('X0 Y3', 0.5) ham2 += 0.6 * QubitOperator('X0 Y3')
Note
Adding terms to QubitOperator is faster using += (as this is done by inplace addition). Specifying the coefficient in the __init__ is faster than by multiplying a QubitOperator with a scalar as calls an outofplace multiplication.
Parameters:  coefficient (complex float, optional) – The coefficient of the first term of this QubitOperator. Default is 1.0.
 term (optional, empy tuple, a tuple of tuples, or a string) –
 Default is None which means there are no terms in the QubitOperator hence it is the “zero” Operator
 An empty tuple means there are no nontrivial Pauli operators acting on the qubits hence only identities with a coefficient (which by default is 1.0).
 A sorted tuple of tuples. The first element of each tuple is an integer indicating the qubit on which a nontrivial local operator acts, starting from zero. The second element of each tuple is a string, either ‘X’, ‘Y’ or ‘Z’, indicating which local operator acts on that qubit.
 A string of the form ‘X0 Z2 Y5’, indicating an X on qubit 0, Z on qubit 2, and Y on qubit 5. The string should be sorted by the qubit number. ‘’ is the identity.
Raises: QubitOperatorError
– Invalid operators provided to QubitOperator.

__or__
(qubits)[source]¶ Operator overload which enables the following syntax:
QubitOperator(...)  qureg QubitOperator(...)  (qureg,) QubitOperator(...)  qubit QubitOperator(...)  (qubit,)
Unlike other gates, this gate is only allowed to be applied to one quantum register or one qubit and only if the QubitOperator is unitary, i.e., consists of one term with a coefficient whose absolute values is 1.
Example:
eng = projectq.MainEngine() qureg = eng.allocate_qureg(6) QubitOperator('X0 X5', 1.j)  qureg # Applies X to qubit 0 and 5 # with an additional global # phase of 1.j
While in the above example the QubitOperator gate is applied to 6 qubits, it only acts nontrivially on the two qubits qureg[0] and qureg[5]. Therefore, the operator will create a new rescaled QubitOperator, i.e, it sends the equivalent of the following new gate to the MainEngine:
QubitOperator('X0 X1', 1.j)  [qureg[0], qureg[5]]
which is only a two qubit gate.
Parameters: qubits – one Qubit object, one list of Qubit objects, one Qureg object, or a tuple of the former three cases.
Raises: TypeError
– If QubitOperator is not unitary or applied to more than one quantum register.ValueError
– If quantum register does not have enough qubits

compress
(abs_tol=1e12)[source]¶ Eliminates all terms with coefficients close to zero and removes imaginary parts of coefficients that are close to zero.
Parameters: abs_tol (float) – Absolute tolerance, must be at least 0.0

get_inverse
()[source]¶ Return the inverse gate of a QubitOperator if applied as a gate.
Raises: NotInvertible
– Not implemented for QubitOperators which have multiple terms or a coefficient with absolute value not equal to 1.

get_merged
(other)[source]¶ Return this gate merged with another gate.
Standard implementation of get_merged:
Raises: NotMergeable
– merging is not possible

isclose
(other, rel_tol=1e12, abs_tol=1e12)[source]¶ Returns True if other (QubitOperator) is close to self.
Comparison is done for each term individually. Return True if the difference between each term in self and other is less than the relative tolerance w.r.t. either other or self (symmetric test) or if the difference is less than the absolute tolerance.
Parameters:  other (QubitOperator) – QubitOperator to compare against.
 rel_tol (float) – Relative tolerance, must be greater than 0.0
 abs_tol (float) – Absolute tolerance, must be at least 0.0


class
projectq.ops.
SelfInverseGate
[source]¶ Selfinverse basic gate class.
Automatic implementation of the get_inversemember function for self inverse gates.
Example
# get_inverse(H) == H, it is a selfinverse gate: get_inverse(H)  qubit

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented


class
projectq.ops.
SqrtSwapGate
[source]¶ Squareroot Swap gate class

__init__
()[source]¶ 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]])


class
projectq.ops.
StatePreparation
(final_state)[source]¶ Gate for transforming qubits in state 0> to any desired quantum state.

__init__
(final_state)[source]¶ Initialize StatePreparation gate.
Example
qureg = eng.allocate_qureg(2) StatePreparation([0.5, 0.5j, 0.5, 0.5])  qureg
Note
final_state[k] is taken to be the amplitude of the computational basis state whose string is equal to the binary representation of k.
Parameters: final_state (list[complex]) – wavefunction of the desired quantum state. len(final_state) must be 2**len(qureg). Must be normalized!


class
projectq.ops.
SwapGate
[source]¶ Swap gate class (swaps 2 qubits)

__init__
()[source]¶ 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]])


class
projectq.ops.
Tensor
(gate)[source]¶ Wrapper class allowing to apply a (singlequbit) 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

class
projectq.ops.
TimeEvolution
(time, hamiltonian)[source]¶ Gate for time evolution under a Hamiltonian (QubitOperator object).
This gate is the unitary time evolution propagator: exp(i * H * t), where H is the Hamiltonian of the system and t is the time. Note that i factor is stored implicitely.
Example
wavefunction = eng.allocate_qureg(5) hamiltonian = 0.5 * QubitOperator("X0 Z1 Y5") # Apply exp(i * H * t) to the wavefunction: TimeEvolution(time=2.0, hamiltonian=hamiltonian)  wavefunction

time
¶ float, int – time t

hamiltonian
¶ QubitOperator – hamiltonaian H

__init__
(time, hamiltonian)[source]¶ Initialize time evolution gate.
Note
The hamiltonian must be hermitian and therefore only terms with real coefficients are allowed. Coefficients are internally converted to float.
Parameters:  time (float, or int) – time to evolve under (can be negative).
 hamiltonian (QubitOperator) – hamiltonian to evolve under.
Raises: TypeError
– If time is not a numeric type and hamiltonian is not a QubitOperator.NotHermitianOperatorError
– If the input hamiltonian is not hermitian (only real coefficients).

__or__
(qubits)[source]¶ Operator overload which enables the following syntax:
TimeEvolution(...)  qureg TimeEvolution(...)  (qureg,) TimeEvolution(...)  qubit TimeEvolution(...)  (qubit,)
Unlike other gates, this gate is only allowed to be applied to one quantum register or one qubit.
Example:
wavefunction = eng.allocate_qureg(5) hamiltonian = QubitOperator("X1 Y3", 0.5) TimeEvolution(time=2.0, hamiltonian=hamiltonian)  wavefunction
While in the above example the TimeEvolution gate is applied to 5 qubits, the hamiltonian of this TimeEvolution gate acts only nontrivially on the two qubits wavefunction[1] and wavefunction[3]. Therefore, the operator will rescale the indices in the hamiltonian and sends the equivalent of the following new gate to the MainEngine:
h = QubitOperator("X0 Y1", 0.5) TimeEvolution(2.0, h)  [wavefunction[1], wavefunction[3]]
which is only a two qubit gate.
Parameters: qubits – one Qubit object, one list of Qubit objects, one Qureg object, or a tuple of the former three cases.

get_merged
(other)[source]¶ Return self merged with another TimeEvolution gate if possible.
 Two TimeEvolution gates are merged if:
 both have the same terms
 the proportionality factor for each of the terms must have relative error <= 1e9 compared to the proportionality factors of the other terms.
Note
While one could merge gates for which both hamiltonians commute, we are not doing this as in general the resulting gate would have to be decomposed again.
Note
We are not comparing if terms are proportional to each other with an absolute tolerance. It is up to the user to remove terms close to zero because we cannot choose a suitable absolute error which works for everyone. Use, e.g., a decomposition rule for that.
Parameters: other – TimeEvolution gate Raises: NotMergeable
– If the other gate is not a TimeEvolution gate or hamiltonians are not suitable for merging.Returns: New TimeEvolution gate equivalent to the two merged gates.


class
projectq.ops.
UniformlyControlledRy
(angles)[source]¶ Uniformly controlled Ry gate as introduced in arXiv:quantph/0312218.
This is an nqubit gate. There are n1 control qubits and one target qubit. This gate applies Ry(angles(k)) to the target qubit if the n1 control qubits are in the classical state k. As there are 2^(n1) classical states for the control qubits, this gate requires 2^(n1) (potentially different) angle parameters.
Example
controls = eng.allocate_qureg(2) target = eng.allocate_qubit() UniformlyControlledRy(angles=[0.1, 0.2, 0.3, 0.4])  (controls, target)
Note
The first quantum register contains the control qubits. When converting the classical state k of the control qubits to an integer, we define controls[0] to be the least significant (qu)bit. controls can also be an empty list in which case the gate corresponds to an Ry.
Parameters: angles (list[float]) – Rotation angles. Ry(angles[k]) is applied conditioned on the control qubits being in state k. 
__init__
(angles)[source]¶ 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]])

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented

get_merged
(other)[source]¶ Return this gate merged with another gate.
Standard implementation of get_merged:
Raises: NotMergeable
– merging is not implemented


class
projectq.ops.
UniformlyControlledRz
(angles)[source]¶ Uniformly controlled Rz gate as introduced in arXiv:quantph/0312218.
This is an nqubit gate. There are n1 control qubits and one target qubit. This gate applies Rz(angles(k)) to the target qubit if the n1 control qubits are in the classical state k. As there are 2^(n1) classical states for the control qubits, this gate requires 2^(n1) (potentially different) angle parameters.
Example
controls = eng.allocate_qureg(2) target = eng.allocate_qubit() UniformlyControlledRz(angles=[0.1, 0.2, 0.3, 0.4])  (controls, target)
Note
The first quantum register are the contains qubits. When converting the classical state k of the control qubits to an integer, we define controls[0] to be the least significant (qu)bit. controls can also be an empty list in which case the gate corresponds to an Rz.
Parameters: angles (list[float]) – Rotation angles. Rz(angles[k]) is applied conditioned on the control qubits being in state k. 
__init__
(angles)[source]¶ 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]])

get_inverse
()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible
– inverse is not implemented

get_merged
(other)[source]¶ Return this gate merged with another gate.
Standard implementation of get_merged:
Raises: NotMergeable
– merging is not implemented
