Non-unitary Operations

Contrary to unitary gates, non-unitary operations based on measurements make the quantum state collapse. Find in the following sections all the non-unitary operations supported by MIMIQ.

Note

As a rule of thumb all non-unitary operations can be added to the circuit using the function push() by giving the index of the targets in the following order:raw:: quantum register index -> classical register index.

Note

Noise can also be interpreted as a non-unitary operations but will not be treated here, check the noise documentation page to learn more about it.

Note

Once a non-unitary operation is added to your circuit the speed of execution might be reduced. This is because in this case the circuit needs to be re-run for every sample since the final quantum state might be different each time. This is always true except for Measure operations placed at the very end of a circuit. To learn more about this head to the simulation page.

Note

Some features of unitary gates are not available for non-unitary operations, for instance, matrix(), inverse(), power(), control(), parallel().

Measure

Mathematical definition

Measurements are defined by a basis of projection operators \(P_k\), one for each different possible outcome \(k\). The probability \(p_k\) of measuring outcome \(k\) is given by the expectation value of \(P_k\), that is

\[p_k = \bra{\psi} P_k \ket{\psi}.\]

If the outcome \(k\) is observed, the system is left in the state

\[\frac{P_k\ket{\psi}}{\sqrt{p_k}}.\]

It is common to measure in the Z basis (\(P_0=\ket{0}\bra{0}\) and \(P_1=\ket{1}\bra{1}\)), but measurements in other bases are possible too.

How to use measurements

Available measurement operations: Measure, MeasureX, MeasureY, MeasureZ, MeasureXX, MeasureYY, MeasureZZ, MeasurePauli.

With MIMIQ you can measure the qubits at any point in the circuit (not only at the end of the circuit) using one of the measurement operations (Measure…). You can add it to the circuit like gates using push(), but you will need to precise both the index for the quantum register (qubit to measure) and classical register (where to store the result):

>>> circuit = Circuit()
>>> circuit.push(Measure(), 0, 0)
1-qubit, 1-bit circuit with 1 instruction:
└── M @ q[0], c[0]

This will add a Measure() on the first qubit of the quantum register to the circuit and write the result on the first bit of the classical register. Recall that the targets are always ordered as quantum register -> classical register -> z register. To learn more about registers head to the Registers: quantum/classical/Z-register section.

You can also use iterators to Measure multiple qubits at once, as for gates:

>>> circuit.push(Measure(), range(0, 10), range(0,10))
10-qubit, 10-bit circuit with 11 instructions:
├── M @ q[0], c[0]
├── M @ q[0], c[0]
├── M @ q[1], c[1]
├── M @ q[2], c[2]
├── M @ q[3], c[3]
├── M @ q[4], c[4]
├── M @ q[5], c[5]
├── M @ q[6], c[6]
├── M @ q[7], c[7]
├── M @ q[8], c[8]
└── M @ q[9], c[9]

MeasurePauli measures a multi-qubit Pauli product observable, such as \(X_0 Z_2\), and writes a single outcome bit (0 for eigenvalue \(+1\), 1 for \(-1\)). It targets one qubit per character of the Pauli string; qubits marked I are not measured:

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

Note

In the absence of any non-unitary operations in the circuit, MIMIQ will sample (and, therefore, measure) all the qubits at the end of the circuit by default, see simulation page.

Reset

Available reset operations: Reset, ResetX, ResetY, ResetZ, and PrepareStateT, which leaves the qubit in the magic state \(T\ket{+}\).

A reset operation consists in measuring the qubits in some basis and then applying an operation conditioned on the measurement outcome to leave the qubits in some pre-defined state. For example, Reset() leaves all qubits in \(\ket{0}\) (by measuring in \(Z\) and flipping the state if the outcome is 1).

Here is an example of how to add a reset operation to a circuit:

>>> circuit = Circuit()
>>> circuit.push(Reset(), 0)
1-qubit circuit with 1 instruction:
└── Reset @ q[0]

Importantly, even though a reset operation technically measures the qubits, the information is not stored in the classical register, so we only need to specify the qubit register. If you want to store the result, see the Measure-Reset section.

Note that a reset operation can be technically seen as noise and is described by the same mathematical machinery, see noise page. For this reason, some of the functionality provided by MIMIQ for noise is also available for resets. Here is one example:

>>> Reset().krausoperators()
[P₀(1.0), SigmaMinus(1.0)]

Measure-Reset

Available measure-reset operations: MeasureReset, MeasureResetX, MeasureResetY, MeasureResetZ.

A measure-reset operation is the same as a reset operation except that we store the result of the measurement, see Measure and Reset sections. Because of that, we need to specify both quantum and classical registers when adding it to a circuit:

>>> circuit = Circuit()
>>> circuit.push(MeasureReset(), 0, 0)
1-qubit, 1-bit circuit with 1 instruction:
└── MR @ q[0], c[0]

Conditional logic

If statements

An if statement consists in applying an operation conditional on the value of some classical register. In that sense, it resembles a classical if statement.

In MIMIQ you can implement it using IfStatement, which requires two arguments: an operation to apply and a BitString as the condition (see Bitstrings page for more information):

>>> IfStatement(GateX(), BitString("111"))
IF (c==111) X

Note

At the moment, MIMIQ only allows to pass unitary gates as arguments to an if statement (which makes if statements unitary for now).

To add an IfStatement to a circuit use the push() function. The first (quantum) indices will determine the qubits to apply the gate to, whereas the last (classical) indices will be used to compare against the condition given. For example:

>>> circuit  = Circuit()

>>> # Apply a GateX on qubit 1 if the qubits 2 and 4 are in the state 1 and qubit 3 in the state 0.
>>> circuit.push(IfStatement(GateX(), BitString("101")), 0, 1, 2, 3)
1-qubit, 4-bit circuit with 1 instruction:
└── IF(c==101) X @ q[0], condition[1:3]

Here, an X gate will be applied to qubit 1, if classical registers 2 and 4 are 1, and classical register 3 is 0. Of course, if the gate targets more than 1 qubit, then all qubit indices will be specified before the classical registers, as usual (see circuit page).

The body of an IfStatement is allowed to write to one of the bits used in the condition. The classical-target layout is [op_bits..., condition_bits...], so when the body and the condition share a bit you simply repeat that bit index in the push() call. See the Target aliasing section below for the rules.

While statements

A while statement applies an operation repeatedly while a classical register matches a given pattern. It is the loop counterpart of IfStatement and resembles a classical while loop.

In MIMIQ you can implement it using WhileStatement, which takes the same two arguments as IfStatement: an operation to apply each iteration and a BitString acting as the loop condition.

>>> WhileStatement(Not(), BitString('1'))
WHILE(c==1) !

WhileStatement is added to a circuit with push() using the same target layout as IfStatement: quantum targets first, then the body’s classical bits, then the condition bits. For example, the loop below decrements c[0] while it is set:

>>> circuit = Circuit()
>>> circuit.push(WhileStatement(Not(), BitString('1')), 0, 0)
1-bit circuit with 1 instruction:
└── WHILE(c==1) ! @ c[0], condition[0]

For the loop to make progress, the body must mutate at least one bit that appears in the condition — otherwise the register never changes and the loop runs forever. Because of this, WhileStatement explicitly allows the body’s bit targets to overlap (alias) the condition’s bit targets, even though most operations forbid repeated bit targets (see Target aliasing below).

Warning

There is no built-in iteration cap: a non-terminating circuit is the user’s responsibility, exactly as in any classical language. Make sure the body can falsify the condition.

Note

As with IfStatement, the inner operation must currently be unitary.

Target aliasing

Most operations require their qubit, classical-bit, and z-variable targets to be all distinct within a single instruction — pushing the same index twice raises an error. Two exceptions:

  • Qubits are always required to be unique. This reflects the no-cloning theorem and is never relaxed.

  • Bits and z-variables can be reused by operations that opt in via the allow_bit_aliasing() and allow_zvar_aliasing() class-level flags.

Operations that opt into bit aliasing today are And, Or, Xor, IfStatement, and WhileStatement. For example, you can read and write the same bit in a single classical operation:

>>> circuit = Circuit()
>>> # c[0] = c[0] AND c[1]
>>> circuit.push(And(), 0, 0, 1)
2-bit circuit with 1 instruction:
└── c[0] &= c[1]

Or use a bit both as the condition and as the body’s target inside an IfStatement:

>>> circuit = Circuit()
>>> # Toggle c[0] when c[0] == 1 (the condition bit is also the body's target).
>>> circuit.push(IfStatement(Not(), BitString('1')), 0, 0)
1-bit circuit with 1 instruction:
└── IF(c==1) ! @ c[0], condition[0]

Operations that opt into z-variable aliasing today are Add, Multiply, and Pow — see the Z-register operations page for examples like z[0] += z[0] + z[1].

Operators

Mathematical definition

Operators refer to any linear operation on a state. An operator does not need to be unitary, as is the case of a gate. This means that any \(2^N \times 2^N\) matrix can in principle represent an operator on \(N\) qubits.

Note

Do not confuse operator with operation. In MIMIQ, the word operation is used as the supertype for all transformations of a quantum state (gates, measurements, statistical operations…), whereas an operator is a sort of generalized gate, a linear tranformation.

Operators available in MIMIQ

Custom operators: Operator

Special operators: DiagonalOp, SigmaPlus, SigmaMinus, Projector0, ProjectorZ0, Projector1, ProjectorZ1, ProjectorX0, ProjectorX1, ProjectorY0, ProjectorY1, Projector00, Projector01, Projector10, Projector11

Methods available: Gate;matrix().

How to use operators

Operators cannot be applied to a state directly (it cannot be added to a circuit using push()), because that would correspond to an unphysical transformation. However, they can be used within other operations such as ExpectationValue or to create custom noise models with Kraus, see noise and statistical operations pages.

Operators can be used to compute expectation values as follows (see also ExpectationValue):

>>> op = SigmaPlus()
>>> ev = ExpectationValue(op)
>>> circuit = Circuit()
>>> circuit.push(ev, 0, 0)
1-qubit, 1-zvar circuit with 1 instruction:
└── ⟨SigmaPlus(1)⟩ @ q[0], z[0]

Similarly, operators can also be used to define non-mixed unitary Kraus channels (see also Kraus). For example, we can define the amplitude damping channel as follows:

>>> gamma = 0.1
>>> k1 = DiagonalOp(1, math.sqrt(1-gamma))    # Kraus operator 1
>>> k2 = SigmaMinus(math.sqrt(gamma))    # Kraus operator 2
>>> kraus = Kraus([k1,k2])

This is equivalent to

>>> gamma = 0.1
>>> ampdamp = AmplitudeDamping(gamma)
>>> ampdamp.krausoperators()
[D(1, 0.948683298050514), SigmaMinus(0.316227766016838)]

Note

Whenever possible, using specialized operators, such as DiagonalOp and SigmaMinus, as opposed to custom operators, such as Operator, is generally better for performance.

Reference

class Measure[source]

Bases: AbstractMeasurement

Single-qubit measurement in the computational (Z) basis.

Projects the qubit onto \(|0⟩\) or \(|1⟩\) and writes the outcome, 0 or 1, to a classical bit. The instruction takes one qubit and one bit.

Warning

Measurements are not reversible: inverse, power and control raise TypeError.

Examples

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

Targets can be ranges, lists or tuples; one instruction is added per qubit-bit pair:

>>> c = Circuit()
>>> c.push(Measure(), range(0,3), range(0,3))
3-qubit, 3-bit circuit with 3 instructions:
├── M @ q[0], c[0]
├── M @ q[1], c[1]
└── M @ q[2], c[2]
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

iswrapper()[source]

Whether the operation wraps another operation.

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

Returns:

bool

get_operation()[source]

Return the operation that this one wraps, or the operation itself.

Wrappers such as Control or Power return the operation they wrap; other operations return themselves.

Returns:

Operation

class MeasurePauli(pauli)[source]

Bases: AbstractMeasurement

Pauli product measurement.

Projective measurement of the \(N\)-qubit observable \(P = P_1 \otimes P_2 \otimes \dots \otimes P_N\), with each \(P_i \in \{I, X, Y, Z\}\).

The instruction targets \(N\) qubits and one classical bit. The state is projected onto the \(+1\) or \(-1\) eigenspace of \(P\) and the bit records the outcome: 0 for \(+1\), 1 for \(-1\). Qubits marked I are targets of the instruction but are not measured.

To measure \(-P\), measure \(P\) and flip the bit with Not.

Parameters:

pauli (PauliString | str) – The observable, as a PauliString or a string of I, X, Y, Z. Stored in the pauli attribute as a PauliString.

Raises:
  • TypeError – If pauli is neither a PauliString nor a str.

  • ValueError – If the string is empty, contains a character other than I, X, Y, Z, or is the identity.

See also

PauliString, RPauli, MeasureZZ, MeasureXX, MeasureYY, pauli_based_computation()

Each measured qubit is rotated to the Z basis (H for X, SDG then H for Y), CX gates collect the parity of the measured qubits on the last one, that qubit is measured, and the CX gates and rotations are undone. Only H, S, SDG, CX, Measure and ID (on a trailing identity factor, to keep the width) appear, so QASMBasis decomposes it. StimBasis and CliffordTBasis keep it as it is, as Stim measures Pauli products natively (MPP).

Measurements are not reversible: inverse, power and control raise TypeError.

Examples

Measure \(X_0 Z_2\) on qubits 0 to 2 and store the outcome in bit 0. Qubit 1 is a target, but is left untouched:

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

One decomposition step shows the basis change and parity collection:

>>> decompose_step(MeasurePauli("XZ"))
2-qubit, 1-bit circuit with 5 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── M @ q[1], c[0]
├── CX @ q[0], q[1]
└── H @ q[0]
pstring()[source]

Return the Pauli string as a plain str.

iswrapper()[source]

Whether the operation wraps another operation.

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

Returns:

bool

get_operation()[source]

Return the operation that this one wraps, or the operation itself.

Wrappers such as Control or Power return the operation they wrap; other operations return themselves.

Returns:

Operation

class Reset[source]

Bases: krauschannel

Reset a qubit to \(|0⟩\).

Puts the qubit in \(|0⟩\) whatever its state, without recording an outcome. It is the Kraus channel with operators \(|0⟩⟨0|\) and \(|0⟩⟨1|\).

Warning

Not reversible: inverse, power and control raise TypeError.

See also

ResetX, ResetY, ResetZ, MeasureReset

Examples

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

Targets can be ranges, lists or tuples; one instruction is added per qubit:

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

>>> # the two Kraus operators: project on |0>, or move |1> to |0>
>>> Reset().krausoperators()
[P₀(1.0), SigmaMinus(1.0)]
inverse()[source]

Kraus channels have no inverse.

Raises:

NotImplementedError – Always.

power(pwr)[source]

Kraus channels cannot be raised to a power.

Raises:

NotImplementedError – 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

krausoperators(normaliz=None)[source]

Return the Kraus operators \(|0⟩⟨0|\) and \(|0⟩⟨1|\).

Parameters:

normaliz (list) – Two numbers; each operator is divided by the matching entry. Defaults to [1, 1].

Returns:

[Projector0(...), SigmaMinus(...)].

Return type:

list

Raises:

ValueError – If normaliz does not have length 2.

class PrepareStateT[source]

Bases: krauschannel

Prepare one qubit in the magic state.

Prepares the magic state \(T\ket{+} = (\ket{0} + e^{i\pi/4}\ket{1})/\sqrt{2}\), whatever the previous state of the qubit.

A magic state is the resource consumed by a \(\pi/8\) Pauli rotation when the rotation is carried out with Pauli product measurements (see pauli_based_computation()). Fault-tolerant architectures produce these states separately, by distillation, so a dedicated operation lets them be counted and scheduled.

The operation is a Kraus channel with operators \(T\ket{+}\bra{0}\) and \(T\ket{+}\bra{1}\), and is equivalent to Reset, GateH, GateT. It cannot be inverted, raised to a power or controlled: inverse, power and control raise TypeError.

PrepareMagic is a deprecated alias of this class.

Examples

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

The decomposition resets the qubit to \(\ket{0}\), then applies H and T:

>>> PrepareStateT().decompose()
1-qubit circuit with 3 instructions:
├── Reset @ q[0]
├── H @ q[0]
└── T @ q[0]

See also

Reset, ResetX, MeasurePauli

inverse()[source]

Kraus channels have no inverse.

Raises:

NotImplementedError – Always.

power(pwr)[source]

Kraus channels cannot be raised to a power.

Raises:

NotImplementedError – 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

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

krausoperators()[source]

Return the Kraus operators \(T\ket{+}\bra{0}\) and \(T\ket{+}\bra{1}\).

Returns:

Two Operator objects.

Return type:

list

class MeasureReset[source]

Bases: AbstractMeasurement

Measure a qubit in the Z basis, then reset it to \(|0⟩\).

Writes the outcome to a classical bit and then applies GateX to the qubit if the outcome is 1, which leaves it in \(|0⟩\). It decomposes into Measure followed by an IfStatement of GateX conditioned on that bit. The instruction takes one qubit and one bit.

Warning

Not reversible: inverse, power and control raise TypeError.

See also

MeasureResetX, MeasureResetY, Reset

Examples

>>> from mimiqcircuits import *
>>> # measure qubit 1 into bit 0 and leave it in |0>
>>> c = Circuit()
>>> c.push(MeasureReset(), 1, 0)
2-qubit, 1-bit circuit with 1 instruction:
└── MR @ q[1], c[0]

>>> # the same as a measurement followed by a conditional X
>>> MeasureReset().decompose()
1-qubit, 1-bit circuit with 2 instructions:
├── M @ q[0], c[0]
└── IF(c==1) X @ q[0], condition[0]
iswrapper()[source]

Whether the operation wraps another operation.

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

Returns:

bool

get_operation()[source]

Return the operation that this one wraps, or the operation itself.

Wrappers such as Control or Power return the operation they wrap; other operations return themselves.

Returns:

Operation

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 WhileStatement(operation, bitstring)[source]

Bases: Operation

Operation applied repeatedly while classical bits match a bitstring.

WhileStatement(op, bs) is the loop counterpart of IfStatement. Before each iteration the condition bits are compared with bs; while they match, op is applied again.

The instruction takes the same targets as an IfStatement: qubits of op, classical bits of op, len(bs) condition bits, then z-variables of op. For the loop to end, op must change at least one condition bit, so the bits of op may overlap with the condition bits. There is no limit on the number of iterations: a loop whose condition never changes does not terminate.

Parameters:
  • operation – The loop body, or an operation class built with no arguments.

  • bitstring (BitString) – The values the condition bits must hold for the loop to continue.

Raises:

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

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> # measure and reset qubit 0 as long as bit 0 holds 1: the
>>> # measurement writes bit 0, which is also the condition bit, and
>>> # after the reset it reads 0, which ends the loop
>>> c.push(WhileStatement(MeasureReset(), BitString('1')), 0, 0, 0)
1-qubit, 1-bit circuit with 1 instruction:
└── WHILE(c==1) MR @ q[0], c[0], condition[0]

>>> # a classical body: flipping bit 1 while it is 1 runs at most once
>>> c.push(WhileStatement(Not(), BitString('1')), 1, 1)
1-qubit, 2-bit circuit with 2 instructions:
├── WHILE(c==1) MR @ q[0], c[0], condition[0]
└── WHILE(c==1) ! @ c[1], condition[1]

See also

IfStatement

property op

The loop body. 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

getparams()[source]

Return the parameters of the loop body.

inverse()[source]

Not supported for loops.

Raises:

NotImplementedError – Always.

power(power)[source]

Not supported for loops.

Raises:

NotImplementedError – Always.

control(num_controls)[source]

Not supported for loops.

Raises:

NotImplementedError – Always.

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 loop body, op.

get_bitstring()[source]

Return the condition, bitstring.

class Operator(mat)[source]

Bases: AbstractOperator

N-qubit operator given by a \(2^N \times 2^N\) matrix.

The matrix does not have to be unitary. Only one- and two-qubit operators are supported. The matrix is stored as a SymEngine matrix in the mat attribute.

Parameters:

mat (symengine.Matrix | sympy.Matrix | numpy.ndarray) – The square matrix of the operator, of size 2 or 4.

Raises:
  • TypeError – If mat is not a SymEngine, SymPy or NumPy matrix.

  • ValueError – If mat is not square, its size is not a power of 2, or it acts on more than two qubits.

See also

AbstractOperator, ExpectationValue, Kraus

Examples

>>> from mimiqcircuits import *
>>> from symengine import Matrix
>>> op = Operator(Matrix([[1, 2], [3, 4]]))
>>> op
1-qubit Operator:
├── 1 2
└── 3 4
>>> op = Operator(Matrix([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]]))
>>> op
2-qubit Operator:
├── 1 0 0 1
├── 0 0 0 0
├── 0 0 0 0
└── 1 0 0 1

Operators can be used for expectation values:

>>> c = Circuit()
>>> c.push(ExpectationValue(Operator(Matrix([[0, 1], [0, 0]]))), 1, 1)
2-qubit, 2-zvar circuit with 1 instruction:
└── ⟨Operator([[0, 1], [0, 0]])⟩ @ q[1], z[1]
static is_valid_power_of_2(n)[source]

Return whether n is a positive power of 2.

opname()[source]

Return "Operator".

property parnames

("mat",).

Type:

Names of the parameters

iswrapper()[source]

Operators do not wrap another operation. Returns None.

unwrappedmatrix()[source]

Return the numeric matrix of the operator as a NumPy array.

Use this instead of matrix() when plain numbers are needed, for example to feed a simulator. Gates with a fast numeric path (see mimiqcircuits.numerics) skip SymEngine entirely; other operators build the SymEngine matrix and convert it.

Operators fully determined by their type return a cached, read-only array. Copy it before modifying it.

Returns:

The matrix, with dtype complex128.

Return type:

numpy.ndarray

Raises:

UnexpectedSymbolics – If any parameter is still symbolic.

Examples

>>> from mimiqcircuits import *
>>> GateX().unwrappedmatrix()
array([[0.+0.j, 1.+0.j],
       [1.+0.j, 0.+0.j]])
__repr__()[source]

Return a pretty-printed representation.

__str__()[source]

Return Operator(<matrix>) for one qubit and Operator(...) for two.

pretty_print()[source]

Return the matrix as a multi-line string, one row per line.

opsquared()[source]

Return \(O^\dagger O\) as a new Operator.

class Kraus(E, rtol=1e-12)[source]

Bases: krauschannel

Custom N-qubit Kraus channel given by a list of Kraus operators.

The channel acts on a density matrix as

\[\mathcal{E}(\rho) = \sum_k E_k \rho E_k^\dagger,\]

where the Kraus operators \(E_k\) must fulfill \(\sum_k E_k^\dagger E_k = I\). If all Kraus operators are proportional to unitaries, MixedUnitary is the better choice, since it can be sampled as a random unitary.

Matrices are written in the computational basis in the usual textbook order, with the first qubit as the left-most one: \(|0\rangle, |1\rangle\) for one qubit, \(|00\rangle, |01\rangle, |10\rangle, |11\rangle\) for two.

A Kraus channel models qubit loss when one or more of its operators is a LossyOperator. The entries of a LossyOperator are amplitudes, not probabilities: losseffect() returns the loss probabilities as \(\sum_k L_k^\dagger L_k\) over the lossy branches \(L_k\). hasloss(), lossoperators() and survivaloperators() split the channel into lossy and surviving branches.

Parameters:
  • E (List[MutableDenseMatrix | ndarray | sympy.Matrix | AbstractOperator]) – Kraus operators, each a \(2^N \times 2^N\) matrix (symengine, sympy or numpy) or an operator such as Operator, Projector0 or LossyOperator. Matrices are wrapped in Operator. All entries must act on the same number of qubits \(N\).

  • rtol – Tolerance of the check \(\sum_k E_k^\dagger E_k = I\) (default 1e-12). The check is skipped when any entry is symbolic.

Raises:
  • ValueError – If E is empty, the operators have different sizes, the size is not a power of 2, \(N\) is not 1 or 2, or the numeric operators do not fulfill \(\sum_k E_k^\dagger E_k = I\).

  • TypeError – If an entry of E is neither a matrix nor an operator.

Note

Only 1- and 2-qubit custom Kraus channels are supported.

See also

MixedUnitary, GateCustom, LossyOperator, Operator

Examples

>>> from mimiqcircuits import *
>>> from symengine import *
>>> # amplitude damping with gamma = 0.1, written out by hand
>>> c = Circuit()
>>> c.push(Kraus([Matrix([[1, 0], [0, sqrt(0.9)]]), Matrix([[0, sqrt(0.1)], [0, 0]])]), 0)
1-qubit circuit with 1 instruction:
└── Kraus(Operator([[1, 0], [0, 0.948683298050514]]), Operator([[0, 0.316227766016838], [0, 0]])) @ q[0]
>>> # the Kraus matrices can be read back
>>> g = Kraus([Matrix([[1, 0], [0, sqrt(0.9)]]), Matrix([[0, sqrt(0.1)], [0, 0]])])
>>> g.krausmatrices()
[[1.0, 0]
[0, 0.948683298050514]
, [0, 0.316227766016838]
[0, 0]
]
>>> # operators can be used directly: here a Z-basis dephasing
>>> c = Circuit()
>>> c.push(Kraus([Projector0(), Projector1()]), 0)
1-qubit circuit with 1 instruction:
└── Kraus(P₀(1), P₁(1)) @ q[0]
>>> # matrices and operators can be mixed
>>> c = Circuit()
>>> c.push(Kraus([Matrix([[1, 0], [0, 0]]), Projector1()]), 0)
1-qubit circuit with 1 instruction:
└── Kraus(Operator([[1, 0], [0, 0]]), P₁(1)) @ q[0]
>>> # a lossy branch: the qubit is lost from |1> with probability 0.2
>>> lossy = LossyOperator(Matrix([[0, 0], [0, sqrt(0.2)]]))
>>> survival = Operator(Matrix([[1, 0], [0, sqrt(0.8)]]))
>>> lk = Kraus([survival, lossy])
>>> lk.hasloss()
True
>>> lk.lossoperators()
[1-qubit LossyOperator (lossy=(1,)):
├── 0 0
└── 0 0.447213595499958]
>>> lk.survivaloperators()
[1-qubit Operator:
├── 1 0
└── 0 0.894427190999916]
>>> lk.losseffect()
1-qubit Operator:
├── 0.0 + 0.0*I 0.0 + 0.0*I
└── 0.0 + 0.0*I 0.2 + 0.0*I
>>> # symbolic parameters are substituted with evaluate
>>> x = Symbol("x")
>>> g = Kraus([Projector0(), Projector1(x)])
>>> g
Kraus(P₀(1), P₁(x))
>>> g.evaluate({x: 1})
Kraus(P₀(1), P₁(1))
evaluate(values)[source]

Return a copy with symbols substituted by values.

The normalization check runs again on the result when it is fully numeric, with the default tolerance.

Parameters:

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

Returns:

A new channel with substituted operators.

Return type:

Kraus

Raises:

ValueError – If the substituted operators do not fulfill \(\sum_k E_k^\dagger E_k = I\).

krausoperators()[source]

Return the Kraus operators, in the order they were given.

hasloss()[source]

Whether any Kraus operator is a LossyOperator.

Same result as haslossybranch().

lossoperators()[source]

Return the Kraus operators that are LossyOperator, in order.

survivaloperators()[source]

Return the Kraus operators that are not LossyOperator, in order.

losseffect(tol=1e-12)[source]

Compute the loss-probability operator over all lossy branches.

This returns the operator

\[\Lambda = \sum_k L_k^\dagger L_k,\]

where \(L_k\) runs over the LossyOperator branches of the channel.

\(\Lambda\) is a positive semidefinite operator whose diagonal entries give the loss probabilities for each computational basis state. For a basis state \(|i\rangle\),

\[\langle i|\Lambda|i\rangle\]

is the probability that \(|i\rangle\) leaks out of the computational subspace. For a general state \(|\psi\rangle\), the total loss probability is \(\langle\psi|\Lambda|\psi\rangle\).

The survival and lossy operators together satisfy

\[\sum_k S_k^\dagger S_k + \Lambda = I,\]

where \(S_k\) are the non-lossy branches.

If the channel has no lossy operators, the zero matrix is returned.

Parameters:

tol – Entries with absolute value below tol are set to zero (default 1e-12).

Returns:

\(\Lambda\) as a numeric Operator.

Return type:

Operator

Raises:

RuntimeError – If a lossy operator has symbolic entries.

See also

Kraus, lossoperators(), survivaloperators()

Examples

>>> from mimiqcircuits import *
>>> from symengine import Matrix, sqrt
>>> g = Kraus([Matrix([[1, 0], [0, sqrt(0.9)]]),
...            LossyOperator(Matrix([[0, 0], [0, sqrt(0.1)]]))])
>>> g.losseffect()
1-qubit Operator:
├── 0.0 + 0.0*I 0.0 + 0.0*I
└── 0.0 + 0.0*I 0.1 + 0.0*I
__str__()[source]

String representation, listing either AbstractOperators or matrix slices.

unwrappedkrausmatrices()[source]

Return the Kraus matrices; same as krausmatrices().

class DiagonalOp(a, b)[source]

Bases: AbstractOperator

One-qubit diagonal operator.

Matrix Representation

\[\begin{split}\begin{pmatrix} a & 0 \\ 0 & b \end{pmatrix}\end{split}\]

The operator does not have to be unitary. Use it in an ExpectationValue or as a Kraus operator.

Parameters:
  • a – The top-left entry, a real number or a symbolic expression.

  • b – The bottom-right entry, a real number or a symbolic expression.

Raises:

ValueError – If a or b is neither a real number nor a symbolic expression.

See also

Operator, Projector0, Projector1

Examples

>>> from mimiqcircuits import *
>>> DiagonalOp(1, 0.5)
D(1, 0.5)
>>> # expectation value on qubit 1, stored in z-variable 2
>>> c = Circuit()
>>> c.push(ExpectationValue(DiagonalOp(1, 0.5)), 1, 2)
2-qubit, 3-zvar circuit with 1 instruction:
└── ⟨D(1, 0.5)⟩ @ q[1], z[2]
property parnames

Names of the operation’s parameters, as a tuple of strings.

Read-only: assigning to it raises ValueError.

opsquared()[source]

Return \(O^\dagger O\), the diagonal operator with entries \(|a|^2\) and \(|b|^2\).

class SigmaPlus(a=1)[source]

Bases: AbstractOperator

One-qubit operator corresponding to \(|1 \rangle\langle 0|\).

Matrix Representation

\[\begin{split}\begin{pmatrix} 0 & 0\\ a & 0 \end{pmatrix}\end{split}\]

The factor a scales the operator, for example to add a phase. The operator is not unitary, so it cannot be applied to a circuit directly; use it in an ExpectationValue or as a Kraus operator.

Parameters:

a (complex) – Scaling factor. Defaults to 1.

See also

SigmaMinus

Examples

>>> from mimiqcircuits import *
>>> SigmaPlus()
SigmaPlus(1)
>>> SigmaPlus(0.5)
SigmaPlus(0.5)
>>> # expectation value on qubit 1, stored in z-variable 1
>>> c = Circuit()
>>> c.push(ExpectationValue(SigmaPlus()), 1, 1)
2-qubit, 2-zvar circuit with 1 instruction:
└── ⟨SigmaPlus(1)⟩ @ q[1], z[1]
property parnames

Names of the operation’s parameters, as a tuple of strings.

Read-only: assigning to it raises ValueError.

property num_qubits

Number of qubits the operation acts on.

Read-only: assigning to it raises ValueError.

opsquared()[source]

Return \(O^\dagger O = |a|^2 |0\rangle\langle 0|\) as a Projector0.

class SigmaMinus(a=1)[source]

Bases: AbstractOperator

One-qubit operator corresponding to \(|0 \rangle\langle 1|\).

Matrix Representation

\[\begin{split}\begin{pmatrix} 0 & a\\ 0 & 0 \end{pmatrix}\end{split}\]

The factor a scales the operator, for example to add a phase. The operator is not unitary, so it cannot be applied to a circuit directly; use it in an ExpectationValue or as a Kraus operator.

Parameters:

a (complex) – Scaling factor. Defaults to 1.

See also

SigmaPlus

Examples

>>> from mimiqcircuits import *
>>> SigmaMinus()
SigmaMinus(1)
>>> SigmaMinus(0.5)
SigmaMinus(0.5)
>>> # expectation value on qubit 1, stored in z-variable 1
>>> c = Circuit()
>>> c.push(ExpectationValue(SigmaMinus()), 1, 1)
2-qubit, 2-zvar circuit with 1 instruction:
└── ⟨SigmaMinus(1)⟩ @ q[1], z[1]
property parnames

Names of the operation’s parameters, as a tuple of strings.

Read-only: assigning to it raises ValueError.

property num_qubits

Number of qubits the operation acts on.

Read-only: assigning to it raises ValueError.

opsquared()[source]

Return \(O^\dagger O = |a|^2 |1\rangle\langle 1|\) as a Projector1.