# Quantum Instructions in Parallel (QuIP)¶

## Gates¶

class trueq.Gate(u)

Represents a unitary quantum gate.

import trueq as tq

x = tq.Gate([[0, 1], [1, 0]])
cz = tq.Gate([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])


Note

Gates are not checked to be unitary on instantiation; call Gate.is_unitary manually to check.

Many standard gates can be instantiatied through convenience attributes:

tq.Gate.id
tq.Gate.x
tq.Gate.y
tq.Gate.z

tq.Gate.h
tq.Gate.s
tq.Gate.t

tq.Gate.cx
tq.Gate.cy
tq.Gate.cz
tq.Gate.swap
tq.Gate.iswap


The static method from_generators() can be used to construct gates of the form $$exp(-1j * \sum_i (\pi\theta_i/180) P_i/ 2)$$ where $$P_i$$ are the input Pauli strings and $$\theta_i$$ are the input rotation angles in degrees. This can be input either as an alternating sequence of Pauli strings and angles, or as a dictionary.

g1 = tq.Gate.from_generators("X", 90)
g2 = tq.Gate.from_generators("XX", 90, "YY", 180)
g3 = tq.Gate.from_generators({"XX": 90, "YY": 180})


Finally, the constructor also allows gates to be entered as coefficients on the pauli basis (rather than rotation angles) as follows.

g1 = tq.Gate({"I": np.sqrt(1/2), "X": -1j * np.sqrt(1/2)})
g2 = tq.Gate({"II": np.sqrt(1/2), "XY": -1j * np.sqrt(1/2)})

Parameters

u (numpy.ndarray-like | dict) – Either a unitary matrix in the computational basis, or a dictionary specifying coefficients of the pauli basis; see examples above.

static from_generators(*args)

Constructs a Gate instance from rotations about Paulis. Specifically, the gate is constructed as $$exp(-1j * \sum_i (\pi\theta_i/180) P_i/ 2)$$ where $$P_i$$ are the input Pauli strings and $$\theta_i$$ are the input rotation angles in degrees. This can be input either as an alternating sequence of Pauli strings and angles, or as a dict.

g1 = tq.Gate.from_generators("X", 90)
g2 = tq.Gate.from_generators("XX", 90, "YY", 180)
g3 = tq.Gate.from_generators({"XX": 90, "YY": 180})

Parameters

args – A dictionary mapping Pauli strings to angles in degrees, or an alternating sequence thereof.

Return type

Gate

property is_unitary

Whether or not this gate is unitary.

Type

bool

property is_identity

Whether or not this gate is the identity gate.

Type

bool

property mat

The matrix representation of this gate in the canonical basis.

Type

numpy.ndarray

property width

The number of columns of the matrix representation of this gate.

Type

int

property expansion

Assuming this gate acts on qubits, a sparse representation of this gate in terms of the trueq.math.pauli_basis; a dictionary mapping Pauli strings to (complex) coefficients.

Type

dict

static from_alias(alias)

Returns a Gate from common names, such as CX, swap, H, S etc.

ALIASES is a dictionary which stores available gates.

Raises

property generators

Assumes this gate acts on qubits and returns rotations about Pauli axes performed by this Gate. Specifically, outputs a description of this gate in the form: $$exp(-1j * \sum_i (\pi\theta_i/180) P_i/ 2)$$ where $$P_i$$ are the Pauli strings and $$\theta_i$$ are the rotation angles in degrees.

g1 = tq.Gate.from_generators("X", 90).generators
{"X": 90}
g2 = tq.Gate.from_generators("X", 90, "Z", 20).generators
{"X": 90, "Z": 20}

Type

dict

property adj

The conjugate transpose of this gate, returns a new Gate.

Type

Gate

static random(dim)

Generate a Haar random unitary gate of dimension dim.

Parameters

dim (int) – The dimension of the gate.

Return type

Gate

plot(abs_max=None, ax=None)

Plots the matrix representation of this gate.

Parameters
• abs_max (None | float) – The value to scale absolute values of the matrix by; the value at which plotted colors become fully opaque. By default, this is the largest absolute magnitude of the input matrix.

• ax (matplotlib.Axis) – An existing axis to plot on. If not given, a new figure will be created.

## Native Gates¶

class trueq.NativeGate(name, u, params=None, classname=None)

A Gate-like object that also contains a name and parameters used on a physical system.

This class is a thin layer on top of Gate to additionally store gate names and parameters used to construct the gate by the physical system. From the perspective of a NativeGate, this information is static throughout its lifetime and treated as meta-data.

Native gates are typically (and most easily) constructed by trueq.config.GateFactory’s, which are usually owned by trueq.Config objects.

>>> conf = Config(file)
>>> gate = conf.x(phi=90)
>>> gate
NativeGate.conf_name.x(phi=90)
>>> gate.parameters
{"phi": 90}
>>> gate.name
x


Native gates are not intended to be mutable, and the parameters and names should not be changed after instantiation.

Parameters
• name (str) – Name of the gate operation.

• u (dict) – See Gate.

• params (dict) – Any parameters that the gate needs in order to be constructed.

• classname (str) – This is used for recordkeeping in the trueq.config.GateFactory.

static from_generators(name, *args, params=None, classname=None)

Constructs a NativeGate instance from rotations about Paulis. Also adds a name and any parameters used to construct the native gate. Specifically, the output gate in this case is given by $$exp(-1j * \sum_i (\pi\theta_i/180) P_i/ 2)$$ where $$P_i$$ are the input Pauli strings and $$\theta_i$$ are the input rotation angles in degrees. This can be input either as an alternating sequence of Pauli strings and angles, or as a dict.

g1 = tq.NativeGate.from_generators("name", {}, "X", 90)
g2 = tq.NativeGate.from_generators("name", {}, "XX", 90, "YY", 180)
g3 = tq.NativeGate.from_generators("name", {}, {"XX": 90, "YY": 180})

Parameters
• name (str) – Name of the gate operation.

• params (dict) – Any parameters that the gate needs in order to be constructed.

• args – A dictionary mapping Pauli strings to angles in degrees, or an alternating sequence thereof.

• classname (str) – This is used for recordkeeping in the trueq.config.GateFactory.

Return type

Gate

property parameters

The stored parameters.

Type

dict

property name

The name of the NativeGate.

Type

str

## Cycles¶

class trueq.Cycle(content=None, immutable=None)

Represents a “clock cycle” of a Circuit; a set of Gates that happen in parallel to a disjoint set of systems. The storage format is a dict that maps tuples of system labels to Gate objects. Any given system can only be addressed once in a Cycle.

This class is iterable, yielding tuples of the form (labels, gate).

Note

We are agnostic to the physical duration of a cycle, and different cycles in a circuit do not need to have the same duration.

Parameters
add(labels, operator)

Adds a Operator to this Cycle. In particular, this can be a Gate, NativeGate, Prep, or Meas.

As a convenience, if the operator acts on one qudit (such as single qubit gates, Meas, or Prep), then this operation is added to each label, even when multiple labels are provided.

Parameters
• labels – Which systems this gate targets. Note that the order of labels is relevant for multi-system gates. For example, it controls the direction of a CX.

• operator – A Operator object or a gate alias.

property dim

The dimension of each subsystem, e.g. 2 if this cycle acts on qubits. However, if no gates have been added to this cycle, then the dimension is unknown and this value is equal to None.

Type

int | None

property immutable

Whether or not this cycle is immutable.

Type

bool

property labels

The sorted union of all system labels acted on by Gates in this Cycle.

Type

tuple

property n_gates

The number of gates in this Cycle.

Type

int

property n_meas

The number of measurements (Meas) in this Cycle.

Type

int

property n_prep

The number of preparations (Prep) in this Cycle.

Type

int

property n_block

The number of preparations (Prep) in this Cycle.

Type

int

property n_operators

The total number of operators in this Cycle, equal to the sum of n_gates, n_meas, and n_prep.

Type

int

property n_sys

The number of distinct systems participating in this Cycle.

Type

int

property gates

The dict of Gates in this Cycle.

Type

dict

property gates_single

The single-qudit gates of this cycle; a dict of Gates in this Cycle that act on one subsystem.

Type

dict

property gates_multi

The multi-qudit gates of this cycle; a dict of Gates in this Cycle that act on at least two subsystems.

Type

dict

property gate_labels

A sorted tuple of all labels in the cycle that have gates (i.e. labels that point to a Gate operation).

Type

list

property prep

The dict of Preparations in this Cycle.

Type

dict

property prep_labels

A sorted tuple of all labels in the cycle that are a preparation (i.e. labels that point to a Prep operation).

Type

list

property meas

The dict of Measurements in this Cycle.

Type

dict

property meas_labels

A sorted tuple of all labels in the cycle that are a preparation (i.e. labels that point to a Meas operation).

Type

list

property block

The dict of Blocks in this Cycle.

Type

dict

property block_labels

A sorted tuple of all labels in the cycle that are blocked (i.e. labels that point to a Block operation).

Type

list

property operators

The total dict of Operators in this Cycle.

Type

dict

tensor(labels=None)

Returns a Tensor representation of the Gates in this Cycle.

The matrix representation (which will be exponentially sized in the number of systems!) of this cycle can be obtained with:

cycle.tensor().mat

Parameters

labels (list) – An optional list of labels to force into the tensor in case they are not already present as labels in this cycle.

Return type

Tensor

is_equivalent(other, ignore_imm=True, ignore_id=True)

Checks if this cycle is equivalent to another cycle.

Parameters
• other (Cycle) – Another cycle to compare this one to.

• ignore_imm (bool) – Whether to return false if this cycle and the other cycle have different values of immutable. Default is True.

• ignore_id (bool) – Whether to treat all identity gates as though they are not present. Default is True.

Return type

bool

to_dict()

Returns a dictionary representation of a Cycle object. This dictionary representation contains only base Python classes.

Return type

dict

static from_dict(dic)

Returns a Cycle constructed from a dictionary representation.

Parameters

dic (dict) – A dictionary used to construct a new Cycle.

Return type

Cycle

pop(item)

Deletes the operator from this cycle that acts on the given label tuple and returns it.

cycle = tq.Cycle({(0,): tq.Gate.x, (1,): tq.Meas()})
cycle.pop((0,))
# tq.Gate.x

Parameters

item (tuple) – A tuple of qudit labels.

Raises
• KeyError – If no operation acts on the given label tuple.

• ValueError – If the cycle is immutable.

## Circuits¶

class trueq.Circuit(cycles=None, key=None, results=None)

Represents a quantum Circuit to be performed on a device, along with relevant additional information about the circuit.

Note

All True-Qᵀᴹ circuit generation and analysis methods assume that circuits are run by initializing systems independently in the ground state, applying the parallelized gates (referred to as cycles) obtained by iterating over the circuit, measuring the systems in the computational basis, and populating results with the results.

Specifically, all local gates required to rotate preparations and measurements are already included in cycles.

A circuit is stored as a list of Cycles. It also has private attributes for ease of use with randomized compiling and standard quantum algorithms.

Parameters
• cycles (list) – Cycles of the circuit. This is a list of the form, for example, [{(1,): tq.Gate.x, (0, 2): tq.Gate.cz}, ...].

• key (Key) – A hashable object used to group similar circuits for analysis. For example, Key(protocol=SRB,n_random_cycles=10).

• results (Results | dict) – Results to add to the circuit on construction, see also Circuit.results.

measure_all()

Add a cycle of measurements at the end of the current circuit.

This adds trueq.Meas onto each label currently in the circuit.

property dim

The dimension of each subsystem, e.g. 2 if this circuit acts on qubits. This property is inherited from its cycles. If no cycles specify a dimension, then the dimension is unknown and this value is equal to None.

Type

int | None

property key

Metadata related to this circuit. This is used in analysis methods of protocols, and for organizing circuits within CircuitCollections.

Type

Key

property n_sys

The number of distinct systems participating in this Circuit.

Type

int

property labels

The sorted union of all system labels acted on by gates in this Circuit.

Type

tuple

property n_cycles

The number of Cycles in this Circuit.

Type

int

property cycles

A list of Cycles that represent the Circuit.

Type

list

property results

Results from running this Circuit on a quantum device; a dictionary whose keys are bitstrings, and whose values are total observations of corresponding bitstrings.

Bitstrings are python strings containing $$0$$ and $$1$$, e.g., '0110', see Recording Experimental Results.

The initial value of this property is {}, which implies that has_results is False.

Note that these values will internally be normalized to their sum, and not to $$1$$ —for example, with respect to all of our analysis routines, the following results are identical:

{'0': 123, '1': 4}
{'0': 1230, '1': 40}
{'0': 12300, '1': 400}

Type

dict

property has_results

Whether the results property has been set.

Type

bool

expectation_values(labels=None)

Finds the expectation value(s) of the Circuit, marginalized over specified labels.

The labels can be a list of labels, in which case each label is separately marginalized over. For example, labels = [0, 1, 2] shows the expectation value for qubits 0, 1, and 2 separately. The labels can also be a list of lists of labels; each list will be separately marginalized over. For example, labels = [, , ] is equivalent to labels = [0, 1, 2], but labels = [[0, 1], ] will report the expectation value of the subregister [0, 1] and the expectation value of the subregister 2.

If labels are not provided, they are taken from key.twirl if it exists.

Parameters

labels (list) – A list of labels (or list of lists of labels) specifying which which group(s) of subregisters to marginalize over.

Return type

A KeyMap whose keys are grouped based on labels, and whose values are lists of expectation values for those labels.

add_cycle(cycles)

Adds a Cycle to this Circuit and updates its labels with those found in the Cycle.

Parameters

cyclesCycle: A Cycle or iterable of Cycles.

property meas_locs

Returns a list of the locations of all measurements in the Circuit.

The ordering of this list is the same as the expected bit-string order in the circuit’s Results.

The order of measurements is decided first by the index of the cycle, e.g.: measurements placed in the first cycle of a circuit are returned before measurements in later cycles. Then the order inside of a cycle is decided by the label on which the measurement is placed, e.g.: measurements placed on label (0,) comes before label (5,)

The returned list contains tuples, where the first entry of tuple is the cycle index, and the second entry of the tuple is the label the measurement is on.

Examples:

circ = Circuit([{(0,): Meas()}, {(5,): Meas(), (1,): Meas()}])

circ.meas_locs
# [(0, 0), (1, 1), (1, 5)]
# Cycle 0, Qubit 0, Cycle 1, Qubit 1 and 5

Return type

list of tuple

property n_meas

The total number of measurement operations in the circuit.

Type

int

to_dict(include_cycles=True)

Returns a dictionary representation of a Circuit object. This dictionary representation contains only base Python classes.

Parameters

include_cycles (bool) – Whether to include the cycles in the dictionary representation.

Return type

dict

static from_dict(dic)

Returns a Circuit constructed from a dictionary representation.

Return type

Circuit

to_cirq(metadata=None, config='ZXZ', device=None, join_meas=True)

Converts a True-Qᵀᴹ Circuit into an Cirq Circuit object.

import cirq
import trueq as tq

mat = cirq.ops.FSimGate(theta=5, phi=1)._unitary_()

fsim_factory = tq.config.GateFactory("fsim", matrix=mat)
x90_factory = tq.config.GateFactory("x", hamiltonian=[["X", 90]])
z_factory = tq.config.GateFactory("z", hamiltonian=[["Z", "phi"]])

config = tq.Config.from_params(
name="example",
n_sys=2,
mode="ZXZXZ",
factories=[z_factory, x90_factory, fsim_factory],
)

circ = tq.Circuit([{(0, 1): tq.Gate.cx}])

tq.interface.cirq.from_trueq_circ(circ, config=config)


Note

If nothing else is provided, this automatically decomposes single qubit operations into $$R_Z(\theta)R_X(\phi)R_Z(\gamma)$$ single qubit gates.

Parameters
• circuit (Circuit) – A True-Qᵀᴹ circuit to be converted into an Cirq Circuit

• metadata (trueq.interface.metadata.CirqMetadata) – Metadata required to accurately reproduce the original cirq circuit. If this is not provided, measurements are added at the end of the circuit.

• config (Config or str) – If a Config which contains gates which are directly decomposable into Cirq native gates is provided, then conversion will take place into gates specified by that config. Additionally config also accepts text strings describing decomposition methods, strings must be of paulis which are defined in trueq.config.decomposition.QubitMode, then Gates are decomposed into all allowed Cirq gates, with single qubit operations being decomposed into the specified pauli string.

• device (None or cirq.Device) – A cirq.Device, if no device is provided, an unconstrained device with cirq.GridQubit is assumed.

• join_meas (bool) – This determines if Meas are joined into single cirq.meas() objects, or single meas object in parallel in the given moment/cycle.

Returns

A Cirq circuit representation of the Circuit

to_pyquil(metadata=None, config='ZXZ')

Converts from a Circuit to a pyquil.Program.

This accepts a metadata object which contains information not present in a trueq circuit object.

Note

Measurements are always assumed to be at the end of a circuit.

If metadata is not provided, measurements are placed at the end of the circuit on all qubits, reading out to a classical register called ‘ro’

Aribtrary single qubit gates are decomposed using the ZXZ decomposition by default.

If an SU(4) gate is provided which is not performable by Pyquil, it is decomposed using the trueq.compilation.Compiler().

Parameters
• circ (Circuit) – The True-Qᵀᴹ circuit to be converted to pyquil.

• metadata (PyquilMetadata) – Metadata which may not be present in the True-Qᵀᴹ representation, but is present in pyquil.

• config (Config or str) – If a Config which contains gates which are directly decomposable into Pyquil native gates is provided, then conversion will take place into gates specified by that config. Additionally config also accepts text strings describing decomposition methods, strings must be of paulis which are defined in trueq.config.decomposition.QubitMode, then Gates are decomposed into all allowed Pyquil gates, with single qubit operations being decomposed into the specified pauli string.

to_qiskit(metadata=None, config=None)

Converts a True-Qᵀᴹ circuit into an Qiskit Circuit.

Note

If nothing else is provided, this adds measurements on all qubits at the end of the circuit.

Single qubit gates are reduced to the simplest they can up to numerical rounding, IE: some U3 gates become U2 or U1.

Blocking operations are added at the end of every Cycle

Parameters
• circuit (Circuit) – A True-Qᵀᴹ circuit to be converted into an Qiskit QuantumCircuit

• metadata (QiskitMetadata) – Metadata required to accurately reproduce the original qiskit circuit. If this is not provided, only 1 quantum register is created, and on classical register, then measurements are added at the end of the circuit mapping each quantum bit to each classical bit.

• config (Config) – A given config object which contains gates which can be performed by qiskit, but also has hardware restrictions. For example, a Config object can represent a CNOT gate that is restricted to specific sets of qubits, and a CNOT gate is a known native gate in Qiskit. Providing this config means that not only will the circuit be converted into Qiskit representation, but also that it will satisfy hardware restrictions. If no config is provided, all possible qiskit gates are used in the compilation.

Returns

A Qiskit circuit representation of the Circuit

Return type

qiskit.QuantumCircuit

## Circuit Collections¶

class trueq.CircuitCollection(circuits=None)

Represents a collection of instances of Circuit.

Parameters

circuits (list) – A list of Circuits to initially populate this collection with, or None.

property n_circuits

The number of Circuits in this collection.

Type

int

property n_sys

The number of systems of all Circuits in this collection.

Type

int

property labels

Which systems are targeted by this Circuit.

Type

tuple

append(circuit)

Appends one or more Circuits to the collection.

Parameters

circuit (Circuit | Iterable) – An instance of Circuit, or any iterable of Circuit objects (including another CircuitCollection).

property n_results

The number of experimental Circuits that have been populated with results, an integer between $$0$$ and n_circuits.

Type

int

property has_no_results

Whether none of the experimental Circuit’s have been populated with data.

Type

bool

property has_some_results

Whether at least one of the experimental Circuits have been populated with data.

Type

bool

property has_all_results

Whether all of the experimental Circuits have been populated with data.

Type

bool

save(filename, overwrite=False, include_cycles=True)

Saves this collection to disk in a binary format, including all results. This collection can be reinstantiated at a later time using trueq.utils.load().

import trueq as tq
circuits = tq.make_srb(, [4, 20])
# save without cycle/gate information for a smaller filesize
circuits.save("myfile1.bin", include_cycles=False)
# save with all cycle/gate information
circuits.save("myfile2.bin")

Parameters
• filename (str) – A filename to save the circuit collection as.

• overwrite (bool) – Any existing file will be overwritten if this is True, else saving will raise FileExistsError

• include_cycles (bool) – Whether the cycle information in each circuit should be retained. If false, then all circuits will have their cycles stripped in the saved version to save space. Results and other information will be saved so that analysis and plotting will work on a reinstantiated copy.

expectation_values(labels=None, **filter)

Finds the expectation values of all applicable Circuits, marginalized over specified labels.

The labels can be a list of labels, in which case each label is separately marginalized over. For example, labels = [0, 1, 2] shows the expectation value for qubits 0, 1, and 2 separately. The labels can also be a list of lists of labels; each list will be separately marginalized over. For example, labels = [, , ] is equivalent to labels = [0, 1, 2], but labels = [[0, 1], ] will report the expectation value of the subregister [0, 1] and the expectation value of the subregister 2.

If labels are not provided, they are taken from looking at all existing key.twirl values in the relevant Key of this CircuitCollection. If two different twirl values are found, constructing labels is ambiguous and this functions raises.

Parameters
• labels (list) – A list of labels (or list of lists of labels) specifying which subset of systems (or list of subsets) to marginalize over when computing expectaion values.

• filter – A filter to apply to the datastructure, for example, circuits.fit(protocol="SRB").

Returns

A KeyMap whose keys specify grouped collections of circuits, and whose values are lists of expectation values for circuits in those collections.

Return type

KeyMap

fit(labels=None, **filter)

Fits all applicable data to exponential curves and returns a ParameterCollection detailing summary statistics.

The labels can be a list of labels, in which case each label is separately marginalized over. For example, labels = [0, 1, 2] shows the expectation value for qubits 0, 1, and 2 separately. The labels can also be a list of lists of labels; each list will be separately marginalized over. For example, labels = [, , ] is equivalent to labels = [0, 1, 2], but labels = [[0, 1], ] will report the expectation value of the subregister [0, 1] and the expectation value of the subregister 2.

If labels are not provided, they are taken from looking at all existing ‘twirl’ values in the relevant Key of this CircuitCollection. If two different twirl values are found, constructing labels is ambiguous and this functions raises.

Parameters
• labels (list) – A list of labels (or list of lists of labels) specifying which qubit subset (or list of qubit subsets) to marginalize over when producing fits.

• return_expectations (bool) – Whether to return the expectation values as well as the ParameterCollection; the return is (fits, decay_data) in this case.

• filter – A filter to apply to the datastructure, for example, circuits.fit(protocol="SRB").

Return type

ParameterCollection

plot = PlottingSuite(<8 plotters>)

An object that stores all plotting functions deemed relevant to this CircuitCollection. If one of these functions is called, the data from this circuit collection is analyzed and used.

Note

If there is a plotting function that you expected to be present but is not, double check the circuit’s Keys to see which types of circuits are present, and also verify that circuits relevant to the plot you want have results entered.

Type

PlottingSuite

batch(max_size, extra_circuits=None, sequencer=None)

Divides the circuits in this collection into a series of batches that are limited in size. This is useful if, for example, your hardware has a finite amount of memory to store circuits with.

import trueq as tq
import trueq.assessments as tqa
# make a bunch of circuits
circuits = tqa.make_crosstalk_diagnostics([0, 1, 2], [4, 70])

# split collection into batches such that there are no more than 80
# circuits in each batch
# assume we have a hardware device called my_device with a method run()
# which returns the results for each member of the batch
for batch in circuits.batch(80):
batch.results = my_device.run(batch)

# we can also set batch size by total number of cycles or gates
import trueq.sequencer as tqs
circuits.batch(tqs.NCycles(1000))
circuits.batch(tqs.NGates(1e6))

# we can riffle the circuits by sequence length
for batch in circuits.batch(80, sequencer=tqs.RIFFLER):
batch.results = my_device.run(batch)


The batcher also supports automatically adding a fixed set of circuits to each batch. For example, we can add readout calibration circuits to each batch:

circuits = tqa.make_crosstalk_diagnostics([0, 1, 2], [4, 70])

for batch in circuits.batch(80, extra_circuits=ro_circuits):
batch.results = my_device.run(batch)

Parameters
• max_size (int | list | CircuitRuler) – The maximum number of circuits per batch, or any CircuitRuler such as :NCycles, py:class:~trueq.sequencer.Gates, :or py:class:~trueq.sequencer.TotalTime. You can also specify a list of CircuitRulers; every batch will not surpass any of the rulers’ limits.

• extra_circuits (CircuitCollection) – A list of circuits to be placed at the start of every batch. Copies are made of these circuits in every batch.

• sequencer (CircuitSequencer) – Specifies how the circuits should be ordered when batching. This is useful, for example, if you want to riffle long circuits with short sequences within a batch, so that all of your long circuits don’t end up in the same batch, see trueq.sequencer.RIFFLER. If no sequencer is given, the existing circuit collection order is used.

keys(**filter)

Returns a KeySet of unique keys in this CircuitCollection that match the given name/values present in the filter.

Parameters

filter – Key/value pairs to be used as a filter.

Return type

set

similar_keys(*names, invert=False, **filter)

Returns a generator over disjoint KeySets, where all of the keys in each set have equal values for all names appearing in the given names, and have any specific values specified in filter.

circuits = tq.make_srb(, [4, 10, 50], 30)
for keys in circuits.similar_keys("protocol"):
print(keys)
KeySet(
Key(n_random_cycles=4, protocol='SRB'),
Key(n_random_cycles=10, protocol='SRB'),
Key('n_random_cycles=50, protocol='SRB')
)
for keys in circuits.similar_keys("protocol", "n_random_cycles"):
print(keys)
KeySet(Key(n_random_cycles=10, protocol='SRB'))
KeySet(Key(n_random_cycles=4, protocol='SRB'))
KeySet(Key(n_random_cycles=50, protocol='SRB'))

Parameters
• names (list) – An iterable of key names.

• invert (bool) – Whether the list of names to use should be those presented, or all names execpt those presented.

• filter – Key/value pairs to be used as a filter.

update_keys(**kwargs)

Updates every circuit’s key in this collection with new keywords/values. If a given key does not have a given keyword, it is added. If it already exists, it is overwritten.

import trueq as tq
circuits = tq.make_srb(0, [4, 10])

# give each circuit a new keyword 'banana' with value 10
circuits.update_keys(banana=10)

# change 'n_random_cycles' to 5 for those circuits where it is 4
circuits.subset(n_random_cycles=4).update_keys(n_random_cycles=5)

Parameters

kwargs – Keywords ands values to update with.

subset(has_results=None, new_collection=True, **filter)

Selects a subset of this collection’s Circuits by matching against a filter. This returns a new CircuitCollection, with references to the original circuits, i.e. no circuit copies are made. Optionally, by using the new_collection flag, the output type can be a generator over circuits that match the filter rather than a new collection object.

# make a new CircuitCollection with only SRB circuits
srb_circuits = circuits.subset(protocol="SRB")
assert srb_circuits.keys().protocol == {"SRB"}

# for efficiency, use new_collection=False to avoid new instantiation
for circuit in circuits.subset(has_results=False, new_collection=False):
circuit.results = {"0": 1}

Parameters
• has_results (None | bool) – Whether to filter on circuits which have or do not have results entered. If True, only circuits with results are included, if False, only circuits without results are included, and if None (default) all circuits are included.

• new_collection (bool) – Whether to create a new CircuitCollection and return it. Otherwise, a generator over circuits will be returned, which saves memory.

• filter – Key/value pairs to be used as a filter.

Return type

generator | CircuitCollection

to_dict_list(include_cycles=True)

Returns a list of dictionary representations of the Circuit objects in this collection.

Parameters

include_cycles (bool) – Whether to include the cycles in the dictionary representations.

Return type

list

static from_dict_list(lst)

Returns a CircuitCollection constructed from a list of dictionary representations of trueq.Circuits.

Return type

CircuitCollection

batch_size(ruler)

The size of this collection according to the given method of counting circuit size. For example, NCycles, NGates, or TotalTime.

Parameters

ruler (CircuitRuler) – A callable that returns the size of a given circuit.

property results

A list of the Results for every circuit in this collection, where the order of this list matches the order of this collection. This property is also settable, see Circuit.results for allowed formats for setting.

import trueq as tq
circuits = tq.make_srb(, [4, 100])
circuits.results
# [Results(), Results(), ....]

# set all results to the same value
circuits.results = [{"0": 10, "1": 100}] * len(circuits)

Type

list

sum_results(decompile_paulis=True, **filter)

Sums together all results in the collection that match the given filter.

import trueq as tq
circuits = tq.make_srb(, [4, 100])
circuits.append(tq.make_xrb(, [4, 100]))

circuits.sum_results()
# Results({'1': 1187, '0': 1213})
circuits.sum_results(protocol="XRB").n_shots
# 1800
circuits.sum_results(n_random_cycles=4).n_shots
# 1200

Parameters
• decompile_paulis (bool) – Whether to adjust ditstrings of each circuit’s results by the 'compiled_pauli' key value of the corresponding circuit when summing. In most cases, and especially for randomized compiling, this value should be True.

• filter – Key/value pairs to be used as a filter.

Return type

Results