Special Operations

MIMIQ offers further possibilities to create circuits, such as new gate declarations, or wrappers for common combinations of gates.

Gate Declaration & Gate Calls

Using MIMIQ you can define your own gates with a given name, arguments and instructions. For examples if you wish to apply an H gate followed by an RX gate with a specific argument for the rotation you can use GateDecl as follows:

>>> from symengine import *
>>> rot = symbols('x')
>>> @gatedecl("ansatz")
... def ansatz(rot):
...     c= Circuit()
...     c.push(GateX(),0)
...     c.push(GateP(rot),1)
...     return c

>>> ansatz(rot)
ansatz(x)

Here, ansatz is simply the name that will be shown when printing or drawing the circuit, (rot) defines the gate parameters.

As you can see in the code above, to generate your own gate declaration you will need to instantiate Circuit. A circuit is created by sequentially applying operations using push(), where each operation is followed by its targets. The target order follows the standard convention quantum register -> classical register -> Z-register order. passed as an argument.

>>> ansatz(rot)
ansatz(x)

You can check the instructions inside ansatz by using decompose method:

>>> ansatz(pi/2).decompose()
2-qubit circuit with 2 instructions:
├── X @ q[0]
└── P((1/2)*pi) @ q[1]

After declaration you can add it to your circuit using push().

>>> c = Circuit()
>>> c.push(ansatz(pi/2), 0 , 1)
2-qubit circuit with 1 instruction:
└── ansatz((1/2)*pi) @ q[0:1]

Note

A gate declared with GateDecl must be unitary.

Note

The gatedecl() decorator transforms a function into one that produces GateCall objects based on the logic defined in a GateDecl. When you call ansatz(pi), it creates an instance of GateCall, representing a specific instantiation of the unitary gates with the provided parameters.

Creating a gate declaration allows you to add easily the same sequence of gates in a very versatile way and manipulate your new gate like you would with any other gate. This means that you can combine it with other gates via Control, add noise to the whole block in one call, use it as an operator for ExpectationValue, use it within an IfStatement etc. See non-unitary operations, and noise pages.

For example, here is how to add noise to the previous gate declaration:

>>> c = Circuit()
>>> my_gate = ansatz(pi)
>>> c.push(my_gate, 0, 1)
2-qubit circuit with 1 instruction:
└── ansatz(pi) @ q[0:1]

>>> c.add_noise(my_gate, Depolarizing2(0.1))
2-qubit circuit with 2 instructions:
├── ansatz(pi) @ q[0:1]
└── Depolarizing(0.1) @ q[0:1]


>>> c.draw()
                                ┌────────────┐  ┌───────────────────┐
                         q[0]: ╶┤0           ├──┤0                  ├──────────────────────────────────╴
                                │  ansatz(pi)│  │  Depolarizing(0.1)│
                         q[1]: ╶┤1           ├──┤1                  ├──────────────────────────────────╴
                                └────────────┘  └───────────────────┘

Gate declarations can be combined with other quantum operations like Control, noise, or even conditional logic. Use it within an IfStatement:

>>> IfStatement(my_gate, BitString("111"))
IF (c==111) ansatz(pi)

Note that this type of combined operation does not work if we pass a circuit as an argument, instead of a declared gate (more precisely, a GateCall, see note above).

Blocks of Instructions

Blocks in MIMIQ allow you to encapsulate a collection of quantum operations as a reusable unit. They’re particularly useful when you want to group instructions together that implement a specific algorithm or subroutine.

Unlike gate declarations that create new gates, blocks simply group existing instructions without restriction on their nature or type.

A Block` can be created in several ways:

# From an existing circuit
>>> circ = Circuit()
>>> circ.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]


>>> circ.push(GateCX(), 0, 1)
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]


>>> block = Block(circ)
>>> block
2-qubit block ... with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]

# From a list of instructions
>>> inst = [Instruction(GateX(), (0,)), Instruction(GateY(), (1,))]
>>> block2 = Block(inst)
>>> block2
2-qubit block ... with 2 instructions:
├── X @ q[0]
└── Y @ q[1]

# Empty block with specified dimensions
>>> block3 = Block(2, 1, 0)  # 2 qubits, 1 classical bit, 0 z-variables
>>> block3
empty block

Example: Error Correction Code Block

>>> def error_detection_block():
...     c = Circuit()
...     c.push(GateCX(), 0, 1)
...     c.push(GateCX(), 0, 2)
...     c.push(MeasureZ(), 1, 0)  # Measure q[1] → c[0]
...     c.push(MeasureZ(), 2, 1)  # Measure q[2] → c[1]
...     c.push(IfStatement(GateX(), BitString("01")), 0, 0, 1)  # Error correction
...     c.push(IfStatement(GateX(), BitString("10")), 0, 0, 1)  # Error correction
...     return Block(c)

>>> error_detection = error_detection_block()
>>> error_detection
3-qubit, 2-bit block 777ce7f5de00 with 6 instructions:
├── CX @ q[0], q[1]
├── CX @ q[0], q[2]
├── M @ q[1], c[0]
├── M @ q[2], c[1]
├── IF(c==01) X @ q[0], condition[0:1]
└── IF(c==10) X @ q[0], condition[0:1]

>>> main_circuit = Circuit()
>>> main_circuit.push(error_detection, 0, 1, 2, 0, 1)
3-qubit, 2-bit circuit with 1 instruction:
└── block 777ce7f5de00 @ q[0,1,2], c[0,1]


>>> main_circuit.push(GateH(), 1)
3-qubit, 2-bit circuit with 2 instructions:
├── block ... @ q[0,1,2], c[0,1]
└── H @ q[1]



>>> main_circuit.push(error_detection, 0, 1, 2, 0, 1)
3-qubit, 2-bit circuit with 3 instructions:
├── block ... @ q[0,1,2], c[0,1]
├── H @ q[1]
└── block ... @ q[0,1,2], c[0,1]

Working with Blocks

>>> b = Block(2, 1, 0)
>>> b
empty block
>>> b.push(GateH(), 0)
2-qubit, 1-bit block 777ce7f596d0 with 1 instructions:
└── H @ q[0]
>>> b.push(GateX(), 1)
2-qubit, 1-bit block 777ce7f596d0 with 2 instructions:
├── H @ q[0]
└── X @ q[1]
>>> b.push(GateCX(), 0, 1)
2-qubit, 1-bit block 777ce7f596d0 with 3 instructions:
├── H @ q[0]
├── X @ q[1]
└── CX @ q[0], q[1]

Blocks can be iterated over, indexed, and have a length just like circuits:

>>> len(b)
3

>>> b[0]
H @ q[0]

Trying to add operations that use more resources than the block dimensions will result in an error:

>>> try:
...     b.push(GateZ(), 3)
... except Exception as e:
...     print(type(e).__name__)
ValueError

When to Use Blocks vs Gate Declarations

Use Block when you want to:

  • Group a sequence of operations for organization

  • Reuse a routine with control/measurement logic

  • Include operations that are not unitary

Use GateDecl when you want to:

  • Define a new named unitary gate

  • Create parameterized gates

  • Use symbolic arguments and controlled gate behavior

Use BlockDecl when you want a named, parametric routine that is not unitary, for example one that measures or resets. Calling it gives a BlockCall, which you push like a block. All calls share the same declaration.

Repeated Operations

The Repeat operation allows you to apply the same quantum instruction multiple times. operation allows you to apply the same quantum operation multiple times. This can be particularly useful for algorithms that require iterative application of the same operation, such as quantum walks or amplitude amplification.

Creating Repeated Operations

There are two main ways to create repeated operations:

# Method 1: Using the Repeat constructor directly
Repeat(n, operation)  # Repeats the given operation `n` times

# Method 2: Using the `repeat` helper function (recommended)
repeat(n, operation)  # Repeats the operation with optional simplification logic

# Alternative: Using the `.repeat()` method on an operation instance
operation.repeat(n)   # Shorthand for repeating an operation `n` times
>>> Repeat(3, GateX())
∏³ X

>>> GateRX(Symbol("theta")).repeat(5)
∏⁵ RX(theta)

>>> repeat(5, GateRX(Symbol("theta"))).evaluate({"theta": 1})
∏⁵ RX(1)

>>> c = Circuit()
>>> c.push(repeat(3, GateH()), 0)
1-qubit circuit with 1 instruction:
└── ∏³ H @ q[0]


>>> c.push(repeat(5, GateRX(Symbol("θ"))), 1)
2-qubit circuit with 2 instructions:
├── ∏³ H @ q[0]
└── ∏⁵ RX(θ) @ q[1]


>>> c.decompose()
2-qubit circuit with 8 instructions:
├── U((1/2)*pi, 0, pi, 0.0) @ q[0]
├── U((1/2)*pi, 0, pi, 0.0) @ q[0]
├── U((1/2)*pi, 0, pi, 0.0) @ q[0]
├── U(θ, (-1/2)*pi, (1/2)*pi, 0.0) @ q[1]
├── U(θ, (-1/2)*pi, (1/2)*pi, 0.0) @ q[1]
├── U(θ, (-1/2)*pi, (1/2)*pi, 0.0) @ q[1]
├── U(θ, (-1/2)*pi, (1/2)*pi, 0.0) @ q[1]
└── U(θ, (-1/2)*pi, (1/2)*pi, 0.0) @ q[1]

Composite Gates

MIMIQ provides several composite gates to facilitate circuit building. These gates simplify constructing complex operations.

Pauli String

A PauliString is an N-qubit tensor product of Pauli operators of the form:

\[P_1 \otimes P_2 \otimes P_3 \otimes \ldots \otimes P_N,\]

where each \(P_i \in \{ I, X, Y, Z \}\) is a single-qubit Pauli operator, including the identity.

To create an operator using PauliString we simply pass as argument the Pauli string written as a String:

>>> c = Circuit()
>>> c.push(PauliString("IXYZ"), 1, 2, 3, 4)
5-qubit circuit with 1 instruction:
└── IXYZ @ q[1:4]

You can specify any number of Pauli operators.

Quantum Fourier Transform

The QFT gate implements the The Quantum Fourier Transform which is a circuit used to realize a linear transformation on qubits and is a building block of many larger circuits such as Shor’s Algorithm or the Quantum Phase Estimation.

The QFT maps an arbitrary quantum state \(\ket{x} = \sum_{j=0}^{N-1} x_{j} \ket{j}\) to a quantum state \(\sum_{k=0}^{N-1} y_{k} \ket{k}\) according to the formula:

\[y_{k} = \frac{1}{\sqrt{N}} \sum_{j=0}^{N-1} x_{j}w_{N}^{-jk}\]

where \(w_N = e^{2\pi i / N}\).

In MIMIQ, the QFT gate allows you to quickly implement a QFT in your circuit on an arbitrary N number of qubits. You can instantiate the QFT gate by providing the number of qubits you want to use, QFT(N), and add it like any other gate in the circuit.

>>> c = Circuit()
>>> c.push(QFT(5), 1, 2, 3, 4, 5)
6-qubit circuit with 1 instruction:
└── QFT @ q[1:5]

This adds a 5-qubit QFT to the circuit.

Phase Gradient

The PhaseGradient applies a phase shift to a quantum register of N qubits, where each computational basis state \(\ket{k}\) experiences a phase proportional to its integer value k:

\[\operatorname{PhaseGradient} = \sum_{k=0}^{N-1} \mathrm{e}^{i \frac{2 \pi}{N} k} \ket{k}\bra{k}\]

To use it, you can simply provide the number of qubit targets and add it to the circuit as shown in the following examples:

>>> c = Circuit()
>>> c.push(PhaseGradient(5), 1, 2, 3, 4, 5)
6-qubit circuit with 1 instruction:
└── PhaseGradient @ q[1:5]

This will add a 5 qubits PhaseGradient to the first 5 qubits of the quantum register.

Polynomial Oracle

Warning

The PolynomialOracle works only with the state vector simulator and not with MPS, because of ancillas qubit use.

The PolynomialOracle is a quantum oracle for a polynomial function of two registers. It applies a \(\pi\) phase shift to any basis state that satisfies \(a \cdot xy + b \cdot x + c \cdot y + d = 0\), where \(\ket{x}\) and \(\ket{y}\) are the states of the two registers.

Here is how to use the PolynomialOracle:

>>> c = Circuit()
>>> c.push(PolynomialOracle(5, 5, 1, 2, 3, 4), *range(10))
10-qubit circuit with 1 instruction:
└── PolynomialOracle(1, 2, 3, 4) @ q[0:4], q[5:9]

RNZ Gate

The GateRNZ applies a rotation along the Z-axis conditioned on the parity of the qubits.

>>> c = Circuit()
>>> c.push(GateRNZ(5, 0.5), 1, 2, 3, 4, 5)
6-qubit circuit with 1 instruction:
└── RNZ(0.5) @ q[1:5]

Diffusion

The Diffusion operator corresponds to Grover’s diffusion operator. It implements the unitary transformation:

\[H^{\otimes n} (1 - 2\ket{0^n} \bra{0^n}) H^{\otimes n}\]

Here is how to use Diffusion:

>>> c = Circuit()
>>> c.push(Diffusion(10), *range(10))
10-qubit circuit with 1 instruction:
└── Diffusion @ q[0:9]

You need to specify both the number of targets and their corresponding indices.

More about composite gates

All composite gates can be decomposed using decompose() to extract their implementation, except for PolynomialOracle.

>>> QFT(5).decompose()
5-qubit circuit with 15 instructions:
├── H @ q[4]
├── CP((1/2)*pi) @ q[3], q[4]
├── H @ q[3]
├── CP((1/4)*pi) @ q[2], q[4]
├── CP((1/2)*pi) @ q[2], q[3]
├── H @ q[2]
├── CP((1/8)*pi) @ q[1], q[4]
├── CP((1/4)*pi) @ q[1], q[3]
├── CP((1/2)*pi) @ q[1], q[2]
├── H @ q[1]
├── CP((1/16)*pi) @ q[0], q[4]
├── CP((1/8)*pi) @ q[0], q[3]
├── CP((1/4)*pi) @ q[0], q[2]
├── CP((1/2)*pi) @ q[0], q[1]
└── H @ q[0]

Barrier

The Barrier is a non-op operation that does not affect the quantum state but prevents compression or optimization across execution. As of now, Barrier is only useful when combined with the MPS backend.

To add barriers to the circuit, you can use the Barrier operation:

Example usage:

# Add a Gate
>>> c.push(GateX(), 0)
1-qubit circuit with 1 instruction:
└── X @ q[0]


# Apply the Barrier on qubit 0.
>>> c.push(Barrier(1), 0)
1-qubit circuit with 2 instructions:
├── X @ q[0]
└── Barrier @ q[0]


# Add a Gate between barriers
>>> c.push(GateX(), 0)
1-qubit circuit with 3 instructions:
├── X @ q[0]
├── Barrier @ q[0]
└── X @ q[0]


# Apply individual barriers on multiple qubits
>>> c.push(Barrier(1), range(3))
3-qubit circuit with 6 instructions:
├── X @ q[0]
├── Barrier @ q[0]
├── X @ q[0]
├── Barrier @ q[0]
├── Barrier @ q[1]
└── Barrier @ q[2]


# Add gates on multiple qubits
>>> c.push(GateX(), range(3))
3-qubit circuit with 9 instructions:
├── X @ q[0]
├── Barrier @ q[0]
├── X @ q[0]
├── Barrier @ q[0]
├── Barrier @ q[1]
├── Barrier @ q[2]
├── X @ q[0]
├── X @ q[1]
└── X @ q[2]


# Apply one general Barrier on multiple qubits (effectively the same as above)
>>> c.push(Barrier(3), *range(3))
3-qubit circuit with 10 instructions:
├── X @ q[0]
├── Barrier @ q[0]
├── X @ q[0]
├── Barrier @ q[0]
├── Barrier @ q[1]
├── Barrier @ q[2]
├── X @ q[0]
├── X @ q[1]
├── X @ q[2]
└── Barrier @ q[0:2]


>>> c.draw()
                                ┌─┐ ┌─┐ ┌─┐
                         q[0]: ╶┤X├░┤X├░┤X├░───────────────────────────────────────────────────────────╴
                                └─┘░└─┘░├─┤░
                         q[1]: ╶───────░┤X├░───────────────────────────────────────────────────────────╴
                                       ░├─┤░
                         q[2]: ╶───────░┤X├░───────────────────────────────────────────────────────────╴
                                       ░└─┘░

Reference

class GateDecl(name, arguments, circuit, num_ancillas=0)[source]

Bases: object

Declaration of a named, parametric gate defined by a circuit.

A GateDecl stores a name, a tuple of symbolic arguments and a body circuit of gates written with those symbols. Calling the declaration with values, decl(v1, v2, ...), returns a GateCall that can be pushed to circuits like any other gate. The body is copied, so later changes to the original circuit do not affect the declaration.

The gatedecl() decorator is the usual way to build one.

Parameters:
  • name (str) – Name of the gate, used when printing calls.

  • arguments (tuple of symengine.Symbol) – The symbolic parameters.

  • circuit (Circuit) – The body. Its qubits 0..n-1 become the qubits of the declared gate.

Raises:
  • TypeError – If an argument is not a symengine.Symbol.

  • ValueError – If the circuit is empty or contains an operation that is not a Gate.

GateDecl(name, arguments, circuit, num_ancillas=0) declares a gate whose body is circuit. num_ancillas says how many of its last qubits are clean ancillas: each call must find them in |0>, and gets them back in |0>. On other inputs the call is still a unitary on all its qubits, but not the gate it was built for. decompose() sets it when it wraps a decomposition that uses clean ancillas.

Examples

>>> from symengine import symbols
>>> from mimiqcircuits import *
>>> x, y = symbols('x y')
>>> # write the body with symbolic parameters
>>> c = Circuit()
>>> c.push(GateXXplusYY(x, y), 0, 1)
2-qubit circuit with 1 instruction:
└── XXplusYY(x, y) @ q[0:1]

>>> c.push(GateRX(x), 1)
2-qubit circuit with 2 instructions:
├── XXplusYY(x, y) @ q[0:1]
└── RX(x) @ q[1]

>>> # declare the gate from the body
>>> decl = GateDecl("ansatz", (x, y), c)
>>> decl
gate ansatz(x, y) =
├── XXplusYY(x, y) @ q[0:1]
└── RX(x) @ q[1]

>>> # calling the declaration gives a gate with concrete parameters
>>> g = decl(2, 4)
>>> g
ansatz(2, 4)
>>> g.decompose()
2-qubit circuit with 2 instructions:
├── XXplusYY(2, 4) @ q[0:1]
└── RX(2) @ q[1]

>>> # push the call on any two qubits
>>> Circuit().push(g, 10, 22)
23-qubit circuit with 1 instruction:
└── ansatz(2, 4) @ q[10,22]
property num_ancillas

Number of clean ancillas, the last targets of each call.

property num_qubits

Number of qubits of the body circuit. Read-only.

property num_bits

Number of classical bits of the body circuit, always 0. Read-only.

property num_zvars

Number of z-variables of the body circuit, always 0. Read-only.

gatedecl(name)[source]

Decorator that turns a function returning a circuit into a GateDecl.

The names of the function’s arguments become the symbolic parameters of the declaration. The function is called once, with those symbols, to build the body. The decorated name is bound to the GateDecl, not to the function; calling it with values gives a GateCall.

Parameters:

name – Name of the declared gate.

Returns:

A decorator that returns the GateDecl.

Raises:

ValueError – If the decorated function does not return a Circuit.

Examples

>>> from mimiqcircuits import *
>>> # the argument name ``theta`` becomes the symbol of the declaration
>>> @gatedecl("ansatz")
... def ansatz(theta):
...     return Circuit().push(GateX(), 0).push(GateRX(theta), 1)
>>> ansatz
gate ansatz(theta) =
├── X @ q[0]
└── RX(theta) @ q[1]

>>> # call it with a value to get a gate
>>> ansatz(0.5)
ansatz(0.5)
>>> ansatz(0.5).decompose()
2-qubit circuit with 2 instructions:
├── X @ q[0]
└── RX(0.5) @ q[1]

>>> # the call is pushed like any gate
>>> Circuit().push(ansatz(0.5), 3, 4)
5-qubit circuit with 1 instruction:
└── ansatz(0.5) @ q[3:4]
class Block(*args, num_ancillas=0)[source]

Bases: Operation

Reusable group of instructions, applied as a single operation.

A block holds a list of instructions on its own local qubits, bits and z-variables, numbered from 0. Pushing a block to a circuit maps those local indices to the targets given to push, in the order qubits, bits, z-variables. Decomposing the circuit replaces the block with its instructions.

The constructor accepts:

  • Block(): an empty block with no qubits, bits or z-variables.

  • Block(circuit): a copy of the instructions of a circuit or block. The sizes are inferred from the highest index used.

  • Block(instructions): a block from a list of Instruction objects, with sizes inferred the same way.

  • Block(num_qubits, num_bits, num_zvars): an empty block of the given sizes, to be filled with push().

  • Block(num_qubits, num_bits, num_zvars, instructions): a block of the given sizes holding instructions.

Every form takes a num_ancillas keyword (default 0): the number of its last qubits that are clean ancillas, found and returned in |0>.

The instructions are deep-copied, so later changes to the source circuit do not affect the block. The sizes are fixed once the block is created.

Raises:
  • TypeError – If an argument has the wrong type, for example a list holding something other than instructions.

  • ValueError – If the number of arguments is not 0, 1, 3 or 4.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateCX(), 1, 2)
3-qubit circuit with 1 instruction:
└── CX @ q[1], q[2]
>>> c.push(GateCX(), 1, 3)
4-qubit circuit with 2 instructions:
├── CX @ q[1], q[2]
└── CX @ q[1], q[3]
>>> c.push(MeasureZZ(), 1, 2, 1)
4-qubit, 2-bit circuit with 3 instructions:
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
└── MZZ @ q[1:2], c[1]

Each block prints with a unique identifier, shown as ... here.

>>> block = Block(c)
>>> block  
4-qubit, 2-bit block ... with 3 instructions:
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
└── MZZ @ q[1:2], c[1]
>>> main = Circuit()
>>> main.push(block, 0, 1, 2, 3, 0, 1)  
4-qubit, 2-bit circuit with 1 instruction:
└── block ... @ q[0,1,2,3], c[0,1]

Decomposing expands the block, and decomposes MeasureZZ further:

>>> main.decompose()
4-qubit, 2-bit circuit with 5 instructions:
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
├── CX @ q[1], q[2]
├── M @ q[2], c[1]
└── CX @ q[1], q[2]

A block can also be built empty with fixed sizes and filled with push:

>>> bell = Block(2, 0, 0)
>>> _ = bell.push(GateH(), 0)
>>> bell.push(GateCX(), 0, 1)  
2-qubit block ... with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]

See also

Instruction, Circuit

property num_ancillas

Number of clean ancillas, the last qubit targets of the block.

push(operation, *args)[source]

Add an operation to the end of the block.

Works like Circuit.push(), but every target must fit inside the block’s fixed sizes.

Parameters:
  • operation – The operation, or an Instruction.

  • *args – The targets: qubits, then bits, then z-variables.

Returns:

The block itself, so calls can be chained.

Return type:

Block

Raises:

ValueError – If a target index is not smaller than the block’s number of qubits, bits or z-variables.

is_symbolic()[source]

Whether any parameter contains a free symbol.

For wrappers such as Control or Power, the wrapped operation is checked too.

Returns:

True if at least one parameter is symbolic.

Return type:

bool

Examples

>>> from mimiqcircuits import *
>>> from symengine import Symbol
>>> GateRX(Symbol("theta")).is_symbolic()
True
>>> GateRX(0.5).is_symbolic()
False
listvars()[source]

List the symbolic variables of all the instructions of the block.

Returns:

Each symengine.Symbol once, in no particular order.

Return type:

list

evaluate(d)[source]

Substitute values for the symbols in the operation’s parameters.

Operations without symbolic parameters may return themselves.

Parameters:

d (dict) – Map from symbols (or their names) to values.

Returns:

The operation with the symbols substituted.

Return type:

Operation

supports_canonical_rewrite()[source]

Whether CanonicalRewrite may decompose this operation.

Operations opt in: only those the canonical rewrite knows how to handle return True.

Returns:

bool

__call__(circuit, *targets)[source]

Push the block’s instructions, mapped to targets, to circuit.

Unlike pushing the block itself, this inlines its instructions.

Parameters:
  • circuit – The circuit to add the instructions to.

  • *targets – Qubits, then bits, then z-variables, one for each of the block’s own.

Returns:

The circuit.

Raises:

ValueError – If the number of targets does not match the block.

iswrapper()[source]

Whether the operation wraps another operation.

True for composite operations such as Control, Power, Inverse, Parallel or IfStatement, False otherwise.

Returns:

bool

blockid()[source]

Return the label that identifies this block when printed.

class BlockDecl(name, arguments, body, num_ancillas=None)[source]

Bases: object

Declaration of a named block with symbolic arguments.

A BlockDecl is to Block what GateDecl is to a gate: a reusable body that can hold any instruction (measurements, resets, noise, conditionals, z-variable operations) and takes arguments. A declaration cannot be pushed to a circuit; calling it with values gives a BlockCall, which can.

Every symbol used in the body must be one of the arguments, so evaluating a call only changes the call’s values and all calls keep sharing the same declaration.

Parameters:
  • name (str) – Name of the block.

  • arguments (tuple) – The symbolic arguments, as symengine.Symbol.

  • body – A Circuit, a Block or a list of Instruction. A Block keeps its declared sizes; for the others the sizes are those used by the instructions.

  • num_ancillas (int) – How many of the last qubits of each call are clean ancillas, found and returned in |0>. Defaults to that of body when it is a Block, and to 0 otherwise.

Raises:
  • TypeError – If an argument is not a symbol.

  • ValueError – If the arguments repeat, the body uses a symbol that is not an argument, or num_ancillas is negative or larger than the number of qubits.

Examples

Declare a block that rotates a qubit, entangles it with a second one and measures the second one.

>>> from symengine import symbols
>>> from mimiqcircuits import *
>>> theta = symbols("theta")
>>> body = Circuit()
>>> _ = body.push(GateRX(theta), 0)
>>> _ = body.push(GateCX(), 0, 1)
>>> _ = body.push(Measure(), 1, 0)
>>> syndrome = BlockDecl("syndrome", (theta,), body)
>>> syndrome
block syndrome(theta) =
├── RX(theta) @ q[0]
├── CX @ q[0], q[1]
└── M @ q[1], c[0]

Calling the declaration gives a BlockCall, which is pushed like any other operation: here on qubits 0 and 1 with bit 0, then on qubits 3 and 2 with bit 1. Both calls refer to the same declaration.

>>> c = Circuit()
>>> _ = c.push(syndrome(0.1), 0, 1, 0)
>>> _ = c.push(syndrome(0.2), 3, 2, 1)
>>> c
4-qubit, 2-bit circuit with 2 instructions:
├── syndrome(0.1) @ q[0], q[1], c[0]
└── syndrome(0.2) @ q[3], q[2], c[1]

One decomposition step replaces each call with its body, with the values in place of the arguments.

>>> decompose_step(c)
4-qubit, 2-bit circuit with 6 instructions:
├── RX(0.1) @ q[0]
├── CX @ q[0], q[1]
├── M @ q[1], c[0]
├── RX(0.2) @ q[3]
├── CX @ q[3], q[2]
└── M @ q[2], c[1]
property num_qubits

Number of qubits a call to this block acts on.

property num_ancillas

Number of clean ancillas, the last qubit targets of each call.

property num_bits

Number of classical bits a call to this block acts on.

property num_zvars

Number of z-variables a call to this block acts on.

blockdecl(name)[source]

Decorator that turns a function returning a circuit into a BlockDecl.

The names of the function’s arguments become the symbolic arguments of the declaration. The function is called once, with those symbols, to build the body. The decorated name is bound to the BlockDecl, not to the function; calling it with values gives a BlockCall.

Parameters:

name – Name of the declared block.

Returns:

A decorator that returns the BlockDecl.

Raises:

ValueError – If the decorated function does not return a Circuit or a Block.

Examples

>>> from mimiqcircuits import *
>>> # the argument name ``phi`` becomes the symbol of the declaration
>>> @blockdecl("prepare")
... def prepare(phi):
...     return Circuit().push(GateRY(phi), 0).push(Measure(), 0, 0)
>>> prepare
block prepare(phi) =
├── RY(phi) @ q[0]
└── M @ q[0], c[0]

>>> # call it with a value and push it on qubit 2 and bit 1
>>> Circuit().push(prepare(0.5), 2, 1)
3-qubit, 2-bit circuit with 1 instruction:
└── prepare(0.5) @ q[2], c[1]
class Repeat(repeats, op)[source]

Bases: Operation

Operation applied several times in a row on the same targets.

Repeat(n, op) applies op n times on the same qubits, bits and z-variables. Unlike Power, it works for any operation, not only gates, and keeps the repetitions explicit: decomposing it gives n copies of op.

The repeat method of a gate and the repeat() function are shorthands for it.

Parameters:
  • repeats (int) – Number of repetitions, zero or more.

  • op (Operation) – The operation to repeat.

Raises:
  • ValueError – If repeats is not a non-negative int.

  • TypeError – If op is not an operation.

Examples

>>> from mimiqcircuits import *
>>> from symengine import *
>>> # five X gates in a row
>>> Repeat(5, GateX())
∏⁵ X
>>> Repeat(3, GateRX(Symbol("x")))
∏³ RX(x)
>>> # nested repeats are kept as they are
>>> Repeat(2, Repeat(3, GateX()))
∏² ∏³ X
>>> # without a count, repeat() returns a lazy expression
>>> Parallel(2, GateH()).repeat()
lazy repeat(?, ⨷ ² H)
>>> Parallel(2, GateH()).repeat()(10)
∏¹⁰ ⨷ ² H
>>> c = Circuit().push(Repeat(2, GateX()), 0)
>>> c
1-qubit circuit with 1 instruction:
└── ∏² X @ q[0]
>>> # decomposing gives the individual repetitions
>>> Repeat(2, GateX()).decompose()
1-qubit circuit with 2 instructions:
├── X @ q[0]
└── X @ q[0]
>>> Repeat(3, GateSWAP()).decompose()
2-qubit circuit with 3 instructions:
├── SWAP @ q[0:1]
├── SWAP @ q[0:1]
└── SWAP @ q[0:1]
get_operation()[source]

Return the repeated operation, op.

getparam(name)[source]

Return the parameter name of the repeated operation.

getparams()[source]

Return the parameters of the repeated operation.

power(pow)[source]

Return the repetitions of op raised to pow.

Parameters:

pow – The exponent.

Returns:

Repeat(repeats, op.power(pow)).

Return type:

Repeat

parallel(repeat)[source]

Return the repetitions of repeat parallel copies of op.

Parameters:

repeat – Number of parallel copies.

Returns:

Repeat(repeats, op.parallel(repeat)).

Return type:

Repeat

control(repeat)[source]

Return the repetitions of op controlled by repeat qubits.

Parameters:

repeat – Number of control qubits.

Returns:

Repeat(repeats, op.control(repeat)).

Return type:

Repeat

inverse()[source]

Return the repetitions of the inverse of op.

Returns:

Repeat(repeats, op.inverse()). Fails when op has no inverse.

Return type:

Repeat

iswrapper()[source]

Whether the operation wraps another operation.

True for composite operations such as Control, Power, Inverse, Parallel or IfStatement, False otherwise.

Returns:

bool

supports_canonical_rewrite()[source]

Whether CanonicalRewrite may decompose this operation.

Operations opt in: only those the canonical rewrite knows how to handle return True.

Returns:

bool

evaluate(d)[source]

Substitute values for the symbols in the operation’s parameters.

Operations without symbolic parameters may return themselves.

Parameters:

d (dict) – Map from symbols (or their names) to values.

Returns:

The operation with the symbols substituted.

Return type:

Operation

copy()[source]

Return a shallow copy of the operation.

The copy shares its attributes (for example a wrapped operation) with the original. Use deepcopy() for an independent copy.

Returns:

A new operation of the same type.

Return type:

Operation

deepcopy()[source]

Return a deep copy of the operation and all its attributes.

Returns:

A new operation equal to the original that shares no mutable state with it.

Return type:

Operation

repeat(*args)[source]

Build a Repeat operation, or a lazy one that waits for its count.

repeat(n, op) is Repeat(n, op). repeat(op) returns a lazy expression; calling it with n builds Repeat(n, op).

Parameters:

*args – (n, op) or (op,).

Returns:

The operation, or the lazy expression.

Return type:

Repeat or LazyExpr

Raises:

TypeError – If called with no arguments or with more than two.

Examples

>>> from mimiqcircuits import *
>>> repeat(3, GateX())
∏³ X
>>> repeat(GateX())(3)
∏³ X
class IfStatement(operation, bitstring)[source]

Bases: Operation

Operation applied only when classical bits match a bitstring.

IfStatement(op, bs) applies op when the condition bits hold the values in bs, the first condition bit compared with the first character of bs, and so on. Otherwise it does nothing.

The instruction takes the targets of op followed by the condition bits: qubits of op, classical bits of op, len(bs) condition bits, then z-variables of op. The condition bits may overlap with the bits of op.

Parameters:
  • operation – The operation to apply, or an operation class built with no arguments.

  • bitstring (BitString) – The values the condition bits must hold.

Raises:

ValueError – If operation is not an operation or bitstring is not a BitString.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> # measure qubit 0 into bit 0
>>> c.push(Measure(), 0, 0)
1-qubit, 1-bit circuit with 1 instruction:
└── M @ q[0], c[0]

>>> # flip qubit 1 only if bit 0 is 1
>>> c.push(IfStatement(GateX(), BitString('1')), 1, 0)
2-qubit, 1-bit circuit with 2 instructions:
├── M @ q[0], c[0]
└── IF(c==1) X @ q[1], condition[0]

>>> # measure qubit 1 into bit 3 if bits 1 and 2 are 0 and 1:
>>> # the bit of the measurement comes before the condition bits
>>> c.push(IfStatement(Measure(), BitString('01')), 1, 3, 1, 2)
2-qubit, 4-bit circuit with 3 instructions:
├── M @ q[0], c[0]
├── IF(c==1) X @ q[1], condition[0]
└── IF(c==01) M @ q[1], c[3], condition[1:2]
property op

The conditioned operation. Read-only.

property bitstring

The values the condition bits must hold, as a BitString.

iswrapper()[source]

Whether the operation wraps another operation.

True for composite operations such as Control, Power, Inverse, Parallel or IfStatement, False otherwise.

Returns:

bool

supports_canonical_rewrite()[source]

Whether CanonicalRewrite may decompose this operation.

Operations opt in: only those the canonical rewrite knows how to handle return True.

Returns:

bool

getparams()[source]

Return the parameters of the conditioned operation.

inverse()[source]

Not supported for conditional operations.

Raises:

NotImplementedError – Always.

power(power)[source]

Not supported for conditional operations.

Raises:

NotImplementedError – Always.

control(num_controls)[source]

Not supported for conditional operations.

Raises:

NotImplementedError – Always.

format_with_targets(qubits, bits, zvars)[source]

Nested conditional formatting (explicit IF(c==..) chain).

evaluate(d)[source]

Substitute values for the symbols in the operation’s parameters.

Operations without symbolic parameters may return themselves.

Parameters:

d (dict) – Map from symbols (or their names) to values.

Returns:

The operation with the symbols substituted.

Return type:

Operation

get_operation()[source]

Return the conditioned operation, op.

get_bitstring()[source]

Return the condition, bitstring.

class PauliString(pauli)[source]

Bases: Gate

Tensor product of Pauli operators on \(N\) qubits.

Represents \(P_1 \otimes P_2 \otimes \dots \otimes P_N\) with each \(P_i \in \{I, X, Y, Z\}\). The \(i\)-th character of the string acts on the \(i\)-th target qubit. A Pauli string is its own inverse and can only be raised to integer powers.

Parameters:

pauli (str | chr) – A non-empty string of "I", "X", "Y" and "Z" characters, for example "IXXYZ".

Raises:

ValueError – If the string is empty or contains other characters.

Examples

>>> from mimiqcircuits import *
>>> g = PauliString("XYZ")
>>> g.matrix()
[0, 0, 0, 0, 0, 0, 0.0 - 1.0*I, 0]
[0, 0, 0, 0, 0, 0, 0, 0.0 + 1.0*I]
[0, 0, 0, 0, 0.0 + 1.0*I, 0, 0, 0]
[0, 0, 0, 0, 0, 0.0 - 1.0*I, 0, 0]
[0, 0, 0.0 - 1.0*I, 0, 0, 0, 0, 0]
[0, 0, 0, 0.0 + 1.0*I, 0, 0, 0, 0]
[0.0 + 1.0*I, 0, 0, 0, 0, 0, 0, 0]
[0, 0.0 - 1.0*I, 0, 0, 0, 0, 0, 0]

>>> c = Circuit()
>>> c.push(PauliString("XYZ"), 0, 1, 2)
3-qubit circuit with 1 instruction:
└── XYZ @ q[0:2]

>>> g.power(2), g.inverse()
(III, XYZ)
>>> g.decompose()
3-qubit circuit with 3 instructions:
├── X @ q[0]
├── Y @ q[1]
└── Z @ q[2]
classmethod from_string(pauli_expr)[source]

Build a PauliString from a string; same as PauliString(pauli_expr).

property num_qubits

Number of qubits, the length of the string.

property parnames

("pauli",).

Type:

Parameter names

inverse()[source]

Return the inverse of the gate.

Gates with a known inverse return it directly (for example GateS().inverse() is GateSDG()); otherwise the gate is wrapped in Inverse.

unwrappedmatrix()[source]

Return the matrix as a NumPy array with dtype complex128.

unwrapped_matrix()[source]

Return the matrix as a NumPy array of SymEngine numbers (dtype=object).

is_identity()[source]

Return True if every character is "I". Same as isidentity().

evaluate(d)[source]

Return self: a Pauli string has no symbolic parameters.

isidentity()[source]

Return True if every character is "I".

class QFT(*args)[source]

Bases: Gate

Quantum Fourier transform on num_qubits qubits.

Implements the unitary

\[\frac{1}{2^{n/2}} \sum_{x=0}^{2^n-1} \sum_{y=0}^{2^n-1} e^{2\pi i \frac{xy}{2^n}} |y\rangle\langle \tilde{x}|\]

where \(\tilde{x}\) is \(x\) with its bits reversed: the input is read with the first qubit as the least significant bit, the output with the first qubit as the most significant bit. The decomposition uses Hadamard and controlled-phase gates and no final SWAPs. The inverse is QFT(n).inverse(). QFT() with no arguments returns a lazy expression that takes the number of qubits later.

The gate has no matrix representation: matrix() raises NotImplementedError.

Parameters:

num_qubits (int) – Number of qubits, at least 1.

Raises:

ValueError – If num_qubits is less than 1, or more than one argument is given.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(QFT(2), 1, 2)
3-qubit circuit with 1 instruction:
└── QFT @ q[1:2]

>>> c.push(QFT(2).inverse(), 1, 2)
3-qubit circuit with 2 instructions:
├── QFT @ q[1:2]
└── QFT† @ q[1:2]

>>> QFT(2).decompose()
2-qubit circuit with 3 instructions:
├── H @ q[1]
├── CP((1/2)*pi) @ q[0], q[1]
└── H @ q[0]
class PhaseGradient(*args)[source]

Bases: Gate

Phase gradient gate on num_qubits qubits.

Each computational basis state \(|k\rangle\) gets a phase proportional to its integer value \(k\), with the first qubit as the most significant bit:

\[\operatorname{PhaseGradient} = \sum_{k=0}^{2^n-1} \mathrm{e}^{i \frac{2 \pi}{2^n} k} |k\rangle\langle k|\]

The gate decomposes into one GateP per qubit. PhaseGradient() with no arguments returns a lazy expression that takes the number of qubits later. The gate has no matrix representation: matrix() raises NotImplementedError.

Parameters:

num_qubits (int) – Number of qubits.

Raises:

ValueError – If more than one argument is given.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(PhaseGradient(2), 9, 8)
10-qubit circuit with 1 instruction:
└── PhaseGradient @ q[9,8]

>>> PhaseGradient(3).decompose()
3-qubit circuit with 3 instructions:
├── P((1/4)*pi) @ q[2]
├── P((1/2)*pi) @ q[1]
└── P(pi) @ q[0]
class PolynomialOracle(*args)[source]

Bases: Gate

Quantum oracle for a polynomial of two registers.

Applies a \(\pi\) phase to every basis state \(|x\rangle|y\rangle\) with \(a xy + b x + c y + d = 0\), where \(x\) and \(y\) are the integer values of the two registers. Each register is little-endian: its first qubit is the least significant bit. The gate is its own inverse.

PolynomialOracle(a, b, c, d) with four arguments returns a lazy expression that takes the two register sizes later.

The oracle has no matrix representation. It decomposes into one multi-controlled Z per solution, so the decomposition is only practical when there are few solutions. A decomposition without solutions is a single GateID on the last qubit, which keeps the oracle’s width.

Parameters:
  • nx (int) – Number of qubits in the \(x\) register.

  • ny (int) – Number of qubits in the \(y\) register.

  • a (int) – Coefficient of \(xy\).

  • b (int) – Coefficient of \(x\).

  • c (int) – Coefficient of \(y\).

  • d (int) – Constant term.

Raises:

ValueError – If a coefficient is not an integer, or the number of arguments is neither 4 nor 6.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(PolynomialOracle(5, 5, 1, 2, 3, 4), *range(1, 11))
11-qubit circuit with 1 instruction:
└── PolynomialOracle(1, 2, 3, 4) @ q[1:5], q[6:10]

>>> # lazy form: the register sizes are given later
>>> PolynomialOracle(1, 2, 3, 4)(5, 5)
PolynomialOracle(1, 2, 3, 4)
inverse()[source]

Return the inverse of the gate.

Gates with a known inverse return it directly (for example GateS().inverse() is GateSDG()); otherwise the gate is wrapped in Inverse.

supports_canonical_rewrite()[source]

Return True: the oracle decomposes into multi-controlled Z gates.

class GateRNZ(*args)[source]

Bases: Gate

Multi-qubit Z-parity rotation.

Applies \(e^{-i\frac{\theta}{2} Z^{\otimes n}}\): each computational basis state gets the phase \(e^{-i\theta/2}\) if it has an even number of ones and \(e^{i\theta/2}\) if odd.

Matrix Representation

\[\operatorname{RNZ}(\theta) = \operatorname{diag}\left( e^{-i(-1)^{|k|}\theta/2}\right)_{k=0}^{2^n-1}\]

where \(|k|\) is the number of ones in the binary form of \(k\).

With fewer than two arguments the constructor returns a lazy expression that takes the missing arguments later.

Parameters:
  • n (int) – Number of qubits, a positive integer.

  • theta – Rotation angle in radians, numeric or symbolic.

Raises:

ValueError – If n is not a positive integer or more than two arguments are given.

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi, Symbol
>>> GateRNZ(2, pi/2)
RNZ((1/2)*pi)
>>> GateRNZ(2, Symbol('theta')).matrix()
[exp(-1/2*I*theta), 0, 0, 0]
[0, exp(1/2*I*theta), 0, 0]
[0, 0, exp(1/2*I*theta), 0]
[0, 0, 0, exp(-1/2*I*theta)]

>>> c = Circuit()
>>> c.push(GateRNZ(3, pi/2), 1, 2, 3)
4-qubit circuit with 1 instruction:
└── RNZ((1/2)*pi) @ q[1:3]

>>> GateRNZ(2, pi/2).power(2), GateRNZ(2, pi/2).inverse()
(RNZ(pi), RNZ((-1/2)*pi))
>>> GateRNZ(2, pi/2).decompose()
2-qubit circuit with 3 instructions:
├── CX @ q[0], q[1]
├── RZ((1/2)*pi) @ q[1]
└── CX @ q[0], q[1]

>>> # lazy forms
>>> GateRNZ()
lazy GateRNZ(?, ?)
>>> GateRNZ(2)
lazy GateRNZ(2, ?)
inverse()[source]

Return the inverse of the gate.

Gates with a known inverse return it directly (for example GateS().inverse() is GateSDG()); otherwise the gate is wrapped in Inverse.

power(pwr)[source]

Return GateRNZ(n, theta * pwr).

evaluate(d)[source]

Substitute symbols in theta and return a new gate.

Parameters:

d (dict) – Map from symbols to the values to substitute.

Returns:

A new gate with the substituted angle.

Return type:

GateRNZ

class Diffusion(*args)[source]

Bases: Gate

Grover’s diffusion operator on num_qubits qubits.

Implements the unitary

\[H^{\otimes n} \left(1 - 2 |0^n\rangle\langle 0^n|\right) H^{\otimes n}\]

Diffusion() with no arguments returns a lazy expression that takes the number of qubits later. The gate has no matrix representation: matrix() raises NotImplementedError.

Parameters:

num_qubits (int) – Number of qubits, at least 1.

Raises:

ValueError – If num_qubits is not an integer or is less than 1, or more than one argument is given.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(Diffusion(2), 1, 2)
3-qubit circuit with 1 instruction:
└── Diffusion @ q[1:2]

>>> Diffusion(2).decompose()
2-qubit circuit with 5 instructions:
├── RY((1/2)*pi) @ q[0]
├── RY((1/2)*pi) @ q[1]
├── CZ @ q[0], q[1]
├── RY((-1/2)*pi) @ q[0]
└── RY((-1/2)*pi) @ q[1]
inverse()[source]

Return the inverse of the gate.

Gates with a known inverse return it directly (for example GateS().inverse() is GateSDG()); otherwise the gate is wrapped in Inverse.

class Barrier(*args)[source]

Bases: Operation

No-op that stops circuit optimizations from moving gates across it.

A barrier does not change the quantum state. Compression and optimization passes do not merge, cancel or reorder operations across it.

Barrier(n) covers n qubits. Barrier() without arguments returns a lazy expression that takes the number of qubits later.

Parameters:

num_qubits – Number of qubits the barrier covers, at least 1.

Raises:

ValueError – If num_qubits is less than 1, or if more than one argument is given.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> # a single-qubit barrier on qubit 1
>>> c.push(Barrier(1), 1)
2-qubit circuit with 1 instruction:
└── Barrier @ q[1]

Pushing a single-qubit barrier to a range adds one barrier per qubit:

>>> c = Circuit()
>>> c.push(Barrier(1), range(0,4))
4-qubit circuit with 4 instructions:
├── Barrier @ q[0]
├── Barrier @ q[1]
├── Barrier @ q[2]
└── Barrier @ q[3]

A multi-qubit barrier is a single instruction across all its qubits:

>>> c = Circuit()
>>> c.push(Barrier(5),1,2,3,4,5)
6-qubit circuit with 1 instruction:
└── Barrier @ q[1:5]
__init__(num_qubits)[source]

Create a barrier on num_qubits qubits.

Parameters:

num_qubits – Number of qubits the barrier covers.

Raises:

ValueError – If num_qubits is less than 1.

inverse()[source]

Return the barrier itself; it is its own inverse.

power(p)[source]

Not supported for barriers.

Raises:

TypeError – Always.

control(num_qubits)[source]

Not supported for barriers.

Raises:

TypeError – Always.

iswrapper()[source]

Whether the operation wraps another operation.

True for composite operations such as Control, Power, Inverse, Parallel or IfStatement, False otherwise.

Returns:

bool

static isunitary()[source]

Whether the operation acts unitarily on the quantum state.

Returns:

True for gates, annotations, Barrier, and the operations that only read the state into a z-variable, such as ExpectationValue or Amplitude. False for everything else: measurements, resets, noise channels, classical operations, and containers such as Block or IfStatement.

Return type:

bool