ops
The operations collection consists of various default gates and is a work-in-progress, as users start to work with ProjectQ.
Definitions of some of the most basic quantum gates. |
|
The apply_command function and the Command class. |
|
Definition of the basic set of quantum gates. |
|
Definition of some meta gates. |
|
Definition of the quantum amplitude amplification gate. |
|
Definition of the QFT gate. |
|
Definition of the quantum phase estimation gate. |
|
QubitOperator stores a sum of Pauli operators acting on qubits. |
|
A few shortcuts for certain gates. |
|
Definition of the state preparation gate. |
|
Definition of the time evolution gate. |
|
Definition of uniformly controlled Ry- and Rz-rotation gates. |
|
Shortcut (instance of) |
|
Dirty qubit allocation gate class. |
|
Qubit allocation gate class. |
|
Apply a command. |
|
Barrier gate class. |
|
Base class of all gates. |
|
|
Base class for all math gates. |
|
Base class for all phase gates. |
Base class of for all rotation gates. |
|
|
Return n-controlled version of the provided gate. |
Classical instruction gate. |
|
|
Class used as a container to store commands. |
|
Controlled version of a gate. |
|
Shortcut for C(Rz(angle), n_qubits=1). |
|
Enum type to initialise the control state of qubits. |
Wrapper class allowing to execute the inverse of a gate, even when it does not define one. |
|
Qubit deallocation gate class. |
|
Entangle gate class. |
|
Base class for fast-forward gates. |
|
|
Gate for flipping qubits by means of XGates. |
Flush gate (denotes the end of the circuit). |
|
|
Return the inverse of a gate. |
Hadamard gate class. |
|
Exception thrown when trying to set two incompatible states for a control qubit. |
|
|
Return True if the gate is an identity gate. |
|
A gate class whose instances are defined by a matrix. |
Measurement gate class (for single qubits). |
|
Exception thrown when trying to invert a gate which is not invertable. |
|
Exception thrown when trying to merge two gates which are not mergeable. |
|
|
Phase gate (global phase). |
|
Quantum Aplitude Amplification gate. |
Quantum Fourier Transform gate. |
|
|
Quantum Phase Estimation gate. |
|
A sum of terms acting on qubits, e.g., 0.5 * 'X0 X5' + 0.3 * 'Z1 Z2'. |
|
Phase-shift gate (equivalent to Rz up to a global phase). |
|
RotationX gate class. |
|
RotationXX gate class. |
|
RotationY gate class. |
|
RotationYY gate class. |
|
RotationZ gate class. |
|
RotationZZ gate class. |
Self-inverse basic gate class. |
|
S gate class. |
|
Square-root Swap gate class. |
|
Square-root X gate class. |
|
|
Gate for transforming qubits in state |0> to any desired quantum state. |
Swap gate class (swaps 2 qubits). |
|
|
Wrapper class allowing to apply a (single-qubit) gate to every qubit in a quantum register. |
T gate class. |
|
|
Gate for time evolution under a Hamiltonian (QubitOperator object). |
Uniformly controlled Ry gate as introduced in arXiv:quant-ph/0312218. |
|
Uniformly controlled Rz gate as introduced in arXiv:quant-ph/0312218. |
|
Pauli-X gate class. |
|
Pauli-Y gate class. |
|
Pauli-Z gate class. |
Submodules
_basics
Definitions of some of the most basic quantum gates.
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]
Generate a command.
The command object created consists 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
- is_identity()[source]
Return True if the gate is an identity gate. In this base class, always returns False.
- 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]
Get the math function associated with a BasicMathGate.
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]
Base class for all phase gates.
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]
Base class of for all rotation gates.
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 fast-forward gates.
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]
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
- exception projectq.ops._basics.NotInvertible[source]
Exception thrown when trying to invert a gate which is not invertable.
This exception is also thrown if the inverse is not implemented (yet).
- exception projectq.ops._basics.NotMergeable[source]
Exception thrown when trying to merge two gates which are not mergeable.
This exception is also thrown if the merging is not implemented (yet)).
_command
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=(), control_state=CtrlAll.One)[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
- tags
The list of tag objects associated with this command (e.g., ComputeTag, UncomputeTag, LoopTag, …). tag objects need to support ==, != (__eq__ and __ne__) for comparison as used in e.g. TagRemover. New tags should always be added to the end of the list. This means that if there are e.g. two LoopTags in a command, tag[0] is from the inner scope while tag[1] is from the other scope as the other scope receives the command after the inner scope LoopEngine and hence adds its LoopTag to the end.
- add_control_qubits(qubits, state=CtrlAll.One)[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
state (int,str,CtrlAll) – Control state (ie. positive or negative) for the qubits being added as control qubits.
- property 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.
- property control_state[source]
Return the state of the control qubits (ie. either positively- or negatively-controlled).
- property 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.
- property 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.
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._command.CtrlAll(value)[source]
Enum type to initialise the control state of qubits.
_gates
Definition of the basic set of quantum 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>
Shortcut (instance of)
projectq.ops.AllocateQubitGate
- projectq.ops._gates.AllocateDirty = <projectq.ops._gates.AllocateDirtyQubitGate object>
Shortcut (instance of)
projectq.ops.AllocateDirtyQubitGate
- projectq.ops._gates.Barrier = <projectq.ops._gates.BarrierGate object>
Shortcut (instance of)
projectq.ops.BarrierGate
- projectq.ops._gates.Deallocate = <projectq.ops._gates.DeallocateQubitGate object>
Shortcut (instance of)
projectq.ops.DeallocateQubitGate
- projectq.ops._gates.Entangle = <projectq.ops._gates.EntangleGate object>
Shortcut (instance of)
projectq.ops.EntangleGate
- class projectq.ops._gates.EntangleGate[source]
Entangle gate class.
(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>
Shortcut (instance of)
projectq.ops.HGate
- projectq.ops._gates.Measure = <projectq.ops._gates.MeasureGate object>
Shortcut (instance of)
projectq.ops.MeasureGate
- projectq.ops._gates.NOT = <projectq.ops._gates.XGate object>
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>
Shortcut (instance of)
projectq.ops.SGate
- projectq.ops._gates.Sdag = <projectq.ops._metagates.DaggeredGate object>
Inverse (and shortcut) of
projectq.ops.SGate
- projectq.ops._gates.Sdagger = <projectq.ops._metagates.DaggeredGate object>
Inverse (and shortcut) of
projectq.ops.SGate
- projectq.ops._gates.SqrtSwap = <projectq.ops._gates.SqrtSwapGate object>
Shortcut (instance of)
projectq.ops.SqrtSwapGate
- projectq.ops._gates.SqrtX = <projectq.ops._gates.SqrtXGate object>
Shortcut (instance of)
projectq.ops.SqrtXGate
- projectq.ops._gates.Swap = <projectq.ops._gates.SwapGate object>
Shortcut (instance of)
projectq.ops.SwapGate
- projectq.ops._gates.T = <projectq.ops._gates.TGate object>
Shortcut (instance of)
projectq.ops.TGate
- projectq.ops._gates.Tdag = <projectq.ops._metagates.DaggeredGate object>
Inverse (and shortcut) of
projectq.ops.TGate
- projectq.ops._gates.Tdagger = <projectq.ops._metagates.DaggeredGate object>
Inverse (and shortcut) of
projectq.ops.TGate
- projectq.ops._gates.X = <projectq.ops._gates.XGate object>
Shortcut (instance of)
projectq.ops.XGate
- projectq.ops._gates.Y = <projectq.ops._gates.YGate object>
Shortcut (instance of)
projectq.ops.YGate
- projectq.ops._gates.Z = <projectq.ops._gates.ZGate object>
Shortcut (instance of)
projectq.ops.ZGate
_metagates
Definition of some meta gates.
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.Tensor
- projectq.ops._metagates.C(gate, n_qubits=1)[source]
Return n-controlled version of the provided gate.
- Parameters
gate – Gate to turn into its controlled version
n_qubits – 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
Definition of the quantum amplitude amplification gate.
- class projectq.ops._qaagate.QAA(algorithm, oracle)[source]
Quantum Aplitude Amplification 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
Definition of the QFT gate.
- projectq.ops._qftgate.QFT = <projectq.ops._qftgate.QFTGate object>
Shortcut (instance of)
projectq.ops.QFTGate
_qpegate
Definition of the quantum phase estimation gate.
_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]
Compress the coefficient of a QubitOperator.
Eliminate 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]
Return 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
A few shortcuts for certain gates.
These include: * CNOT = C(NOT) * CRz = C(Rz) * Toffoli = C(NOT,2) = C(CNOT)
_state_prep
Definition of the state preparation gate.
_time_evolution
Definition of the time evolution gate.
- exception projectq.ops._time_evolution.NotHermitianOperatorError[source]
Error raised if an operator is non-hermitian.
- 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
- 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
Definition of uniformly controlled Ry- and Rz-rotation gates.
- 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.
Module contents
ProjectQ module containing all basic gates (operations)
- projectq.ops.All[source]
Shortcut (instance of)
projectq.ops.Tensor
- 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]
Generate a command.
The command object created consists 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
- is_identity()[source]
Return True if the gate is an identity gate. In this base class, always returns False.
- 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) super().__init__(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]
Get the math function associated with a BasicMathGate.
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]
Base class for all phase gates.
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]
Base class of for all rotation gates.
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_qubits=1)[source]
Return n-controlled version of the provided gate.
- Parameters
gate – Gate to turn into its controlled version
n_qubits – 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=(), control_state=CtrlAll.One)[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
- tags
The list of tag objects associated with this command (e.g., ComputeTag, UncomputeTag, LoopTag, …). tag objects need to support ==, != (__eq__ and __ne__) for comparison as used in e.g. TagRemover. New tags should always be added to the end of the list. This means that if there are e.g. two LoopTags in a command, tag[0] is from the inner scope while tag[1] is from the other scope as the other scope receives the command after the inner scope LoopEngine and hence adds its LoopTag to the end.
- __init__(engine, gate, qubits, controls=(), tags=(), control_state=CtrlAll.One)[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.
control_state (int,str,projectq.meta.CtrlAll) –
- add_control_qubits(qubits, state=CtrlAll.One)[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
state (int,str,CtrlAll) – Control state (ie. positive or negative) for the qubits being added as control qubits.
- property 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.
- property control_state[source]
Return the state of the control qubits (ie. either positively- or negatively-controlled).
- property 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.
- property 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.
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 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.EntangleGate[source]
Entangle gate class.
(Hadamard on first qubit, followed by CNOTs applied to all other qubits).
- class projectq.ops.FastForwardingGate[source]
Base class for fast-forward gates.
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 a 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.
- 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.
- exception projectq.ops.IncompatibleControlState[source]
Exception thrown when trying to set two incompatible states for a control qubit.
- class projectq.ops.MatrixGate(matrix=None)[source]
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
- class projectq.ops.MeasureGate[source]
Measurement gate class (for single qubits).
- __or__(qubits)[source]
Operator| overload which enables the syntax Gate | qubits.
Previously (ProjectQ <= v0.3.6) MeasureGate/Measure was allowed to be applied to any number of quantum registers. Now the MeasureGate/Measure is strictly a single qubit gate.
- Raises
RuntimeError – Since ProjectQ v0.6.0 if the gate is applied to multiple qubits.
- exception projectq.ops.NotInvertible[source]
Exception thrown when trying to invert a gate which is not invertable.
This exception is also thrown if the inverse is not implemented (yet).
- exception projectq.ops.NotMergeable[source]
Exception thrown when trying to merge two gates which are not mergeable.
This exception is also thrown if the merging is not implemented (yet)).
- class projectq.ops.QAA(algorithm, oracle)[source]
Quantum Aplitude Amplification 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
- class projectq.ops.QPE(unitary)[source]
Quantum Phase Estimation gate.
See setups.decompositions for the complete implementation
- 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]
Initialize a QubitOperator object.
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 syntax Gate | qubits.
In particular, enable 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]
Compress the coefficient of a QubitOperator.
Eliminate 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]
Return 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
- class projectq.ops.StatePreparation(final_state)[source]
Gate for transforming qubits in state |0> to any desired quantum state.
- __init__(final_state)[source]
Initialize a 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.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
- __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 syntax Gate | qubits.
In particular, enable 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: .. code-block:: python
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.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.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.
- 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