ops¶
The operations collection consists of various default gates and is a work-in-progress, as users start to work with ProjectQ.
projectq.ops._basics |
Defines the BasicGate class, the base class of all gates, the BasicRotationGate class, the SelfInverseGate, the FastForwardingGate, the ClassicalInstruction gate, and the BasicMathGate class. |
projectq.ops._command |
This file defines the apply_command function and the Command class. |
projectq.ops._gates |
Contains definitions of standard gates such as * Hadamard (H) * Pauli-X (X / NOT) * Pauli-Y (Y) * Pauli-Z (Z) * S and its inverse (S / Sdagger) * T and its inverse (T / Tdagger) * SqrtX gate (SqrtX) * Swap gate (Swap) * SqrtSwap gate (SqrtSwap) * Entangle (Entangle) * Phase gate (Ph) * Rotation-X (Rx) * Rotation-Y (Ry) * Rotation-Z (Rz) * Rotation-XX on two qubits (Rxx) * Rotation-YY on two qubits (Ryy) * Rotation-ZZ on two qubits (Rzz) * Phase-shift (R) * Measurement (Measure) |
projectq.ops._metagates |
Contains meta gates, i.e., * DaggeredGate (Represents the inverse of an arbitrary gate) * ControlledGate (Represents a controlled version of an arbitrary gate) * Tensor/All (Applies a single qubit gate to all supplied qubits), e.g., Example: .. |
projectq.ops._qaagate |
|
projectq.ops._qftgate |
|
projectq.ops._qpegate |
|
projectq.ops._qubit_operator |
QubitOperator stores a sum of Pauli operators acting on qubits. |
projectq.ops._shortcuts |
Defines a few shortcuts for certain gates such as * CNOT = C(NOT) * CRz = C(Rz) * Toffoli = C(NOT,2) = C(CNOT) |
projectq.ops._state_prep |
|
projectq.ops._time_evolution |
|
projectq.ops._uniformly_controlled_rotation |
|
projectq.ops._unitary_gates |
|
projectq.ops.All |
Shortcut (instance of) projectq.ops.Tensor |
projectq.ops.AllocateDirtyQubitGate() |
Dirty qubit allocation gate class |
projectq.ops.AllocateQubitGate() |
Qubit allocation gate class |
projectq.ops.apply_command(cmd) |
Apply a command. |
projectq.ops.BarrierGate() |
Barrier gate class |
projectq.ops.BasicGate() |
Base class of all gates. |
projectq.ops.BasicMathGate(math_fun) |
Base class for all math gates. |
projectq.ops.BasicPhaseGate(angle) |
Defines a base class of a phase gate. |
projectq.ops.BasicRotationGate(angle) |
Defines a base class of a rotation gate. |
projectq.ops.C(gate[, n]) |
Return n-controlled version of the provided gate. |
projectq.ops.ClassicalInstructionGate() |
Classical instruction gate. |
projectq.ops.Command(engine, gate, qubits[, …]) |
Class used as a container to store commands. |
projectq.ops.ControlledGate(gate[, n]) |
Controlled version of a gate. |
projectq.ops.ControlQubitError |
Exception thrown when wrong number of control qubits are supplied. |
projectq.ops.CRz(angle) |
Shortcut for C(Rz(angle), n=1). |
projectq.ops.DaggeredGate(gate) |
Wrapper class allowing to execute the inverse of a gate, even when it does not define one. |
projectq.ops.DeallocateQubitGate() |
Qubit deallocation gate class |
projectq.ops.dynamic_import(name) |
|
projectq.ops.EntangleGate() |
Entangle gate (Hadamard on first qubit, followed by CNOTs applied to all other qubits). |
projectq.ops.FastForwardingGate() |
Base class for classical instruction gates which require a fast-forward through compiler engines that cache / buffer gates. |
projectq.ops.FlipBits(bits_to_flip) |
Gate for flipping qubits by means of XGates |
projectq.ops.FlushGate() |
Flush gate (denotes the end of the circuit). |
projectq.ops.get_inverse(gate) |
Return the inverse of a gate. |
projectq.ops.HGate() |
Hadamard gate class |
projectq.ops.import_module(name[, package]) |
Import a module. |
projectq.ops.is_identity(gate) |
Return True if the gate is an identity gate. |
projectq.ops.MatrixGate([matrix]) |
Defines a gate class whose instances are defined by a matrix. |
projectq.ops.MeasureGate() |
Measurement gate class (for single qubits). |
projectq.ops.NotHermitianOperatorError |
|
projectq.ops.NotInvertible |
Exception thrown when trying to invert a gate which is not invertable (or where the inverse is not implemented (yet)). |
projectq.ops.NotMergeable |
Exception thrown when trying to merge two gates which are not mergeable (or where it is not implemented (yet)). |
projectq.ops.Ph(angle) |
Phase gate (global phase) |
projectq.ops.pkg_name |
str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str |
projectq.ops.QAA(algorithm, oracle) |
Quantum Aplitude Aplification gate. |
projectq.ops.QFTGate() |
Quantum Fourier Transform gate. |
projectq.ops.QPE(unitary) |
Quantum Phase Estimation gate. |
projectq.ops.QubitOperator([term, coefficient]) |
A sum of terms acting on qubits, e.g., 0.5 * ‘X0 X5’ + 0.3 * ‘Z1 Z2’. |
projectq.ops.QubitOperatorError |
|
projectq.ops.R(angle) |
Phase-shift gate (equivalent to Rz up to a global phase) |
projectq.ops.Rx(angle) |
RotationX gate class |
projectq.ops.Rxx(angle) |
RotationXX gate class |
projectq.ops.Ry(angle) |
RotationY gate class |
projectq.ops.Ryy(angle) |
RotationYY gate class |
projectq.ops.Rz(angle) |
RotationZ gate class |
projectq.ops.Rzz(angle) |
RotationZZ gate class |
projectq.ops.SelfInverseGate() |
Self-inverse basic gate class. |
projectq.ops.SGate() |
S gate class |
projectq.ops.SqrtSwapGate() |
Square-root Swap gate class |
projectq.ops.SqrtXGate() |
Square-root X gate class |
projectq.ops.StatePreparation(final_state) |
Gate for transforming qubits in state |0> to any desired quantum state. |
projectq.ops.SwapGate() |
Swap gate class (swaps 2 qubits) |
projectq.ops.Tensor(gate) |
Wrapper class allowing to apply a (single-qubit) gate to every qubit in a quantum register. |
projectq.ops.TGate() |
T gate class |
projectq.ops.TimeEvolution(time, hamiltonian) |
Gate for time evolution under a Hamiltonian (QubitOperator object). |
projectq.ops.U(alpha, beta, gamma, delta) |
General unitary gate |
projectq.ops.U1(theta) |
Diagonal single-qubit gate. |
projectq.ops.U2(phi, lam) |
One pulse single-qubit gate (cf. |
projectq.ops.U3(theta, phi, lam) |
Two pulse single-qubit gate (cf. |
projectq.ops.UniformlyControlledRy(angles) |
Uniformly controlled Ry gate as introduced in arXiv:quant-ph/0312218. |
projectq.ops.UniformlyControlledRz(angles) |
Uniformly controlled Rz gate as introduced in arXiv:quant-ph/0312218. |
projectq.ops.XGate() |
Pauli-X gate class |
projectq.ops.YGate() |
Pauli-Y gate class |
projectq.ops.ZGate() |
Pauli-Z gate class |
Submodules¶
_basics¶
Defines the BasicGate class, the base class of all gates, the BasicRotationGate class, the SelfInverseGate, the FastForwardingGate, the ClassicalInstruction gate, and the BasicMathGate class.
Gates overload the | operator to allow the following syntax:
Gate | (qureg1, qureg2, qureg2)
Gate | (qureg, qubit)
Gate | qureg
Gate | qubit
Gate | (qubit,)
This means that for more than one quantum argument (right side of | ), a tuple needs to be made explicitely, while for one argument it is optional.
-
class
projectq.ops._basics.BasicGate[source]¶ Base class of all gates. (Don’t use it directly but derive from it)
-
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._basics.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 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)
-
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._basics.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).
-
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 non-rotation gates or rotation gates of different type.Returns: New object representing the merged gates.
-
-
class
projectq.ops._basics.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).
-
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 non-rotation gates or rotation gates of different type.Returns: New object representing the merged gates.
-
-
class
projectq.ops._basics.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._basics.FastForwardingGate[source]¶ 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 why a final
is required before the circuit gets sent through the API.
-
class
projectq.ops._basics.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
-
get_inverse()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible– inverse is not implemented
-
-
exception
projectq.ops._basics.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._basics.NotMergeable[source]¶ Exception thrown when trying to merge two gates which are not mergeable (or where it is not implemented (yet)).
-
class
projectq.ops._basics.SelfInverseGate[source]¶ Self-inverse basic gate class.
Automatic implementation of the get_inverse-member function for self- inverse gates.
Example
# get_inverse(H) == H, it is a self-inverse gate: get_inverse(H) | qubit
-
get_inverse()[source]¶ Return the inverse gate.
Standard implementation of get_inverse:
Raises: NotInvertible– inverse is not implemented
-
_command¶
This file defines the apply_command function and the Command class.
When a gate is applied to qubits, e.g.,
CNOT | (qubit1, qubit2)
a Command object is generated which represents both the gate, qubits and control qubits. This Command object then gets sent down the compilation pipeline.
In detail, the Gate object overloads the operator| (magic method __or__) to generate a Command object which stores the qubits in a canonical order using interchangeable qubit indices defined by the gate to allow the optimizer to cancel the following two gates
Swap | (qubit1, qubit2)
Swap | (qubit2, qubit1)
The command then gets sent to the MainEngine via the apply wrapper (apply_command).
-
class
projectq.ops._command.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.
-
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]]
-
is_identity()[source]¶ Evaluate if the gate called in the command object is an identity gate.
Returns: True if the gate is equivalent to an Identity gate, False otherwise
-
qubits[source]
-
_gates¶
Contains definitions of standard gates such as * Hadamard (H) * Pauli-X (X / NOT) * Pauli-Y (Y) * Pauli-Z (Z) * S and its inverse (S / Sdagger) * T and its inverse (T / Tdagger) * SqrtX gate (SqrtX) * Swap gate (Swap) * SqrtSwap gate (SqrtSwap) * Entangle (Entangle) * Phase gate (Ph) * Rotation-X (Rx) * Rotation-Y (Ry) * Rotation-Z (Rz) * Rotation-XX on two qubits (Rxx) * Rotation-YY on two qubits (Ryy) * Rotation-ZZ on two qubits (Rzz) * Phase-shift (R) * Measurement (Measure)
and meta gates, i.e., * Allocate / Deallocate qubits * Flush gate (end of circuit) * Barrier * FlipBits
-
projectq.ops._gates.Allocate= <projectq.ops._gates.AllocateQubitGate object>[source]¶ Shortcut (instance of)
projectq.ops.AllocateQubitGate
-
projectq.ops._gates.AllocateDirty= <projectq.ops._gates.AllocateDirtyQubitGate object>[source]¶ Shortcut (instance of)
projectq.ops.AllocateDirtyQubitGate
-
projectq.ops._gates.Barrier= <projectq.ops._gates.BarrierGate object>[source]¶ Shortcut (instance of)
projectq.ops.BarrierGate
-
projectq.ops._gates.Deallocate= <projectq.ops._gates.DeallocateQubitGate object>[source]¶ Shortcut (instance of)
projectq.ops.DeallocateQubitGate
-
projectq.ops._gates.Entangle= <projectq.ops._gates.EntangleGate object>[source]¶ Shortcut (instance of)
projectq.ops.EntangleGate
-
class
projectq.ops._gates.EntangleGate[source]¶ Entangle gate (Hadamard on first qubit, followed by CNOTs applied to all other qubits).
-
class
projectq.ops._gates.FlipBits(bits_to_flip)[source]¶ Gate for flipping qubits by means of XGates
-
class
projectq.ops._gates.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.
-
projectq.ops._gates.H= <projectq.ops._gates.HGate object>[source]¶ Shortcut (instance of)
projectq.ops.HGate
-
projectq.ops._gates.Measure= <projectq.ops._gates.MeasureGate object>[source]¶ Shortcut (instance of)
projectq.ops.MeasureGate
-
projectq.ops._gates.NOT= <projectq.ops._gates.XGate object>[source]¶ Shortcut (instance of)
projectq.ops.XGate
-
class
projectq.ops._gates.R(angle)[source]¶ Phase-shift gate (equivalent to Rz up to a global phase)
-
projectq.ops._gates.S= <projectq.ops._gates.SGate object>[source]¶ Shortcut (instance of)
projectq.ops.SGate
-
projectq.ops._gates.Sdag= <projectq.ops._metagates.DaggeredGate object>[source]¶ Inverse (and shortcut) of
projectq.ops.SGate
-
projectq.ops._gates.Sdagger= <projectq.ops._metagates.DaggeredGate object>[source]¶ Inverse (and shortcut) of
projectq.ops.SGate
-
projectq.ops._gates.SqrtSwap= <projectq.ops._gates.SqrtSwapGate object>[source]¶ Shortcut (instance of)
projectq.ops.SqrtSwapGate
-
projectq.ops._gates.SqrtX= <projectq.ops._gates.SqrtXGate object>[source]¶ Shortcut (instance of)
projectq.ops.SqrtXGate
-
projectq.ops._gates.Swap= <projectq.ops._gates.SwapGate object>[source]¶ Shortcut (instance of)
projectq.ops.SwapGate
-
projectq.ops._gates.T= <projectq.ops._gates.TGate object>[source]¶ Shortcut (instance of)
projectq.ops.TGate
-
projectq.ops._gates.Tdag= <projectq.ops._metagates.DaggeredGate object>[source]¶ Inverse (and shortcut) of
projectq.ops.TGate
-
projectq.ops._gates.Tdagger= <projectq.ops._metagates.DaggeredGate object>[source]¶ Inverse (and shortcut) of
projectq.ops.TGate
-
projectq.ops._gates.X= <projectq.ops._gates.XGate object>[source]¶ Shortcut (instance of)
projectq.ops.XGate
-
projectq.ops._gates.Y= <projectq.ops._gates.YGate object>[source]¶ Shortcut (instance of)
projectq.ops.YGate
-
projectq.ops._gates.Z= <projectq.ops._gates.ZGate object>[source]¶ Shortcut (instance of)
projectq.ops.ZGate
_metagates¶
Contains meta gates, i.e., * DaggeredGate (Represents the inverse of an arbitrary gate) * ControlledGate (Represents a controlled version of an arbitrary gate) * Tensor/All (Applies a single qubit gate to all supplied qubits), e.g.,
- Example:
Tensor(H) | (qubit1, qubit2) # apply H to qubit #1 and #2
As well as the meta functions * get_inverse (Tries to access the get_inverse member function of a gate
and upon failure returns a DaggeredGate)
- C (Creates an n-ary controlled version of an arbitrary gate)
-
projectq.ops._metagates.All[source]¶ Shortcut (instance of)
projectq.ops.Tensoralias of
projectq.ops._metagates.Tensor
-
projectq.ops._metagates.C(gate, n=1)[source]¶ 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)
-
exception
projectq.ops._metagates.ControlQubitError[source]¶ Exception thrown when wrong number of control qubits are supplied.
-
class
projectq.ops._metagates.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 control-qubits 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
-
class
projectq.ops._metagates.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.
-
class
projectq.ops._metagates.Tensor(gate)[source]¶ 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
-
projectq.ops._metagates.get_inverse(gate)[source]¶ 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)
-
projectq.ops._metagates.is_identity(gate)[source]¶ Return True if the gate is an identity gate.
Tries to call gate.is_identity and, upon failure, returns False
Parameters: gate – Gate of which to get the inverse Example
get_inverse(Rx(2*math.pi)) # returns True get_inverse(Rx(math.pi)) # returns False
_qaagate¶
-
class
projectq.ops._qaagate.QAA(algorithm, oracle)[source]¶ Quantum Aplitude Aplification gate.
(Quick reference https://en.wikipedia.org/wiki/Amplitude_amplification. Complete reference G. Brassard, P. Hoyer, M. Mosca, A. Tapp (2000) Quantum Amplitude Amplification and Estimation https://arxiv.org/abs/quant-ph/0005055)
Quantum Amplitude Amplification (QAA) executes the algorithm, but not the final measurement required to obtain the marked state(s) with high probability. The starting state on wich the QAA algorithm is executed is the one resulting of aplying the Algorithm on the |0> state.
Example
def func_algorithm(eng,system_qubits): All(H) | system_qubits def func_oracle(eng,system_qubits,qaa_ancilla): # This oracle selects the state |010> as the one marked with Compute(eng): All(X) | system_qubits[0::2] with Control(eng, system_qubits): X | qaa_ancilla Uncompute(eng) system_qubits = eng.allocate_qureg(3) # Prepare the qaa_ancilla qubit in the |-> state qaa_ancilla = eng.allocate_qubit() X | qaa_ancilla H | qaa_ancilla # Creates the initial state form the Algorithm func_algorithm(eng, system_qubits) # Apply Quantum Amplitude Amplification the correct number of times num_it = int(math.pi/4.*math.sqrt(1 << 3)) with Loop(eng, num_it): QAA(func_algorithm, func_oracle) | (system_qubits, qaa_ancilla) All(Measure) | system_qubits
Warning
No qubit allocation/deallocation may take place during the call to the defined Algorithm
func_algorithm-
func_algorithm¶ Algorithm that initialite the state and to be used in the QAA algorithm
-
func_oracle¶ The Oracle that marks the state(s) as “good”
-
system_qubits¶ the system we are interested on
-
qaa_ancilla¶ auxiliary qubit that helps to invert the amplitude of the “good” states
-
_qftgate¶
-
projectq.ops._qftgate.QFT= <projectq.ops._qftgate.QFTGate object>[source]¶ Shortcut (instance of)
projectq.ops.QFTGate
_qpegate¶
_qubit_operator¶
QubitOperator stores a sum of Pauli operators acting on qubits.
-
class
projectq.ops._qubit_operator.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[n-1]
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¶ key: A term represented by a tuple containing all non-trivial local Pauli operators (‘X’, ‘Y’, or ‘Z’). A non-trivial local Pauli operator is specified by a tuple with the first element being an integer indicating the qubit on which a non-trivial local operator acts and the second element being a string, either ‘X’, ‘Y’, or ‘Z’, indicating which non-trivial Pauli operator acts on that qubit. Examples: ((1, ‘X’),) or ((1, ‘X’), (4,’Z’)) or the identity (). The tuples representing the non-trivial local terms are sorted according to the qubit number they act on, starting from 0. value: Coefficient of this term as a (complex) float
Type: dict
-
compress(abs_tol=1e-12)[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=1e-12, abs_tol=1e-12)[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
-
_shortcuts¶
Defines a few shortcuts for certain gates such as * CNOT = C(NOT) * CRz = C(Rz) * Toffoli = C(NOT,2) = C(CNOT)
_state_prep¶
_time_evolution¶
-
class
projectq.ops._time_evolution.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¶ time t
Type: float, int
-
hamiltonian¶ hamiltonaian H
Type: QubitOperator
-
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 <= 1e-9 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.
-
_uniformly_controlled_rotation¶
-
class
projectq.ops._uniformly_controlled_rotation.UniformlyControlledRy(angles)[source]¶ Uniformly controlled Ry gate as introduced in arXiv:quant-ph/0312218.
This is an n-qubit gate. There are n-1 control qubits and one target qubit. This gate applies Ry(angles(k)) to the target qubit if the n-1 control qubits are in the classical state k. As there are 2^(n-1) classical states for the control qubits, this gate requires 2^(n-1) (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.
-
class
projectq.ops._uniformly_controlled_rotation.UniformlyControlledRz(angles)[source]¶ Uniformly controlled Rz gate as introduced in arXiv:quant-ph/0312218.
This is an n-qubit gate. There are n-1 control qubits and one target qubit. This gate applies Rz(angles(k)) to the target qubit if the n-1 control qubits are in the classical state k. As there are 2^(n-1) classical states for the control qubits, this gate requires 2^(n-1) (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.
_unitary_gates¶
-
class
projectq.ops._unitary_gates.U(alpha, beta, gamma, delta)[source]¶ General unitary gate
-
projectq.ops._unitary_gates.U1(theta)[source]¶ Diagonal single-qubit gate.
Parameters: theta (float) – Angle of rotation (saved modulo 4 * pi)
-
class
projectq.ops._unitary_gates.U2(phi, lam)[source]¶ One pulse single-qubit gate (cf. IBM u2 gate)
Module contents¶
-
projectq.ops.All[source]¶ Shortcut (instance of)
projectq.ops.Tensoralias 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 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)[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 non-rotation 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 non-rotation gates or rotation gates of different type.Returns: New object representing the merged gates.
-
-
projectq.ops.C(gate, n=1)[source]¶ 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[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 (Qureg|list[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]]
-
is_identity()[source]¶ Evaluate if the gate called in the command object is an identity gate.
Returns: True if the gate is equivalent to an Identity gate, False otherwise
-
qubits[source]
-
-
exception
projectq.ops.ControlQubitError[source]¶ Exception thrown when wrong number of control qubits are supplied.
-
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 control-qubits 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 n-th 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 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 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]|str|int) – 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_flip-1 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.QAA(algorithm, oracle)[source]¶ Quantum Aplitude Aplification gate.
(Quick reference https://en.wikipedia.org/wiki/Amplitude_amplification. Complete reference G. Brassard, P. Hoyer, M. Mosca, A. Tapp (2000) Quantum Amplitude Amplification and Estimation https://arxiv.org/abs/quant-ph/0005055)
Quantum Amplitude Amplification (QAA) executes the algorithm, but not the final measurement required to obtain the marked state(s) with high probability. The starting state on wich the QAA algorithm is executed is the one resulting of aplying the Algorithm on the |0> state.
Example
def func_algorithm(eng,system_qubits): All(H) | system_qubits def func_oracle(eng,system_qubits,qaa_ancilla): # This oracle selects the state |010> as the one marked with Compute(eng): All(X) | system_qubits[0::2] with Control(eng, system_qubits): X | qaa_ancilla Uncompute(eng) system_qubits = eng.allocate_qureg(3) # Prepare the qaa_ancilla qubit in the |-> state qaa_ancilla = eng.allocate_qubit() X | qaa_ancilla H | qaa_ancilla # Creates the initial state form the Algorithm func_algorithm(eng, system_qubits) # Apply Quantum Amplitude Amplification the correct number of times num_it = int(math.pi/4.*math.sqrt(1 << 3)) with Loop(eng, num_it): QAA(func_algorithm, func_oracle) | (system_qubits, qaa_ancilla) All(Measure) | system_qubits
Warning
No qubit allocation/deallocation may take place during the call to the defined Algorithm
func_algorithm-
func_algorithm¶ Algorithm that initialite the state and to be used in the QAA algorithm
-
func_oracle¶ The Oracle that marks the state(s) as “good”
-
system_qubits¶ the system we are interested on
-
qaa_ancilla¶ auxiliary qubit that helps to invert the amplitude of the “good” states
-
__init__(algorithm, oracle)[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.QPE(unitary)[source]¶ Quantum Phase Estimation gate.
See setups.decompositions for the complete implementation
-
__init__(unitary)[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.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[n-1]
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¶ key: A term represented by a tuple containing all non-trivial local Pauli operators (‘X’, ‘Y’, or ‘Z’). A non-trivial local Pauli operator is specified by a tuple with the first element being an integer indicating the qubit on which a non-trivial local operator acts and the second element being a string, either ‘X’, ‘Y’, or ‘Z’, indicating which non-trivial Pauli operator acts on that qubit. Examples: ((1, ‘X’),) or ((1, ‘X’), (4,’Z’)) or the identity (). The tuples representing the non-trivial local terms are sorted according to the qubit number they act on, starting from 0. value: Coefficient of this term as a (complex) float
Type: dict
-
__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 in-place addition). Specifying the coefficient in the __init__ is faster than by multiplying a QubitOperator with a scalar as calls an out-of-place 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 non-trivial 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 non-trivial 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 non-trivially 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=1e-12)[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=1e-12, abs_tol=1e-12)[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]¶ Self-inverse basic gate class.
Automatic implementation of the get_inverse-member function for self- inverse gates.
Example
# get_inverse(H) == H, it is a self-inverse 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]¶ Square-root 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 (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
-
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¶ time t
Type: float, int
-
hamiltonian¶ hamiltonaian H
Type: QubitOperator
-
__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 non-trivially 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 <= 1e-9 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.U(alpha, beta, gamma, delta)[source]¶ General unitary gate
-
__init__(alpha, beta, gamma, delta)[source]¶ Initialize a general unitary gate
U(α, β, γ, λ) := exp(iα)Rz(β)Ry(γ)Rz(δ)
Parameters: - alpha (float) – First angle of rotation (saved modulo 2 * pi)
- beta (float) – Second angle of rotation (saved modulo 4 * pi)
- gamma (float) – Third angle of rotation (saved modulo 4 * pi)
- delta (float) – Third angle of rotation (saved modulo 4 * pi)
-
-
projectq.ops.U1(theta)[source]¶ Diagonal single-qubit gate.
Parameters: theta (float) – Angle of rotation (saved modulo 4 * pi)
-
class
projectq.ops.U2(phi, lam)[source]¶ One pulse single-qubit gate (cf. IBM u2 gate)
-
class
projectq.ops.U3(theta, phi, lam)[source]¶ Two pulse single-qubit gate (cf. IBM u3 gate)
-
class
projectq.ops.UniformlyControlledRy(angles)[source]¶ Uniformly controlled Ry gate as introduced in arXiv:quant-ph/0312218.
This is an n-qubit gate. There are n-1 control qubits and one target qubit. This gate applies Ry(angles(k)) to the target qubit if the n-1 control qubits are in the classical state k. As there are 2^(n-1) classical states for the control qubits, this gate requires 2^(n-1) (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:quant-ph/0312218.
This is an n-qubit gate. There are n-1 control qubits and one target qubit. This gate applies Rz(angles(k)) to the target qubit if the n-1 control qubits are in the classical state k. As there are 2^(n-1) classical states for the control qubits, this gate requires 2^(n-1) (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
-
-
projectq.ops.apply_command(cmd)[source]¶ 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)[source]¶ 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)