Skip to content

API Reference

bartiq

bartiq

Classes

CompiledRoutine dataclass

Bases: BaseRoutine[T]

Functions
filter_ports
filter_ports(
    directions: Iterable[str],
) -> dict[str, Port[T]]

Returns all the ports with given directions

from_qref classmethod
from_qref(
    qref_obj: AnyQrefType, backend: SymbolicBackend[T]
) -> CompiledRoutine[T]

Load CompiledRoutine from a QREF definition, using specified backend for parsing expressions.

to_qref
to_qref(backend: SymbolicBackend[T]) -> SchemaV1

Exports CompiledRoutine to QREF.

Parameters:

Name Type Description Default
backend SymbolicBackend[T]

backend used to serialize the symbolic expressions.

required

Returns:

Type Description
SchemaV1

QREF object representing provided routine.

Port dataclass

Bases: Generic[T]

Class for representing a port in a routine.

PortDirection

Bases: str, Enum

Class for representing port direction. This class is used to categorize ports in routines, such as input, output, and through ports.

Possible values
  • input: Represents an input Port for receiving data.
  • output: Represents an output Port for sending data.
  • through: Represents a through Port for passing data without modification.

ResourceType

Bases: str, Enum

Class for representing types of resources. This class is used to categorize resources in routines, such as time, energy, qubits, etc.

Possible values
  • additive: Represents an additive resource, such as time or energy.
  • multiplicative: Represents a multiplicative resource, such as qubits or gates.
  • qubits: Represents the number of qubits used in a Routine.
  • other: Represents any other resource type not covered by the above categories.

Routine dataclass

Bases: BaseRoutine[T]

Functions
filter_ports
filter_ports(
    directions: Iterable[str],
) -> dict[str, Port[T]]

Returns all the ports with given directions

from_qref classmethod
from_qref(
    qref_obj: AnyQrefType, backend: SymbolicBackend[T]
) -> Routine[T]

Load Routine from a QREF definition, using specified backend for parsing expressions.

to_qref
to_qref(backend: SymbolicBackend[T]) -> SchemaV1

Exports Routine to QREF.

Parameters:

Name Type Description Default
backend SymbolicBackend[T]

backend used to serialize the symbolic expressions.

required

Returns:

Type Description
SchemaV1

QREF object representing provided routine.

Functions

routine_to_qref

routine_to_qref(
    routine: Routine[T] | CompiledRoutine[T],
    backend: SymbolicBackend[T],
) -> SchemaV1

Exports a Routine or CompiledRoutine object to QREF.

Parameters:

Name Type Description Default
routine Routine[T] | CompiledRoutine[T]

routine to be exported.

required
backend SymbolicBackend[T]

backend used to serialize the symbolic expressions.

required

Returns:

Type Description
SchemaV1

QREF object representing provided routine.

compile_routine

compile_routine(
    routine: SchemaV1 | RoutineV1 | Routine[T],
    *,
    backend: SymbolicBackend[T] = sympy_backend,
    preprocessing_stages: Iterable[
        PreprocessingStage[T]
    ] = DEFAULT_PREPROCESSING_STAGES,
    postprocessing_stages: Iterable[
        PostprocessingStage[T]
    ] = DEFAULT_POSTPROCESSING_STAGES,
    derived_resources: Iterable[DerivedResources] = (),
    compilation_flags: CompilationFlags | None = None
) -> CompilationResult[T]

Performs symbolic compilation of a given routine.

In this context, compilation means transforming a routine defined in terms of routine-local variables into one defined in terms of global input parameters.

Parameters:

Name Type Description Default
routine SchemaV1 | RoutineV1 | Routine[T]

routine to be compiled.

required
backend SymbolicBackend[T]

a backend used for manipulating symbolic expressions.

sympy_backend
preprocessing_stages Iterable[PreprocessingStage[T]]

functions used for preprocessing of a given routine to make sure it can be correctly compiled by Bartiq.

DEFAULT_PREPROCESSING_STAGES
postprocessing_stages Iterable[PostprocessingStage[T]]

functions used for postprocessing of a given routine after compilation is done.

DEFAULT_POSTPROCESSING_STAGES
derived_resources Iterable[DerivedResources]

iterable with dictionaries describing how to calculate derived resources. Each dictionary should contain the derived resource's name, type and the function mapping a routine to the value of resource.

()
compilation_flags CompilationFlags | None

bitwise combination of compilation flags to tailor the compilation process; access these through the CompilationFlags object. By default None.

None

Raises:

Type Description
BartiqCompilationError

if the routine is not valid, or if the verification step fails.

evaluate

evaluate(
    compiled_routine: CompiledRoutine[T],
    assignments: Assignments[T],
    *,
    backend: SymbolicBackend[T] = sympy_backend,
    functions_map: FunctionsMap[T] | None = None
) -> EvaluationResult[T]

Substitutes variables into compiled routine.

Parameters:

Name Type Description Default
compiled_routine CompiledRoutine[T]

a compiled routine to be evaluated.

required
assignments Assignments[T]

a dictionary mapping a subset of input params of compiled_routine either into concrete values, or other expressions. Expressions can be provided either as concrete instances of symbolic expressions understood by backend, or via strings, e.g. `{"N": 2, "M": "k+3"}.

required
backend SymbolicBackend[T]

a backend used for manipulating symbolic expressions.

sympy_backend
functions_map FunctionsMap[T] | None

a dictionary mapping function names to their concrete implementations.

None

Returns:

Type Description
EvaluationResult[T]

A new instance of CompiledRoutine with appropriate substitutions made.

bartiq.analysis

bartiq.analysis

The bartiq analysis module provides methods to manipulate symbolic expressions.

Functions

sympy_rewriter

sympy_rewriter(
    expression: str | Expr,
) -> SympyExpressionRewriter

Initialize a Sympy rewriter instance.

Parameters:

Name Type Description Default
expression str | Expr

An expression to rewrite, either str or sympy.Expr.

required

Returns:

Type Description
SympyExpressionRewriter

An instance of the SympyExpressionRewriter.

bartiq.analysis.rewriters

bartiq.analysis.rewriters.expression

Base classes for rewriting symbolic expressions.

Classes

ExpressionRewriter dataclass

Bases: ABC, Generic[T]

An abstract base class for rewriting expressions.

Attributes:

Name Type Description
expression T

The expression of interest.

_original_expression T

Private attribute to store the original expression with no modifications. On initialisation, should be set to equal self.expression.

backend SymbolicBackend[T]

Which symbolic backend to use.

linked_symbols dict[str, Iterable[str]]

A dictionary of symbols that have been substituted in place of others. Helpful for tracking substitutions.

_previous tuple[Instruction, Self | None]

The tuple of the most recent Instruction applied and the rewriter instance it was applied to. By default (Initial(), None).

Attributes
assumptions property
assumptions: tuple[Assumption, ...]

Return all assumptions applied to this instance, in the order they were applied.

substitutions property
substitutions: tuple[Substitution, ...]

Return all substitutions applied to this instance, in the order they were applied.

original property
original: Self

Return a rewriter with the original expression, and no modifications.

free_symbols abstractmethod property
free_symbols: Iterable[T]

Return the free symbols in the expression.

individual_terms abstractmethod property
individual_terms: Iterable[T]

Return the expression as an iterable of individual terms.

Functions
history
history() -> list[Instruction]

Show a chronological history of all rewriter-transforming commands that have resulted in this instance of the rewriter.

Returns:

Type Description
list[Instruction]

A list of chronologically ordered Instructions, where index 0 corresponds to initialisation.

undo_previous
undo_previous(num_operations_to_undo: int = 1) -> Self

Undo a number of previous operations.

Rewinds the rewriter back to a previous instance.

Parameters:

Name Type Description Default
num_operations_to_undo int

The number of previous steps to undo, by default 1.

1

Returns:

Type Description
Self

A previous instance of the rewriter.

evaluate_expression
evaluate_expression(
    assignments: Mapping[str, TExpr[T]],
    functions_map: (
        Mapping[str, Callable[[TExpr[T]], TExpr[T]]] | None
    ) = None,
) -> TExpr[T]

Temporarily evaluate the expression.

This method does not store the result, and employs the 'substitute' method of the given backend.

Parameters:

Name Type Description Default
assignments Mapping[str, TExpr[T]]

A mapping of symbols to numeric values or expressions.

required
functions_map Mapping[str, Callable[[TExpr[T]], TExpr[T]]] | None

A mapping for user-defined functions in the expressions. By default None.

None

Returns:

Type Description
TExpr[T]

The expression with the evaluations applied.

focus abstractmethod
focus(symbols: str | Iterable[str]) -> T

Return an expression containing terms that involve specific symbols.

Parameters:

Name Type Description Default
symbols str | Iterable[str]

The symbols to focus on.

required

Returns:

Type Description
T

Subexpression of the overall expression, such that each term contains at least one of the input symbols.

expand
expand() -> Self

Expand all brackets in the expression.

simplify
simplify() -> Self

Run the backend `simplify' functionality.

assume
assume(assumption: str | Assumption) -> Self

Add an assumption for a symbol.

Parameters:

Name Type Description Default
assumption str | Assumption

Either str in the form X > a where X is a symbol or subexpression, and a is a scalar value; or Assumption dataclass. Valid comparators are >, <, >=, <=.

required
reapply_all_assumptions
reapply_all_assumptions() -> Self

Reapply all previously applied assumptions.

substitute
substitute(expr: str, replace_with: str) -> Self

Substitute a symbol or subexpression for another symbol or subexpression.

By default performs a one-to-one mapping. If a symbol in expr is prefaced with $, it is flagged as a wild symbol. Wild symbols match anything except zero values. These allow for global pattern substitutions, rather than one-to-one substitutions.

Parameters:

Name Type Description Default
expr str

The (sub)expression to substitute.

required
replace_with str

The replacement (sub)expression to substitute in.

required
with_instructions
with_instructions(
    instructions: Sequence[Instruction],
) -> Self

Apply a sequence of instructions.

Sequentially apply each instruction in the provided list to the expression, with each instruction being applied to the result of the previous one.

Parameters:

Name Type Description Default
instructions Sequence[Instruction]

A list of Instructions to apply in order. Each instruction will be applied to the result of the previous instruction.

required

Returns:

Type Description
Self

A new ExpressionRewriter instance with all instructions applied.

Examples:

Apply expand, simplify, and an assumption:

>>> rewriter.with_instructions(
...     [Expand(), Simplify(), Assumption("x>0")]
... )

bartiq.analysis.rewriters.sympy_expression

A rewriter class for SymPy expressions.

Classes

SympyExpressionRewriter dataclass

Bases: ExpressionRewriter[Expr]

Rewrite SymPy expressions.

This class accepts a SymPy expression as input, and provides methods for efficient simplification / rewriting of the input expression.

Attributes
original property
original: Self

Return a rewriter with the original expression, and no modifications.

Functions
get_symbol
get_symbol(symbol_name: str) -> Symbol | None

Get the SymPy Symbol object, given the Symbol's name.

If the symbol does not exist in the expression, return None.

Parameters:

Name Type Description Default
symbol_name str

Name of the symbol.

required

Returns:

Type Description
Symbol | None

A SymPy Symbol object, or None.

focus
focus(symbols: str | Iterable[str]) -> Expr | None

Focus on specific symbol(s), by only showing terms in the expression that include the input symbols.

Parameters:

Name Type Description Default
symbols str | Iterable[str]

symbol name(s) to focus on.

required

Returns:

Type Description
Expr | None

A SymPy expression whose terms include the input symbols. If none are found, returns None.

all_functions_and_arguments
all_functions_and_arguments() -> set[Expr]

Get a set of all unique functions and their arguments in the expression.

The returned set will include all functions at every level of the expression, i.e.

All functions and arguments of the following expression:

max(a, 1 - max(b, 1 - max(c, lamda)))
would be returned as:
{
    Max(c, lamda),
    Max(b, 1 - Max(c, lamda)),
    Max(a, 1 - Max(b, 1 - Max(c, lamda)))
}

Returns:

Type Description
set[Expr]

A set of unique functions that exist in the expression.

list_arguments_of_function
list_arguments_of_function(
    function_name: str,
) -> list[tuple[Expr, ...] | Expr]

Return a list of arguments X, such that each function_name(x) (for x in X) exists in the expression.

Parameters:

Name Type Description Default
function_name str

function name to return the arguments of.

required

Returns:

Type Description
list[tuple[Expr, ...] | Expr]

A list of arguments of the input function. If the function takes multiple arguments, they are returned as a tuple in the order they appear.

Functions

sympy_rewriter

sympy_rewriter(
    expression: str | Expr,
) -> SympyExpressionRewriter

Initialize a Sympy rewriter instance.

Parameters:

Name Type Description Default
expression str | Expr

An expression to rewrite, either str or sympy.Expr.

required

Returns:

Type Description
SympyExpressionRewriter

An instance of the SympyExpressionRewriter.

bartiq.compilation

bartiq.compilation

The compilation submodule contains routine compilation functionality.

Classes

CompilationFlags

Bases: Flag

A collection of compilation flags to modify compile_routine functionality.

Attributes
EXPAND_RESOURCES class-attribute instance-attribute
EXPAND_RESOURCES = auto()

Expand resource values into full, rather than transitive, expressions.

SKIP_VERIFICATION class-attribute instance-attribute
SKIP_VERIFICATION = auto()

Skip the verification step on the routine.

CompilationResult dataclass

Bases: Generic[T]

Datastructure for storing results of the compilation.

Attributes:

Name Type Description
routine CompiledRoutine[T]

compiled routine

_backend SymbolicBackend[T]

a backend used for manipulating symbolic expressions.

Functions
to_qref
to_qref() -> SchemaV1

Converts routine to QREF using _backend.

EvaluationResult dataclass

Bases: Generic[T]

Datastructure for storing results of the evaluation.

Attributes:

Name Type Description
routine CompiledRoutine[T]

evaluated routine

_backend SymbolicBackend[T]

a backend used for manipulating symbolic expressions.

Functions
to_qref
to_qref() -> SchemaV1

Converts routine to QREF using _backend.

Functions

compile_routine

compile_routine(
    routine: SchemaV1 | RoutineV1 | Routine[T],
    *,
    backend: SymbolicBackend[T] = sympy_backend,
    preprocessing_stages: Iterable[
        PreprocessingStage[T]
    ] = DEFAULT_PREPROCESSING_STAGES,
    postprocessing_stages: Iterable[
        PostprocessingStage[T]
    ] = DEFAULT_POSTPROCESSING_STAGES,
    derived_resources: Iterable[DerivedResources] = (),
    compilation_flags: CompilationFlags | None = None
) -> CompilationResult[T]

Performs symbolic compilation of a given routine.

In this context, compilation means transforming a routine defined in terms of routine-local variables into one defined in terms of global input parameters.

Parameters:

Name Type Description Default
routine SchemaV1 | RoutineV1 | Routine[T]

routine to be compiled.

required
backend SymbolicBackend[T]

a backend used for manipulating symbolic expressions.

sympy_backend
preprocessing_stages Iterable[PreprocessingStage[T]]

functions used for preprocessing of a given routine to make sure it can be correctly compiled by Bartiq.

DEFAULT_PREPROCESSING_STAGES
postprocessing_stages Iterable[PostprocessingStage[T]]

functions used for postprocessing of a given routine after compilation is done.

DEFAULT_POSTPROCESSING_STAGES
derived_resources Iterable[DerivedResources]

iterable with dictionaries describing how to calculate derived resources. Each dictionary should contain the derived resource's name, type and the function mapping a routine to the value of resource.

()
compilation_flags CompilationFlags | None

bitwise combination of compilation flags to tailor the compilation process; access these through the CompilationFlags object. By default None.

None

Raises:

Type Description
BartiqCompilationError

if the routine is not valid, or if the verification step fails.

evaluate

evaluate(
    compiled_routine: CompiledRoutine[T],
    assignments: Assignments[T],
    *,
    backend: SymbolicBackend[T] = sympy_backend,
    functions_map: FunctionsMap[T] | None = None
) -> EvaluationResult[T]

Substitutes variables into compiled routine.

Parameters:

Name Type Description Default
compiled_routine CompiledRoutine[T]

a compiled routine to be evaluated.

required
assignments Assignments[T]

a dictionary mapping a subset of input params of compiled_routine either into concrete values, or other expressions. Expressions can be provided either as concrete instances of symbolic expressions understood by backend, or via strings, e.g. `{"N": 2, "M": "k+3"}.

required
backend SymbolicBackend[T]

a backend used for manipulating symbolic expressions.

sympy_backend
functions_map FunctionsMap[T] | None

a dictionary mapping function names to their concrete implementations.

None

Returns:

Type Description
EvaluationResult[T]

A new instance of CompiledRoutine with appropriate substitutions made.

bartiq.symbolics

bartiq.symbolics

The symbolics submodule manages all implemented symbolic backends.

bartiq.errors

bartiq.errors

Classes

BartiqPreprocessingError

Bases: Exception

Raised for errors during Bartiq function pre-processing.

BartiqPostprocessingError

Bases: Exception

Raised for errors during Bartiq function post-processing.

BartiqCompilationError

Bases: Exception

Raised for errors during Bartiq function compilation.

bartiq.integrations

bartiq.integrations

The integrations submodule permits LaTeX pretty-printing, and implements Jupyter notebook widgets.

Functions

routine_to_latex

routine_to_latex(
    routine: SchemaV1 | RoutineV1,
    show_non_root_resources: bool = True,
    paged=False,
) -> str | list[str]

Returns a snippet of LaTeX used to render the routine using clear LaTeX.

Parameters:

Name Type Description Default
routine SchemaV1 | RoutineV1

The routine to render.

required
show_non_root_costs

If True (default), displays all costs, otherwise only includes costs from the root node.

required

Returns:

Type Description
str | list[str]

A LaTeX snippet of the routine.

bartiq.transform

bartiq.transform

Classes

Functions

postorder_transform

postorder_transform(
    transform: RoutineTransform[T, P]
) -> RoutineTransform[T, P]
postorder_transform(
    transform: CompiledRoutineTransform[T, P]
) -> CompiledRoutineTransform[T, P]
postorder_transform(transform)

Given a callable mapping a routine to a routine, expand it to transform hierarchical graph in postorder fashion.

This function is overloaded to handle different types of routines:

  • RoutineTransform: For working with Routine objects
  • CompiledRoutineTransform: For working with CompiledRoutine objects

Both overloads follow the same pattern: they traverse the hierarchical graph in postorder, applying the transform to each child before applying it to the parent.

Parameters:

Name Type Description Default
transform

A function accepting a routine and a symbolic backend and returning a new routine. The function signature varies based on the overload:

  • For Routine objects: (Routine[T], SymbolicBackend[T], *args, **kwargs) -> Routine[T]
  • For CompiledRoutine objects: (CompiledRoutine[T], SymbolicBackend[T], *args, **kwargs) -> CompiledRoutine[T]
required

Returns:

Type Description

A function with the same signature as transform. The function works by traversing the hierarchical graph in postorder, applying transform to each child before applying it to the parent.

Note

The postorder traversal ensures that child routines are processed before their parents, which is essential for bottom-up transformations where parent behavior depends on the transformed children.

add_aggregated_resources

add_aggregated_resources(
    routine: CompiledRoutine[T],
    aggregation_dict: AggregationDict[T],
    remove_decomposed: bool = True,
    backend: SymbolicBackend[T] = BACKEND,
) -> CompiledRoutine[T]

Add aggregated resources to bartiq routine based on the aggregation dictionary.

Parameters:

Name Type Description Default
routine CompiledRoutine[T]

The program to which the resources will be added.

required
aggregation_dict AggregationDict[T]

A dictionary that decomposes resources into more fundamental components along with their

required
remove_decomposed

Whether to remove the decomposed resources from the routine. Defaults to True.

True
backend

Backend instance to use for handling expressions. Defaults to sympy_backend.

BACKEND

Returns:

Type Description
CompiledRoutine[T]

The routine with aggregated resources added.

add_circuit_volume

add_circuit_volume(
    routine: CompiledRoutine[T],
    name_of_aggregated_t: str = "aggregated_t_gates",
    name_of_qubit_highwater: str = "qubit_highwater",
    backend: SymbolicBackend[T] = BACKEND,
) -> CompiledRoutine[T]

Add a 'circuit_volume' resource to a routine and its children.

This is calculated as

circuit_volume = aggregated_t_gates * qubit_highwater

Parameters:

Name Type Description Default
routine CompiledRoutine[T]

The compiled routine to which the resource will be added.

required
name_of_aggregated_t str

Name of the resource representing the number of T gates (default: 'aggregated_t_gates').

'aggregated_t_gates'
name_of_qubit_highwater str

Name of the resource representing the qubit highwater mark

'qubit_highwater'
(default

'qubit_highwater').

required
backend SymbolicBackend[T]

Symbolic backend to use for symbolic operations.

BACKEND

Returns:

Type Description
CompiledRoutine[T]

CompiledRoutine[T]: The routine with the 'circuit_volume' resource added to each subroutine.