# 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(factories, mode='ZXZXZ', dim=None)

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 which 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.cx, 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)

# The gate definitions can be accessed in several ways:
assert config.z == config[0] == config["z"] == config.get("z")[0]
assert config.cx == config[2] == config["cx"]


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=None, connectivity=None)

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",
connectivity=[(0, 1), (1, 2), (2, 0)],
)

# 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.sz
• 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 | NoneType) – The dimension of the computational system. The default value of None will result in the default dimension obtained from get_dim().

• connectivity (Iterable) – An iterable of labels, which define the connectivity of the entangling operations. If None, then no connectivity is enforced.

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 factories

The tuple of GateFactorys which define all gates present in this config.

Type

tuple

property dim

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

Type

int

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 a 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.from_matrix(
"iSwapLike", 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:
• 'YY': 90.0
• 'XX': 90.0
• 'ZZ': 14.324
• 'ZI': -14.324
• 'IZ': -14.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 from_yaml(conf)

Constructs 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 neighbouring 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
Gates:
- X(phi=90):
Hamiltonian:
- ['X', phi]
Involving:
(0,) : (1, 2)
(1,) : (0, 2)
(2,) : (1, 3)
(3,) : (2,)
- Z:
Hamiltonian:
- ['Z', phi]
Involving:
(0,) : ()
(1,) : ()
(2,) : ()
(3,) : ()
- U3(theta, phi, lam):
Hamiltonian:
- [Z, 180 / pi * phi]
- [Y, 180 / pi * theta]
- [Z, 180 / pi * lam]
- 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:
config = tq.Config.from_yaml(file_contents)
config

Mode: ZXZXZ
Dimension: 2
Gates:
- X(phi=90.0):
Hamiltonian:
- [X, phi]
Involving: {'(0,)': '(1, 2)', '(1,)': '(0, 2)', '(2,)': '(1, 3)', '(3,)': '(2,)'}
- Z(phi):
Hamiltonian:
- [Z, phi]
Involving: {'(0,)': (), '(1,)': (), '(2,)': (), '(3,)': ()}
- U3(theta, phi, lam):
Hamiltonian:
- [Z, 57.29577951308234*phi]
- [Y, 57.29577951308234*theta]
- [Z, 57.29577951308234*lam]
- CNOT:
Matrix:
- [1.0, 0.0, 0.0, 0.0]
- [0.0, 1.0, 0.0, 0.0]
- [0.0, 0.0, 0.0, 1.0]
- [0.0, 0.0, 1.0, 0.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.

In the above YAML file, the U3 gate specifies the (theta, phi, lam) parameters. If these parameters are not provided manually they will automatically be found. The manual specification above is to enforce a specific parameter order when calling the gate factory without using kwargs, this can be seen in the following example:

assert config.U3(2, 3, 4) == config.U3(theta=2, phi=3, lam=4)


Parameters which have been set, such as the X(phi=90) gate above, will be set in the GateFactory during construction and cannot be altered. All NativeGates built from these definitions will have the fixed parameter present in their parameter list. See GateFactory for more information.

assert config.X() == tq.Gate.sx
assert config.X().parameters == {"phi": 90}
config.X()

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:
• X(phi)
Aliases:
• Gate.sx
• Gate.cliff5
Parameters:
• phi = 90.0
Generators:
• 'X': 90.0
Matrix:
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.

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 a 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
Gates:
- z(phi):
Hamiltonian:
- [Z, phi]
- cz:
Matrix:
- [1.0, 0.0, 0.0, 0.0]
- [0.0, 1.0, 0.0, 0.0]
- [0.0, 0.0, 1.0, 0.0]
- [0.0, 0.0, 0.0, -1.0]


Note

This preserves the ordering of factories as specified by names kwarg, if no names are specified, then this preserves the ordering of factories present in factories.

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

static from_dict(dic)

Creates a new config object from a dictionary representation, see to_dict().

Parameters

dic (dict) – A dictionary representation of a config object.

to_yaml()

Returns a YAML representation of the Config.

Return type

str

property factory_names

A list of all factory names present in the config.

Type

list

get(name, labels=None)

Returns a list of factories which match the specified name and optionally match the required labels.

import trueq as tq

config = tq.Config.basic(entangler=tq.Gate.cz)
assert config.get("cz") == [config.cz]
assert config.get("cz", (0, 1)) == [config.cz]

Parameters
• name (str) – The name of a factory.

• labels (tuple | int | NoneType) – Optional, the labels on which the factory operates.

Return type

list

Raises

KeyError – If the specified factory cannot be found.

## Gate Factory

class trueq.config.GateFactory(name, layers, involving=None, parameters=None, dim=None)

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$. Convenience methods are provided which enable construction of the factory using either a unitary matrix definition (GateFactory.from_matrix()), Hamiltonian description (GateFactory.from_hamiltonian()), or through a function (GateFactory.from_function()).

Examples

A simple rotation about the y-axis, in degrees:

from trueq.config import GateFactory

y_factory = GateFactory.from_hamiltonian("y", [["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.sy
• Gate.cliff7
Parameters:
• phi = 90
Generators:
• 'Y': 90.0
Matrix:

Entered as a matrix with a parameter phi:

from trueq.config import GateFactory

phased_iswap_mat = [
[1, 0, 0, 0],
[0, 0, -1j, 0],
[0, -1j, 0, 0],
[0, 0, 0, "exp(-1j * phi / 180)"],
]
iswap_factory = GateFactory.from_matrix("iSwapLike", phased_iswap_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:
• 'YY': 90.0
• 'XX': 90.0
• 'ZZ': 7.162
• 'ZI': -7.162
• 'IZ': -7.162
Matrix:

A sequence of Pauli axis rotations in multiplication order that result in IBM’s U3 gate $U3(\theta, \phi, \lambda) = Z(\lambda)Y(\theta)Z(\phi)$. Note that, here, the parameter names are explicitly defined so that we can control their ordering in the factory (otherwise their order is defined by the order in which they are parsed).

from trueq.config import GateFactory
import numpy as np

u3_factory = GateFactory.from_hamiltonian(
"U3Gate",
[
["Z", "phi * 180 / pi"],
["Y", "theta * 180 / pi"],
["Z", "lam * 180 / pi"],
],
parameters=["theta", "phi", "lam"],
)

assert u3_factory(np.pi / 2, 0, 0) == tq.Gate.ry(90)


The most primitive construction of factories is in terms of Layer instances or its subclasses, provided as a list in matrix multiplication order:

import trueq as tq

test_factory = tq.config.GateFactory(
"test",
layers=[
tq.math.FixedRotation(tq.Gate.h.mat),
tq.math.Rotation.from_pauli("Z", "z"),
],
)
assert test_factory(z=45) == tq.Gate.h @ tq.Gate.rz(45)

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

• layers (list) – A list of Layer instances in multiplication order. When the GateFactory is called, the provided parameters are passed to each layer, and all layers are multiplied together in order to construct a NativeGate.

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

• parameters (list | dict | NoneType) –

An optional specification of the parameters present, this accepts the following inputs:

• NoneType Parameter names are inferred from the layers in a deterministic but arbitrary order, and safe_str() will be applied to all parameter names to ensure that no Python protected keywords are used, but can otherwise be any value.

• list A list of names, this specifies the preferred ordering of the parameters when calling the factory with args. Names present in this list must match the parameters present in the layers exactly, and all parameters are free to be set to any value.

• dict The keys of the dictionary specify the parameters used in the factory, the values may either be None signifying that the parameter may be set to anything, or a specific value that the parameter is always set to. Any parameter with a fixed value will always be included in the constructed NativeGate.

• dim (int | NoneType) – The dimension of the subsystem defined by this gate. The default value of None will result in the default dimension obtained from the layers.

Raises

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

property layers

The Layers which make up the GateFactory.

During construction of the NativeGate these layers construct matrices which are multiplied together in order. The resultant matrix is the unitary representation of the gate.

Type

list

classmethod from_function(name, function, involving=None, parameters=None, dim=None)

Constructs a GateFactory from a function which returns a square, unitary matrix.

The matrix output of the function must obey the following conditions:

• Square and unitary.

• The matrix can be written as a product of n Rotations with a single optional FixedRotation.

• Each parameter accepted by the function can be mapped to exactly one Rotation.

• This means there can be no more than n+1 total layers, where n is the number of arguments of the function.

If these conditions are met, the Layers which define the function are used to construct the GateFactory.

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

• function (function) – A function that, when called, generates a unitary matrix.

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

• parameters (list | dict | NoneType) – An optional specification of the parameters present, see GateFactory for more details.

• dim (int | NoneType) – The dimension of the subsystem defined by this gate. The default value of None will result in the default dimension obtained from the layers.

Raises

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

classmethod from_matrix(name, matrix, involving=None, parameters=None, dim=None)

Constructs a GateFactory from a matrix definition which is square and unitary.

The matrix must obey the following conditions:

• Square and unitary.

• The matrix can be written as a product of n Rotations with a single optional FixedRotation.

• Each parameter present in the matrix can be mapped to exactly one Rotation.

• This means there can be no more than n+1 total layers, where n is the number of free parameters in the matrix.

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.

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

• parameters (list | dict | NoneType) – An optional specification of the parameters present, see GateFactory for more details.

• dim (int | NoneType) – The dimension of the subsystem defined by this gate. The default value of None will result in the default dimension obtained from the layers.

Raises

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

classmethod from_hamiltonian(name, hamiltonian, involving=None, parameters=None, dim=None)

Constructs a GateFactory from a Hamiltonian definition.

Example:

from trueq.config import GateFactory
import numpy as np

u3_factory = GateFactory.from_hamiltonian(
"U3Gate",
[
["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.sy
• 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)$

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

• 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 | dict | NoneType) – An optional specification of the parameters present, see GateFactory for more details.

• dim (int | NoneType) – The dimension of the subsystem defined by this gate. The default value of None will result in the default dimension of 2.

Raises

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

classmethod embed_layers(layers, labels, all_labels, name='embedded')

Constructs a GateFactory by extending a each layer in a list of layers to act on additional subsystems, as defined in all_labels. This extension utilizes the function add_subsystems(), effectively reshuffling subsystems and tensoring on additional identity matrices as necessary. For example,

import trueq.config as tqc

# Create a factory acting on a single system
y_factory = tqc.GateFactory.from_hamiltonian("y", [["Y", "phi"]])

# Embed the layers of this factory to act on two systems
embedded_fact = tqc.GateFactory.embed_layers(y_factory.layers, (0,), (0, 1))

assert embedded_fact.layers[0].pauli_const == ("YI", 1.0)

Parameters
• layers (list) – The list of layers to embed in the larger space.

• labels (tuple) – The labels associated with the list of layers.

• all_labels (tuple) – The target label ordering (including new labels).

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.from_matrix(
"cz", 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', layers=[FixedRotation(<matrix>)], 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

fix_parameters(involving=None, **params)

Constructs a new GateFactory with an updated parameters dictionary, and optionally a new set of involving restrictions.

import trueq as tq

factory = tq.config.GateFactory.from_hamiltonian("x", [["X", "phi"]])
factories = [factory.fix_parameters(phi=x) for x in [0, 90, 180, 270]]
tq.Config(factories=factories)

Mode: ZXZXZ
Dimension: 2
Gates:
- x(phi=0):
Hamiltonian:
- [X, phi]
- x(phi=90):
Hamiltonian:
- [X, phi]
- x(phi=180):
Hamiltonian:
- [X, phi]
- x(phi=270):
Hamiltonian:
- [X, phi]

Parameters
• involving (dict) – A dictionary describing the limitations of the gate, see Config description for a more in-depth description. If this is None, use the exising involving, otherwise overwrite.

• params (dict) – kwargs which specify the parameter values to fix, see the example above.

Return type

GateFactory

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).

from trueq.config import GateFactory
import numpy as np

factory = GateFactory.from_hamiltonian("Rz", [["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).

from trueq.config import GateFactory

factory = GateFactory.from_hamiltonian("Rz", [["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.

Parameters
• *args – Ordered arguments entered as gate parameters. Cannot be used in combination with kwargs.

• **kwargs – Argements entered as gate parameters. Cannot be used in combination with args.

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.

check_subspace(ideal=None)

If this factory only produces gates that are block diagonal where exactly one block has size 2 and all others are size 1, then the location of the 2-by-2 block is returned along with a gate generated by this factory as a pair (subsystem, gate). If no such subspace is found, None is returned.

If this factory has no parameters, then gate will be equal to the only gate this factory produces. Otherwise, and if the qubit gate ideal is provided, this method will attempt to find factory parameters which cause the subspace to be equal to ideal up to a phase. If this fails, or if ideal is not provided, gate will be some random gate from this factory.

Parameters

ideal (Gate NoneType) – A qubit gate to attempt on the subspace when this factory is parametrized.

Return type

tuple

property n_sys

The number of systems this gate factory acts on.

Type

int

property 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 dictionary of all the parameters in the functional definition of the gate.

The values of the dictionary contain either the fixed value associated with that paramter, or None signifying that any value is allowed.

Type

dict

property free_parameters

A list containing all of the free parameters.

Type

list

property n_params

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

Type

int

property fixed_parameters

Fixed values in the factory which cannot be changed, these values are added to all parameters present in NativeGates constructed by this factory.

Type

dict

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

static from_dict(dic)

Creates a GateFactory from a dictionary representation.

Parameters

dic (dict) – A dictionary representation of the factory as generated by GateFactory.to_dict().

Return type

GateFactory

property is_u1

Tests if a trueq.config.GateFactory is a U1 gate. In order to pass this test, the factory must have the same parameter names and same definition as the U1Gate defined in Qiskit.

Type

bool

property is_u2

Tests if a trueq.config.GateFactory is a U2 gate. In order to pass this test, the factory must have the same parameter names and same definition as the U2Gate defined in Qiskit.

Type

bool

property is_u3

Tests if a trueq.config.GateFactory is a U3 gate. In order to pass this test, the factory must have the same parameter names and same definition as the U3Gate defined in Qiskit.

Type

bool

property is_r

Tests if a trueq.config.GateFactory is an R gate. An R gate is defined as a $Z(-\theta) X(90) Z(\theta)$ gate in multiplication ordering.

Type

bool

## 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 | NoneType) – 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

f = parse_func("5*sin(x) + y")
print(f(x=np.pi, y=1))

1.0000000000000007


Note

This uses safe_str() to sanitize func_str, it may alter keywords which are Python protected.

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"}


Note

This uses safe_str() to sanitize func_str, it may alter keywords which are Python protected.

Parameters

func_str (str) – A string describing the function.

Return type

list

## Pre-Defined factories

trueq.config.factory.u1_factory = GateFactory(name='U1Gate', layers=[Rotation.from_pauli('Z', 'theta', 57.29577951308234)], parameters={'theta': None})

A single qubit U1 Gate as defined by Qiskit, equivalent to a $Z(\theta)$ rotation.

trueq.config.factory.u2_factory = GateFactory(name='U2Gate', layers=[Rotation.from_pauli('Z', 'phi', 57.29577951308234), FixedRotation.from_pauli('Y', 90.0), Rotation.from_pauli('Z', 'lam', 57.29577951308234)], parameters={'phi': None, 'lam': None})

A single qubit U2 Gate as defined by Qiskit, equivalent to a $Z(\lambda)Y(90)Z(\phi)$ rotation.

trueq.config.factory.u3_factory = GateFactory(name='U3Gate', layers=[Rotation.from_pauli('Z', 'phi', 57.29577951308234), Rotation.from_pauli('Y', 'theta', 57.29577951308234), Rotation.from_pauli('Z', 'lam', 57.29577951308234)], parameters={'theta': None, 'phi': None, 'lam': None})

A single qubit U3 Gate as defined by Qiskit, equivalent to a $Z(\lambda)Y(\theta)Z(\phi)$ rotation.

trueq.config.factory.phasedXPow_factory = GateFactory(name='PhasedXPow', layers=[Rotation.from_pauli('Z', 'lam', 180.0), Rotation.from_pauli('X', 'theta', 180.0), Rotation.from_pauli('Z', 'lam', -180.0)], parameters={'lam': None, 'theta': None})

A single qubit PhasedXPow Gate as defined by Cirq, equivalent to a $Z(-\lambda / 180)X(\theta / 180)Z(\lambda / 180)$ rotation.

trueq.config.factory.r_factory = GateFactory(name='R', layers=[Rotation.from_pauli('Z', 'theta', -1.0), FixedRotation.from_pauli('X', 90.0), Rotation.from_pauli('Z', 'theta', 1.0)], parameters={'theta': None})

A single qubit R Gate, equivalent to a $Z(-\theta / 180)X(90)Z(\theta / 180)$ rotation.

trueq.config.factory.ms_factory = GateFactory(name='MS', layers=[Rotation.from_pauli('XX', 'theta', 1.0)], parameters={'theta': None})

A two qubit Molmer-Sorensen Gate, equivalent to a $XX(\theta)$ rotation.

trueq.config.factory.fsim_factory = GateFactory(name='FSim', layers=[Rotation(<matrix>, 'phi'), Rotation(<matrix>, 'theta')], parameters={'theta': None, 'phi': None})

A two qubit F-Sim Gate as defined by Cirq.