Python API

To use OpenQL from Python, you need to install the qutechopenql module using pip, and then

import openql as ql

Note

It used to be necessary to use import openql.openql as ql. This is still supported for backward compatibility.

The typical usage pattern for OpenQL is as follows:

  • call initialize() to initialize the OpenQL library and clean up any leftovers from compiling a previous program;

  • set some global options with set_option();

  • build a Platform;

  • build a Program using the platform;

  • build one or more Kernel s using the platform, and add them to the program with add_kernel();

  • compile the program with compile().

Note

The initialize() didn’t use to exist. Therefore, for backward compatibility, it is called automatically by the constructor of Platform, the constructor of Compiler, or by set_option() if it has not been called yet within this Python interpreter.

Warning

Calling Program.compile() or Compiler.compile() multiple times on the same program is currently not a supported use case: the compile() function mutates the contents of the program as compilation progresses. There are currently no API methods on Program or Kernel to read back the compilation result, but these may be added in the future. Therefore, if you want to compile a program multiple times, you’ll have to rebuild the program from scratch each time.

For more advanced usage of the OpenQL compiler, the default compilation strategy might not be good enough, or the global options may be too restrictive for what you want. For this reason, the Compiler interface was recently added. The easiest way to make use of it is through Platform.get_compiler() or Program.get_compiler(); this returns a reference that allows you to change the default compilation strategy or set options for particular passes. Once you do this, however, any changes made to global options will cease to have an effect on that particular Platform/Program/Compiler triplet; you must use Compiler.set_option() and friends from that point onwards. Note that the names of the options in this interface have been revised compared to the global options, so you can’t just replace a global set_option() with a Compiler.set_option() without a bit of work.

Index

Regular functions

initialize()

Initializes the OpenQL library, for as far as this must be done.

ensure_initialized()

Calls initialize() if it hasn’t been called yet.

compile(-> None)

Entry point for compiling from a cQASM file directly, rather than using the Python API to build the program and platform.

get_version()

Returns the compiler’s version string.

set_option(option, value)

Sets a global option for the compiler.

get_option(option)

Returns the current value for a global option.

Classes

Platform(*args)

Quantum platform description.

Program(name, platform[, qubit_count, …])

Represents a complete quantum program.

Kernel(name, platform[, qubit_count, …])

Represents a kernel of a quantum program, a.k.a.

CReg(id)

Wrapper for a classical integer register with the given index.

Operation(*args)

Wrapper for a classical operation.

Unitary(name, matrix)

Unitary matrix interface.

Compiler(*args)

Wrapper for the compiler/pass manager.

Pass()

Wrapper for a pass that belongs to some pass manager.

cQasmReader(*args)

Legacy cQASM reader interface.

Documentation retrieval functions

print_options()

Prints the documentation for all available global options.

dump_options()

Returns the result of print_options() as a string.

print_architectures()

Prints the documentation for all available target architectures.

dump_architectures()

Returns the result of print_architectures() as a string.

print_passes()

Prints the documentation for all available passes.

dump_passes()

Returns the result of print_passes() as a string.

print_resources()

Prints the documentation for all available scheduler resources.

dump_resources()

Returns the result of print_resources() as a string.

print_platform_docs()

Prints the documentation for platform configuration files.

dump_platform_docs()

Returns the result of print_platform_docs() as a string.

Platform class

class openql.Platform(*args)

Quantum platform description. This describes everything that the compiler needs to know about the target quantum chip, instruments, etc. Platforms are created from either the default configuration for a particular architecture variant or from JSON (+ comments) configuration files: there is no way to modify a platform using the API, and introspection is limited. Instead, if you want to use a custom configuration, you will need to write a JSON configuration file for it, or use get_platform_json() and from_json() to modify an existing one from within Python.

The syntax of the platform configuration file is too extensive to describe here. It has its own section in the manual.

In addition to the platform itself, the Platform object provides an interface for obtaining a Compiler object. This object describes the strategy for transforming the quantum algorithm to something that can be executed on the device described by the platform. You can think of the difference between them as the difference between a verb and a noun: the platform describes something that just exists, while the compilation strategy describes how to get there.

The (initial) strategy can be set using a separate configuration file (compiler_config), directly from within the platform configuration file, or one can be inferred based on the previously hardcoded defaults. Unlike the platform itself however, an extensive API is available for adjusting the strategy as you see fit; just use get_compiler() to get a reference to a Compiler object that may be used for this purpose. If you don’t do anything with the compiler methods and object, don’t specify the compiler_config_file parameter, and the “eqasm_compiler” key of the platform configuration file refers to one of the previously-hardcoded compiler, a strategy will be generated to mimic the old logic for backward compatibility.

Eight constructors are provided:

  • Platform(): shorthand for Platform(‘none’, ‘none’).

  • Platform(name): shorthand for Platform(name, name).

  • Platform(name, platform_config): builds a platform with the given name (only used for log messages) and platform configuration, the latter of which can be either a recognized platform name with or without variant suffix (for example “cc” or “cc_light.s7”), or a path to a JSON configuration filename.

  • Platform(name, platform_config, compiler_config): as above, but specifies a custom compiler configuration file in addition.

  • Platform.from_json(name, platform_config_json): instead of loading the platform JSON data from a file, it is taken from its Python object representation (as per json.loads()/dumps()).

  • Platform.from_json(name, platform_config_json, compiler_config): as above, with compiler JSON file override.

  • Platform.from_json_string(name, platform_config_json): as from_json, but loads the data from a string rather than a Python object.

  • Platform.from_json_string(name, platform_config_json, compiler_config): as from_json, but loads the data from a string rather than a Python object.

property name

The user-given name of the platform.

property config_file

The configuration file that the platform was loaded from.

__init__(self, name: str, platform_config: str, compiler_config: str)Platform
__init__(self, name: str, platform_config: str)Platform
__init__(self, name: str)Platform
__init__(self)Platform
static from_json_string(name: str, platform_config_json: str, compiler_config: str)Platform
static from_json_string(name: str, platform_config_json: str)Platform

Alternative constructor. Instead of the platform JSON data being loaded from a file, they are loaded from the given string. See also from_json().

Parameters
  • name (str) – The name for the platform.

  • platform_config_json (str) – The platform JSON configuration data as a string. This will accept anything that the normal constructor accepts when it reads the configuration from a file.

  • compiler_config (str) – Optional compiler configuration JSON filename. This is NOT JSON data.

Returns

The constructed platform.

Return type

Platform

static get_platform_json_string(platform_config: str)str
static get_platform_json_string()str

Returns the default platform configuration data as a JSON + comments string. The comments use double-slash syntax. Note that JSON itself does not support such comments (or comments of any kind), so these comments need to be removed from the data before the JSON data can be parsed.

Parameters

platform_config (str) – The platform configuration. Same syntax as the platform constructor, so this supports architecture names, architecture variant names, or JSON filenames. In the latter case, this function just loads the file contents into a string and returns it.

Returns

The JSON + comments data for the given platform configuration string.

Return type

str

get_qubit_number(self)int

Returns the number of qubits in the platform.

Parameters

None

Returns

The number of qubits in the platform.

Return type

int

print_info(self)None

Prints some basic information about the platform.

Parameters

None

Returns

Return type

None

dump_info(self)str

Returns the result of print_info() as a string.

Parameters

None

Returns

The result of print_info() as a string.

Return type

str

get_info(self)str

Old alias for dump_info(). Deprecated.

Parameters

None

Returns

The result of print_info() as a string.

Return type

str

has_compiler(self)bool

Returns whether a custom compiler configuration has been attached to this platform. When this is the case, programs constructed from this platform will use it to implement Program.compile(), rather than generating the compiler in-place from defaults and global options during the call.

Parameters

None

Returns

Whether a custom compiler configuration has been attached to this platform.

Return type

bool

get_compiler(self)Compiler

Returns the custom compiler configuration associated with this platform. If no such configuration exists yet, the default one is created, attached, and returned.

Parameters

None

Returns

A Compiler object that may be used to introspect or modify the compilation strategy associated with this platform.

Return type

Compiler

set_compiler(self, compiler: Compiler)None

Sets the compiler associated with this platform. Any programs constructed from this platform after this call will use the given compiler.

Parameters

compiler (Compiler) – The new compiler configuration.

Returns

Return type

None

static from_json(name: str, platform_config_json: Dict[], compiler_config: str)Platform
static from_json(name: str, platform_config_json: Dict[])Platform

Alternative constructor. Instead of the platform JSON data being loaded from a file, they are loaded from the given Python object representation of the JSON platform configuration data.

This is useful when you only need to change a builtin platform for some architecture variant a little bit. In this case, you can get the default JSON data using get_platform_json(), introspect and modify it programmatically, and then use this to build the platform from the modified configuration.

Parameters
  • name (str) – The name for the platform.

  • platform_config_json (JSON-like object) – The platform JSON configuration data in Python object representation (anything accepted by json.dumps()).

  • compiler_config (str) – Optional compiler configuration JSON filename. This is NOT JSON data.

Returns

The constructed platform.

Return type

Platform

static get_platform_json(platform_config: str) -> Dict[...]     get_platform_json()Dict[]

Returns the default platform configuration data as the Python object representation of the JSON data (as returned by json.loads()).

Parameters

platform_config (str) – The platform configuration. Same syntax as the platform constructor, so this supports architecture names, architecture variant names, or JSON filenames. In the latter case, this function just parses the file contents and returns it.

Returns

The Python object representation of the JSON data corresponding to the given platform configuration string.

Return type

str

Program class

class openql.Program(name, platform, qubit_count=0, creg_count=0, breg_count=0)

Represents a complete quantum program.

The constructor creates a new program with the given name, using the given platform. The third, fourth, and fifth arguments optionally specify the desired number of qubits, classical integer registers, and classical bit registers. If not specified, the number of qubits is taken from the platform, and no classical or bit registers will be allocated.

property name

The name given to the program by the user.

property platform

The platform associated with the program.

property qubit_count

The number of (virtual) qubits allocated for the program.

property creg_count

The number of classical integer registers allocated for the program.

property breg_count

The number of classical bit registers allocated for the program.

__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0, breg_count: int = 0)Program
__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0)Program
__init__(self, name: str, platform: Platform, qubit_count: int = 0)Program
__init__(self, name: str, platform: Platform)Program
add_kernel(self, k: Kernel)None

Adds an unconditionally-executed kernel to the end of the program.

Parameters

k (Kernel) – The kernel to add.

Returns

Return type

None

add_program(self, p: Program)None

Adds an unconditionally-executed subprogram to the end of the program.

Parameters

p (Program) – The subprogram to add.

Returns

Return type

None

add_if(self, k: Kernel, operation: Operation)None
add_if(self, p: Program, operation: Operation)None

Adds a conditionally-executed kernel or subprogram to the end of the program. The kernel/subprogram will be executed if the given classical condition evaluates to true.

Parameters
  • k (Kernel) – The kernel to add.

  • p (Program) – The subprogram to add.

  • operation (Operation) – The operation that must evaluate to true for the kernel/subprogram to be executed.

Returns

Return type

None

add_if_else(self, k_if: Kernel, k_else: Kernel, operation: Operation)None
add_if_else(self, p_if: Program, p_else: Program, operation: Operation)None

Adds two conditionally-executed kernels/subprograms with inverted conditions to the end of the program. The first kernel/subprogram will be executed if the given classical condition evaluates to true; the second kernel/subprogram will be executed if it evaluates to false.

Parameters
  • k_if (Kernel) – The kernel to execute when the condition evaluates to true.

  • p_if (Program) – The subprogram to execute when the condition evaluates to true.

  • k_else (Kernel) – The kernel to execute when the condition evaluates to false.

  • p_else (Program) – The subprogram to execute when the condition evaluates to false.

  • operation (Operation) – The operation that determines which kernel/subprogram will be executed.

Returns

Return type

None

add_do_while(self, k: Kernel, operation: Operation)None
add_do_while(self, p: Program, operation: Operation)None

Adds a kernel/subprogram that will be repeated until the given classical condition evaluates to true. The kernel/subprogram is executed at least once, since the condition is evaluated at the end of the loop body.

Parameters
  • k (Kernel) – The kernel that represents the loop body.

  • p (Program) – The subprogram that represents the loop body.

  • operation (Operation) – The operation that must evaluate to true at the end of the loop body for the loop body to be executed again.

Returns

Return type

None

add_for(self, k: Kernel, iterations: int)None
add_for(self, p: Program, iterations: int)None

Adds an unconditionally-executed kernel/subprogram that will loop for the given number of iterations.

Parameters
  • k (Kernel) – The kernel that represents the loop body.

  • p (Program) – The subprogram that represents the loop body.

  • iterations (int) – The number of loop iterations.

Returns

Return type

None

has_compiler(self)bool

Whether a custom compiler configuration has been attached to this program. When this is the case, it will be used to implement compile(), rather than generating the compiler in-place from defaults and global options during the call.

Parameters

None

Returns

Whether a custom compiler configuration has been attached to this program.

Return type

bool

get_compiler(self)Compiler

Returns the custom compiler configuration associated with this program. If no such configuration exists yet, the default one is created, attached, and returned.

Parameters

None

Returns

A Compiler object that may be used to introspect or modify the compilation strategy associated with this program.

Return type

Compiler

set_compiler(self, compiler: Compiler)None

Sets the compiler associated with this program. It will then be used for compile().

Parameters

compiler (Compiler) – The new compiler configuration.

Returns

Return type

None

compile(self)None

Compiles the program.

Parameters

None

Returns

Return type

None

print_interaction_matrix(self)None

Prints the interaction matrix for each kernel in the program.

Parameters

None

Returns

Return type

None

write_interaction_matrix(self)None

Writes the interaction matrix for each kernel in the program to a file. This is one of the few functions that still uses the global output_dir option.

Parameters

None

Returns

Return type

None

Kernel class

class openql.Kernel(name, platform, qubit_count=0, creg_count=0, breg_count=0)

Represents a kernel of a quantum program, a.k.a. a basic block. Kernels are just sequences of gates with no classical control-flow in between: they may end in a (conditional) branch to the start of another kernel, but otherwise, they may only consist of quantum gates and mixed quantum-classical data flow operations.

The constructor creates a new kernel with the given name, using the given platform. The third, fourth, and fifth arguments optionally specify the desired number of qubits, classical integer registers, and classical bit registers. If not specified, the number of qubits is taken from the platform, and no classical or bit registers will be allocated.

Currently, the contents of a kernel can only be constructed by adding gates and classical data flow instructions in the order in which they are to be executed, and there is no way to get information about which gates are in the kernel after the fact. If you need this kind of bookkeeping, you will have to wrap OpenQL’s kernels for now.

Classical flow-control is configured when a completed kernel is added to a program, via basic structured control-flow paradigms (if-else, do-while, and loops with a fixed iteration count).

NOTE: the way gates are represented in OpenQL is on the list to be completely revised. Currently OpenQL works using a mixture of “default gates” and the “custom gates” that you can specify in the platform configuration file, but these two things are not orthogonal and largely incompatible with each other, yet are currently used interchangeably. Furthermore, there is no proper way to specify lists of generic arguments to a gate, leading to lots of code duplication inside OpenQL and long gate() argument lists. Finally, the semantics of gates are largely derived by undocumented and somewhat heuristic string comparisons with the names of gates, which is terrible design in combination with user-specified instruction sets via the platform configuration file. The interface for adding simple quantum gates to a kernel is something we want to keep 100% backward compatible, but the more advanced gate() signatures may change in the (near) future.

NOTE: classical logic is on the list to be completely revised. This interface may change in the (near) future.

NOTE: the higher-order functions for constructing controlled kernels and conjugating kernels have not been maintained for a while and thus probably won’t work right. They may be removed entirely in a later version of OpenQL.

property name

The name of the kernel as given by the user.

property platform

The platform that the kernel was built for.

property qubit_count

The number of (virtual) qubits allocated for the kernel.

property creg_count

The number of classical integer registers allocated for the kernel.

property breg_count

The number of classical bit registers allocated for the kernel.

__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0, breg_count: int = 0)Kernel
__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0)Kernel
__init__(self, name: str, platform: Platform, qubit_count: int = 0)Kernel
__init__(self, name: str, platform: Platform)Kernel
get_custom_instructions(self)str

Old alias for dump_custom_instructions(). Deprecated.

Parameters

None

Returns

A newline-separated list of all custom gates supported by the platform.

Return type

str

print_custom_instructions(self)None

Prints a list of all custom gates supported by the platform.

Parameters

None

Returns

Return type

None

dump_custom_instructions(self)str

Returns the result of print_custom_instructions() as a string.

Parameters

None

Returns

A newline-separated list of all custom gates supported by the platform.

Return type

str

gate_preset_condition(self, condstring: str, condregs: List[int])None

Sets the condition for all gates subsequently added to this kernel. Thus, essentially shorthand notation. Reset with gate_clear_condition().

Parameters
  • condstring (str) –

    Must be one of:

    • ”COND_ALWAYS” or “1”: no condition; gate is always executed.

    • ”COND_NEVER” or “0”: no condition; gate is never executed.

    • ”COND_UNARY” or “” (empty): gate is executed if the single bit specified via condregs is 1.

    • ”COND_NOT” or “!”: gate is executed if the single bit specified via condregs is 0.

    • ”COND_AND” or “&”: gate is executed if the two bits specified via condregs are both 1.

    • ”COND_NAND” or “!&”: gate is executed if either of the two bits specified via condregs is zero.

    • ”COND_OR” or “|”: gate is executed if either of the two bits specified via condregs is one.

    • ”COND_NOR” or “!|”: no condition; gate is always executed.

  • condregs (List[int]) – Depending on condstring, must be a list of 0, 1, or 2 breg indices.

Returns

Return type

None

gate_clear_condition(self)None

Clears a condition previously set via gate_preset_condition().

Parameters

None

Returns

Return type

None

gate(self, name: str, q0: int)None
gate(self, name: str, q0: int, q1: int)None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0, bregs: List[int], condstring: str, condregs: List[int])None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0, bregs: List[int], condstring: str)None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0, bregs: List[int])None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0)None
gate(self, name: str, qubits: List[int], duration: int = 0)None
gate(self, name: str, qubits: List[int])None
gate(self, name: str, qubits: List[int], destination: CReg)None
gate(self, u: Unitary, qubits: List[int])None

Main function for appending arbitrary quantum gates.

Parameters
  • name (str) – The name of the gate. Note that OpenQL currently uses string comparisons with these names all over the place to derive functionality, and to derive what the actual arguments do. This is inherently a bad idea and something we want to move away from, so documenting it all would not be worthwhile. For now, just use common sense, and you’ll probably be okay.

  • q0 (int) – Index of the first qubit to apply the gate to. For controlled gates, this is the control qubit.

  • q1 (int) – Index of the second qubit to apply the gate to. For controlled gates, this is the target qubit.

  • qubits (List[int]) – The full list of qubit indices to apply the gate to.

  • duration (int) – Gate duration in nanoseconds, or 0 to use the default value from the platform configuration file. This is primarily intended to be used for wait gates.

  • angle (float) – Rotation angle in radians for gates that use it (rx, ry, rz, etc). Ignored for all other gates.

  • bregs (List[int]) – The full list of bit register argument indices for the gate, excluding any bit registers used for conditional execution. Currently only used for the measure gate, which may be given an explicit bit register index to return its result in. If no such register is specified, the result is assumed to implicitly go to the bit register with the same index as the qubit being measured. Ignored for gates that don’t use bit registers.

  • condstring (str) –

    If specified, must be one of:

    • ”COND_ALWAYS” or “1”: no condition; gate is always executed.

    • ”COND_NEVER” or “0”: no condition; gate is never executed.

    • ”COND_UNARY” or “” (empty): gate is executed if the single bit specified via condregs is 1.

    • ”COND_NOT” or “!”: gate is executed if the single bit specified via condregs is 0.

    • ”COND_AND” or “&”: gate is executed if the two bits specified via condregs are both 1.

    • ”COND_NAND” or “!&”: gate is executed if either of the two bits specified via condregs is zero.

    • ”COND_OR” or “|”: gate is executed if either of the two bits specified via condregs is one.

    • ”COND_NOR” or “!|”: no condition; gate is always executed.

  • condregs (List[int]) – Depending on condstring, must be a list of 0, 1, or 2 breg indices.

  • destination (CReg) – An integer control register that receives the result of the mixed quantum-classical gate identified by name.

  • u (Unitary) – The unitary gate to insert.

Returns

Return type

None

state_prep(self, array: vectorc, qubits: List[int])None
condgate(self, name: str, qubits: List[int], condstring: str, condregs: List[int])None

Alternative function for appending normal conditional quantum gates. Avoids having to specify duration, angle, and bregs for gates that don’t need it.

Parameters
  • name (str) – The name of the gate. Note that OpenQL currently uses string comparisons with these names all over the place to derive functionality, and to derive what the actual arguments do. This is inherently a bad idea and something we want to move away from, so documenting it all would not be worthwhile. For now, just use common sense, and you’ll probably be okay.

  • qubits (List[int]) – The full list of qubit indices to apply the gate to.

  • condstring (str) –

    If specified, must be one of:

    • ”COND_ALWAYS” or “1”: no condition; gate is always executed.

    • ”COND_NEVER” or “0”: no condition; gate is never executed.

    • ”COND_UNARY” or “” (empty): gate is executed if the single bit specified via condregs is 1.

    • ”COND_NOT” or “!”: gate is executed if the single bit specified via condregs is 0.

    • ”COND_AND” or “&”: gate is executed if the two bits specified via condregs are both 1.

    • ”COND_NAND” or “!&”: gate is executed if either of the two bits specified via condregs is zero.

    • ”COND_OR” or “|”: gate is executed if either of the two bits specified via condregs is one.

    • ”COND_NOR” or “!|”: no condition; gate is always executed.

  • condregs (List[int]) – Depending on condstring, must be a list of 0, 1, or 2 breg indices.

Returns

Return type

None

classical(self, destination: CReg, operation: Operation)None
classical(self, operation: str)None

Appends a classical assignment gate to the circuit. The classical integer register is assigned to the result of the given operation.

Parameters
  • destination (CReg) – An integer control register at the left-hand side of the classical assignment gate.

  • operation (Operation) – The expression to evaluate on the right-hand side of the classical assignment gate.

Returns

Return type

None

identity(self, q0: int)None

Shorthand for an “identity” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

hadamard(self, q0: int)None

Shorthand for appending a “hadamard” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

s(self, q0: int)None

Shorthand for appending an “s” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

sdag(self, q0: int)None

Shorthand for appending an “sdag” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

t(self, q0: int)None

Shorthand for appending a “t” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

tdag(self, q0: int)None

Shorthand for appending a “tdag” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

x(self, q0: int)None

Shorthand for appending an “x” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

y(self, q0: int)None

Shorthand for appending a “y” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

z(self, q0: int)None

Shorthand for appending a “z” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

rx90(self, q0: int)None

Shorthand for appending an “rx90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

mrx90(self, q0: int)None

Shorthand for appending an “mrx90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

rx180(self, q0: int)None

Shorthand for appending an “rx180” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

ry90(self, q0: int)None

Shorthand for appending an “ry90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

mry90(self, q0: int)None

Shorthand for appending an “mry90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

ry180(self, q0: int)None

Shorthand for appending an “ry180” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

rx(self, q0: int, angle: float)None

Shorthand for appending an “rx” gate with a single qubit and the given rotation in radians.

Parameters
  • q0 (int) – The qubit to apply the gate to.

  • angle (float) – The rotation angle in radians.

Returns

Return type

None

ry(self, q0: int, angle: float)None

Shorthand for appending an “ry” gate with a single qubit and the given rotation in radians.

Parameters
  • q0 (int) – The qubit to apply the gate to.

  • angle (float) – The rotation angle in radians.

Returns

Return type

None

rz(self, q0: int, angle: float)None

Shorthand for appending an “rz” gate with a single qubit and the given rotation in radians.

Parameters
  • q0 (int) – The qubit to apply the gate to.

  • angle (float) – The rotation angle in radians.

Returns

Return type

None

measure(self, q0: int)None
measure(self, q0: int, b0: int)None

Shorthand for appending a “measure” gate with a single qubit and implicit or explicit result bit register.

Parameters
  • q0 (int) – The qubit to measure.

  • b0 (int) – The bit register to store the result in. If not specified, the result will be placed in the bit register corresponding to the index of the measured qubit.

Returns

Return type

None

prepz(self, q0: int)None

Shorthand for appending a “prepz” gate with a single qubit.

Parameters

q0 (int) – The qubit to prepare in the Z basis.

Returns

Return type

None

cnot(self, q0: int, q1: int)None

Shorthand for appending a “cnot” gate with two qubits.

Parameters
  • q0 (int) – The control qubit index.

  • q1 (int) – The target qubit index

Returns

Return type

None

cphase(self, q0: int, q1: int)None

Shorthand for appending a “cphase” gate with two qubits.

Parameters
  • q0 (int) – The first qubit index.

  • q1 (int) – The second qubit index.

Returns

Return type

None

cz(self, q0: int, q1: int)None

Shorthand for appending a “cz” gate with two qubits.

Parameters
  • q0 (int) – The first qubit index.

  • q1 (int) – The second qubit index.

Returns

Return type

None

toffoli(self, q0: int, q1: int, q2: int)None

Shorthand for appending a “toffoli” gate with three qubits.

Parameters
  • q0 (int) – The first control qubit index.

  • q1 (int) – The second control qubit index.

  • q2 (int) – The target qubit index.

Returns

Return type

None

clifford(self, id: int, q0: int)None

Shorthand for appending the Clifford gate with the specific number using the minimal number of rx90, rx180, mrx90, ry90, ry180, and mry90 gates.

Parameters
  • id (int) –

    The Clifford gate expansion index:

    • 0: no gates inserted.

    • 1: ry90; rx90

    • 2: mrx90, mry90

    • 3: rx180

    • 4: mry90, mrx90

    • 5: rx90, mry90

    • 6: ry180

    • 7: mry90, rx90

    • 8: rx90, ry90

    • 9: rx180, ry180

    • 10: ry90, mrx90

    • 11: mrx90, ry90

    • 12: ry90, rx180

    • 13: mrx90

    • 14: rx90, mry90, mrx90

    • 15: mry90

    • 16: rx90

    • 17: rx90, ry90, rx90

    • 18: mry90, rx180

    • 19: rx90, ry180

    • 20: rx90, mry90, rx90

    • 21: ry90

    • 22: mrx90, ry180

    • 23: rx90, ry90, mrx90

  • q0 (int) – The target qubit.

Returns

Return type

None

wait(self, qubits: List[int], duration: int)None

Shorthand for appending a “wait” gate with the specified qubits and duration in nanoseconds. If no qubits are specified, the wait applies to all qubits instead (a wait with no qubits is meaningless). Note that the duration will usually end up being rounded up to multiples of the platform’s cycle time.

Parameters
  • qubits (List[int]) – The list of qubits to apply the wait gate to. If empty, the list will be replaced with the set of all qubits.

  • duration (int) – The duration of the wait gate in nanoseconds.

Returns

Return type

None

barrier(self, qubits: List[int])None
barrier(self)None

Shorthand for appending a “wait” gate with the specified qubits and duration 0. If no qubits are specified, the wait applies to all qubits instead (a wait with no qubits is meaningless).

Parameters

qubits (List[int]) – The list of qubits to apply the wait gate to. If empty or unspecified, the list will be replaced with the set of all qubits.

Returns

Return type

None

display(self)None

Shorthand for appending a “display” gate with no qubits.

Parameters

None

Returns

Return type

None

diamond_excite_mw(self, envelope: int, duration: int, frequency: int, phase: int, amplitude: int, qubit: int)None

Appends the diamond “excite_mw” instruction.

Parameters
  • envelope (int) – The envelope of the microwave.

  • duration (int) – The duration of the microwave in nanoseconds.

  • frequency (int) – The frequency of the microwave in kilohertz.

  • phase (int) – The phase of the microwave.

  • amplitude (int) – The amplitude of the microwave.

  • qubit (int) – The target qubit index.

Returns

Return type

None

diamond_memswap(self, qubit: int, nuclear_qubit: int)None

Appends the diamond “memswap” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • nuclear_qubit (int) – The index of the nuclear spin qubit of the color center.

Returns

Return type

None

diamond_qentangle(self, qubit: int, nuclear_qubit: int)None

Appends the diamond “qentangle” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • nuclear_qubit (int) – The index of the nuclear spin qubit of the color center.

Returns

Return type

None

diamond_sweep_bias(self, qubit: int, value: int, dacreg: int, start: int, step: int, max: int, memaddress: int)None

Appends the diamond “sweep_bias” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • value (int) – The value that has to be send to the dac for biasing.

  • dacreg (int) – The index or address of the register of the dac.

  • start (int) – The start frequency value of the sweep.

  • step (int) – The step frequency value of the sweep.

  • max (int) – The maximum frequency value of the sweep.

  • memaddress (int) – The memory address to write the results to.

Returns

Return type

None

diamond_crc(self, qubit: int, threshold: int, value: int)None

Appends the diamond “crc” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • treshold (int) – The threshold value that has to be matched.

  • value (int) – The value of the voltage sent to the dac.

Returns

Return type

None

diamond_rabi_check(self, qubit: int, measurements: int, duration: int, t_max: int)None

Appends the diamond “rabi_check” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • measurements (int) – How manu measurements have to be recorded.

  • duration (int) – The starting value of the duration of the microwave.

  • t_max (int) – The value of the voltage sent to the dac.

Returns

Return type

None

controlled(self, k: Kernel, control_qubits: List[int], ancilla_qubits: List[int])None

Appends a controlled kernel. The number of control and ancilla qubits must be equal.

Parameters
  • k (Kernel) – The kernel to make controlled.

  • control_qubits (List[int]) – The qubits that control the kernel.

  • ancilla_qubits (List[int]) – The ancilla qubits to use to make the kernel controlled. The number of ancilla qubits must equal the number of control qubits.

Returns

Return type

None

conjugate(self, k: Kernel)None

Appends the conjugate of the given kernel to this kernel.

NOTE: this high-level functionality is poorly/not maintained, and relies on default gates, which are on the list for removal.

Parameters

k (Kernel) – The kernel to conjugate.

Returns

Return type

None

CReg class

class openql.CReg(id)

Wrapper for a classical integer register with the given index.

NOTE: classical logic is on the list to be completely revised. This interface may change in the (near) future.

__init__(self, id: int)CReg

Operation class

class openql.Operation(*args)

Wrapper for a classical operation.

A classical operation acts as a simple expression that returns an integer or a boolean. The expression can be a literal number (val), a single CReg (lop, primarily used for assignments), a unary function applied to one CReg (op/rop), or a binary function applied to two CRegs (lop/op/rop).

Function selection is done via strings. The following unary functions are recognized:

  • ‘~’: bitwise NOT.

The following binary functions are recognized:

  • ‘+’: addition.

  • ‘-‘: subtraction.

  • ‘&’: bitwise AND.

  • ‘|’: bitwise OR.

  • ‘^’: bitwise XOR.

  • ‘==’: equality.

  • ‘!=’: inequality.

  • ‘>’: greater-than.

  • ‘>=’: greater-or-equal.

  • ‘<’: less-than.

  • ‘<=’: less-or-equal.

NOTE: classical logic is on the list to be completely revised. This interface may change in the (near) future.

__init__(self, lop: CReg, op: str, rop: CReg)Operation
__init__(self, op: str, rop: CReg)Operation
__init__(self, lop: CReg)Operation
__init__(self, val: int)Operation

Unitary class

class openql.Unitary(name, matrix)

Unitary matrix interface.

The constructor creates a unitary gate from the given row-major, square, unitary matrix.

property name

The name given to the unitary gate.

__init__(self, name: str, matrix: vectorc)Unitary
decompose(self)None

Explicitly decomposes the gate. Does not need to be called; it will be called automatically when the gate is added to the kernel.

Parameters

None

Returns

Return type

None

static is_decompose_support_enabled()bool

Returns whether OpenQL was built with unitary decomposition support enabled.

Parameters

None

Returns

Whether OpenQL was built with unitary decomposition support enabled.

Return type

bool

Compiler class

class openql.Compiler(*args)

Wrapper for the compiler/pass manager.

This allows you to change the compilation strategy, if the defaults are insufficient for your application. You can get access to a Compiler via several methods:

  • using Platform.get_compiler();

  • using Program.get_compiler();

  • using one of the constructors.

Using the constructors, you can get an empty compiler (by specifying no arguments or only specifying name), a default compiler for a given platform (by specifying a name and a platform), or a compiler based on a compiler configuration JSON file (by specifying a name and a filename). For the structure of this JSON file, refer to the configuration section of the ReadTheDocs documentation or, equivalently, the result of openql.print_compiler_docs().

property name

User-given name for this compiler.

NOTE: not actually used for anything. It’s only here for consistency with the rest of the API objects.

__init__(self, name: str)Compiler
__init__(self)Compiler
__init__(self, name: str, filename: str)Compiler
__init__(self, name: str, platform: Platform)Compiler
print_pass_types(self)None

Prints documentation for all available pass types, as well as the option documentation for the passes.

Parameters

None

Returns

Return type

None

dump_pass_types(self)str

Returns documentation for all available pass types, as well as the option documentation for the passes.

Parameters

None

Returns

The list of pass types and their documentation as a multiline string.

Return type

str

print_strategy(self)None

Prints the currently configured compilation strategy.

Parameters

None

Returns

Return type

None

dump_strategy(self)str

Returns the currently configured compilation strategy as a string.

Parameters

None

Returns

The current compilation strategy as a multiline string.

Return type

str

set_option(self, path: str, value: str, must_exist: bool = True)int
set_option(self, path: str, value: str)int

Sets a pass option. The path must consist of the target pass instance name and the option name, separated by a period. The former may include * or ? wildcards. If must_exist is set an exception will be thrown if none of the passes were affected, otherwise 0 will be returned.

Parameters
  • path (str) – The path to the option, consisting of the pass name and the option name separated by a period.

  • value (str) – The value to set the option to.

  • must_exist (bool) – When set, an exception will be thrown when no options matched the path.

Returns

The number of pass options affected.

Return type

int

get_option(self, path: str)str

Returns the current value of an option.

Parameters

path (str) – The path to the option, consisting of pass name and the actual option name separated by a period.

Returns

The value of the option. If the option has not been set, the default value is returned.

Return type

str

append_pass(self, type_name: str, instance_name: str, options: Dict[str, str])Pass
append_pass(self, type_name: str, instance_name: str)Pass
append_pass(self, type_name: str)Pass

Appends a pass to the end of the pass list. Returns a reference to the constructed pass.

Parameters
  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

prefix_pass(self, type_name: str, instance_name: str, options: Dict[str, str])Pass
prefix_pass(self, type_name: str, instance_name: str)Pass
prefix_pass(self, type_name: str)Pass

Appends a pass to the beginning of the pass list. Returns a reference to the constructed pass.

Parameters
  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

insert_pass_after(self, target: str, type_name: str, instance_name: str, options: Dict[str, str])Pass
insert_pass_after(self, target: str, type_name: str, instance_name: str)Pass
insert_pass_after(self, target: str, type_name: str)Pass

Inserts a pass immediately after the target pass (named by instance). If target does not exist, an exception is thrown. Returns a reference to the constructed pass.

Parameters
  • target (str) – The name of the pass to insert the new pass after.

  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

insert_pass_before(self, target: str, type_name: str, instance_name: str, options: Dict[str, str])Pass
insert_pass_before(self, target: str, type_name: str, instance_name: str)Pass
insert_pass_before(self, target: str, type_name: str)Pass

Inserts a pass immediately before the target pass (named by instance). If target does not exist, an exception is thrown. Returns a reference to the constructed pass.

Parameters
  • target (str) – The name of the pass to insert the new pass before.

  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

get_pass(self, target: str)Pass

Returns a reference to the pass with the given instance name. If no such pass exists, an exception is thrown.

Parameters

target (str) – The name of the pass to retrieve a reference to.

Returns

A reference to the targeted pass.

Return type

Pass

does_pass_exist(self, target: str)bool

Returns whether a pass with the target instance name exists.

Parameters

target (str) – The name of the pass to query existence of.

Returns

Whether a pass with the target name exists.

Return type

bool

get_num_passes(self)int

Returns the total number of passes in the root hierarchy.

Parameters

None

Returns

The number of passes (or groups) within the root pass list.

Return type

int

get_passes(self)List[Pass]

Returns a list with references to all passes in the root hierarchy.

Parameters

None

Returns

The list of all passes in the root hierarchy.

Return type

list[Pass]

get_passes_by_type(self, target: str)List[Pass]

Returns a list with references to all passes in the root hierarchy with the given type.

Parameters

target (str) – The target pass type name.

Returns

The list of all passes in the root hierarchy with the given type.

Return type

list[Pass]

remove_pass(self, target: str)None

Removes the pass with the given target instance name, or throws an exception if no such pass exists.

Parameters

target (str) – The name of the pass to remove.

Returns

Return type

None

clear_passes(self)None

Clears the entire pass list.

Parameters

None

Returns

Return type

None

compile(self, program: Program)None

Ensures that all passes have been constructed, and then runs the passes on the given program. This is the same as Program.compile() when the program is referencing the same compiler.

Parameters

program (Program) – The program to compile.

Returns

Return type

None

compile_with_frontend(self, platform: Platform)None

Ensures that all passes have been constructed, and then runs the passes without specification of an input program. The first pass should then act as a language frontend. The cQASM reader satisfies this requirement, for instance.

If no platform is specified, it will default to the none architecture, but the intended use case is to have the first pass load the platform. Again, the cQASM reader can do this.

Parameters

platform (Platform) – The platform to compile for.

Returns

Return type

None

Pass class

class openql.Pass

Wrapper for a pass that belongs to some pass manager.

NOTE: while it’s possible to construct a pass manually, the resulting object cannot be used in any way. The only way to obtain a valid pass object is through a Compiler object.

__init__(self)Pass
get_type(self)str

Returns the full, desugared type name that this pass was constructed with.

Parameters

None

Returns

The type name.

Return type

str

get_name(self)str

Returns the instance name of the pass within the surrounding group.

Parameters

None

Returns

The instance name.

Return type

str

print_pass_documentation(self)None

Prints the documentation for this pass.

Parameters

None

Returns

Return type

None

dump_pass_documentation(self)str

Returns the documentation for this pass as a string.

Parameters

None

Returns

The documentation for this pass as a multiline string.

Return type

str

print_options(self, only_set: bool = False)None
print_options(self)None

Prints the current state of the options.

Parameters

only_set (bool) – When set, only the options that were explicitly configured are dumped.

Returns

Return type

None

dump_options(self, only_set: bool = False)str
dump_options(self)str

Returns the string printed by print_options().

Parameters

only_set (bool) – When set, only the options that were explicitly configured are dumped.

Returns

The option documentation as a multiline string.

Return type

str

set_option(self, option: str, value: str)None

Sets an option.

Parameters
  • option (str) – The option name.

  • value (str) – The value to set the option to.

Returns

Return type

None

get_option(self, option: str)str

Returns the current value of an option.

Parameters

path (str) – The path to the option.

Returns

The value of the option. If the option has not been set, the default value is returned.

Return type

str

cQasmReader class

class openql.cQasmReader(*args)

Legacy cQASM reader interface.

The preferred way to read cQASM files is to use the cQASM reader pass (io.cqasm.read). The pass supports up to cQASM 1.2, and handles all features that OpenQL supports within its intermediate representation properly, whereas this interface only supports version 1.0 and requires an additional JSON file with gate conversion rules to work.

To read a cQASM file using this interface, build a cQASM reader for the an already-existing program, and then call file2circuit or string2circuit to add the kernels from the cQASM file/string to the program. Optionally a platform can be specified as well, but this is redundant (it must be the same platform as the one that the program was constructed with); these overloads only exist for backward compatibility.

Because OpenQL supports custom gates and cQASM (historically) does not, and also because OpenQL’s internal representation of gates is still a bit different from what cQASM uses (at least when constructing the IR using the Python API), you may need custom conversion rules for the gates. This can be done by specifying a gateset configuration JSON file using gateset_fname. This file must consist of a JSON array containing objects with the following structure:

{
    "name": "<name>",               # mandatory
    "params": "<typespec>",         # mandatory
    "allow_conditional": <bool>,    # whether conditional gates of this type are accepted, defaults to true
    "allow_parallel": <bool>,       # whether parallel gates of this type are accepted, defaults to true
    "allow_reused_qubits": <bool>,  # whether reused qubit args for this type are accepted, defaults to false
    "ql_name": "<name>",            # defaults to "name"
    "ql_qubits": [                  # list or "all", defaults to the "Q" args
        0,                          # hardcoded qubit index
        "%0"                        # reference to argument 0, which can be a qubitref, bitref, or int
    ],
    "ql_cregs": [                   # list or "all", defaults to the "I" args
        0,                          # hardcoded creg index
        "%0"                        # reference to argument 0, which can be an int variable reference, or int for creg index
    ],
    "ql_bregs": [                   # list or "all", defaults to the "B" args
        0,                          # hardcoded breg index
        "%0"                        # reference to argument 0, which can be an int variable reference, or int for creg index
    ],
    "ql_duration": 0,               # duration; int to hardcode or "%i" to take from param i (must be of type int), defaults to 0
    "ql_angle": 0.0,                # angle; float to hardcode or "%i" to take from param i (must be of type int or real), defaults to first arg of type real or 0.0
    "ql_angle_type": "<type>",      # interpretation of angle arg; one of "rad" (radians), "deg" (degrees), or "pow2" (2pi/2^k radians), defaults to "rad"
    "implicit_sgmq": <bool>,        # if multiple qubit args are present, a single-qubit gate of this type should be replicated for these qubits (instead of a single gate with many qubits)
    "implicit_breg": <bool>         # the breg operand(s) that implicitly belongs to the qubit operand(s) in the gate should be added to the OpenQL operand list
}

The typespec string defines the expected argument types for the gate. Each character in the string represents an argument. The following characters are supported by libqasm:

  • Q = qubit

  • B = assignable bit/boolean (measurement register)

  • b = bit/boolean

  • a = axis (x, y, or z)

  • I = assignable integer

  • i = integer

  • r = real

  • c = complex

  • u = complex matrix of size 4^n, where n is the number of qubits in the parameter list (automatically deduced)

  • s = (quoted) string

  • j = json

Note that OpenQL only uses an argument if it is referred to in one of the “ql_*” keys, either implicitly or explicitly.

If no custom configuration is specified, the reader defaults to the logic that was hardcoded before it was made configurable. This corresponds to the following JSON:

[
    {"name": "measure",     "params": "Q",      "ql_name": "measz"},
    {"name": "measure",     "params": "QB",     "ql_name": "measz"},
    {"name": "measure_x",   "params": "Q",      "ql_name": "measx"},
    {"name": "measure_x",   "params": "QB",     "ql_name": "measx"},
    {"name": "measure_y",   "params": "Q",      "ql_name": "measy"},
    {"name": "measure_y",   "params": "QB",     "ql_name": "measy"},
    {"name": "measure_z",   "params": "Q",      "ql_name": "measz"},
    {"name": "measure_z",   "params": "QB",     "ql_name": "measz"},
    {"name": "prep",        "params": "Q",      "ql_name": "prepz"},
    {"name": "prep_x",      "params": "Q",      "ql_name": "prepx"},
    {"name": "prep_y",      "params": "Q",      "ql_name": "prepy"},
    {"name": "prep_z",      "params": "Q",      "ql_name": "prepz"},
    {"name": "i",           "params": "Q"},
    {"name": "h",           "params": "Q"},
    {"name": "x",           "params": "Q"},
    {"name": "y",           "params": "Q"},
    {"name": "z",           "params": "Q"},
    {"name": "s",           "params": "Q"},
    {"name": "sdag",        "params": "Q"},
    {"name": "t",           "params": "Q"},
    {"name": "tdag",        "params": "Q"},
    {"name": "x90",         "params": "Q",      "ql_name": "rx90"},
    {"name": "mx90",        "params": "Q",      "ql_name": "xm90"},
    {"name": "y90",         "params": "Q",      "ql_name": "ry90"},
    {"name": "my90",        "params": "Q",      "ql_name": "ym90"},
    {"name": "rx",          "params": "Qr"},
    {"name": "ry",          "params": "Qr"},
    {"name": "rz",          "params": "Qr"},
    {"name": "cnot",        "params": "QQ"},
    {"name": "cz",          "params": "QQ"},
    {"name": "swap",        "params": "QQ"},
    {"name": "cr",          "params": "QQr"},
    {"name": "crk",         "params": "QQi",    "ql_angle": "%2", "ql_angle_type": "pow2"},
    {"name": "toffoli",     "params": "QQQ"},
    {"name": "measure_all", "params": "",       "ql_qubits": "all", "implicit_sgmq": true},
    {"name": "display",     "params": ""},
    {"name": "wait",        "params": ""},
    {"name": "wait",        "params": "i"}
]
property platform

The platform associated with the reader.

property program

The program that the cQASM circuits will be added to.

__init__(self, platform: Platform, program: Program, gateset_fname: str)cQasmReader
__init__(self, platform: Platform, program: Program)cQasmReader
__init__(self, program: Program, gateset_fname: str)cQasmReader
__init__(self, program: Program)cQasmReader
string2circuit(self, cqasm_str: str)None

Interprets a string as cQASM file and adds its contents to the program associated with this reader.

Parameters

cqasm_str (str) – The string representing the contents of the cQASM file.

Returns

Return type

None

file2circuit(self, cqasm_file_path: str)None

Interprets a string as cQASM file and adds its contents to the program associated with this reader.

Parameters

cqasm_file_path (str) – The path to the cQASM file to load.

Returns

Return type

None

Functions and miscellaneous

openql.initialize()None

Initializes the OpenQL library, for as far as this must be done. This should ideally be called by the user (in Python) before anything else, but set_option() and the constructors of Compiler and Platform will automatically call this when it hasn’t been done yet as well.

Currently this just resets the options to their default values to give the user a clean slate to work with in terms of global variables (in case someone else has used the library in the same interpreter before them, for instance, as might happen with ipython/Jupyter in a shared notebook server, or during test suites), but it may initialize more things in the future.

Parameters

None

Returns

Return type

None

openql.ensure_initialized()None

Calls initialize() if it hasn’t been called yet.

Parameters

None

Returns

Return type

None

openql.compile(fname: str, read_options: Dict[str, str])None
openql.compile(fname: str)None

Entry point for compiling from a cQASM file directly, rather than using the Python API to build the program and platform.

The platform must be encoded using a pragma @ql.platform(…) annotation at the front of the file; refer to the documentation of the cQASM reader pass for more information. If specified, the read_options parameter is passed to the cQASM reader pass that is automatically prefixed to the pass list.

Parameters
  • fname (str) – Path to the cQASM file to read.

  • read_options (dict[str, str]) – A list of options to set for the cQASM reader pass.

Returns

Return type

None

openql.get_version()str

Returns the compiler’s version string.

Parameters

None

Returns

version number as a string

Return type

str

openql.set_option(option: str, value: str)None

Sets a global option for the compiler. Use print_options() to get a list of all available options.

Parameters
  • option (str) – Name of the option to set.

  • value (str) – The value to set the option to.

Returns

Return type

None

openql.get_option(option: str)str

Returns the current value for a global option. Use print_options() to get a list of all available options.

Parameters

option (str) – Name of the option to retrieve the value of.

Returns

The value that the option has been set to, or its default value if the option has not been set yet.

Return type

str

openql.print_options()None

Prints the documentation for all available global options.

Parameters

None

Returns

Return type

None

openql.dump_options()str

Returns the result of print_options() as a string.

Parameters

None

Returns

The documentation for the options.

Return type

str

openql.print_architectures()None

Prints the documentation for all available target architectures.

Parameters

None

Returns

Return type

None

openql.dump_architectures()str

Returns the result of print_architectures() as a string.

Parameters

None

Returns

The documentation for the supported architectures.

Return type

str

openql.print_passes()None

Prints the documentation for all available passes.

Parameters

None

Returns

Return type

None

openql.dump_passes()str

Returns the result of print_passes() as a string.

Parameters

None

Returns

The documentation for the supported passes.

Return type

str

openql.print_resources()None

Prints the documentation for all available scheduler resources.

Parameters

None

Returns

Return type

None

openql.dump_resources()str

Returns the result of print_resources() as a string.

Parameters

None

Returns

The documentation for the supported scheduler resources.

Return type

str

openql.print_platform_docs()None

Prints the documentation for platform configuration files.

Parameters

None

Returns

Return type

None

openql.dump_platform_docs()str

Returns the result of print_platform_docs() as a string.

Parameters

None

Returns

The documentation for the platform configuration file.

Return type

str

openql.print_compiler_docs()None

Prints the documentation for compiler configuration files.

Parameters

None

Returns

Return type

None

openql.dump_compiler_docs()str

Returns the result of print_compiler_docs() as a string.

Parameters

None

Returns

The documentation for the compiler configuration file.

Return type

str

class openql.Platform(*args)

Quantum platform description. This describes everything that the compiler needs to know about the target quantum chip, instruments, etc. Platforms are created from either the default configuration for a particular architecture variant or from JSON (+ comments) configuration files: there is no way to modify a platform using the API, and introspection is limited. Instead, if you want to use a custom configuration, you will need to write a JSON configuration file for it, or use get_platform_json() and from_json() to modify an existing one from within Python.

The syntax of the platform configuration file is too extensive to describe here. It has its own section in the manual.

In addition to the platform itself, the Platform object provides an interface for obtaining a Compiler object. This object describes the strategy for transforming the quantum algorithm to something that can be executed on the device described by the platform. You can think of the difference between them as the difference between a verb and a noun: the platform describes something that just exists, while the compilation strategy describes how to get there.

The (initial) strategy can be set using a separate configuration file (compiler_config), directly from within the platform configuration file, or one can be inferred based on the previously hardcoded defaults. Unlike the platform itself however, an extensive API is available for adjusting the strategy as you see fit; just use get_compiler() to get a reference to a Compiler object that may be used for this purpose. If you don’t do anything with the compiler methods and object, don’t specify the compiler_config_file parameter, and the “eqasm_compiler” key of the platform configuration file refers to one of the previously-hardcoded compiler, a strategy will be generated to mimic the old logic for backward compatibility.

Eight constructors are provided:

  • Platform(): shorthand for Platform(‘none’, ‘none’).

  • Platform(name): shorthand for Platform(name, name).

  • Platform(name, platform_config): builds a platform with the given name (only used for log messages) and platform configuration, the latter of which can be either a recognized platform name with or without variant suffix (for example “cc” or “cc_light.s7”), or a path to a JSON configuration filename.

  • Platform(name, platform_config, compiler_config): as above, but specifies a custom compiler configuration file in addition.

  • Platform.from_json(name, platform_config_json): instead of loading the platform JSON data from a file, it is taken from its Python object representation (as per json.loads()/dumps()).

  • Platform.from_json(name, platform_config_json, compiler_config): as above, with compiler JSON file override.

  • Platform.from_json_string(name, platform_config_json): as from_json, but loads the data from a string rather than a Python object.

  • Platform.from_json_string(name, platform_config_json, compiler_config): as from_json, but loads the data from a string rather than a Python object.

property name

The user-given name of the platform.

property config_file

The configuration file that the platform was loaded from.

__init__(self, name: str, platform_config: str, compiler_config: str)Platform
__init__(self, name: str, platform_config: str)Platform
__init__(self, name: str)Platform
__init__(self)Platform
static from_json_string(name: str, platform_config_json: str, compiler_config: str)Platform
static from_json_string(name: str, platform_config_json: str)Platform

Alternative constructor. Instead of the platform JSON data being loaded from a file, they are loaded from the given string. See also from_json().

Parameters
  • name (str) – The name for the platform.

  • platform_config_json (str) – The platform JSON configuration data as a string. This will accept anything that the normal constructor accepts when it reads the configuration from a file.

  • compiler_config (str) – Optional compiler configuration JSON filename. This is NOT JSON data.

Returns

The constructed platform.

Return type

Platform

static get_platform_json_string(platform_config: str)str
static get_platform_json_string()str

Returns the default platform configuration data as a JSON + comments string. The comments use double-slash syntax. Note that JSON itself does not support such comments (or comments of any kind), so these comments need to be removed from the data before the JSON data can be parsed.

Parameters

platform_config (str) – The platform configuration. Same syntax as the platform constructor, so this supports architecture names, architecture variant names, or JSON filenames. In the latter case, this function just loads the file contents into a string and returns it.

Returns

The JSON + comments data for the given platform configuration string.

Return type

str

get_qubit_number(self)int

Returns the number of qubits in the platform.

Parameters

None

Returns

The number of qubits in the platform.

Return type

int

print_info(self)None

Prints some basic information about the platform.

Parameters

None

Returns

Return type

None

dump_info(self)str

Returns the result of print_info() as a string.

Parameters

None

Returns

The result of print_info() as a string.

Return type

str

get_info(self)str

Old alias for dump_info(). Deprecated.

Parameters

None

Returns

The result of print_info() as a string.

Return type

str

has_compiler(self)bool

Returns whether a custom compiler configuration has been attached to this platform. When this is the case, programs constructed from this platform will use it to implement Program.compile(), rather than generating the compiler in-place from defaults and global options during the call.

Parameters

None

Returns

Whether a custom compiler configuration has been attached to this platform.

Return type

bool

get_compiler(self)Compiler

Returns the custom compiler configuration associated with this platform. If no such configuration exists yet, the default one is created, attached, and returned.

Parameters

None

Returns

A Compiler object that may be used to introspect or modify the compilation strategy associated with this platform.

Return type

Compiler

set_compiler(self, compiler: Compiler)None

Sets the compiler associated with this platform. Any programs constructed from this platform after this call will use the given compiler.

Parameters

compiler (Compiler) – The new compiler configuration.

Returns

Return type

None

static from_json(name: str, platform_config_json: Dict[], compiler_config: str)Platform
static from_json(name: str, platform_config_json: Dict[])Platform

Alternative constructor. Instead of the platform JSON data being loaded from a file, they are loaded from the given Python object representation of the JSON platform configuration data.

This is useful when you only need to change a builtin platform for some architecture variant a little bit. In this case, you can get the default JSON data using get_platform_json(), introspect and modify it programmatically, and then use this to build the platform from the modified configuration.

Parameters
  • name (str) – The name for the platform.

  • platform_config_json (JSON-like object) – The platform JSON configuration data in Python object representation (anything accepted by json.dumps()).

  • compiler_config (str) – Optional compiler configuration JSON filename. This is NOT JSON data.

Returns

The constructed platform.

Return type

Platform

static get_platform_json(platform_config: str) -> Dict[...]     get_platform_json()Dict[]

Returns the default platform configuration data as the Python object representation of the JSON data (as returned by json.loads()).

Parameters

platform_config (str) – The platform configuration. Same syntax as the platform constructor, so this supports architecture names, architecture variant names, or JSON filenames. In the latter case, this function just parses the file contents and returns it.

Returns

The Python object representation of the JSON data corresponding to the given platform configuration string.

Return type

str

class openql.Program(name, platform, qubit_count=0, creg_count=0, breg_count=0)

Represents a complete quantum program.

The constructor creates a new program with the given name, using the given platform. The third, fourth, and fifth arguments optionally specify the desired number of qubits, classical integer registers, and classical bit registers. If not specified, the number of qubits is taken from the platform, and no classical or bit registers will be allocated.

property name

The name given to the program by the user.

property platform

The platform associated with the program.

property qubit_count

The number of (virtual) qubits allocated for the program.

property creg_count

The number of classical integer registers allocated for the program.

property breg_count

The number of classical bit registers allocated for the program.

__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0, breg_count: int = 0)Program
__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0)Program
__init__(self, name: str, platform: Platform, qubit_count: int = 0)Program
__init__(self, name: str, platform: Platform)Program
add_kernel(self, k: Kernel)None

Adds an unconditionally-executed kernel to the end of the program.

Parameters

k (Kernel) – The kernel to add.

Returns

Return type

None

add_program(self, p: Program)None

Adds an unconditionally-executed subprogram to the end of the program.

Parameters

p (Program) – The subprogram to add.

Returns

Return type

None

add_if(self, k: Kernel, operation: Operation)None
add_if(self, p: Program, operation: Operation)None

Adds a conditionally-executed kernel or subprogram to the end of the program. The kernel/subprogram will be executed if the given classical condition evaluates to true.

Parameters
  • k (Kernel) – The kernel to add.

  • p (Program) – The subprogram to add.

  • operation (Operation) – The operation that must evaluate to true for the kernel/subprogram to be executed.

Returns

Return type

None

add_if_else(self, k_if: Kernel, k_else: Kernel, operation: Operation)None
add_if_else(self, p_if: Program, p_else: Program, operation: Operation)None

Adds two conditionally-executed kernels/subprograms with inverted conditions to the end of the program. The first kernel/subprogram will be executed if the given classical condition evaluates to true; the second kernel/subprogram will be executed if it evaluates to false.

Parameters
  • k_if (Kernel) – The kernel to execute when the condition evaluates to true.

  • p_if (Program) – The subprogram to execute when the condition evaluates to true.

  • k_else (Kernel) – The kernel to execute when the condition evaluates to false.

  • p_else (Program) – The subprogram to execute when the condition evaluates to false.

  • operation (Operation) – The operation that determines which kernel/subprogram will be executed.

Returns

Return type

None

add_do_while(self, k: Kernel, operation: Operation)None
add_do_while(self, p: Program, operation: Operation)None

Adds a kernel/subprogram that will be repeated until the given classical condition evaluates to true. The kernel/subprogram is executed at least once, since the condition is evaluated at the end of the loop body.

Parameters
  • k (Kernel) – The kernel that represents the loop body.

  • p (Program) – The subprogram that represents the loop body.

  • operation (Operation) – The operation that must evaluate to true at the end of the loop body for the loop body to be executed again.

Returns

Return type

None

add_for(self, k: Kernel, iterations: int)None
add_for(self, p: Program, iterations: int)None

Adds an unconditionally-executed kernel/subprogram that will loop for the given number of iterations.

Parameters
  • k (Kernel) – The kernel that represents the loop body.

  • p (Program) – The subprogram that represents the loop body.

  • iterations (int) – The number of loop iterations.

Returns

Return type

None

has_compiler(self)bool

Whether a custom compiler configuration has been attached to this program. When this is the case, it will be used to implement compile(), rather than generating the compiler in-place from defaults and global options during the call.

Parameters

None

Returns

Whether a custom compiler configuration has been attached to this program.

Return type

bool

get_compiler(self)Compiler

Returns the custom compiler configuration associated with this program. If no such configuration exists yet, the default one is created, attached, and returned.

Parameters

None

Returns

A Compiler object that may be used to introspect or modify the compilation strategy associated with this program.

Return type

Compiler

set_compiler(self, compiler: Compiler)None

Sets the compiler associated with this program. It will then be used for compile().

Parameters

compiler (Compiler) – The new compiler configuration.

Returns

Return type

None

compile(self)None

Compiles the program.

Parameters

None

Returns

Return type

None

print_interaction_matrix(self)None

Prints the interaction matrix for each kernel in the program.

Parameters

None

Returns

Return type

None

write_interaction_matrix(self)None

Writes the interaction matrix for each kernel in the program to a file. This is one of the few functions that still uses the global output_dir option.

Parameters

None

Returns

Return type

None

class openql.Kernel(name, platform, qubit_count=0, creg_count=0, breg_count=0)

Represents a kernel of a quantum program, a.k.a. a basic block. Kernels are just sequences of gates with no classical control-flow in between: they may end in a (conditional) branch to the start of another kernel, but otherwise, they may only consist of quantum gates and mixed quantum-classical data flow operations.

The constructor creates a new kernel with the given name, using the given platform. The third, fourth, and fifth arguments optionally specify the desired number of qubits, classical integer registers, and classical bit registers. If not specified, the number of qubits is taken from the platform, and no classical or bit registers will be allocated.

Currently, the contents of a kernel can only be constructed by adding gates and classical data flow instructions in the order in which they are to be executed, and there is no way to get information about which gates are in the kernel after the fact. If you need this kind of bookkeeping, you will have to wrap OpenQL’s kernels for now.

Classical flow-control is configured when a completed kernel is added to a program, via basic structured control-flow paradigms (if-else, do-while, and loops with a fixed iteration count).

NOTE: the way gates are represented in OpenQL is on the list to be completely revised. Currently OpenQL works using a mixture of “default gates” and the “custom gates” that you can specify in the platform configuration file, but these two things are not orthogonal and largely incompatible with each other, yet are currently used interchangeably. Furthermore, there is no proper way to specify lists of generic arguments to a gate, leading to lots of code duplication inside OpenQL and long gate() argument lists. Finally, the semantics of gates are largely derived by undocumented and somewhat heuristic string comparisons with the names of gates, which is terrible design in combination with user-specified instruction sets via the platform configuration file. The interface for adding simple quantum gates to a kernel is something we want to keep 100% backward compatible, but the more advanced gate() signatures may change in the (near) future.

NOTE: classical logic is on the list to be completely revised. This interface may change in the (near) future.

NOTE: the higher-order functions for constructing controlled kernels and conjugating kernels have not been maintained for a while and thus probably won’t work right. They may be removed entirely in a later version of OpenQL.

property name

The name of the kernel as given by the user.

property platform

The platform that the kernel was built for.

property qubit_count

The number of (virtual) qubits allocated for the kernel.

property creg_count

The number of classical integer registers allocated for the kernel.

property breg_count

The number of classical bit registers allocated for the kernel.

__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0, breg_count: int = 0)Kernel
__init__(self, name: str, platform: Platform, qubit_count: int = 0, creg_count: int = 0)Kernel
__init__(self, name: str, platform: Platform, qubit_count: int = 0)Kernel
__init__(self, name: str, platform: Platform)Kernel
get_custom_instructions(self)str

Old alias for dump_custom_instructions(). Deprecated.

Parameters

None

Returns

A newline-separated list of all custom gates supported by the platform.

Return type

str

print_custom_instructions(self)None

Prints a list of all custom gates supported by the platform.

Parameters

None

Returns

Return type

None

dump_custom_instructions(self)str

Returns the result of print_custom_instructions() as a string.

Parameters

None

Returns

A newline-separated list of all custom gates supported by the platform.

Return type

str

gate_preset_condition(self, condstring: str, condregs: List[int])None

Sets the condition for all gates subsequently added to this kernel. Thus, essentially shorthand notation. Reset with gate_clear_condition().

Parameters
  • condstring (str) –

    Must be one of:

    • ”COND_ALWAYS” or “1”: no condition; gate is always executed.

    • ”COND_NEVER” or “0”: no condition; gate is never executed.

    • ”COND_UNARY” or “” (empty): gate is executed if the single bit specified via condregs is 1.

    • ”COND_NOT” or “!”: gate is executed if the single bit specified via condregs is 0.

    • ”COND_AND” or “&”: gate is executed if the two bits specified via condregs are both 1.

    • ”COND_NAND” or “!&”: gate is executed if either of the two bits specified via condregs is zero.

    • ”COND_OR” or “|”: gate is executed if either of the two bits specified via condregs is one.

    • ”COND_NOR” or “!|”: no condition; gate is always executed.

  • condregs (List[int]) – Depending on condstring, must be a list of 0, 1, or 2 breg indices.

Returns

Return type

None

gate_clear_condition(self)None

Clears a condition previously set via gate_preset_condition().

Parameters

None

Returns

Return type

None

gate(self, name: str, q0: int)None
gate(self, name: str, q0: int, q1: int)None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0, bregs: List[int], condstring: str, condregs: List[int])None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0, bregs: List[int], condstring: str)None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0, bregs: List[int])None
gate(self, name: str, qubits: List[int], duration: int = 0, angle: float = 0.0)None
gate(self, name: str, qubits: List[int], duration: int = 0)None
gate(self, name: str, qubits: List[int])None
gate(self, name: str, qubits: List[int], destination: CReg)None
gate(self, u: Unitary, qubits: List[int])None

Main function for appending arbitrary quantum gates.

Parameters
  • name (str) – The name of the gate. Note that OpenQL currently uses string comparisons with these names all over the place to derive functionality, and to derive what the actual arguments do. This is inherently a bad idea and something we want to move away from, so documenting it all would not be worthwhile. For now, just use common sense, and you’ll probably be okay.

  • q0 (int) – Index of the first qubit to apply the gate to. For controlled gates, this is the control qubit.

  • q1 (int) – Index of the second qubit to apply the gate to. For controlled gates, this is the target qubit.

  • qubits (List[int]) – The full list of qubit indices to apply the gate to.

  • duration (int) – Gate duration in nanoseconds, or 0 to use the default value from the platform configuration file. This is primarily intended to be used for wait gates.

  • angle (float) – Rotation angle in radians for gates that use it (rx, ry, rz, etc). Ignored for all other gates.

  • bregs (List[int]) – The full list of bit register argument indices for the gate, excluding any bit registers used for conditional execution. Currently only used for the measure gate, which may be given an explicit bit register index to return its result in. If no such register is specified, the result is assumed to implicitly go to the bit register with the same index as the qubit being measured. Ignored for gates that don’t use bit registers.

  • condstring (str) –

    If specified, must be one of:

    • ”COND_ALWAYS” or “1”: no condition; gate is always executed.

    • ”COND_NEVER” or “0”: no condition; gate is never executed.

    • ”COND_UNARY” or “” (empty): gate is executed if the single bit specified via condregs is 1.

    • ”COND_NOT” or “!”: gate is executed if the single bit specified via condregs is 0.

    • ”COND_AND” or “&”: gate is executed if the two bits specified via condregs are both 1.

    • ”COND_NAND” or “!&”: gate is executed if either of the two bits specified via condregs is zero.

    • ”COND_OR” or “|”: gate is executed if either of the two bits specified via condregs is one.

    • ”COND_NOR” or “!|”: no condition; gate is always executed.

  • condregs (List[int]) – Depending on condstring, must be a list of 0, 1, or 2 breg indices.

  • destination (CReg) – An integer control register that receives the result of the mixed quantum-classical gate identified by name.

  • u (Unitary) – The unitary gate to insert.

Returns

Return type

None

state_prep(self, array: vectorc, qubits: List[int])None
condgate(self, name: str, qubits: List[int], condstring: str, condregs: List[int])None

Alternative function for appending normal conditional quantum gates. Avoids having to specify duration, angle, and bregs for gates that don’t need it.

Parameters
  • name (str) – The name of the gate. Note that OpenQL currently uses string comparisons with these names all over the place to derive functionality, and to derive what the actual arguments do. This is inherently a bad idea and something we want to move away from, so documenting it all would not be worthwhile. For now, just use common sense, and you’ll probably be okay.

  • qubits (List[int]) – The full list of qubit indices to apply the gate to.

  • condstring (str) –

    If specified, must be one of:

    • ”COND_ALWAYS” or “1”: no condition; gate is always executed.

    • ”COND_NEVER” or “0”: no condition; gate is never executed.

    • ”COND_UNARY” or “” (empty): gate is executed if the single bit specified via condregs is 1.

    • ”COND_NOT” or “!”: gate is executed if the single bit specified via condregs is 0.

    • ”COND_AND” or “&”: gate is executed if the two bits specified via condregs are both 1.

    • ”COND_NAND” or “!&”: gate is executed if either of the two bits specified via condregs is zero.

    • ”COND_OR” or “|”: gate is executed if either of the two bits specified via condregs is one.

    • ”COND_NOR” or “!|”: no condition; gate is always executed.

  • condregs (List[int]) – Depending on condstring, must be a list of 0, 1, or 2 breg indices.

Returns

Return type

None

classical(self, destination: CReg, operation: Operation)None
classical(self, operation: str)None

Appends a classical assignment gate to the circuit. The classical integer register is assigned to the result of the given operation.

Parameters
  • destination (CReg) – An integer control register at the left-hand side of the classical assignment gate.

  • operation (Operation) – The expression to evaluate on the right-hand side of the classical assignment gate.

Returns

Return type

None

identity(self, q0: int)None

Shorthand for an “identity” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

hadamard(self, q0: int)None

Shorthand for appending a “hadamard” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

s(self, q0: int)None

Shorthand for appending an “s” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

sdag(self, q0: int)None

Shorthand for appending an “sdag” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

t(self, q0: int)None

Shorthand for appending a “t” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

tdag(self, q0: int)None

Shorthand for appending a “tdag” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

x(self, q0: int)None

Shorthand for appending an “x” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

y(self, q0: int)None

Shorthand for appending a “y” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

z(self, q0: int)None

Shorthand for appending a “z” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

rx90(self, q0: int)None

Shorthand for appending an “rx90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

mrx90(self, q0: int)None

Shorthand for appending an “mrx90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

rx180(self, q0: int)None

Shorthand for appending an “rx180” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

ry90(self, q0: int)None

Shorthand for appending an “ry90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

mry90(self, q0: int)None

Shorthand for appending an “mry90” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

ry180(self, q0: int)None

Shorthand for appending an “ry180” gate with a single qubit.

Parameters

q0 (int) – The qubit to apply the gate to.

Returns

Return type

None

rx(self, q0: int, angle: float)None

Shorthand for appending an “rx” gate with a single qubit and the given rotation in radians.

Parameters
  • q0 (int) – The qubit to apply the gate to.

  • angle (float) – The rotation angle in radians.

Returns

Return type

None

ry(self, q0: int, angle: float)None

Shorthand for appending an “ry” gate with a single qubit and the given rotation in radians.

Parameters
  • q0 (int) – The qubit to apply the gate to.

  • angle (float) – The rotation angle in radians.

Returns

Return type

None

rz(self, q0: int, angle: float)None

Shorthand for appending an “rz” gate with a single qubit and the given rotation in radians.

Parameters
  • q0 (int) – The qubit to apply the gate to.

  • angle (float) – The rotation angle in radians.

Returns

Return type

None

measure(self, q0: int)None
measure(self, q0: int, b0: int)None

Shorthand for appending a “measure” gate with a single qubit and implicit or explicit result bit register.

Parameters
  • q0 (int) – The qubit to measure.

  • b0 (int) – The bit register to store the result in. If not specified, the result will be placed in the bit register corresponding to the index of the measured qubit.

Returns

Return type

None

prepz(self, q0: int)None

Shorthand for appending a “prepz” gate with a single qubit.

Parameters

q0 (int) – The qubit to prepare in the Z basis.

Returns

Return type

None

cnot(self, q0: int, q1: int)None

Shorthand for appending a “cnot” gate with two qubits.

Parameters
  • q0 (int) – The control qubit index.

  • q1 (int) – The target qubit index

Returns

Return type

None

cphase(self, q0: int, q1: int)None

Shorthand for appending a “cphase” gate with two qubits.

Parameters
  • q0 (int) – The first qubit index.

  • q1 (int) – The second qubit index.

Returns

Return type

None

cz(self, q0: int, q1: int)None

Shorthand for appending a “cz” gate with two qubits.

Parameters
  • q0 (int) – The first qubit index.

  • q1 (int) – The second qubit index.

Returns

Return type

None

toffoli(self, q0: int, q1: int, q2: int)None

Shorthand for appending a “toffoli” gate with three qubits.

Parameters
  • q0 (int) – The first control qubit index.

  • q1 (int) – The second control qubit index.

  • q2 (int) – The target qubit index.

Returns

Return type

None

clifford(self, id: int, q0: int)None

Shorthand for appending the Clifford gate with the specific number using the minimal number of rx90, rx180, mrx90, ry90, ry180, and mry90 gates.

Parameters
  • id (int) –

    The Clifford gate expansion index:

    • 0: no gates inserted.

    • 1: ry90; rx90

    • 2: mrx90, mry90

    • 3: rx180

    • 4: mry90, mrx90

    • 5: rx90, mry90

    • 6: ry180

    • 7: mry90, rx90

    • 8: rx90, ry90

    • 9: rx180, ry180

    • 10: ry90, mrx90

    • 11: mrx90, ry90

    • 12: ry90, rx180

    • 13: mrx90

    • 14: rx90, mry90, mrx90

    • 15: mry90

    • 16: rx90

    • 17: rx90, ry90, rx90

    • 18: mry90, rx180

    • 19: rx90, ry180

    • 20: rx90, mry90, rx90

    • 21: ry90

    • 22: mrx90, ry180

    • 23: rx90, ry90, mrx90

  • q0 (int) – The target qubit.

Returns

Return type

None

wait(self, qubits: List[int], duration: int)None

Shorthand for appending a “wait” gate with the specified qubits and duration in nanoseconds. If no qubits are specified, the wait applies to all qubits instead (a wait with no qubits is meaningless). Note that the duration will usually end up being rounded up to multiples of the platform’s cycle time.

Parameters
  • qubits (List[int]) – The list of qubits to apply the wait gate to. If empty, the list will be replaced with the set of all qubits.

  • duration (int) – The duration of the wait gate in nanoseconds.

Returns

Return type

None

barrier(self, qubits: List[int])None
barrier(self)None

Shorthand for appending a “wait” gate with the specified qubits and duration 0. If no qubits are specified, the wait applies to all qubits instead (a wait with no qubits is meaningless).

Parameters

qubits (List[int]) – The list of qubits to apply the wait gate to. If empty or unspecified, the list will be replaced with the set of all qubits.

Returns

Return type

None

display(self)None

Shorthand for appending a “display” gate with no qubits.

Parameters

None

Returns

Return type

None

diamond_excite_mw(self, envelope: int, duration: int, frequency: int, phase: int, amplitude: int, qubit: int)None

Appends the diamond “excite_mw” instruction.

Parameters
  • envelope (int) – The envelope of the microwave.

  • duration (int) – The duration of the microwave in nanoseconds.

  • frequency (int) – The frequency of the microwave in kilohertz.

  • phase (int) – The phase of the microwave.

  • amplitude (int) – The amplitude of the microwave.

  • qubit (int) – The target qubit index.

Returns

Return type

None

diamond_memswap(self, qubit: int, nuclear_qubit: int)None

Appends the diamond “memswap” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • nuclear_qubit (int) – The index of the nuclear spin qubit of the color center.

Returns

Return type

None

diamond_qentangle(self, qubit: int, nuclear_qubit: int)None

Appends the diamond “qentangle” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • nuclear_qubit (int) – The index of the nuclear spin qubit of the color center.

Returns

Return type

None

diamond_sweep_bias(self, qubit: int, value: int, dacreg: int, start: int, step: int, max: int, memaddress: int)None

Appends the diamond “sweep_bias” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • value (int) – The value that has to be send to the dac for biasing.

  • dacreg (int) – The index or address of the register of the dac.

  • start (int) – The start frequency value of the sweep.

  • step (int) – The step frequency value of the sweep.

  • max (int) – The maximum frequency value of the sweep.

  • memaddress (int) – The memory address to write the results to.

Returns

Return type

None

diamond_crc(self, qubit: int, threshold: int, value: int)None

Appends the diamond “crc” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • treshold (int) – The threshold value that has to be matched.

  • value (int) – The value of the voltage sent to the dac.

Returns

Return type

None

diamond_rabi_check(self, qubit: int, measurements: int, duration: int, t_max: int)None

Appends the diamond “rabi_check” instruction.

Parameters
  • qubit (int) – The index of the qubit.

  • measurements (int) – How manu measurements have to be recorded.

  • duration (int) – The starting value of the duration of the microwave.

  • t_max (int) – The value of the voltage sent to the dac.

Returns

Return type

None

controlled(self, k: Kernel, control_qubits: List[int], ancilla_qubits: List[int])None

Appends a controlled kernel. The number of control and ancilla qubits must be equal.

Parameters
  • k (Kernel) – The kernel to make controlled.

  • control_qubits (List[int]) – The qubits that control the kernel.

  • ancilla_qubits (List[int]) – The ancilla qubits to use to make the kernel controlled. The number of ancilla qubits must equal the number of control qubits.

Returns

Return type

None

conjugate(self, k: Kernel)None

Appends the conjugate of the given kernel to this kernel.

NOTE: this high-level functionality is poorly/not maintained, and relies on default gates, which are on the list for removal.

Parameters

k (Kernel) – The kernel to conjugate.

Returns

Return type

None

class openql.CReg(id)

Wrapper for a classical integer register with the given index.

NOTE: classical logic is on the list to be completely revised. This interface may change in the (near) future.

__init__(self, id: int)CReg
class openql.Operation(*args)

Wrapper for a classical operation.

A classical operation acts as a simple expression that returns an integer or a boolean. The expression can be a literal number (val), a single CReg (lop, primarily used for assignments), a unary function applied to one CReg (op/rop), or a binary function applied to two CRegs (lop/op/rop).

Function selection is done via strings. The following unary functions are recognized:

  • ‘~’: bitwise NOT.

The following binary functions are recognized:

  • ‘+’: addition.

  • ‘-‘: subtraction.

  • ‘&’: bitwise AND.

  • ‘|’: bitwise OR.

  • ‘^’: bitwise XOR.

  • ‘==’: equality.

  • ‘!=’: inequality.

  • ‘>’: greater-than.

  • ‘>=’: greater-or-equal.

  • ‘<’: less-than.

  • ‘<=’: less-or-equal.

NOTE: classical logic is on the list to be completely revised. This interface may change in the (near) future.

__init__(self, lop: CReg, op: str, rop: CReg)Operation
__init__(self, op: str, rop: CReg)Operation
__init__(self, lop: CReg)Operation
__init__(self, val: int)Operation
class openql.Unitary(name, matrix)

Unitary matrix interface.

The constructor creates a unitary gate from the given row-major, square, unitary matrix.

property name

The name given to the unitary gate.

__init__(self, name: str, matrix: vectorc)Unitary
decompose(self)None

Explicitly decomposes the gate. Does not need to be called; it will be called automatically when the gate is added to the kernel.

Parameters

None

Returns

Return type

None

static is_decompose_support_enabled()bool

Returns whether OpenQL was built with unitary decomposition support enabled.

Parameters

None

Returns

Whether OpenQL was built with unitary decomposition support enabled.

Return type

bool

class openql.Compiler(*args)

Wrapper for the compiler/pass manager.

This allows you to change the compilation strategy, if the defaults are insufficient for your application. You can get access to a Compiler via several methods:

  • using Platform.get_compiler();

  • using Program.get_compiler();

  • using one of the constructors.

Using the constructors, you can get an empty compiler (by specifying no arguments or only specifying name), a default compiler for a given platform (by specifying a name and a platform), or a compiler based on a compiler configuration JSON file (by specifying a name and a filename). For the structure of this JSON file, refer to the configuration section of the ReadTheDocs documentation or, equivalently, the result of openql.print_compiler_docs().

property name

User-given name for this compiler.

NOTE: not actually used for anything. It’s only here for consistency with the rest of the API objects.

__init__(self, name: str)Compiler
__init__(self)Compiler
__init__(self, name: str, filename: str)Compiler
__init__(self, name: str, platform: Platform)Compiler
print_pass_types(self)None

Prints documentation for all available pass types, as well as the option documentation for the passes.

Parameters

None

Returns

Return type

None

dump_pass_types(self)str

Returns documentation for all available pass types, as well as the option documentation for the passes.

Parameters

None

Returns

The list of pass types and their documentation as a multiline string.

Return type

str

print_strategy(self)None

Prints the currently configured compilation strategy.

Parameters

None

Returns

Return type

None

dump_strategy(self)str

Returns the currently configured compilation strategy as a string.

Parameters

None

Returns

The current compilation strategy as a multiline string.

Return type

str

set_option(self, path: str, value: str, must_exist: bool = True)int
set_option(self, path: str, value: str)int

Sets a pass option. The path must consist of the target pass instance name and the option name, separated by a period. The former may include * or ? wildcards. If must_exist is set an exception will be thrown if none of the passes were affected, otherwise 0 will be returned.

Parameters
  • path (str) – The path to the option, consisting of the pass name and the option name separated by a period.

  • value (str) – The value to set the option to.

  • must_exist (bool) – When set, an exception will be thrown when no options matched the path.

Returns

The number of pass options affected.

Return type

int

get_option(self, path: str)str

Returns the current value of an option.

Parameters

path (str) – The path to the option, consisting of pass name and the actual option name separated by a period.

Returns

The value of the option. If the option has not been set, the default value is returned.

Return type

str

append_pass(self, type_name: str, instance_name: str, options: Dict[str, str])Pass
append_pass(self, type_name: str, instance_name: str)Pass
append_pass(self, type_name: str)Pass

Appends a pass to the end of the pass list. Returns a reference to the constructed pass.

Parameters
  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

prefix_pass(self, type_name: str, instance_name: str, options: Dict[str, str])Pass
prefix_pass(self, type_name: str, instance_name: str)Pass
prefix_pass(self, type_name: str)Pass

Appends a pass to the beginning of the pass list. Returns a reference to the constructed pass.

Parameters
  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

insert_pass_after(self, target: str, type_name: str, instance_name: str, options: Dict[str, str])Pass
insert_pass_after(self, target: str, type_name: str, instance_name: str)Pass
insert_pass_after(self, target: str, type_name: str)Pass

Inserts a pass immediately after the target pass (named by instance). If target does not exist, an exception is thrown. Returns a reference to the constructed pass.

Parameters
  • target (str) – The name of the pass to insert the new pass after.

  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

insert_pass_before(self, target: str, type_name: str, instance_name: str, options: Dict[str, str])Pass
insert_pass_before(self, target: str, type_name: str, instance_name: str)Pass
insert_pass_before(self, target: str, type_name: str)Pass

Inserts a pass immediately before the target pass (named by instance). If target does not exist, an exception is thrown. Returns a reference to the constructed pass.

Parameters
  • target (str) – The name of the pass to insert the new pass before.

  • type_name (str) – The type of the pass to add.

  • instance_name (str) – A unique name for the pass instance. If empty or unspecified, a name will be generated.

  • options (dict[str, str]) – A list of initial options to set for the pass. This is just shorthand notation for calling set_option() on the returned Pass object.

Returns

A reference to the added pass.

Return type

Pass

get_pass(self, target: str)Pass

Returns a reference to the pass with the given instance name. If no such pass exists, an exception is thrown.

Parameters

target (str) – The name of the pass to retrieve a reference to.

Returns

A reference to the targeted pass.

Return type

Pass

does_pass_exist(self, target: str)bool

Returns whether a pass with the target instance name exists.

Parameters

target (str) – The name of the pass to query existence of.

Returns

Whether a pass with the target name exists.

Return type

bool

get_num_passes(self)int

Returns the total number of passes in the root hierarchy.

Parameters

None

Returns

The number of passes (or groups) within the root pass list.

Return type

int

get_passes(self)List[Pass]

Returns a list with references to all passes in the root hierarchy.

Parameters

None

Returns

The list of all passes in the root hierarchy.

Return type

list[Pass]

get_passes_by_type(self, target: str)List[Pass]

Returns a list with references to all passes in the root hierarchy with the given type.

Parameters

target (str) – The target pass type name.

Returns

The list of all passes in the root hierarchy with the given type.

Return type

list[Pass]

remove_pass(self, target: str)None

Removes the pass with the given target instance name, or throws an exception if no such pass exists.

Parameters

target (str) – The name of the pass to remove.

Returns

Return type

None

clear_passes(self)None

Clears the entire pass list.

Parameters

None

Returns

Return type

None

compile(self, program: Program)None

Ensures that all passes have been constructed, and then runs the passes on the given program. This is the same as Program.compile() when the program is referencing the same compiler.

Parameters

program (Program) – The program to compile.

Returns

Return type

None

compile_with_frontend(self, platform: Platform)None

Ensures that all passes have been constructed, and then runs the passes without specification of an input program. The first pass should then act as a language frontend. The cQASM reader satisfies this requirement, for instance.

If no platform is specified, it will default to the none architecture, but the intended use case is to have the first pass load the platform. Again, the cQASM reader can do this.

Parameters

platform (Platform) – The platform to compile for.

Returns

Return type

None

class openql.Pass

Wrapper for a pass that belongs to some pass manager.

NOTE: while it’s possible to construct a pass manually, the resulting object cannot be used in any way. The only way to obtain a valid pass object is through a Compiler object.

__init__(self)Pass
get_type(self)str

Returns the full, desugared type name that this pass was constructed with.

Parameters

None

Returns

The type name.

Return type

str

get_name(self)str

Returns the instance name of the pass within the surrounding group.

Parameters

None

Returns

The instance name.

Return type

str

print_pass_documentation(self)None

Prints the documentation for this pass.

Parameters

None

Returns

Return type

None

dump_pass_documentation(self)str

Returns the documentation for this pass as a string.

Parameters

None

Returns

The documentation for this pass as a multiline string.

Return type

str

print_options(self, only_set: bool = False)None
print_options(self)None

Prints the current state of the options.

Parameters

only_set (bool) – When set, only the options that were explicitly configured are dumped.

Returns

Return type

None

dump_options(self, only_set: bool = False)str
dump_options(self)str

Returns the string printed by print_options().

Parameters

only_set (bool) – When set, only the options that were explicitly configured are dumped.

Returns

The option documentation as a multiline string.

Return type

str

set_option(self, option: str, value: str)None

Sets an option.

Parameters
  • option (str) – The option name.

  • value (str) – The value to set the option to.

Returns

Return type

None

get_option(self, option: str)str

Returns the current value of an option.

Parameters

path (str) – The path to the option.

Returns

The value of the option. If the option has not been set, the default value is returned.

Return type

str

class openql.cQasmReader(*args)

Legacy cQASM reader interface.

The preferred way to read cQASM files is to use the cQASM reader pass (io.cqasm.read). The pass supports up to cQASM 1.2, and handles all features that OpenQL supports within its intermediate representation properly, whereas this interface only supports version 1.0 and requires an additional JSON file with gate conversion rules to work.

To read a cQASM file using this interface, build a cQASM reader for the an already-existing program, and then call file2circuit or string2circuit to add the kernels from the cQASM file/string to the program. Optionally a platform can be specified as well, but this is redundant (it must be the same platform as the one that the program was constructed with); these overloads only exist for backward compatibility.

Because OpenQL supports custom gates and cQASM (historically) does not, and also because OpenQL’s internal representation of gates is still a bit different from what cQASM uses (at least when constructing the IR using the Python API), you may need custom conversion rules for the gates. This can be done by specifying a gateset configuration JSON file using gateset_fname. This file must consist of a JSON array containing objects with the following structure:

{
    "name": "<name>",               # mandatory
    "params": "<typespec>",         # mandatory
    "allow_conditional": <bool>,    # whether conditional gates of this type are accepted, defaults to true
    "allow_parallel": <bool>,       # whether parallel gates of this type are accepted, defaults to true
    "allow_reused_qubits": <bool>,  # whether reused qubit args for this type are accepted, defaults to false
    "ql_name": "<name>",            # defaults to "name"
    "ql_qubits": [                  # list or "all", defaults to the "Q" args
        0,                          # hardcoded qubit index
        "%0"                        # reference to argument 0, which can be a qubitref, bitref, or int
    ],
    "ql_cregs": [                   # list or "all", defaults to the "I" args
        0,                          # hardcoded creg index
        "%0"                        # reference to argument 0, which can be an int variable reference, or int for creg index
    ],
    "ql_bregs": [                   # list or "all", defaults to the "B" args
        0,                          # hardcoded breg index
        "%0"                        # reference to argument 0, which can be an int variable reference, or int for creg index
    ],
    "ql_duration": 0,               # duration; int to hardcode or "%i" to take from param i (must be of type int), defaults to 0
    "ql_angle": 0.0,                # angle; float to hardcode or "%i" to take from param i (must be of type int or real), defaults to first arg of type real or 0.0
    "ql_angle_type": "<type>",      # interpretation of angle arg; one of "rad" (radians), "deg" (degrees), or "pow2" (2pi/2^k radians), defaults to "rad"
    "implicit_sgmq": <bool>,        # if multiple qubit args are present, a single-qubit gate of this type should be replicated for these qubits (instead of a single gate with many qubits)
    "implicit_breg": <bool>         # the breg operand(s) that implicitly belongs to the qubit operand(s) in the gate should be added to the OpenQL operand list
}

The typespec string defines the expected argument types for the gate. Each character in the string represents an argument. The following characters are supported by libqasm:

  • Q = qubit

  • B = assignable bit/boolean (measurement register)

  • b = bit/boolean

  • a = axis (x, y, or z)

  • I = assignable integer

  • i = integer

  • r = real

  • c = complex

  • u = complex matrix of size 4^n, where n is the number of qubits in the parameter list (automatically deduced)

  • s = (quoted) string

  • j = json

Note that OpenQL only uses an argument if it is referred to in one of the “ql_*” keys, either implicitly or explicitly.

If no custom configuration is specified, the reader defaults to the logic that was hardcoded before it was made configurable. This corresponds to the following JSON:

[
    {"name": "measure",     "params": "Q",      "ql_name": "measz"},
    {"name": "measure",     "params": "QB",     "ql_name": "measz"},
    {"name": "measure_x",   "params": "Q",      "ql_name": "measx"},
    {"name": "measure_x",   "params": "QB",     "ql_name": "measx"},
    {"name": "measure_y",   "params": "Q",      "ql_name": "measy"},
    {"name": "measure_y",   "params": "QB",     "ql_name": "measy"},
    {"name": "measure_z",   "params": "Q",      "ql_name": "measz"},
    {"name": "measure_z",   "params": "QB",     "ql_name": "measz"},
    {"name": "prep",        "params": "Q",      "ql_name": "prepz"},
    {"name": "prep_x",      "params": "Q",      "ql_name": "prepx"},
    {"name": "prep_y",      "params": "Q",      "ql_name": "prepy"},
    {"name": "prep_z",      "params": "Q",      "ql_name": "prepz"},
    {"name": "i",           "params": "Q"},
    {"name": "h",           "params": "Q"},
    {"name": "x",           "params": "Q"},
    {"name": "y",           "params": "Q"},
    {"name": "z",           "params": "Q"},
    {"name": "s",           "params": "Q"},
    {"name": "sdag",        "params": "Q"},
    {"name": "t",           "params": "Q"},
    {"name": "tdag",        "params": "Q"},
    {"name": "x90",         "params": "Q",      "ql_name": "rx90"},
    {"name": "mx90",        "params": "Q",      "ql_name": "xm90"},
    {"name": "y90",         "params": "Q",      "ql_name": "ry90"},
    {"name": "my90",        "params": "Q",      "ql_name": "ym90"},
    {"name": "rx",          "params": "Qr"},
    {"name": "ry",          "params": "Qr"},
    {"name": "rz",          "params": "Qr"},
    {"name": "cnot",        "params": "QQ"},
    {"name": "cz",          "params": "QQ"},
    {"name": "swap",        "params": "QQ"},
    {"name": "cr",          "params": "QQr"},
    {"name": "crk",         "params": "QQi",    "ql_angle": "%2", "ql_angle_type": "pow2"},
    {"name": "toffoli",     "params": "QQQ"},
    {"name": "measure_all", "params": "",       "ql_qubits": "all", "implicit_sgmq": true},
    {"name": "display",     "params": ""},
    {"name": "wait",        "params": ""},
    {"name": "wait",        "params": "i"}
]
property platform

The platform associated with the reader.

property program

The program that the cQASM circuits will be added to.

__init__(self, platform: Platform, program: Program, gateset_fname: str)cQasmReader
__init__(self, platform: Platform, program: Program)cQasmReader
__init__(self, program: Program, gateset_fname: str)cQasmReader
__init__(self, program: Program)cQasmReader
string2circuit(self, cqasm_str: str)None

Interprets a string as cQASM file and adds its contents to the program associated with this reader.

Parameters

cqasm_str (str) – The string representing the contents of the cQASM file.

Returns

Return type

None

file2circuit(self, cqasm_file_path: str)None

Interprets a string as cQASM file and adds its contents to the program associated with this reader.

Parameters

cqasm_file_path (str) – The path to the cQASM file to load.

Returns

Return type

None