Skip to content

Reference: Qubricks

Contents


Qubrick Class

psiqworkbench.Qubrick

Qubrick(name=None, **kwargs)

The base class for defining quantum computational units (Qubricks).

A Qubrick is a modular quantum algorithm component that provides:

  • Automatic uncomputation of quantum operations.
  • Management of temporary qubit registers and auxiliary qubits.
  • Customizable control flow with symbolic computations.
  • Resource estimation via Workbench.

For more details, see High-Level Routines: Qubricks tutorial.

Settings

  • do_gates: If True, implements actual quantum gates.
  • alloc_result: If True, places the result in a newly allocated register.
  • release_ancillae: If True, releases unused auxiliary qubits after uncompute.

Attributes:

Name Type Description
name str

The name of the Qubrick.

do_gates bool

Whether quantum gates should be executed.

show_allocated bool

If True, allocated qubits are displayed.

alloc_result bool

Whether the result is stored in an allocated register.

release_ancillae bool

Whether unused auxiliary qubits are released.

allow_multi_qubit_ctrl bool

If False, reduces multi-control gates to a single control.

debug_check bool

Enables debug checks for errors like overflows.

debug_check_warnings bool

If True, warnings are emitted for debug errors.

rotation_error_param float

The error parameter used for synthesized rotations.

dagger bool

Whether the Qubrick applies its dagger (inverse operation).

qc QPU or None

The associated QPU instance.

modifies_state_vector_directly bool

Whether the Qubrick modifies the state vector non-physically.

never_uncompute bool

If True, prevents automatic uncomputation.

use_custom_uncompute bool

If True, uses _uncompute() instead of auto-uncompute.

skip_recompute_playback bool

If True, disables gate playback during auto-recompute.

_cs_stack deque

Stack of QubrickComputeState instances.

Example

class Parity(Qubrick):
    def _compute(self, input_qreg):
        anc = self.alloc_temp_qreg(1, 'anc')
        self.set_result_qreg(anc)
        anc.lelbow(input_qreg[0])
        for bit in range(1, input_qreg.num_qubits):
            anc.x(input_qreg[bit])

qc = QPU(num_qubits=5)
reg = Qubits(4, "reg", qc)
parity = Parity()
with parity.computed(reg) as result:
    result.z()
Notes
  • The compute() and uncompute() methods handle execution logic.
  • Use computed() as a context manager for automatic uncompute.
  • Implements daggered operations if dagger=True.

Parameters:

Name Type Description Default
name str

A name for this Qubrick

None
**kwargs Any

Settings for this qubrick. A full list can be seen in the QubrickSettings dataclass.

{}

get_cs

get_cs()

Return the current QubrickComputeState off the stack.

Returns:

Type Description
QubrickComputeState

The current compute state.

get_qc

get_qc()

Get the QPU associated with this Qubrick.

alloc_temp_qreg

alloc_temp_qreg(num_qubits, name, release_after_compute=False, release_after_uncompute=True)

Allocates a temporary qubit register for use in compute().

This function:

  • Allocates a new Qubits register if not in symbolic mode.
  • Allocates a SymbolicQubits register if is_symbolic=True.
  • Handles automatic qubit release based on release_after_compute and release_after_uncompute.

For more details, see Auxiliary Qubit Management in Qubricks tutorial.

Parameters:

Name Type Description Default
num_qubits int or Parameter

Number of qubits to allocate.

required
name str

The name of the allocated register.

required
release_after_compute bool

If True, the qubits will be released after compute. Default is False.

False
release_after_uncompute bool

If True, the qubits will be released after uncompute. Default is True.

True

Returns:

Type Description
Qubits or SymbolicQubits

The allocated qubit register.

Raises:

Type Description
ValueError

If num_qubits <= 0, indicating an invalid allocation request.

set_result_qreg

set_result_qreg(qreg, name='result')

Set a named Qubits-based result, such as a comparison result or the output of a quantum addition. This may be a newly-allocated register, or an existing register. Note that this is stored in the QubrickComputeState, so it's safe to use for deep Qubrick call stacks.

For more details, see Auxiliary Qubit Management in Qubricks tutorial.

Parameters:

Name Type Description Default
qreg Qubits

The Qubits register to set as the result.

required
name str

The name of the result param to set. Default is 'result', which is also returned by with computed() as.

'result'

get_result_qreg

get_result_qreg(name='result')

Get a named Qubits-based result, such as a comparison result or the output of a quantum addition. This may be a newly-allocated register, or an existing register. Note that this is stored in the QubrickComputeState, so it's safe to use for deep Qubrick call stacks.

For more details, see Auxiliary Qubit Management in Qubricks tutorial.

Parameters:

Name Type Description Default
name str

The name of the result param to get. Default is 'result', which is also returned by with computed() as.

'result'

set_classical_result

set_classical_result(result_data, name='result')

Set a named classical result, such as measurement results, to be returned from the compute() call. Note that this is stored in the QubrickComputeState, so it's safe to use for deep Qubrick call stacks.

Parameters:

Name Type Description Default
result_data Any

The value to set as the result.

required
name str

The name of the result param to set. Default is 'result'.

'result'

get_classical_result

get_classical_result(name='result')

Get a named classical result, such as measurement results from the compute() call. Note that this is stored in the QubrickComputeState, so it's safe to use for deep Qubrick call stacks.

Parameters:

Name Type Description Default
name str

The name of the result param to get. Default is 'result'.

'result'

get_input_qreg

get_input_qreg(name: str)

Get a named Qubits-based input which was passed at compute() call, such as the inputs to a quantum addition. Note that this is stored in the QubrickComputeState, so it's safe to use for deep Qubrick call stacks.

Parameters:

Name Type Description Default
name str

The name of the input to get.

required

set_debug_error

set_debug_error(regs, message, do_warning=True)

Indicate that an error has occurred.

Parameters:

Name Type Description Default
regs list of Qubits

The registers involved in the error.

required
message str

A description of the problem.

required

estimate

estimate(*args, **kwargs)

Alias for compute(), used when running in symbolic mode.

Parameters:

Name Type Description Default
*args Any

Positional arguments passed to _unestimate().

()
**kwargs Any

Keyword arguments passed to _unestimate().

{}

unestimate

unestimate(*args, **kwargs)

Alias for uncompute(), used when running in symbolic mode.

Parameters:

Name Type Description Default
*args Any

Positional arguments passed to _unestimate().

()
**kwargs Any

Keyword arguments passed to _unestimate().

{}

compute

compute(*args, **kwargs)

Executes the quantum computation defined by this Qubrick.

This method:

  • Calls _compute(*args, **kwargs) to apply the main quantum logic.
  • Manages temporary qubit registers automatically.
  • Handles symbolic computation when used in a resource estimation mode.

For more details, see High-Level Routines: Qubricks tutorial.

Parameters:

Name Type Description Default
*args Any

Positional arguments passed to _compute().

()
**kwargs Any

Keyword arguments passed to _compute().

{}

Example

parity = Parity()
qc = QPU(num_qubits=5)
reg = Qubits(4, "reg", qc)

parity.compute(reg)  # Apply the Qubrick computation
parity.uncompute()   # Uncompute it manually

Note: - If dagger=True, applies the inverse operation. - If do_gates=False, only visualizes the operation. - If symbolic mode is enabled, captures computation for analysis.

Best Practice

  • Prefer using computed() context manager when possible for automatic uncompute.

uncompute

uncompute(*args, **kwargs)

Automatically uncomputes the quantum operations applied during compute().

This function attempts to reverse the effects of compute() using one of the following methods:

  1. Simple Daggering (default): The recorded operations in compute_ops are reversed and executed.
  2. Custom Uncompute (if _uncompute() exists): A specialized _uncompute() method is called instead.
  3. Symbolic Uncompute (if is_symbolic=True): Calls _unestimate() instead of _uncompute().
  4. Never Uncompute (if never_uncompute=True): Raises an error if uncompute is called.

For more details, see Uncomputation Using Qubricks tutorial.

Parameters:

Name Type Description Default
*args Any

Deprecated and will be removed in WB 5.0.0 - Uncompute does not accept arguments.

()
**kwargs Any

Deprecated and will be removed in WB 5.0.0 - Uncompute does not accept keyword arguments.

{}

Raises:

Type Description
RuntimeError

If uncompute() is called without a matching compute().

RuntimeError

If never_uncompute=True is set for this Qubrick.

Example

parity = Parity()
parity.compute(input_qreg)
parity.uncompute()  # This reverses compute() operations

Automatic Uncompute Using computed()

with parity.computed(input_qreg) as result:
    result.z()  # Uncompute is called automatically when exiting the block
Note
  • If compute() used custom logic, _uncompute() is used instead.
  • If symbolic mode is active (is_symbolic=True), _unestimate() is used.
  • If never_uncompute=True, an error is raised instead of uncomputing.
  • If compute_ops is None, make_dagger_ops() is used to generate the inverse operations.

release_temp_qubits

release_temp_qubits(release_compute=True, release_uncompute=True)

Releases temporary qubit registers allocated during compute() and uncompute().

This function: - Ensures that no auxiliary qubits remain allocated after execution. - Releases temporary registers after compute and/or uncompute.

Parameters:

Name Type Description Default
release_compute bool

If True, releases qubits after compute(). Default is True.

True
release_uncompute bool

If True, releases qubits after uncompute(). Default is True.

True

Raises:

Type Description
RuntimeError

If called before compute() has started.

Notes - This function prevents qubit memory leaks. - If a qubit is still allocated at the end, a warning is raised.

computed

computed(*args, **kwargs)

Context manager for automatic computation and uncomputation.

When used in a with block, compute() is called upon entry and uncompute() is called upon exit.

For more details, see Uncomputation Context Manager tutorial.

Parameters:

Name Type Description Default
*args Any

Arguments to pass to compute().

()
**kwargs Any

Keyword arguments to pass to compute().

{}

Returns:

Type Description
AutoUncomputeBlock

A context manager that automatically uncomputes.

Example

with my_qubrick.computed(input_register) as result:
    result.z()
Note
  • Preferred over manually calling compute() and uncompute() for better readability and safety.

QubrickComputeState Class

psiqworkbench.qubricks.qubrick.QubrickComputeState

QubrickComputeState(qbk, compute_args)

Stores compute state information for a Qubrick instance.

Parameters:

Name Type Description Default
qbk Qubrick

The Qubrick instance associated with this compute state.

required
compute_args dict

Arguments passed to _compute().

required

Attributes:

Name Type Description
verbose bool

If True, enables debug-level printing for this compute state.

qbk Qubrick

The Qubrick instance that owns this compute state.

qc QPU

The associated quantum processing unit.

compute_args dict

The arguments passed to _compute() for this state.

dagger bool

Indicates if the Qubrick is daggered (inverse computation).

temp_qregs list[Qubits]

List of temporary qubit registers.

input_qregs dict[str, Qubits]

Dictionary mapping input register names to Qubits.

result_qregs dict[str, Qubits]

Dictionary storing result qubit registers.

result_qregs_by_alloc_name dict[str, Qubits]

Maps allocated register names to result qubits.

classical_results dict[str, Any]

Dictionary storing classical results (e.g. measurements).

compute_ops list

Stores quantum operations applied during compute().

dagger_ops list

Stores daggered (inverse) operations.

compute_iterations int

Number of times _compute() is executed.

debug_errors list[dict]

Stores debugging error messages with associated registers.

cs_key int

Unique identifier for this compute state, assigned by the QPU.

debug_errors list[dict]

Stores recorded debug errors encountered during execution.

result_qregs_by_alloc_name dict[str, Qubits]

Maps allocated register names to result registers.

compute_iterations int

The number of times the _compute() function has been called.

symbolics bool

If True, indicates that this computation is running in symbolic mode.

temp_qregs list[Qubits]

A list of temporary quantum registers allocated during computation.

input_qregs dict[str, Qubits]

Dictionary storing the input quantum registers.

classical_results dict[str, Any]

Stores classical results associated with the computation.

debug_errors list[dict]

A list of dictionaries recording debug errors and messages.

compute_ops list

The quantum operations executed during compute().

dagger_ops list

The corresponding dagger (inverse) operations for compute_ops.

cs_key int

A unique key assigned to track compute state in the QPU.

Note
  • Unallocated temporary registers are cleared before usage.
  • cs_key is used to track compute state events within the QPU.

is_symbolic property

is_symbolic: bool

Indicates whether QubrickComputeState operates in symbolic mode.

temp_qreg

temp_qreg(name)

Retrieves a temporary qubit register by name.

Parameters:

Name Type Description Default
name str

The name of the temporary qubit register.

required

Returns:

Type Description
Qubits or list[Qubits]
  • The requested qubit register if exactly one match is found.
  • A list of registers if multiple matches exist.
  • None if no matching register is found.

qreg

qreg(name)

Retrieves a qubit register by name, searching both temporary and input registers.

Parameters:

Name Type Description Default
name str

The name of the register to retrieve.

required

Returns:

Type Description
Qubits or None
  • The requested register if found.
  • None if no matching register exists.

get_all_qregs

get_all_qregs()

Retrieves all qubit registers used in the computation.

Returns:

Type Description
dict

A dictionary containing:

  • "input": A dictionary of input qubit registers.
  • "temp": A list of temporary qubit registers.

set_debug_error

set_debug_error(regs, message, do_warning=True)

Records an arithmetic error for debugging purposes.

Parameters:

Name Type Description Default
regs list of Qubits

The registers involved in the error.

required
message str

A description of the problem.

required
do_warning bool

If True, prints a warning. Default is True.

True
Note
  • Errors are stored inside the QubrickComputeState for debugging.
  • If do_warning=True, a warning is printed immediately.

get_debug_errors

get_debug_errors()

Retrieves a list of recorded debug errors.

Returns:

Type Description
list

A list of dictionaries containing:

  • "regs": The affected qubit registers.
  • "message": A description of the error.
Note
  • This function is used for debugging arithmetic errors.

alloc_temp_qreg

alloc_temp_qreg(num_qubits, name, release_after_compute=False, release_after_uncompute=True)

Allocates a temporary qubit register for use in compute().

This function:

  • Allocates a new Qubits register if not in symbolic mode.
  • Allocates a SymbolicQubits register if is_symbolic=True.
  • Handles automatic qubit release based on release_after_compute and release_after_uncompute.

Parameters:

Name Type Description Default
num_qubits int or Parameter

Number of qubits to allocate.

required
name str

The name of the allocated register.

required
release_after_compute bool

If True, the qubits will be released after compute. Default is False.

False
release_after_uncompute bool

If True, the qubits will be released after uncompute. Default is True.

True

Returns:

Type Description
Qubits or SymbolicQubits

The allocated qubit register.

Raises:

Type Description
ValueError

If num_qubits <= 0, indicating an invalid allocation request.

set_result_qreg

set_result_qreg(qreg, name='result')

Stores a Qubits-based computation result for later retrieval.

This function:

  • Assigns a result register that can be accessed after computation.
  • Tracks the register in self.result_qregs by name.

Parameters:

Name Type Description Default
qreg Qubits or None

The qubit register to store as a result.

required
name str

The name to assign to the result. Default is 'result'.

'result'

get_result_qreg

get_result_qreg(name='result')

Retrieves a Qubits-based result register stored during computation.

Parameters:

Name Type Description Default
name str

The name of the result register to retrieve. Default is 'result'.

'result'

Returns:

Type Description
Qubits or None

The stored result register, or None if not found.

set_classical_result

set_classical_result(result, name='result')

Stores a classical computation result for retrieval.

This function:

  • Assigns a classical result under a specific name.
  • Useful for storing measurement results or classical values.
  • Complements get_classical_result() for retrieval.

Parameters:

Name Type Description Default
result Any

The classical value to store.

required
name str

The name under which to store the result. Default is 'result'.

'result'
Note
  • If a classical result with the same name already exists, it is overwritten.

get_classical_result

get_classical_result(name='result')

Retrieves a named classical result stored during computation.

Parameters:

Name Type Description Default
name str

Name of the result parameter. Default is 'result'.

'result'

Returns:

Type Description
Any

The stored classical result, or None if not set.

Raises:

Type Description
RuntimeError

If called before compute() has started.

Note
  • If no result has been explicitly set, it falls back to the compute arguments.
  • Complements set_classical_result() for storing and retrieving classical data.