Skip to content

Reference: QPU Class

QPU Class

psiqworkbench.QPU

QPU(pre_filters=None, filters=None, post_filters=None, num_qubits=None)

Bases: BaseQPU

The QPU class serves as the interface between your quantum programs and a quantum processing unit (QPU), whether simulated or physical. It is central to the operation of the PsiQ Workbench and manages resources, parameters, and filters for quantum computation.

This class facilitates the allocation and management of qubits, configuration of simulation or execution parameters, and integration with various filters to process quantum operations.

Attributes:

Name Type Description
debug_check_ops bool

Flag for enabling debugging checks on operations (default is False).

Example

Creating a QPU object and configuring its parameters:

from psiqworkbench import QPU

# Initialize a QPU instance
qc = QPU(num_qubits=4)

# Set random seed for the simulator
qc.set_param('random_seed', 42)

# Perform quantum operations
qc.had()
Notes
  • A QPU object must be instantiated at the beginning of a Workbench program.
  • To improve efficiency during loops, prefer calling QPU.write(0) to reuse existing qubits rather than resetting or creating a new QPU object.
  • The QPU instance supports parameter configuration via the QPU.set_param method.

For more details, see QPU Object tutorial.

Parameters:

Name Type Description Default
pre_filters list

Filters to be applied before the main operation chain. Default is None.

None
filters list

Main filters to process quantum operations. Default includes ['>>state-vector-sim>>', '>>buffer>>'].

None
post_filters list

Filters to be applied after the main operation chain. Default is None.

None
num_qubits int or None

Number of qubits allocated to the QPU instance.

None

effective_rotation_epsilon property

effective_rotation_epsilon: float

Currently active rotation epsilon for this QPU.

all_qubits_mask property

all_qubits_mask

Get a bitmask representing all qubits in the QPU.

This property generates a bitmask where each bit corresponds to a qubit in the QPU, with all bits set to 1. The bitmask covers all qubits from 0 to num_qubits - 1.

Returns:

Type Description
int

A bitmask with all qubits set to 1 (i.e., (1 << num_qubits) - 1).

set_qubit_logic_operator

set_qubit_logic_operator(symbol, qubrick)

Provide a qubrick to be used by logical and arithmetic operations on Qubits objects, replacing the default.

Symbol Operation Default Qubrick
'==' compare equal CompareEQ
'!=' compare not equal CompareNE
'~' bitwise invert CondInvert
'^' bitwise xor CondXor
'<' compare less-than CompareLT
'>' compare greater-than CompareGT
'<=' compare less-than-or-equal CompareLE
'>=' compare greater-than-or-equal CompareGE
'+=' in-place add NaiveAdd
'-=' in-place subtract NaiveAdd

Parameters:

Name Type Description Default
symbol str

The operator to replace.

required
qubrick Qubrick

The Qubrick to be called when this operator is invoked.

required

override_rotation_epsilon

override_rotation_epsilon(epsilon: float)

Temporarily override rotation precision using epsilon for this QPU context.

Parameters:

Name Type Description Default
epsilon float

Additive error.

required

start_cost_event

start_cost_event(cost: dict[str, Any], target: Qubits | int = 0) -> None

Adds a QPU event into the opstream that indicates the start of a black-box cost.

Parameters:

Name Type Description Default
cost dict

A dictionary containing information about costs.

required
target Qubits | int

(Qubits | int): The Qubits the cost corresponds to. Defaults to 0.

0
Example

This functionality allows users to wrap gates in a cost:

cost = {"loop_count": 5, "success_probability": 0.75}
qc.start_cost_event(cost)
# some gates here
qc.end_cost_event(cost)

end_cost_event

end_cost_event(cost: dict[str, Any], target: Qubits | int = 0) -> None

Adds a QPU event into the opstream that indicates the end of a black-box cost.

Parameters:

Name Type Description Default
cost dict

A dictionary containing information about costs.

required
target Qubits | int

(Qubits | int): The Qubits the cost corresponds to. Defaults to 0.

0
Example

This functionality allows users to wrap gates in a cost:

cost = {"loop_count": 5, "success_probability": 0.75}
qc.start_cost_event(cost)
# some gates here
qc.end_cost_event(cost)

add_cost_event

add_cost_event(cost: dict[str, Any], target: Qubits | int = 0) -> None

Convenience method for adding black-box costs into the QPU opstream.

For more details, see Getting Basic Numeric Resource Estimates tutorial.

Parameters:

Name Type Description Default
cost dict

A dictionary containing information about costs.

required
target Qubits | int

(Qubits | int): The Qubits the cost corresponds to. Defaults to 0.

0
Example

To register a cost event, typically used to track resource metrics, such as:

cost = {"loop_count": 5, "success_probability": 0.75}
qc.add_cost_event(cost)

start_capture

start_capture(execute_ops_while_capturing: bool = False) -> QPUCapture

Convenience function to start capturing QPU operations.

Parameters:

Name Type Description Default
execute_ops_while_capturing bool

If True, continue executing operations while capturing.

False

Returns:

Type Description
QPUCapture

An instance of the capture session.

end_capture

end_capture(cap: QPUCapture) -> QPUCapture

Conveience function to end a capture session and finalize the captured operations.

Parameters:

Name Type Description Default
cap QPUCapture

The capture session to end.

required

Returns:

Type Description
QPUCapture

The ended capture session.

playback_capture

playback_capture(cap: QPUCapture, dagger: bool = False) -> None

Convenience function to playback a previously captured QPU operation sequence.

Parameters:

Name Type Description Default
cap QPUCapture

The capture session to playback.

required
dagger bool

If True, playback the operations in reverse order (dagger mode).

False

push_filter

push_filter(filter: OpFilter) -> OpFilter

Push a filter onto the beginning of the filter pipeline.

Parameters:

Name Type Description Default
filter OpFilter

The filter to push onto the pipeline.

required

Returns:

Type Description
OpFilter

The filter object which got pushed

pop_filter

pop_filter(need_flush: bool = False) -> OpFilter

Pop a filter from the beginning of the filter pipeline.

Parameters:

Name Type Description Default
need_flush bool

Flush the filter pipeline before removing this filter.

False

Returns:

Type Description
OpFilter

The filter object which got popped

remove_all_filters

remove_all_filters() -> None

Remove all filters from the filter pipe. Normally there should be at least one filter (the QPU) to execute instructions.

append_filter

append_filter(handler: OpFilter | type[OpFilter]) -> None

Add a filter to the filter pipe.

Parameters:

Name Type Description Default
handler OpFilter instance or type

Append a single filter to the filter pipe.

required

get_filters

get_filters(format: Literal['name'] | None = None)

Get a list of the current filters.

Parameters:

Name Type Description Default
format str

'name' to just get a list of filter names rather than objects.

None

filter_instructions

filter_instructions(instructions, filters)

Apply filters to a list of instructions, returning the result.

Parameters:

Name Type Description Default
instructions list[QPUOp]

The instructions to filter.

required
filters list[OpFilter]

Filters to apply on the instructions.

required

event_start

event_start(label=None, event_info=None, target_mask=0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Start of a high-level function event, like a Qubrick compute/uncompute. These are used for resource estimation, tracking, and profiling.

Parameters:

Name Type Description Default
label str

A label for the event.

None
event_info dict

The event information (type, critical info, etc).

None
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

0
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0
Note

If the following conditions are met at the same time:

  • label is None
  • event_info is not None
  • event_info does not contain qubricks key

then event_info has to contain name key, and the corresponding value will be used for deriving a label for this event.

event_end

event_end(event_info, target_mask=0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

End of a high-level function event, like a Qubrick compute/uncompute. These are used for resource estimation, tracking, and profiling.

Parameters:

Name Type Description Default
event_info dict

The event information (type, critical info, etc).

required
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

0
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0
Note

If event_info does not contain a qubrick key, then event_info must contain name, and the corresponding value will be used to infer a label for this event.

nop

nop(target_mask=0, if_flag=0, repeat=1)

Issue a qpu.nop() instruction.

This instruction performs no action and is used promarily for spacing in circuit diagrams.

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1

0

cnot

cnot(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Alias for psiqworkbench.QPU.x. Deprecated and will be removed in WB 5.0.0. Use QPU.x instead.

phase

phase(theta, target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0, decompose_common_angles=True)

Apply a phase rotation gate by angle θ to specified qubit(s).

The phase gate is represented by the matrix:

\[ \text{Phase}(\theta) = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\theta} \end{pmatrix} \]

Special Cases (if decompose_common_angles=True):

Angle Gate Rotation
45° T gate π/4 rotation
90° S gate π/2 rotation
180° Z gate π rotation
-45° T-dagger gate -π/4 rotation
-90° S-dagger gate -π/2 rotation

Target/Control Rules:

Targets (nt) Controls (nc) Action
nt=0 nc=0 No action
nt=0 nc>0 1 controlled-Z rotation using all controls
nt>0 nc=0 Single-qubit Z rotation on each target
nt>0 nc>0 nt controlled-Z rotations using all controls

Parameters:

Name Type Description Default
theta float | RotationAngle | tuple[int, int]

The rotation angle in degrees (or (theta * units.rad) for radians, or (num,denom) for fraction of pi).

required
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0
error_param int

If non-zero, approximates rotation by truncating angle. Defaults to 0 (ideal rotation).

0
decompose_common_angles bool

Use standard gates (S,T,Z) for common angles. Defaults to True.

True
Note

Differs from rz() by global phase in simulation with no filters. phase() is 2x faster than rz() in this case.

rx

rx(theta, target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Apply an RX rotation gate to specified qubit(s).

This gate applies a rotation of theta around the X-axis, represented by the unitary matrix:

\[ R_x(\theta) = \begin{bmatrix} \cos(\theta/2) & -i\sin(\theta/2) \\ -i\sin(\theta/2) & \cos(\theta/2) \end{bmatrix} \]

Parameters:

Name Type Description Default
theta float | RotationAngle | tuple[int, int]

The rotation angle in degrees (or (theta * units.rad) for radians, or (num,denom) for fraction of pi).

required
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. Defaults to 0 (none).

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit information for the backend.

0
caddr int

Internal use only. Extra control qubit information for the backend.

0
error_param int

If 0, applies an ideal rotation. Otherwise, approximates the rotation based on error_param. Defaults to 0.

0

ry

ry(theta, target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Apply an RY rotation gate to specified qubit(s).

This gate applies a rotation of theta around the Y-axis, represented by the unitary matrix:

\[ R_y(\theta) = \begin{bmatrix} \cos(\theta/2) & -\sin(\theta/2) \\ \sin(\theta/2) & \cos(\theta/2) \end{bmatrix} \]

Parameters:

Name Type Description Default
theta float | RotationAngle | tuple[int, int]

The rotation angle in degrees (or (theta * units.rad) for radians, or (num,denom) for fraction of pi).

required
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. Defaults to 0 (none).

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit information for the backend.

0
caddr int

Internal use only. Extra control qubit information for the backend.

0
error_param int

If 0, applies an ideal rotation. Otherwise, approximates the rotation based on error_param. Defaults to 0.

0

rz

rz(theta, target_mask=~0, condition_mask=0, precision_bits=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Apply an RZ rotation gate to specified qubit(s).

This gate applies a rotation of theta around the Z-axis, represented by the unitary matrix:

\[ R_z(\theta) = \begin{bmatrix} e^{-i\theta/2} & 0 \\ 0 & e^{i\theta/2} \end{bmatrix} \]

Parameters:

Name Type Description Default
theta float | RotationAngle | tuple[int, int]

The rotation angle in degrees (or (theta * units.rad) for radians, or (num,denom) for fraction of pi).

required
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. Defaults to 0 (none).

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit information for the backend.

0
caddr int

Internal use only. Extra control qubit information for the backend.

0
error_param int

If 0, applies an ideal rotation. Otherwise, approximates the rotation based on error_param. Defaults to 0.

0

crx

crx(theta, target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Alias for psiqworkbench.QPU.rx. Deprecated and will be removed in WB 5.0.0. Use QPU.rx instead.

cry

cry(theta, target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Alias for psiqworkbench.QPU.ry. Deprecated and will be removed in WB 5.0.0. Use QPU.ry instead.

crz

crz(theta, target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Alias for psiqworkbench.QPU.rz. Deprecated and will be removed in WB 5.0.0. Use QPU.rz instead.

ppr

ppr(theta, x_mask, z_mask, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, error_param=0)

Apply a Pauli Product Rotation (PPR) to the specified qubits.

The applied unitary operator is as follows:

\[ \text{PPR}(\theta) = \cos(\theta)I - i\sin(\theta) \left(\bigotimes_{j \in \text{x_mask}} X_j \right) \left(\bigotimes_{k \in \text{z_mask}} Z_k \right) \]

Here:

  • \(X_j\) represents a Pauli-X operation on qubit \(j\).

  • \(Z_k\) represents a Pauli-Z operation on qubit \(k\).

Parameters:

Name Type Description Default
theta float | RotationAngle | tuple[int, int]

The rotation angle in degrees (or (theta * units.rad) for radians, or (num,denom) for fraction of pi).

required
x_mask qubit mask

Bitmask specifying the qubits for Pauli-X operations.

required
z_mask qubit mask

Bitmask specifying the qubits for Pauli-Z operations.

required
condition_mask qubit mask

Bitmask specifying control qubits for conditional execution. Defaults to 0 (no controls).

0
cond_xor_mask int

Bitmask to XOR with condition_mask for conditional execution. Defaults to 0 (none).

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Additional target qubit information for the backend.

0
caddr int

Internal use only. Additional condition qubit information for the backend.

0
error_param int

If non-zero, the gate angle is approximated based on this parameter. Defaults to 0 (ideal rotation).

0

ppm_async

ppm_async(sign, x_mask, z_mask, if_flag=0, set_flag=0, taddr=0, caddr=0)

Issue a qpu.ppm() instruction asynchronously. This instruction applies a Pauli product measurement (PPM) to the specified qubits. The result is available asynchronously.

The operation measures the product of the Pauli X and Z operators on the qubits specified by x_mask and z_mask.

Parameters:

Name Type Description Default
sign int

The sign of the operator measured. If -1, the eigenvalue measurement result is flipped.

required
x_mask qubit mask

The X-operation mask.

required
z_mask qubit mask

The Z-operation mask.

required
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
set_flag int

If specified, the flag index to store the result of the measurement.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Returns:

Type Description
AsyncReadResult

The asynchronous read result.

ppm

ppm(sign, x_mask, z_mask, if_flag=0, set_flag=0, taddr=0, caddr=0)

Issue a qpu.ppm() instruction and block until the result is ready.

The Pauli Product Measurement (PPM) measures the observable associated with the operator:

\[ M = \left(\bigotimes_{j \in \text{x_mask}} X_j \right) \left(\bigotimes_{k \in \text{z_mask}} Z_k \right) \]

Here:

  • \(X_j\) is the Pauli-X operator acting on qubit \(j\).

  • \(Z_k\) is the Pauli-Z operator acting on qubit \(k\).

Parameters:

Name Type Description Default
sign int

The sign of the operator measured. If -1, the eigenvalue measurement result is flipped.

required
x_mask qubit mask

The bitmask specifying the qubits for the Pauli-X operation.

required
z_mask qubit mask

The bitmask specifying the qubits for the Pauli-Z operation.

required
if_flag int

If nonzero, apply this operation only if the flag has been evaluated to 1.

0
set_flag int

If specified, the flag index to store the result of the measurement.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Returns:

Type Description
int

The result of the Pauli product measurement: either 0 (for +1 eigenvalue) or 1 (for -1 eigenvalue).

pcp

pcp(all_masks, if_flag=0, taddr=0, caddr=0)

Issue a qpu.pcp() instruction.

This instruction applies a Pauli operation (P1) conditioned on another Pauli operation (P2), where the ops are specified by x and z masks as with PPRs and PPMs. The two Pauli operators must be applied on disjoint sets of qubits (otherwise some qubits would be acting as both target and control, which makes no sense), so a check is made that the masks that specify which qubits each operator is applied on do not overlap and an error is raised if this check fails.

Parameters:

Name Type Description Default
all_masks list

A list of pairs of masks, where each pair contains the qubit masks for the P1 and P2 operators.

required
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0

Raises:

Type Description
ValueError

If the masks do not commute.

lelbow

lelbow(target_mask, condition_mask, cond_xor_mask=0, if_flag=0, set_flag=0, taddr=0, caddr=0)

Issue a qpu.lelbow() instruction (Gidney left elbow) to perform an approximate Toffoli gate with deferred phase correction, optimizing T gate usage in fault-tolerant quantum computing.

In traditional quantum circuits, Toffoli gates (controlled-controlled-NOT gates) are expensive to implement because they require 7 T gates, which are costly in fault-tolerant quantum computing. Gidney introduced the concept of "elbows" as part of a method to halve the T gate cost of a quantum adder. The left elbow (lelbow) applies a Toffoli operation up to a controlled-phase error, allowing intermediate calculations without immediate correction to reduce the total T gate count.

For more details, see Non-standard Gates and Measurements tutorial.

References
  • Craig Gidney, Halving the cost of quantum addition
  • Cody Jones, Low-overhead constructions for the fault-tolerant Toffoli gate

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

required
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

required
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
set_flag int

If specified, the flag index to store the result of the measurement.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

relbow

relbow(target_mask, condition_mask, cond_xor_mask=0, if_flag=0, set_flag=0, taddr=0, caddr=0)

Issues a qpu.relbow() instruction (Gidney right elbow).

In traditional quantum circuits, Toffoli gates (controlled-controlled-NOT gates) are expensive to implement because they require 7 T gates, which are costly in fault-tolerant quantum computing. Gidney introduced the concept of "elbows" as part of a method to halve the T gate cost of a quantum adder. The right elbow (relbow) follows the left elbow (lelbow) by using a measurement and classically conditioned Z to remove the phase error only when necessary. This approach enables intermediate calculations without immediate correction, thus reducing the total T gate count.

For more details, see Non-standard Gates and Measurements tutorial.

References
  • Craig Gidney, Halving the cost of quantum addition
  • Cody Jones, Low-overhead constructions for the fault-tolerant Toffoli gate

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

required
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

required
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
set_flag int

If specified, the flag index to store the result of the measurement.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Returns:

Type Description
AsyncReadResult

The asynchronous read result for the measurement.

relbow_async

relbow_async(target_mask, condition_mask, cond_xor_mask=0, if_flag=0, set_flag=0, taddr=0, caddr=0)

Gidney right elbow is always async, so we provide both entry points. The read value is almost never needed.

Deprecated and will be removed in WB 5.0.0. Use QPU.relbow instead.

x

x(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a Pauli-X gate (quantum NOT) to the specified qubit(s).

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. Allows conditioning on (condition_mask | cond_xor_mask). Defaults to 0.

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Provides extra target qubit information to the backend.

0
caddr int

Internal use only. Provides extra condition qubit information to the backend.

0

y

y(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a Pauli-Y gate to the specified qubit(s).

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. Allows conditioning on (condition_mask | cond_xor_mask). Defaults to 0.

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Provides extra target qubit information to the backend.

0
caddr int

Internal use only. Provides extra condition qubit information to the backend.

0

z

z(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a Pauli-Z gate to the specified qubit(s).

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. Allows conditioning on (condition_mask | cond_xor_mask). Defaults to 0.

0
if_flag int

If nonzero, applies the gate only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Provides extra target qubit information to the backend.

0
caddr int

Internal use only. Provides extra condition qubit information to the backend.

0

identity

identity(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply an identity operation (I) to the specified qubit(s).

The identity gate leaves the state of the qubit(s) unchanged.

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask for flexible conditioning. This allows conditioning on (condition_mask | cond_xor_mask). Defaults to 0.

0
if_flag int

If nonzero, applies the operation only if the flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Provides extra target qubit information to the backend.

0
caddr int

Internal use only. Provides extra condition qubit information to the backend.

0

s

s(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply an S (π/2 phase rotation) gate to specified qubit(s).

The S gate applies a π/2 phase rotation, represented by the matrix:

\[ S = \begin{bmatrix} 1 & 0 \\ 0 & e^{i\pi/2} \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & i \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

t

t(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a T (π/4 phase rotation) gate to specified qubit(s).

The T gate is represented by the matrix:

\[ T = \begin{bmatrix} 1 & 0 \\ 0 & e^{i\pi/4} \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

s_inv

s_inv(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply an inverse S gate (-π/2 phase rotation) to specified qubit(s).

The inverse S gate is represented by the matrix:

\[ S^\dagger = \begin{bmatrix} 1 & 0 \\ 0 & e^{-i\pi/2} \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & -i \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

t_inv

t_inv(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply an inverse T gate (-π/4 phase rotation) to specified qubit(s). The inverse T gate is represented by the matrix:

\[ T^\dagger = \begin{bmatrix} 1 & 0 \\ 0 & e^{-i\pi/4} \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & \frac{1}{\sqrt{2}}(1 - i) \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

had

had(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a Hadamard gate to specified qubit(s).

The Hadamard gate is represented by the matrix:

\[ H = \frac{1}{\sqrt{2}} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

hadamard

hadamard(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Alias for psiqworkbench.QPU.had. Deprecated and will be removed in WB 5.0.0. Use QPU.had instead.

chad

chad(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Alias for psiqworkbench.QPU.had. Deprecated and will be removed in WB 5.0.0. Use QPU.had instead.

cz

cz(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Alias for psiqworkbench.QPU.z. Deprecated and will be removed in WB 5.0.0. Use QPU.z instead.

cx

cx(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Alias for psiqworkbench.QPU.x. Deprecated and will be removed in WB 5.0.0. Use QPU.x instead.

rootx

rootx(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a square root of X gate to specified qubit(s).

This gate is a π/2 rotation around the X-axis, represented by the matrix:

\[ \sqrt{X} = \frac{1}{2} \begin{bmatrix} 1+i & 1-i \\ 1-i & 1+i \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

rootx_inv

rootx_inv(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply an inverse square root of X gate to specified qubit(s).

This gate is a -π/2 rotation around the X-axis, represented by the matrix:

\[ \sqrt{X}^\dagger = \frac{1}{2} \begin{bmatrix} 1-i & 1+i \\ 1+i & 1-i \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

rooty

rooty(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply a square root of Y gate to specified qubit(s).

The square root of Y gate is a π/2 rotation around the Y-axis, represented by the matrix:

\[ \sqrt{Y} = \frac{1}{2} \begin{bmatrix} 1+i & -1+i \\ 1+i & 1-i \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

rooty_inv

rooty_inv(target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Apply an inverse square root of Y gate to specified qubit(s).

This gate is a -π/2 rotation around the Y-axis, represented by the matrix:

\[ \sqrt{Y}^\dagger = \frac{1}{2} \begin{bmatrix} 1-i & -1-i \\ 1-i & 1+i \end{bmatrix} \]

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits (~0).

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 (none).

0
cond_xor_mask int

Bitmask to XOR with condition_mask. For conditioning on (condition_mask | cond_xor_mask). Defaults to 0 (none).

0
if_flag int

If nonzero, only apply if flag evaluates to 1. Defaults to 0.

0
taddr int

Internal use only. Extra target qubit info for backend.

0
caddr int

Internal use only. Extra condition qubit info for backend.

0

get_instructions

get_instructions(filter=None, str_format=None, format=None, filters=None)

Get instructions stored by a stream, optionally using a filter.

print_instructions

print_instructions(instructions=None, str_format=None, format=None)

Print instructions stored by a stream, optionally using a filter.

to_serializable

to_serializable(*, dialect='native') -> dict[str, Any]

Convert this QPU instance to a serializable object.

The contents of the returned dictionary are determined by the specified dialect. Workbench implements only one dialect ("native") by default, which produces a dictionary with the following keys:

  • registers: All registers that were ever allocated, including all slices and composites that were referenced by any operation.
  • used_symbols: All symbols used in the program so far. This key is included only if the QPU is in symbolic mode.
  • operations: All operations (QPU instructions and Qubrick events) performed so far.

Additional dialects may be provided by external plugins. For details on the returned data format of such dialects, refer to the documentation of the respective plugin or package.

Parameters:

Name Type Description Default
dialect str

The dialect that determines the format of the returned data. Defaults to "native".

'native'

Returns:

Type Description
dict[str, Any]

A dictionary consisting only of built-in Python types that can be serialized to JSON.

Raises:

Type Description
ValueError

If the specified dialect cannot be found.

Note
  • New dialects can be registered for use with this method by creating a setuptools plugin under the group: psiqworkbench.serialization.dialect.
  • For more information about the plugin system, see the psiqworkbench.serialization module.
Example

Converting a QPU instance to a serializable dictionary:

    qpu = QPU()
    serializable_dict = qpu.to_serializable(dialect="native")

serialize

serialize(file: str | Path | TextIOBase, *, dialect: str = 'native', format: str | None = None) -> None
serialize(*, format: str, dialect: str = 'native') -> str
serialize(file: str | Path | TextIOBase | None = None, *, dialect: str = 'native', format: str | None = None)

Serialize this QPU instance using the given dialect and format.

Parameters:

Name Type Description Default
file str | Path | TextIO | None

A file into which the serialized content should be written, given either as a file-like object or a path. If a path is passed, the file will be opened with "wt" flags. If None, the QPU will be serialized to a string.

None
dialect str

A dialect determining the contents of the serialized data. Defaults to "native".

'native'
format Optional[str]

Name of the format that should be used for serialization. If not provided, an attempt will be made to infer the correct format based on the file's name. Must not be None if file is None.

None

Returns:

Type Description
Optional[str]

If file is None, a serialized string. Otherwise, None.

Raises:

Type Description
ValueError

If either the selected dialect or format does not exist, or if both format and file are None.

enable_qubit_allocation_debugging

enable_qubit_allocation_debugging(enable: bool = True)

Enable/disable detection of qubit allocation/release anomalies.

If enabled, raises an error if the qubits are released without being measured or returned to the |0⟩ state first.

Parameters:

Name Type Description Default
enable bool

True to enable, False to disable.

True

enable_time_log

enable_time_log(enabled: bool = True)

Enable/disable filter pipe time logging (required for QPU.draw_timing_diagram()).

Parameters:

Name Type Description Default
enabled bool

True to enable, False to disable.

True

reset

reset(num_qubits, num_block_qubits=0, max_ram_size_gb=0, max_num_threads=0, randomized=False, use_opencl=False, _async=True, verbose=False)

Set the number of qubits and initialize the QPU.

This method resets the QPU, setting the number of qubits and initializing the state. It also configures parameters for simulation such as memory usage, threading, and randomization.

Parameters:

Name Type Description Default
num_qubits int

The number of qubits to request. For simulations, the required RAM size is approximately \(16 \cdot 2^n\) bytes, where \(n\) is the number of qubits.

Rules of thumb:

  • 10 qubits = 16 kB
  • 20 qubits = 16 MB
  • 30 qubits = 16 GB
  • 40 qubits = 16 TB
required
num_block_qubits int

The number of block qubits to allocate. Default is 0.

0
max_ram_size_gb int

The maximum allowable RAM size for the simulation in gigabytes. This acts as a safety limit. If the number of qubits requested exceeds the allowed RAM, the request will fail. Default is 0 (no limit).

0
max_num_threads int

The maximum number of threads to use for simulation. Default is 0 (automatically determined based on system capabilities).

0
randomized bool

If True, randomize the initial state of the QPU. Note that for large QPUs (more than 32 qubits), this may take a significant amount of time. Default is False.

False
use_opencl bool

If True, enable OpenCL for acceleration. Default is False.

False
_async bool

Whether to initialize the QPU asynchronously. Default is True.

True
verbose bool

If True, enable verbose logging during initialization. Default is False.

False

Raises:

Type Description
RuntimeError

If num_qubits is not provided or set to zero.

Note

For QPU simulations, ensure your system has sufficient RAM to handle the requested number of qubits.

Example

Resetting a QPU with 10 qubits:

from psiqworkbench import QPU

qc = QPU()
qc.reset(10)

metrics

metrics(metric_names=None, *, symbolic_metrics: bool | None = None, cost_functions: list[Callable[[WitnessCounter, dict, dict], dict]] | None = None, aggregate_functions: list[Callable[[dict], dict]] | None = None, expanded_costs: bool = False, filters: list[str | OpFilter] | None = None, verbose: bool | None = None) -> dict[str, int | float]

Returns a dictionary containing the numerical costs for the QPU program.

Parameters:

Name Type Description Default
metric_names deprecated

Formally used to specify which metrics to return. DEPRECATED AND TO BE REMOVED IN WB 5.0.0.

None
symbolic_metrics deprecated

Whether to use an expanded format for returned costs. DEPRECATED AND TO BE REMOVED IN WB 5.0.0 - USE expanded_costs INSTEAD FOR BACKWARDS-COMPATIBLE BEHAVIOR.

None
cost_functions list[Callable[[WitnessCounter, dict, dict], dict]] | None

Functions that act on a WitnessCounter object and derive costs from the witnessed QPU ops.

None
aggregate_functions list[Callable[[dict], dict]] | None

Functions that act on a dictionary of costs and produce second order costs (e.g. "aggregated_measurements", which is the sum of qc.read and qc.ppm ops).

None
expanded_costs bool

Whether to return a simplified set of costs ( "t_count", "toffoli_count", "rotation_count", "clifford_count", "rotation_count", "measurement_count", "total_num_ops"and"active_volume") or to return the full set of costs calculated. Defaults toFalse`, corresponding to the simplified costs.

False
filters list[str | OpFilter] | None

Filters to use to decompose non-countable ops (such as 5-controlled Toffolis for example). Defaults to None.

None
verbose bool | None

Whether to print out debugging info when calling the function. Defaults to False.

None

metrics_stack

metrics_stack(*, cost_functions: list[Callable[[WitnessCounter, dict, dict], dict]] | None = None, aggregate_functions: list[Callable[[dict], dict]] | None = None, expanded_costs: bool = False, filters: list[str | OpFilter] | None = None, verbose: bool | None = None) -> dict[str, int | float]

Returns a dictionary containing the numerical costs for the QPU program.

Parameters:

Name Type Description Default
cost_functions list[Callable[[WitnessCounter, dict, dict], dict]] | None

Functions that act on a WitnessCounter object and derive costs from the witnessed QPU ops.

None
aggregate_functions list[Callable[[dict], dict]] | None

Functions that act on a dictionary of costs and produce second order costs (e.g. "aggregated_measurements", which is the sum of qc.read and qc.ppm ops).

None
expanded_costs bool

Whether to return a simplified set of costs ( "t_count", "toffoli_count", "rotation_count", "clifford_count", "rotation_count", "measurement_count", "total_num_ops"and"active_volume") or to return the full set of costs calculated. Defaults toFalse`, corresponding to the simplified costs.

False
filters list[str | OpFilter] | None

Filters to use to decompose non-countable ops (such as 5-controlled Toffolis for example). Defaults to None.

None
verbose bool | None

Whether to print out debugging info when calling the function. Defaults to False.

None

flush

flush(until_flag_resolved=None)

Stall until all QPU instructions have finished executing. Any filters with buffer windows must empty them.

Stalling is slow, and typically only used for test and debugging.

Parameters:

Name Type Description Default
until_flag_resolved int

If not None, just flush until the QPU evaluates the given flag.

None

connect

connect(address, port, timeout=60.0 * 30.0)

Connect to a remote filter pipeline, if a >>connect>> filter is in the pipeline.

Parameters:

Name Type Description Default
address int

The address of the remote (use 0.0.0.0 or localhost for local).

required
port int

The port to connect to (the one the remote is listening on).

required
timeout float

Time in seconds to wait for responses (connections, status, measurements, etc) before giving up.

60.0 * 30.0

disconnect

disconnect()

Disconnect from a remote filter pipeline.

get_status

get_status(filters=None)

Get some info from the stream components.

Parameters:

Name Type Description Default
filters list of str, or None

If not empty, only return results from specified handlers.

None

get_filter_by_name

get_filter_by_name(name, first_only=True)

Get the named filter from the chain.

Parameters:

Name Type Description Default
name str

The name of the filter to find.

required
first_only bool

Whether to fetch the first handler in the chain if True, or a list of all matching handlers if False.

True

Returns:

Type Description
OpFilter or list of OpFilter or None

The handler instance or list of instances if found, otherwise None.

get_filters_of_type

get_filters_of_type(filter_type)

Get all filters of a specific type from the chain.

Parameters:

Name Type Description Default
filter_type type

The type of filters to find.

required

get_param

get_param(param_name)

Get a parameter from the QPU.

Built-in params:

  • 'random_seed' (int): Seed for random operations.

set_param

set_param(param_name, param_value)

Set a parameter on the QPU.

Built-in params:

  • 'random_seed' (int): Seed for random operations.

random_seed

random_seed(seed: int)

Set the random seed of the QPU.

Same as set_param('random_seed', seed). Used for simulation only.

Parameters:

Name Type Description Default
seed int

The seed to use for the random number generator.

required

label

label(label: str = '')

Apply a label to any subsequent ops.

Parameters:

Name Type Description Default
label str

The label to apply, or '' or None to un-apply (clear) the label.

''

box

box(box_label='', target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, cs_key=0)

High-level function box, like a label, but with target and condition qubits. Two identical box calls will cause a box to be drawn between them.

Parameters:

Name Type Description Default
box_label str

The label to apply.

''
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Inputs are the same as target_mask. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

error

error(label='', target_mask=~0, if_flag=0, taddr=0, caddr=0)

If this instruction is executed by a backend filter, raise an error.

Parameters:

Name Type Description Default
label str

The error message.

''
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

box_open

box_open(box_label='', target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, cs_key=0)

High-level function box, like a label, but with target and condition qubits. Two identical box calls will cause a box to be drawn between them.

Parameters:

Name Type Description Default
box_label str

The label to apply.

''
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

box_close

box_close(box_label='', target_mask=~0, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0, cs_key=0)

High-level function box, like a label, but with target and condition qubits. Two identical box calls will cause a box to be drawn between them.

Parameters:

Name Type Description Default
box_label str

The label to apply.

''
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

pull_state

pull_state(with_qreg_labels: bool = False, with_qreg_types: bool = True, flush: bool = True)

Pull the entire state vector into a numpy array and return it.

This does not change the state. This is used for simulation only.

Parameters:

Name Type Description Default
with_qreg_labels bool

If True, returns a two-element dictionary, with 'qregs' element storing the tuple of labels of all allocated Qubits registers and 'amps' element storing the dictionary of basis state labels and their amplitudes.

False
with_qreg_types bool

If True, takes into account the type of Qubits registers (integer vs fixed-point and signed vs unsigned) to generate basis state labels. If False, treats all Qubits registers as unsigned integers.

True
flush bool

Flush all instructions before pulling the state vector.

True

pull_state_specific

pull_state_specific(target_qubits, normalize=True, message_list=[], flush=True)

Pull the state data into Python for a specific set of qubits.

This is used for simulation only.

Parameters:

Name Type Description Default
flush bool

Flush all instructions before pulling the state vector

True

peek_read_probability

peek_read_probability(value: int, target_mask: int = ~0, flush: bool = True, stop_at: float = 0.0)

Peek at the read probability of a specific value on the qubits specified by the target mask.

This function retrieves the probability of reading a specific value (bitstring) from the qubits specified by the target_mask. It does this via a non-projective inspection of the statevector and does not change the statevector. It checks if the value is within the bounds of the mask and optionally flushes the operation pipeline before retrieving the probability.

This is used for simulation only.

Parameters:

Name Type Description Default
value int

The value (bitstring) whose read probability is to be queried.

required
target_mask int

A bitmask indicating the target qubits to measure. Defaults to all qubits.

~0
flush bool

If True, flush the pipeline before reading the probability. Defaults to True.

True
stop_at float

If the probability is greater than stop_at, return as quickly as possible with stop_at or greater (used for zero-checking)

0.0

Returns:

Type Description
float

The probability of reading the specified value on the target qubits, or None if no stream head is available.

Raises:

Type Description
ValueError

If the value contains bits outside the target_mask.

postselect

postselect(value: int, target_mask: int = ~0, flush: bool = True)

Perform a non-random postselected read of the desired value, collapsing the state appropriately. If there is no non-zero amplitude term matching the specified value, raise an exception.

This is used for simulation only.

Parameters:

Name Type Description Default
value int

Desired "read" value of each qubit.

required
target_mask int

If specified, which bits to "read".

~0
flush bool

If True, flush all instructions before doing this. (Almost always desired.)

True

peek_n_biggest_terms

peek_n_biggest_terms(num_terms: int, flush: bool = True)

Pull the terms and indices with the largest probabilities as a sorted list.

This does not change the state. This is used for simulation only.

Parameters:

Name Type Description Default
num_terms int

The number of terms to retrieve.

required
flush bool

Flush all instructions before pulling the state vector.

True

peek_value

peek_value(index: int, flush: bool = True)

Get the complex amplitude of the indicated term.

This does not change the state. This is used for simulation only.

Parameters:

Name Type Description Default
index int

The term to retrieve.

required
flush bool

Flush all instructions before pulling the state vector.

True

push_state

push_state(src_buffer, normalize=True, flush=True, target_qubits=0)

Push a partial or entire state vector from a numpy array.

If target_qubits is zero, the array must have the same number of terms as the state (2 ** num_qubits). If target_qubits is nonzero, the array must have the same number of terms as (2 ** number_of_qubits_being_pushed).

This is used for simulation only.

Parameters:

Name Type Description Default
src_buffer ndarray[float | complex]

The amplitudes of all terms to push.

required
normalize bool

Whether to normalize the state after pushing. Defaults to True.

True
flush bool

Whether to flush the filter pipeline. Defaults to True.

True
target_qubits int or Qubits

Specific sub-state to push into. If zero, push the whole state.

0

check_state

check_state(src_buffer, epsilon=1e-06, require_same_global_phase=False, max_to_print=100, flush=True)

Check to see if each term in the current state matches the passed-in state, within epsilon.

This is used for simulation only.

Parameters:

Name Type Description Default
src_buffer numpy array of float or complex

The state to check against.

required
epsilon float

The maximum difference to allow.

1e-06
require_same_global_phase bool

If False, allow states to differ by a global phase.

False
max_to_print int

Maximum number of differing terms to print before giving up.

100
flush bool

If True, finish all QPU instructions before checking the state.

True

normalize

normalize()

Normalize the current QPU state.

This is used for simulation only.

mask_to_qubits

mask_to_qubits(mask, mask_xor=0)

Convert a mask into a Qubits object on the current QPU, with not-conditions if provided.

jump_fwd

jump_fwd(target_id=None, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Issue a forward jump instruction in the QPU program. Useful for loops.

This function creates a forward jump to a specified or automatically determined target based on conditions and optional XOR masks.

Parameters:

Name Type Description Default
target_id int

The ID of the target jump. If None, the next available jump target ID is used.

None
condition_mask int

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Returns:

Type Description
int

The target jump ID.

jump_fwd_target

jump_fwd_target(target_id=None, if_flag=0, taddr=0, caddr=0)

Mark the destination of a previously issued forward jump. Useful for loops.

This function marks the location in the QPU program to which a forward jump will jump.

Parameters:

Name Type Description Default
target_id int

The ID of the target jump. If None, the next available jump target ID is used.

None
if_flag int

If nonzero, the jump target is marked only if this flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Returns:

Type Description
int

The target jump ID.

jump_back

jump_back(target_id=None, condition_mask=0, cond_xor_mask=0, if_flag=0, max_num_loops=0, taddr=0, caddr=0)

Issue a backward jump instruction in the QPU program. Useful for loops.

This function creates a backward jump to a specified or automatically determined target based on conditions and optional XOR masks. It also enforces a loop count for safety.

Parameters:

Name Type Description Default
target_id int

The ID of the target jump. If None, the next available jump target ID is used.

None
condition_mask int

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
max_num_loops int

The maximum number of loops before the jump is invalidated.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Raises:

Type Description
ValueError

If max_num_loops is zero, which prevents infinite loops.

Returns:

Type Description
int

The target jump ID.

jump_back_target

jump_back_target(target_id=None, if_flag=0, max_num_loops=0, taddr=0, caddr=0)

Mark the destination of a previously issued backward jump. Useful for loops.

This function marks the location in the QPU program to which a backward jump will return. It also includes an optional maximum jump length.

Parameters:

Name Type Description Default
target_id int

The ID of the target jump. If None, the next available jump target ID is used.

None
if_flag int

If nonzero, the jump target is marked only if this flag has been evaluated to 1.

0
max_num_loops int

The maximum number of loops before the jump is invalidated.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Returns:

Type Description
int

The target jump ID.

read_async

read_async(target_mask=~0, result=None, if_flag=0, set_flag=None, taddr=0, caddr=0, qint=None, target_xor=0, fallback_read=None)

Perform an asynchronous measurement (read) of the specified qubits.

This function reads the state of the qubits specified by the target mask asynchronously. The result is returned later, allowing other operations to proceed in the meantime.

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
result any

Deprecated; not used and will be removed in WB 5.0.0.

None
if_flag int

Conditional execution flag. The read operation is performed only if this flag is set to 1.

0
set_flag int

If specified, the flag index to store the measurement result.

None
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0
qint optional

Quantum integer to store the result of the read.

None
target_xor int

Bitmask to XOR with the target qubits before reading.

0

Returns:

Type Description
AsyncReadResult

An object that represents the result of the asynchronous read operation.

read

read(target_mask=~0, result=None, if_flag=0, set_flag=None, taddr=0, caddr=0, as_index_list=False, target_xor=0, fallback_read=None)

Perform a synchronous measurement (read) of the specified qubits.

This function reads the state of the qubits specified by the target mask and returns the result immediately.

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
result any

Deprecated; not used and will be removed in WB 5.0.0.

None
if_flag int

Conditional execution flag. The read operation is performed only if this flag is set to 1.

0
set_flag int

If specified, the flag index to store the measurement result.

None
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0
as_index_list bool

If True, returns the measurement result as a list of indices where qubits are 1.

False
target_xor int

Bitmask to XOR with the target qubits before reading.

0

Returns:

Type Description
int or list

The measurement result as an integer or a list of qubit indices if as_index_list is True.

write

write(value, target_mask=~0, if_flag=0, set_flag=0, taddr=0, caddr=0, typed_val=0)

Perform a write operation on the specified qubits. Uses the READ operation followed by the NOT operation.

This function writes the specified value to the target qubits.

Parameters:

Name Type Description Default
value int

The value to write to the qubits.

required
target_mask int or list or Qubits

The qubits to write to. Defaults to all qubits.

~0
if_flag int

Conditional execution flag. The write operation is performed only if this flag is set to 1.

0
set_flag int

If specified, the flag index to store the result of the measurement.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0
typed_val float

The typed value provided by the user.

0

pps

pps(x_mask, z_mask, flush=True)

This function is equivalent to peek_ppm_probability().

Parameters:

Name Type Description Default
x_mask int

A bitmask indicating the qubits to measure in the X-basis.

required
z_mask int

A bitmask indicating the qubits to measure in the Z-basis.

required
flush bool

If True, flush the pipeline before reading the probabilities. Defaults to True.

True

Returns:

Type Description
float

The probability result of the specified Pauli product measurements.

peek_ppm_probability

peek_ppm_probability(x_mask, z_mask, flush=True)

Peek at the Pauli product measurement (PPM) outcome probability for specified qubits.

This function is equivalent to pps() and retrieves the probability of a Pauli product measurement on the qubits specified by the X and Z masks returning 0.

Parameters:

Name Type Description Default
x_mask int

A bitmask indicating the qubits to measure in the X-basis.

required
z_mask int

A bitmask indicating the qubits to measure in the Z-basis.

required
flush bool

If True, flush the pipeline before reading the probabilities. Defaults to True.

True

Returns:

Type Description
float

The probability of the specified Pauli product measurement returning 0.

swap

swap(target_mask, condition_mask=0, cond_xor_mask=0, if_flag=0, taddr=0, caddr=0)

Issue a qpu.swap() instruction (same as swap()). This instruction applies a controlled SWAP operation, exchanging the states of the two target qubits if and only if the control qubit(s) are in the |1⟩ state.

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

required
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0
if_flag int

If nonzero, apply this op only if the flag has been evaluated to 1.

0
taddr int

Used to send extra target qubit information to the backend. Only used internally.

0
caddr int

Used to send extra condition qubit information to the backend. Only used internally.

0

Raises:

Type Description
ValueError

If fewer or more than two target qubits are specified.

reverse_bits

reverse_bits(target_mask=~0, condition_mask=0, cond_xor_mask=0)

Reverse the bits of the quantum register for the given target mask.

This method reverses the order of bits in the quantum register, based on the provided target mask. It selectively swaps qubits in pairs, which can be useful for certain quantum algorithms that rely on bit-reversed indexing.

Parameters:

Name Type Description Default
target_mask qubit mask

The target qubit(s). Defaults to all qubits ~0.

~0
condition_mask qubit mask

The control qubit(s). Defaults to 0 which is none.

0
cond_xor_mask int

Bitmask to apply XOR with condition mask. E.g. if you want to condition on the bitfield (condition_mask | cond_xor_mask), use this. Defaults to 0 which is none.

0

The function identifies bits from the target_mask that should be reversed, and swaps pairs of them in the quantum register.

print_stream_setup

print_stream_setup()

Print the filters attached to the current QPU.

set_random

set_random(flush=True)

Set the quantum state to a random value. if you use this in a test, you should set qc.random_seed(<some value>) beforehand to give deterministic results for pipelines.

This is used for simulation only.

Parameters:

Name Type Description Default
flush bool

If True, flush the pipe before setting the state.

True

finish

finish()

Complete all pending operations on the QPU.

This function signals the QPU to finalize and complete any outstanding operations, ensuring that all tasks are finished.

clear_instructions

clear_instructions(filter=None)

Clear instructions stored in a stream, so that it becomes empty.

Parameters:

Name Type Description Default
filter OpFilter or None

If provided, only flush from this filter down.

None

draw_timing_diagram

draw_timing_diagram(filename=None)

Generate and draw a timing diagram for the current stream of QPU operations.

This function generates a visual timing diagram representing the execution of operations on the QPU. The diagram can be saved to a file.

Parameters:

Name Type Description Default
filename str

The path to the file where the timing diagram should be saved. If None, the diagram is displayed without saving.

None

put_instructions

put_instructions(instructions, filters=None, remap_allocations=False)

Send instructions to the QPU, applying optional filters and remapping allocations.

This function processes and sends instructions to the QPU. It can convert instructions from trace or JSON formats, remap qubit allocations, and apply filters before sending them to the filter pipeline.

Parameters:

Name Type Description Default
instructions list, dict, or str

The instructions to send, which can be in list form, a trace dictionary, or JSON format.

required
filters list

A list of filters to apply to the instructions before execution.

None
remap_allocations bool

If True, remap the qubit allocations before sending the instructions.

False

Raises:

Type Description
AssertionError

If the string provided for instructions is not in JSON format and cannot be converted.

draw

draw(filename=None, instructions=None, filter=None, filters=None, show_qubricks=False, show_allocs=True, show_write_vals=True, format: str = 'svg')

Export enough info to create the diagram.

Parameters:

Name Type Description Default
filename str or None

Save to an SVG file with a given name.

None
instructions list[QPUop] or None

The program to draw.

None
filter StreamHandler or None

If instructions is None, get them from this filter.

None
filters list[OpFilter]

Apply these compilation filters before drawing.

None
show_qubricks bool

If True, include Qubrick boxes in the diagram.

False
show_allocs bool

If True, include qubit allocation/release tags in the diagram.

True
show_write_vals bool

If True, include qubit write-values in the diagram.

True
format str

The desired output format (currently only 'svg' is supported).

'svg'

print_probabilities

print_probabilities(qregs=None, line=-1, min_value_to_print=1e-10, max_num_values=1000, show_unallocated_qubits=True, show_entangled=True, with_qreg_types=True, flush=True) -> None

Prints a human-readable representation of the probabilities of the basis states of the quantum state vector.

Parameters:

Name Type Description Default
qregs list of Qubits or None

Optional list of qubit registers to display. If None, shows all allocated qubits.

None
line int

Line number to print (for debugging). Default is -1.

-1
min_value_to_print float

Minimum absolute amplitude value to display. Default is 1e-10.

1e-10
max_num_values int

Maximum number of state vector entries to print. Default is 1000.

1000
show_unallocated_qubits bool

Whether to show unallocated qubits. Default is True.

True
show_entangled bool

Whether to show qubits that are not included in qregs, but are entangled with qregs, in the probabilities. Default is True.

True
with_qreg_types bool

Whether to show the state vector as the actual values of the register types, or only as an integer value representation, default is True.

True
flush bool

Whether to flush the operation pipeline before printing. Default is True.

True

print_state_vector

print_state_vector(qregs=None, line=-1, min_value_to_print=1e-10, max_num_values=1000, show_unallocated_qubits=True, show_entangled=True, with_qreg_types=True, flush=True) -> None

Prints a human-readable representation of the quantum state vector.

Parameters:

Name Type Description Default
qregs list of Qubits or None

Optional list of qubit registers to display. If None, shows all allocated qubits.

None
line int

Line number to print (for debugging). Default is -1.

-1
min_value_to_print float

Minimum absolute amplitude value to display. Default is 1e-10.

1e-10
max_num_values int

Maximum number of state vector entries to print. Default is 1000.

1000
show_unallocated_qubits bool

Whether to show unallocated qubits. Default is True.

True
show_entangled bool

Whether to show qubits that are not included in qregs, but are entangled with qregs, in the state vector. Default is True.

True
with_qreg_types bool

Whether to show the state vector as the actual values of the register types, or only as an integer value representation, default is True.

True
flush bool

Whether to flush the operation pipeline before printing. Default is True.

True

detect_entanglement

detect_entanglement(qregs=None)

Detects whether the specified qubits are entangled.

Parameters:

Name Type Description Default
qregs list of Qubits or None

Optional list of qubit registers to check for entanglement.

None

Returns:

Type Description
dict

Mapping of qubit register names to lists of entangled qubit register names. Each key is a qubit register name, and its value is a list of other qubit register names that are entangled with it.