Skip to content

API reference

bartiq

Connection

Bases: BaseModel

Connection between two ports.

Attributes:

Name Type Description
source Port

Port which the connection comes from.

target Port

Port the connection targets.

parent Optional[Routine]

Routine this connection belongs to. Note: it is marked as Optional only because of how Routine objects are internally constructed. In correctly constructed routines, no actual connection should have a None as a parent.

Port

Bases: BaseModel

Class representing a port.

Attributes:

Name Type Description
name _Name

Name of this port.

parent Optional[Routine]

Routine to which this port belongs to.

direction PortDirection

Direction of this port. Port can be either input, output or bidirectional.

size Optional[AnnotatedValue]

Size of this port. It might be a concrete value or a variable.

meta Optional[dict[str, Any]]

Additional free-form data associated with this port.

absolute_path

absolute_path(exclude_root_name: bool = False) -> str

Returns a path from root.

Parameters:

Name Type Description Default
exclude_root_name bool

If true, excludes name of root from the path. Default: False

False

PortDirection

Bases: str, Enum

Class for representing port direction.

Resource

Bases: BaseModel

Resource associated with a routine.

Attributes:

Name Type Description
name _Name

Name of the resource.

type ResourceType

Type of the resource.

parent Optional[Routine]

Routine whose resource this object represents.

value AnnotatedValue

Value of the resources, either concrete one or a variable.

ResourceType

Bases: str, Enum

Class for representing types of resources.

Routine

Bases: BaseModel

Subroutine in a quantum program.

Attributes:

Name Type Description
name _Name

Name of the subroutine.

type Optional[str]

Type of the subroutine, might be None.

ports dict[str, Port]

Dictionary mapping port name to corresponding Port object with the same name.

parent Optional[Self]

A Routine whose this routine is subroutine of. Might be None, in which case the routine is considered to be root of computation.

children dict[str, Routine]

Dictionary mapping name of subroutine of this routine into routine object with the same name.

connections list[Connection]

List of connections objects, containing all the directed edges between either ports of this routine and ports of its children or ports of two children. Importantly, by convention, connection objects cannot descend further then one generation (i.e. there might not be a connection between routine and its grandchild).

resources dict[str, Resource]

Dictionary mapping name of the resource to corresponding Resource object.

input_params Sequence[Symbol]

Sequence of symbols determining inputs for this routine.

local_variables dict[str, str]

Convenience aliases to expressions commonly used within this Routine. For instance, for a Routine with input parameter d one of the local variables can be N=ceil(log_2(d)).

linked_params dict[Symbol, list[tuple[str, Symbol]]]

Dictionary defining relations between parameters of this routine and parameters of its children. This dictionary is keyed with this routine's symbols, with the corresponding values being list of pairs (child, param) to which the symbol is connected to. Unlike connections, parameters links might descend further than one generation.

meta Optional[dict[str, Any]]

Addictional free-form information associated with this routine.

input_ports property

input_ports: dict[str, Port]

Dictionary of input ports of this routine.

is_leaf property

is_leaf: bool

Return True if this routine is a leaf, and false otherwise.

By the definition, a routine is a leaf iff it has no children.

is_root property

is_root: bool

Return True if this routine is a root, and false otherwise.

By the definition, a routine is a root iff it doesn't have a parent.

output_ports property

output_ports: dict[str, Port]

Dictionary of output ports of this routine.

absolute_path

absolute_path(exclude_root_name: bool = False) -> str

Returns a path from root.

Parameters:

Name Type Description Default
exclude_root_name bool

If true, excludes name of root from the path. Default: False

False

find_descendant

find_descendant(selector: str) -> Routine

Given a selector of a child, return the corresponding routine.

Parameters:

Name Type Description Default
selector str

a string comprising sequence of names determining the child. For instance, a string "a.b.c" mean child with name "c" of routine with name "b", which itself is a child of routine "a" which is a child of self. If empty string is provided, returns itself.

required

Returns:

Type Description
Routine

Routine corresponding to given selector.

Raises:

Type Description
ValueError

if given child is not found.

relative_path_from

relative_path_from(
    ancestor: Optional[Routine],
    exclude_root_name: bool = False,
) -> str

Return relative path to the ancestor.

Parameters:

Name Type Description Default
ancestor Optional[Routine]

Ancestor from which a relative path to self should be found.

required
exclude_root_name bool

if True, removes the name of the root from the relative path, if it is present.

False

Returns:

Type Description
str

selector s such that ancestor.find_descendant(s) is self.

Raises:

Type Description
ValueError

If ancestor is not, in fact, an ancestor of self.

walk

walk() -> Iterable[Self]

Iterates through all the ancestry, deep-first.

compile_routine

compile_routine(
    routine,
    *,
    backend=sympy_backend,
    precompilation_stages=None,
    global_functions=None,
    functions_map=None,
    skip_verification: bool = False
)

Compile estimates for given uncompiled Routine.

Parameters:

Name Type Description Default
routine

Routine to be compiled

required
backend

The backend to use for manipulating symbolic expressions. Defaults to sympy_backend.

sympy_backend
precompilation_stages

a list of precompilation stages which should be applied. If None, default precompilation stages are used.

None
global_functions

functions in the cost expressions which we don't want to have namespaced.

None
functions_map

a dictionary which specifies non-standard functions which need to applied during compilation.

None
skip_verification bool

if True, skips routine verification before and after compilation.

False

evaluate

evaluate(
    routine,
    assignments,
    *,
    backend=sympy_backend,
    functions_map=None
) -> Routine

Evaluates an estimate of a series of variable assignments.

Parameters:

Name Type Description Default
routine

Routine to evaluate. Note: this must have been compiled already.

required
assignments

A list of variable assignments, such as ['x = 10', 'y = 3.141'].

required
backend

A backend used for manipulating symbolic expressions.

sympy_backend
functions_map

A dictionary with string keys and callable functions as values. If any of the routines contains a function matching the key in this dict, it will be replaced by calling corresponding value of this dict.

None

Returns:

Type Description
Routine

A new estimate with variables assigned to the desired values.

bartiq.analysis

BigO

__init__

__init__(expr: Expr, variable: Optional[Symbol] = None)

Class for representing expressions in Big O notation.

It analyzes given expression and returns all the Big O terms in it. If variable is provided, it analyses scaling in this particular variable, otherwise it assumes all the symbols are variables.

Note

It's an experimental tool and is meant to facilitate the analysis, but it might not produce correct results, especially for more complicated expressions. In case of any problems please create an issue on project's GitHub, we'd love to hear your feedback on this!

Parameters:

Name Type Description Default
expr Expr

sympy expression we want to analyze

required
variable Optional[Symbol]

variable for which we want to performa analysis.

None

bartiq.precompilation

AddPassthroughPlaceholder

Adds placeholder routines whenever passthrough is detected.

Contrary to other precompilation methods, this one is stateful (and therefore implemented as a class), to ensure unique name and register size for each passhtrough.

add_passthrough_placeholders

add_passthrough_placeholders(
    routine: Routine, _backend: SymbolicBackend
) -> None

Detects when a passthrough occurs in given routine and removes it. Passthroughs are problematic for the compilation process and are removed by adding "identity routines". This changes the topology of the routine, but it functionally stays the same.

NOTE: To work properly it needs to be used before remove_non_root_container_input_register_sizes.

add_default_additive_resources

add_default_additive_resources(
    routine: Routine, _backend: SymbolicBackend
) -> None

Adds an additive resources to routine if any of the children contains them.

If given routine: - has children, - children have defined some additive resources - is missing some these resources, it adds the resource which is sum of the resources in subroutines.

add_default_properties

add_default_properties(
    routine: Routine,
    _backend: SymbolicBackend,
    defaults: Optional[DefaultsMap] = None,
) -> None

Adds a default resources/port sizes to a routine based on its type.

default_precompilation_stages

default_precompilation_stages()

Default suite of precompilation stages.

precompile

precompile(
    routine: Routine,
    backend: SymbolicBackend,
    precompilation_stages: Optional[
        list[PrecompilationStage]
    ] = None,
) -> Routine

A precompilation stage that transforms a routine prior to estimate compilation.

If no precompilation stages are specified, the following precompilation stages are performed by default (in order): 1. Adds default resources and register sizes for the following routine types: - merge 2. Adds additive resources to routines if there's an additive resources in any of the children. 3. Adds "fake routines" when passthrough is detected. 4. Removes input register sizes from non-root routines as they will be derived from the connected output ports in the compilation process. 5. Replaces wildcard statements ("~") with appropriate expressions.

Parameters:

Name Type Description Default
routine Routine

A uncompiled routine.

required
backend SymbolicBackend

Backend used to perform expression manipulation.

required
precompilation_stages Optional[list[PrecompilationStage]]

A list of functions that modify routine and all it's sub-routines in place.

None

remove_non_root_container_input_register_sizes

remove_non_root_container_input_register_sizes(
    routine: Routine, _backend: SymbolicBackend
) -> None

Removes any non-root container inputer register sizes defined.

unroll_wildcarded_resources

unroll_wildcarded_resources(
    routine: Routine, backend: SymbolicBackend
) -> None

Unrolls wildcarded expressions in the resources using information from its children. Right now it supports only non-nested expressions.

bartiq.symbolics

bartiq.routing

get_port_source

get_port_source(port: Port) -> Port

Finds the port's source port, i.e. the terminal port reached by following upstream connections. It ignores the intermediate ports, like parent's ports, which only facilitate connections through layers of hierarchy, but do not provide meaningful inputs.

get_port_target

get_port_target(port: Port) -> Port

Finds port's target port, i.e. the terminal port reached by following downstream connections. It ignores the intermediate ports, like parent's ports, which only facilitate connections through layers of hierarchy, but do not provide meaningful inputs.

get_route

get_route(port: Port, forward: bool = True) -> list[Port]

Returns a list of all the ports that will be encountered when following particular port in either direction.

join_paths

join_paths(*paths: str) -> str

Helper function for joining paths in a routine.

bartiq.errors

BartiqCompilationError

Bases: Exception

Raised for errors during Bartiq function compilation.

BartiqPrecompilationError

Bases: Exception

Raised for errors during Bartiq function pre-compilation.

bartiq.integrations

bartiq_to_qref

bartiq_to_qref(
    routine: Routine, version: str = "v1"
) -> SchemaV1

Convert Bartiq routine to QREF object.

qref_to_bartiq

qref_to_bartiq(qref_obj: Union[SchemaV1, dict]) -> Routine

Convert QREF object to a Bartiq routine.

bartiq.verification

VerificationOutput dataclass

Dataclass containing the output of the verification.

is_valid property

is_valid

If true, no issues has been found in the process of verification.

verify_compiled_routine

verify_compiled_routine(
    routine: Routine, backend: SymbolicBackend
) -> VerificationOutput

Verifies whether a compiled routine has correct format.

This function checks:

  • routine's topology
  • if all the expression contain only parameters defined at the top level
  • if all the linked_params are empty

Parameters:

Name Type Description Default
routine Routine

Routine to be verified.

required
backend SymbolicBackend

Backend used for verification

required

verify_routine_topology

verify_routine_topology(
    routine: Routine,
) -> VerificationOutput

Verifies whether the routine has correct topology.

It uses QREF's verify_topology method.

Parameters:

Name Type Description Default
routine Routine

Routine to be verified.

required

verify_uncompiled_routine

verify_uncompiled_routine(
    routine: Routine, backend: SymbolicBackend
) -> VerificationOutput

Verifies whether an uncompiled routine has correct format.

This function checks:

  • routine's topology
  • whether parameter linking is correct
  • if all the expressions in the routine can be parsed by a provided backend

Parameters:

Name Type Description Default
routine Routine

Routine to be verified.

required
backend SymbolicBackend

Backend used for verification

required

Returns:

Type Description
VerificationOutput

verified stuff

bartiq.transform

add_aggregated_resources

add_aggregated_resources(
    routine: Routine,
    aggregation_dict: Dict[str, Dict[str, Any]],
    backend=BACKEND,
) -> Routine

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

Parameters:

Name Type Description Default
routine Routine

The program to which the resources will be added.

required
aggregation_dict Dict[str, Dict[str, Any]]

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

required

Returns:

Name Type Description
Routine Routine

The program with aggregated resources.