# Config¶

 trueq.Config Contains the relevant configuration of a system, including which gates are available to be run, how many systems there are and the dimension of the individual systems. trueq.config.GateFactory Constructs new NativeGates according to a functional description. trueq.config.InvolvingRule A dictionary containing allowable sets of systems. trueq.config.factory.parse_func Creates a Python function from a string containing numbers, variables, and standard math functions.

## Config¶

class trueq.Config(mode='ZXZXZ', factories=None, dim=2)

Contains the relevant configuration of a system, including which gates are available to be run, how many systems there are and the dimension of the individual systems.

This class relies on GateFactorys to describe what gates are available on the hardware, see that documentation for more details.

Here we use a convenience method to create a basic config which may be sufficient in many cases. This config will define a total of three possible gates on the system, two single qubit gates Z (a pauli Z rotation) and X90 (a pauli X rotation of 90 degrees), and a single two qubit gate defined by the entangler keyword.

import trueq as tq
config = tq.Config.basic(entangler=tq.Gate.cnot, mode="ZXZXZ")

# we can access the GateFactory objects via the factories attribute.
config.factories

# for ease of use, individual factories are available as attributes of the config
config.Z

# lets make an Z90 gate using this definition:
config.Z(phi=90)

True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".
Name:
• Z(phi)
Aliases:
• Gate.s
• Gate.cliff9
Parameters:
• phi = 90
Generators:
• 'Z': 90.0
Matrix:

These configs can be saved to a YAML file and loaded back in the future. This facilitates including topology and gate restrictions by specifying Involving keys in the YAML. See from_yaml and to_yaml for more details.

Parameters
Return type

Config

Raises

ValueError – If the provided mode is not defined in QubitMode.

static basic(entangler=Gate.cx, mode='ZXZXZ', dim=2)

Creates a new Config object containing a fixed entangling gate and the Pauli rotation gates required to decompose single-qubit gates into the specified mode.

import trueq as tq
config = tq.Config.basic(entangler=tq.Gate.cnot, mode="ZXZXZ")

# we can access the GateFactory objects via the factories attribute.
config.factories

# individual factories are available as attributes of the config
config.Z

# lets make an Z90 gate using this definition:
config.Z(phi=90)

True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".
Name:
• Z(phi)
Aliases:
• Gate.s
• Gate.cliff9
Parameters:
• phi = 90
Generators:
• 'Z': 90.0
Matrix:
Parameters
• entangler (Gate) – The entangling gate.

• mode (str) – The single qubit decomposition mode, defaults to 'ZXZXZ'

• dim (int) – The dimension of computational system, defaults to 2 (qubits)

Return type

Config

Raises

ValueError – If the provided mode is not defined in QubitMode.

property connectivity

The connectivity graph of all multi-qubit gates in the config.

A set of frozensets which contain all multi-qubit connections defined by the factories present in the config.

Type

set

property dim

The dimension of systems (e.g., 2 for qubits, 3 for qutrits).

Type

int

static from_params(*args, **kwargs)

from_params() was deprecated in version 2.8.0 and will be removed after version 2.9.0. Config.from_params was renamed to Config.__init__ None

static from_parameterized(multiqubit_fact, parameters, mode='ZXZ')

A convenience method for making a configuration file for a quantum system with fixed multi-qubit gates with nonhomogenous parameters.

The example below defines a config containing two fixed rotation entangling gates which are specific parameter combinations of the defined trueq.config.GateFactory. This enables a config to be defined using known interactions, such as the Cross-Resonance interaction, but have unique fixed parameter gate for each physical gate present in hardware.

import trueq as tq
iSwapLike_mat = [[1, 0, 0, 0],
[0, 0, -1j, 0],
[0, -1j, 0, 0],
[0, 0, 0, "exp(-1j * phi / 180)"],
]
iSwapLike_factory = tq.config.GateFactory("iSwapLike", matrix=iSwapLike_mat)
parameters = {(0, 1): 90, (2, 3): 45}
conf = tq.Config.from_parameterized(iSwapLike_factory, parameters)
conf.iSwapLike_0_1()

True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".
Name:
• iSwapLike_0_1()
Likeness:
• Non-Clifford
Generators:
• 'IZ': -14.324
• 'XX': -90.0
• 'YY': -90.0
• 'ZI': -14.324
• 'ZZ': 194.324
Matrix:
Parameters
• multiqubit_fact (GateFactory) – A gate factory that can generate the nonhomogenous gates that can be implemented in the system.

• parameters (dict) – A dictionary mapping tuples of qubit labels to parameters of the given mulit-qubit factory to be used on those particular qubits.

• mode (str) – The mode used to decompose single-qubit operations.

Return type

Config

Raises
• ValueError – If an incorrect number of labels are provided in parameters.

• ValueError – If the provided mode is not defined in QubitMode.

static make_config(*args, **kwargs)

make_config() was deprecated in version 2.8.0 and will be removed after version 2.9.0. Config.make_config was renamed to Config.from_parameterized None

static from_yaml(conf)

Construct a Config from the contents of a yaml file, or filename.

A minimal example .yaml file is presented below. The YAML below defines a four-qubit system, where the gates available are:

• Arbitrary $X(\phi)$ rotations, which cannot be applied while the neighboring qubits are in use.

• Arbitrary $Z(\phi)$ rotations, which can be applied in parallel with anything

• CNOT, which can never be used in parallel with any other gate.

Note that gates can either be defined by the Hamiltonian or Matrix keyword, but never both.

import trueq as tq

file_contents = '''
Dimension: 2
Mode: ZXZXZ
Gate X:
Hamiltonian:
- ['X', phi]
Involving:
(0,) : (1, 2)
(1,) : (0, 2)
(2,) : (1, 3)
(3,) : (2,)
Gate Z:
Hamiltonian:
- ['Z', phi]
Involving:
(0,) : ()
(1,) : ()
(2,) : ()
(3,) : ()
Gate CNOT:
Matrix:
- [1, 0, 0, 0]
- [0, 1, 0, 0]
- [0, 0, 0, 1]
- [0, 0, 1, 0]
Involving:
(0, 1) : (2, 3)
(1, 2) : (0, 3)
(2, 3) : (0, 1)'''

# Configs can be loaded from either a filename, or the contents of a file:
tq.Config.from_yaml(file_contents)

Mode: ZXZXZ
Dimension: 2
Gate X:
Hamiltonian:
- [X, phi]
Involving: {'(0,)': '(1, 2)', '(1,)': '(0, 2)', '(2,)': '(1, 3)', '(3,)': '(2,)'}
Gate Z:
Hamiltonian:
- [Z, phi]
Involving: {'(0,)': (), '(1,)': (), '(2,)': (), '(3,)': ()}
Gate CNOT:
Matrix:
- ['1', '0', '0', '0']
- ['0', '1', '0', '0']
- ['0', '0', '0', '1']
- ['0', '0', '1', '0']
Involving: {'(0, 1)': '(2, 3)', '(1, 2)': '(0, 3)', '(2, 3)': '(0, 1)'}


The above config contains information about physical limitations of the gates. This information is encoded in the Involving key inside of the gate definitions. This involving key is a dictionary whose keys are the sets of systems on which the gate can act. In the YAML example above, the X gate can be applied to any of qubits 0, 1, 2, 3.

The values of the dictionary list which systems cannot have any gates applied to them while the gate acts on the systems specified by the key. For example, when the X gate in the above config is run on qubit 0, no other gates may be applied in parallel on either qubit 1 or 2.

This Involving information is used during compilation to ensure that circuits are compatable with the physical limitations of the hardware.

Since we allow arbitrary functional definition of gates using functions that can be using parse_func(), the Config object can be used to generate new NativeGate objects on the fly based upon the variables defined in the YAML.

Parameters

conf (str) – Path to a configuration YAML file, or a YAML file as a string.

Raises

ValueError – If conf is not a string to a YAML file or the contents of a valid YAML file.

property mode

The mode by which arbitrary single-qubit gates are decomposed in the system to native gates.

Return type

str

subset(labels=None, names=None, strict=True)

Creates a new Config object containing a subset of the gate factories present in this configuration, and each of whose involving rules has been trimmed based on the given labels.

import trueq as tq

# create an basic config using cz gates as the entangler
config = tq.Config.basic(entangler=tq.Gate.cz)

# make a new config acting only on qubits 2, 3 restricted to gates z, cz
config.subset(labels=[2, 3], names=["z", "cz"])

Mode: ZXZXZ
Dimension: 2
Gate cz:
Matrix:
- [(1+0j), 0j, 0j, 0j]
- [0j, (1+0j), 0j, 0j]
- [0j, 0j, (1+0j), 0j]
- [0j, 0j, 0j, (-1+0j)]
Involving: {}

Parameters
• labels (Iterable) – The labels to be present in the new config. If None, no filtering based on labels is done.

• names (Iterable) – A list of gate factory names to keep. If None, no filtering based on factory names is done.

• strict (bool) – Whether to filter gate factories based on being a strict subset of the given labels (True), or based on overlapping with labels at all (False).

Return type

Config

to_dict()

Returns a dictionary representation of this Config.

Return type

dict

to_yaml()

Returns a YAML representation of the Config.

Return type

str

## Gate Factory¶

class trueq.config.GateFactory(name, matrix=None, hamiltonian=None, involving=None, parameters=None, sys_dim=2)

Constructs new NativeGates according to a functional description.

This is useful when you have a description of a gate such as $X(\theta)$ which is an arbitrary rotation around the X axis by some angle $\theta$. Either a unitary matrix definition or Hamiltonian description of the gate may be provided, but not both.

Examples:

import trueq as tq
y_factory = tq.config.GateFactory(name='y', hamiltonian=[['Y', 'phi']])
y_factory(phi=90)

True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".
Name:
• y(phi)
Aliases:
• Gate.cliff7
Parameters:
• phi = 90
Generators:
• 'Y': 90.0
Matrix:
import trueq as tq
iSwapLike_mat = [[1,  0,  0,                      0],
[0,  0,-1j,                      0],
[0,-1j,  0,                      0],
[0,  0,  0, "exp(-1j * phi / 180)"]]
iSwap_factory = tq.config.GateFactory("iSwapLike", matrix=iSwapLike_mat)
iSwap_factory(phi=45)

True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".
Name:
• iSwapLike(phi)
Likeness:
• Non-Clifford
Parameters:
• phi = 45
Generators:
• 'IZ': -7.162
• 'XX': 90.0
• 'YY': 90.0
• 'ZI': -7.162
• 'ZZ': 7.162
Matrix:
import trueq as tq
import numpy as np
u3_factory = tq.config.GateFactory(
name="U3Gate",
hamiltonian=[
["Z", "phi * 180 / pi"],
["Y", "theta * 180 / pi"],
["Z", "lam * 180 / pi"],
],
parameters=["theta", "phi", "lam"],
)

u3_factory(np.pi/2, 0, 0)

True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".
Name:
• U3Gate(theta, phi, ...)
Aliases:
• Gate.cliff7
Parameters:
• theta = 1.570796
• phi = 0
• lam = 0
Generators:
• 'Y': 90.0
Matrix:

The U3 gate as defined by IBM, in this case the gate is defined in terms of radians in the IBM definition (note that this definition is in multiplicative order, but the above Hamiltonian definition is in time order):

$U3(\theta, \phi, \lambda) = Z(\lambda)Y(\theta)Z(\phi)$

This radian based definition means that there has to be a conversion constant on each of the parameters phi, theta, lam from radians to degrees. Additionally, the order of the parameters is important in the U3 definition, so the GateFactory is defined with the parameters options so that the order is recorded correctly.

Parameters
• name (str) – Name of the gate operation which must be a valid identifier examples: CZ, X, CNOT.

• matrix (list) – A unitary matrix description of the gate, this may include string definitions of functions which will be parsed on instantiation and converted into numerical representations which are equivalent to the Hamiltonian description. The matrix definition must be writable as a product of generator matrices $\prod_i e^{i A_i \cdot t_i}$, where each parameter $t_i$ appear only once. If this requirement is too restrictive, the gate may be defined more generally using the Hamiltonian.

• hamiltonian (list) – A Hamiltonian generator description of the gate, defined above. The values may be strings which are parsable into values. The list of provided Hamiltonians will be applied in time ordering, and are not required to commute.

• involving (dict) – A dictionary describing the limitations of the gate, see Config description for a more in-depth description.

• parameters (list) – An optional list of the parameters present in the definition, this allows for the preferred ordering of the parameters to be specified. If None is provided, then parameter names are inferred from the definition in a deterministic but arbitrary order.

• sys_dim (int) – The dimension of the subsystem defined by this gate, defaults to 2 for qubits.

Raises

ValueError – If invalid input arguments or argument combinations are provided.

subset(labels=None, strict=True)

Creates a new GateFactory object with a set of involving rules that is a subset of this factory’s rules.

import trueq as tq
import numpy as np

involving = {(0, 1): (2, 3), (1, 2): (3,), (2, 3): (1,), (3, 8): ()}
factory = tq.config.GateFactory(
name="cz", matrix=np.diag([1, 1, 1, -1]), involving=involving
)

subset = factory.subset(labels=(0, 1, 2), strict=True)
assert subset.involving.rules == {(0, 1): (2, 3), (1, 2): (3,)}
subset

GateFactory(name='cz', matrix=[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]], involving=InvolvingRule(rules={(0, 1): (2, 3), (1, 2): (3,)}, default_allow=False))

Parameters
• labels (Iterable) – The labels to be present in the new config. If None, no filtering based on labels is done.

• strict (bool) – Whether to filter involving labels based on being a strict subset of the given labels (True), or based on overlapping with labels at all (False).

Return type

Config

property pauli_const

If this factory is a simple rotation about a single Pauli axis, specifically a gate which is representable by $exp^{-i \frac{\pi}{360} \text{pauli} \cdot \text{constant} \cdot \text{param}}$, then pauli_const is a tuple which represents the rotation, (Pauli, constant).

If the gate cannot be written in terms of a single Pauli rotation, then pauli_const is (None, None).

import trueq as tq
import numpy as np

factory = tq.config.GateFactory(name="Rz", hamiltonian=[['Z', '5 * phi']])

assert factory.pauli_const[0] == 'Z'
assert abs(factory.pauli_const[1] - 5) < 1e-10

Type

tuple

property pauli_angle

If this factory is a simple fixed angle rotation about a single Pauli axis which may be written as $exp^{-i \frac{\pi}{360} \cdot \text{Pauli} \cdot \text{angle}}$, then pauli_angle is a tuple which represents the rotation, (Pauli, angle).

If the gate cannot be written in terms of a single Pauli rotation, then pauli_angle is (None, None).

import trueq as tq

factory = tq.config.GateFactory(name="Rz", hamiltonian=[['Z', '90']])
assert factory.pauli_angle == ('Z', 90)

Type

tuple

make_gate(*args, **kwargs)

Returns a NativeGate based upon the parameters provided.

Note

Constructed NativeGate objects are memoized and cached based upon the kwargs.

Return type

NativeGate

Raises
• ValueError – If the arguments do not match the parameters found in the description of the gate.

• KeyError – If a functional parameter is missing from kwargs.

property n_sys

The number of systems this gate factory acts on.

Type

int

property sys_dim

The dimension of the subsystems this gate factory acts on.

Type

int

property width

The width of gates produced by this factory, e.g., 2 for a single qubit, 4 for two qubits, etc.

Type

int

property parameters

The list of all the parameters in the functional definition of the gate.

Type

list

property n_params

The number of parameters in the functional definition of the gate.

Type

int

property involving

A specification of which systems can be involved in the gate operation.

Type

InvolvingRule

to_dict()

Returns a dictionary representation of the factory object.

Return type

dict

## Involving Rule¶

class trueq.config.InvolvingRule(rules=None, default_allow=None)

A dictionary containing allowable sets of systems.

from trueq.config import InvolvingRule

# In the default case, any involving check returns as valid
rule = InvolvingRule()

(5, ) in rule,  rule[(1, 5)]

(True, ())

from trueq.config import InvolvingRule

# In the case where rules are provided, it will return the rules
rule = InvolvingRule(rules={(0,): (2, 3, 4)})

rule[(0,)], (1, ) in rule

((2, 3, 4), False)

from trueq.config import InvolvingRule

# In the case where rules are provided, and default_allow=True
# and will return True for all other cases
rule = InvolvingRule(rules={(0,): (2, 3, 4)}, default_allow=True)

rule[(0,)], rule[(1,)]

((2, 3, 4), ())


See Config for more details on how these rules are used.

Parameters
• rules (dict) – A dictionary with both keys and values being tuples of ints. The key represents allowed operations, and the values represent blocking operations that get placed on other qubits due to the key labels.

• default_allow (bool | None) – Defines the behavior if a key is not present in the ruleset. If True, then if a key is not found in the rules, InvolvingRule acts as though it were present. If False, InvolvingRule raise KeyErrors. If None, then default_allow is set to True if no rules are provided, and False if rules are provided.

keys()

Returns the keys for given rules.

Return type

generator

values()

Returns the values for given rules.

Return type

generator

items()

Returns the key, value pairs for given rules.

Return type

generator

unordered_get(key)

Gets the value associated with a given key, regardless of the ordering.

This returns a list of tuples, where the tuples contain the required ordering as defined by the rules, along with the value associated with that key.

from trueq.config import InvolvingRule
rule = InvolvingRule(rules={(0, 1): (2, 3, 4)})

rule.unordered_get((1, 0))

[((0, 1), (2, 3, 4))]


This is useful when connectivity matters, but not the strict ordering of labels.

Parameters

key (tuple) – The key to fetch, must be a tuple of ints.

Return type

tuple

Raises

KeyError – If labels are not present in rules.

unordered_contains(key)

Determines if any permutation of the given key is present in rules.

from trueq.config import InvolvingRule
rule = InvolvingRule(rules={(0, 1): (2, 3, 4)})

rule.unordered_contains((1, 0))

True


This is useful when connectivity matters, but not the strict ordering of labels.

Parameters

key (tuple) – The key to fetch, must be a tuple of ints.

Return type

bool

## Parsing functions¶

trueq.config.factory.parse_func(func_str)

Creates a Python function from a string containing numbers, variables, and standard math functions.

from trueq.config.factory import parse_func, KNOWN_FUNCTIONS
f = parse_func('5*sin(x) + y')
print(f(x=np.pi, y=1))

# all functions in KNOWN_FUNCTIONS can be parsed
print(KNOWN_FUNCTIONS.keys())

1.0000000000000007
dict_keys(['sin', 'cos', 'tan', 'exp', 'sqrt', 'arcsin', 'arccos', 'arctan', 'round', 'ceil', 'floor', 'int', 'float', 'complex', 'pi', 'list', 'tuple', 'dict', 'set'])


Note

Parsing functions adds an overhead relative to directly calling numpy functions. The overhead is approximately a factor of 20 for simple functions.

Parameters

func_str (str) – A string describing the function to be created.

Return type

func

trueq.config.factory.find_parameters(func_str)

Finds all free parameters inside the text description of a fuction using exception handling.

from trueq.config.factory import find_parameters

params = find_parameters("sin(x) + phi / 2 + theta")
assert set(params) == {"x", "phi", "theta"}

Parameters

func_str (str) – A string describing the function.

Return type

list

## Pre-Defined factories¶

factory.u1_factory = GateFactory(name='U1Gate', hamiltonian=[['Z', 'lam * 180 / pi']])
factory.u2_factory = GateFactory(name='U2Gate', hamiltonian=[['Z', 'phi * 180 / pi'], ['Y', '90'], ['Z', 'lam * 180 / pi']])
factory.u3_factory = GateFactory(name='U3Gate', hamiltonian=[['Z', 'phi * 180 / pi'], ['Y', 'theta * 180 / pi'], ['Z', 'lam * 180 / pi']])
factory.phasedXPow_factory = GateFactory(name='PhasedXPow', hamiltonian=[['Z', 'lam * 180'], ['X', 'theta * 180'], ['Z', '-lam * 180']])
factory.r_factory = GateFactory(name='R', hamiltonian=[['Z', '-theta'], ['X', '90'], ['Z', 'theta']])
factory.ms_factory = GateFactory(name='MS', hamiltonian=[['XX', 'theta']])
factory.fsim_factory = GateFactory(name='FSim', matrix=[[1, 0, 0, 0], [0, 'cos(theta * pi / 180)', '-1j*sin(theta * pi / 180)', 0], [0, '-1j*sin(theta * pi / 180)', 'cos(theta * pi / 180)', 0], [0, 0, 0, 'exp(1j * phi * pi / 180)']])