Utilities

trueq.utils.dict_to_words(d, pattern='{}={}')

Formats a dictionary as a comma-separated string that is suitable for insertion into a sentence, such as an error message.

Parameters:
  • d (dict) – The dictionary to format.

  • pattern – The Python string formatting pattern to use.

Return type:

str

trueq.utils.docs()

Loads True-Q documentation.

trueq.utils.get_schema(name)

Returns a JSON schema loaded from the assets folder.

Parameters:

name (str) – The extension-less filename of the schema file in the assets folder.

Return type:

dict

trueq.utils.get_schema_validator(schema, default_behaviour=None)

Returns a JSON schema validator given a JSON schema, which optionally performs default value stripping or default value insertion.

Parameters:
  • schema (dict) – The JSON schema to validate with.

  • default_behaviour (str | NoneType) – If None, a standard validator is returned. If 'strip', whenever a property value is encountered that is equal to the default value of that property (if present), the property will be removed. If 'insert', whenever the schema defines a default value for a property absent from the object being validated, the property is inserted with the default value.

Return type:

function

trueq.utils.use_schema_options(schema)

Decorates a function by replacing its variadic keyword arguments with all of the base-level properties of a JSON schema and their default values.

Parameters:

schema (dict) – The JSON schema to validate with.

Return type:

function

trueq.utils.allclose(a, b)

Returns True if two arrays are equal element-wise, and False otherwise. This function is a drop-in replacement for numpy.allclose(a, b) when no broadcasting is required.

Parameters:
  • a (array-like) – An array of numbers.

  • b (array-like) – An array of numbers.

Return type:

bool

trueq.utils.add_deprecation(obj, deprecated_in, removed_in, reason='')

Adds a deprecation to the list of deprecations and returns a function with no arguments that will issue a deprecation warning when called.

Parameters:
  • obj (object) – The object to deprecate, or some description of it in the case that it is something like a function argument.

  • deprecated_in (str) – The True-Q™ version that the function was deprecated in.

  • removed_in (str) – The first True-Q™ version that will not have this function.

  • reason (str) – A string to be appended to the warning message.

Return type:

function

trueq.utils.deprecated(deprecated_in, removed_in, reason='')

Decorator used to mark functions as deprecated.

The following example shows renaming a function and marking the old name as deprecated.

import trueq as tq

v = tq.__version__


@tq.utils.deprecated(v, v, "Use foo() instead.")
def my_func(x):
    return x
Parameters:
  • deprecated_in (str) – The True-Q™ version that the function was deprecated in.

  • removed_in (str) – The first True-Q™ version that will not have this function.

  • reason (str) – A string to be appended to the warning message.

Return type:

function

trueq.utils.deprecated_class(deprecated_in, removed_in, reason='')

Decorator used to mark an entire class as deprecated.

Parameters:
  • deprecated_in (str) – The True-Q™ version that the function was deprecated in.

  • removed_in (str) – The first True-Q™ version that will not have this function.

  • reason (str) – A string to be appended to the warning message.

Return type:

function

trueq.utils.deprecated_class_property(deprecated_in, removed_in, reason='')

Decorator used to mark class properties as deprecated.

Parameters:
  • deprecated_in (str) – The True-Q™ version that the function was deprecated in.

  • removed_in (str) – The first True-Q™ version that will not have this function.

  • reason (str) – A string to be appended to the warning message.

Return type:

function

trueq.utils.filter_warnings(fil)

Decorator used for applying a specific warnings filter to functions.

Parameters:

fil (str) – Is a warnings filter to apply.

Return type:

function

trueq.utils.rename_deprecation(old_name, new_fn, deprecated_in, removed_in, new_name=None)

Specialization of deprecation() for deprecations that are simply function or method renames.

import trueq as tq

v = tq.__version__


def foo(x):
    return x


bar = tq.utils.rename_deprecation("bar", foo, v, v)
Parameters:
  • old_name (string) – The old name of the function.

  • new_fn (function) – The new function.

  • deprecated_in (str) – The True-Q™ version that the function was deprecated in.

  • removed_in (str) – The first True-Q™ version that will not have this function.

  • new_name (str) – New name for the function, if None then new_fn.__name__ is used.

Return type:

function

trueq.utils.min_max(*args)

Returns a pair (min_val, max_val) of the smallest and largest value across all provided iterables.

Parameters:

*args – One or more values or iterables of values to find the minimum and maximum of.

Return type:

tuple

trueq.utils.shelve_cache(func=None, filename=None)

Returns a decorator that enables shelve-based memoization of function calls.

If no filename is specified, keeps only the local cache of function calls.

This adds several entries to the __dict__ of the wrapped function:

  • func.local_cache() - Local cache, with stringified args, and kwargs as keys.

  • func.info() - A dict of memoizer info, including a count of cache hits, misses and calls.

  • func.clear_cache() - Deletes the contents of the local cache and empties the file if specified.

  • func.set_filename() - This sets the filename of where to save the cache file.

import trueq.utils as tqu


@tqu.shelve_cache
def fib(n):
    "Memoized Fibonacci function"
    if n in [0, 1]:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


print(fib(100))  # 573147844013817084101

fib.info
573147844013817084101
{'hits': 98, 'misses': 101, 'calls': 199, 'filename': None, 'cachesize': 101}
Parameters:
  • func (function) – The function to be memoized.

  • filename (str) – The name of the shelve file where the cache will be saved. shelve may create multiple files depending on underlying shelve methods (see shelve package for more info).

Return type:

decorator

class trueq.utils.delayed_import(name, package=None, recommended_version=None, package_name=None, callback=None)

A module that is not imported until access is attempted on one of its members.

import trueq.utils as tqu

np = tqu.delayed_import("numpy")

# at this point the delayed import has not tried to import NumPy yet (though
# it may already be imported in the session (i.e. it may exist in sys.modules)
# if it has been imported elsewhere)
np.array
# now NumPy has been loaded
<function numpy.array>
Parameters:
  • name (str) – The name of the package to import.

  • package (str) – The package anchor if the name is specified in relative terms.

  • recommended_version (str) – The minimum recommended version.

  • package_name (str) – The name of the package as defined in its setup.py, if None then name or package is used.

  • callback (function) – A function that is called (with the imported module as its only argument) after the module is imported for the first time.

Raises:

ImportError – If the module cannot be imported when (at a later time) importing is attempted.

trueq.utils.optional_import(name, package=None, required_version=None, package_name=None)

Attempts to import the given module name and return it. If there is an ImportError, a BadModule is returned. Optionally, if it is imported but the detected version is less recent than the required version, a warning is raised and a BadModule is returned. If no version is detected, we return the module and raise a different warning.

import trueq.utils as tqu

a = tqu.optional_import("qiskit", required_version="0.8.1")
b = tqu.optional_import(".converters", "qiskit", required_version="0.8.1")
Parameters:
  • name (str) – The name of the package to import.

  • package (str) – The package anchor if the name is specified in relative terms.

  • required_version (str) – The version we require to import.

  • package_name (str) – The name of the package as defined in its setup.py, if None then name or package is used.

Return type:

module | BadModule

trueq.utils.flatten(obj, exclusions=(<class 'str'>, <class 'bytes'>))

Flattens a nested, possibly ragged structure of Iterables into a generator yielding the underlying objects.

import trueq.utils as tqu

# all iterable types will be flattened
assert list(tqu.flatten([3, [[(4, 5), {6}, "abc"]]])) == [3, 4, 5, 6, "abc"]

# non-iterables, i.e. depth-0 iterables, are still yielded
assert list(tqu.flatten(2)) == [2]
Parameters:
  • obj (object) – The object to flatten.

  • exclusions (tuple) – A tuple of types that should not be treated as iterable even if they are. Otherwise, all types that are collections.Iterable will be flattened.

Return type:

generator

trueq.utils.to_tuple_int(param, int_depth)

Converts a nested iterable of ints to a nested tuple of integers. The desired tuple-nesting depth is specified, and the output is guaranteed not to be ragged in this nesting depth. Integers below the final depth are treated as tuples of length one for convenience, hence the validity of the last two examples below.

import numpy as np
from trueq.utils import to_tuple_int

print(to_tuple_int(7, 0))  # 7
print(to_tuple_int([0, 5, 3], 1))  # (0, 5, 3)
print(to_tuple_int([(0,), (5, 3)], 2))  # ((0,), (5, 3))
print(to_tuple_int([([0],), (5, [3])], 3))  # (((0,),), ((5,), (3,)))
print(to_tuple_int([0, 5, (3,)], 2))  # ((0,), (5,), (3,))
7
(0, 5, 3)
((0,), (5, 3))
(((0,),), ((5,), (3,)))
((0,), (5,), (3,))
Parameters:
  • param (int | Iterable) – A nested iterable terminated in integer-likes.

  • int_depth (int) – The depth at which you want integers; int_depth=0 means output will be integer, int_depth=1 means output will be tuple of integers, etc.

Returns:

A nested tuple of ints.

Return type:

tuple | int

Raises:

ValueError – If the input has ragged iterable depth (excepting the int-likes are honorary length-1 tuples rule) or an unexpected type is found.

trueq.utils.dicts_close(dict1, dict2)

Tests if the given dicts whose values are numeric are equal up to numerical precision. np.allclose is used with default tolerance parameters.

Parameters:
  • dict1 (dict) – A dictionary, for example, {'00':0.25, '01':0.75}

  • dict2 (dict2) – A dictionary, for example, {'00':0.25, '01':0.75}

Return type:

bool

trueq.utils.temp_folder(delete=True)

Context to create a temporary folder and switch the current working directory to that folder for the duration of the context. The folder and its contents are deleted by default when the context is exited.

import trueq.utils as tqu
import os

with tqu.temp_folder() as folder:
    with open("new_file.txt", "w") as f:
        f.write("Hello!")

print(f"The folder was called {os.path.basename(folder)} but now it's gone.")
The folder was called tmpboq2dkmx but now it's gone.
Parameters:

delete (bool) – Whether to delete the folder and its contents when the context exits. The current working directory is restored to its original location regardless.

trueq.utils.save(obj, filename, overwrite=False, include_cycles=True)

Saves a Pickle representation of an object to file. Tries to gzip the file contents by default. See trueq.utils.load() to instantiate a new object from the saved file.

import trueq as tq
import os

circuits = tq.make_srb([0, 1], [4, 50, 100], 30)

with tq.utils.temp_folder():
    # the extension ".tq" is optional but encouraged
    tq.utils.save(circuits, "my_circuits.tq")
    print(f"Saved file is {os.path.getsize('my_circuits.tq')} bytes.")
Saved file is 22580 bytes.
Parameters:
  • obj – The object to Pickle.

  • filename (str | io.BytesIO) – The filename to save as, or a writeable binary stream, such as the file object open("filename.tq", "wb").

  • 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 any present Circuits 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.

Raises:
  • FileExistsError – If the provided filename already exists and will not be overwritten.

  • IOError – If any error occurs during the saving of the object.

trueq.utils.load(filenames, verbose=False)

Creates a new instance of a True-Q™ object from a file that was saved to disk. Multiple files are concatenated into a single object if every file stores a EstimateCollection or if every file stores a CircuitCollection.

See trueq.utils.save() to save a True-Q™ object to disk.

import trueq as tq

circuits = tq.make_srb([0, 1], [4, 50, 100], 30)

with tq.utils.temp_folder():
    # the extension ".tq" is optional but encouraged
    tq.utils.save(circuits, "my_circuits.tq")

    loaded = tq.load("my_circuits.tq")
    assert circuits == loaded
Parameters:
  • filenames (str | list) – One or more filenames (or globs) to load.

  • verbose (bool) – Print the version of True-Q™ used to save the file(s) if True.

Returns:

object

Raises:
  • IOError – If an attempt is made to simultaneously load multiple mismatched True-Q™ objects.

  • ValueError – If no files are found that match the input.

trueq.utils.labels_contain_cycle(labels, cycle)

Determines whether a tuple of qubit labels contains a given Cycle.

Parameters:
  • labels (tuple) – A tuple of ints.

  • cycle (Cycle) – A clock cycle of Gates, mapping label tuples to gates.

Return type:

bool

trueq.utils.parallel_map(fn, values, max_workers=None, **kwargs)

Performs a parallel execution of a function for every given value. The return is blocked until all evaluations are complete.

This function falls back to serial execution (via the built-in map) if any of the following conditions are met:

  1. When using Windows.

  2. When max_workers==1.

  3. When the environment variable "trueq_parallel" is equal to "True". This environment variable is set to "True" prior to parallel execution, and set to "False" upon an exception or completion: this prevents this function from being nested, or being run multiple times concurrently in a session.

Parameters:
  • fn (function) – A picklable function.

  • values (Iterable) – An iterator of values to pass as the first argument to fn.

  • max_workers (int | NoneType) – The maximum number of workers to use in parallel. A value of None defaults to the number of processors on the machine. No processes are spawned if this value is equal to 1.

  • kwargs – Keyword arguments to be passed to fn everytime it is called.

Return type:

list | map

trueq.utils.repr_builder(obj, *args, **kwargs)

Returns a repr() for simple class instances.

Parameters:
  • obj (object) – The object instance to produce a repr for.

  • *args – Zero or more values used to construct the object. The repr() of each value will be displayed in the output.

  • **kwargs – A map between constructor argument names and the values used to construct the object. The signature of the object’s constructor is inspected to find the default value of this argument, and this argument is only included in the returned string if the provided value differs from the default value. These arguments are sorted by name in the returned string.

Return type:

str

Raises:

KeyError – If a kwarg name is not explicitly present as a kwarg in the object’s constructor.

trueq.utils.riffle_chain(*iterables)

Chains the given iterables together by riffling their contents. The riffling strategy tries to spread out the shortest given iterables as much as possible over the whole output when the given iterables have non-uniform lengths.

import trueq.utils as tqu

print(list(tqu.riffle_chain([1] * 4, [2] * 4, [3] * 4)))
# [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
print(list(tqu.riffle_chain([1] * 6, [2] * 5, [3] * 2)))
# [1, 1, 1, 2, 2, 3, 1, 1, 1, 2, 2, 3, 2]
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 1, 1, 2, 2, 3, 1, 1, 1, 2, 2, 3, 2]
Parameters:

*iterables – One or more iterable objects with a len attribute.

Return type:

generator

trueq.utils.get_template(filename)

Returns a mako template from the templates in trueq.assets.

Parameters:

filename (str) – The filename of the template file in trueq.assets.

class trueq.utils.BadModule(package, required_version=None)

A placeholder for optional modules that cannot be imported (either because they are not installed or because an old version is installed). If the module is used an ImportError is raised.

Parameters:
  • package (str) – The name of the optional module.

  • required_version (str) – The version we require to import.

Raises:

ImportError – If any attempt is made to use the missing module.

class trueq.utils.ItemSet

Mimics the behaviour of the built-in set class with one additional feature: item fetching (i.e. square bracket notation) passes the argument to each member of the instance and returns a new ItemSet with those values; see the example below. Note that square-bracket notation raises an exception for built-in set.

import trueq as tq

iset = tq.utils.ItemSet([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
iset[1] == tq.utils.ItemSet([2, 5, 8])
True
class trueq.utils.DisplayWrapper(content, width=None, height=None, saved_size_offset=None)

Stores the contents of an HTML renderable display object. In normal use, if the output of a code cell in an interactive notebook is an instance of this class, then the _repr_html() of this class will result in a rendering, which eliminates the need for functions to call the IPython.core.display.display() function directly.

In GALLERY_MODE=True mode, which is aimed at supporting sphinx_gallery, _repr_html() returns the empty string, and the constructor stores a list of instances of this class as they are created. This allows the gallery to collect instances, display them, and flush the history.

Parameters:
  • content – The HTML contents of the display object.

  • width (float | NoneType) – The width of the DIV tag this object is placed in, or None to attempt to find it automatically.

  • height (float | NoneType) – The height of the DIV tag this object is placed in, or None to attempt to find it automatically.

  • saved_size_offset (tuple | NoneType) – A pair of sizes, in pixels, to respectively add to the width and height when save() is called.

save(filename)

Saves the content of this wrapper to disk.

Parameters:

filename (str) – The filename to save as.

class trueq.utils.cached_property(fn, doc=None)

Class method decorator similar to the built-in property decoractor, except that the output is computed only the first time that the attribute is requested for a particular instance. This subclasses the property decorator, and requires __dict__ be available for the class owning the desired cached property.

Parameters:
  • fn (method) – A zero-argument class method to wrap as a cached property.

  • doc (str) – Creates the docstring for the cached property.

class trueq.utils.TrueQUnpickler(*args, **kwargs)

Subclass of pickle.Unpickler for unpickling serialized files with additional checks. In particular, this class will load files saved in earlier versions of True-Q™, handling classes that have been modified, deprecated, or removed.

REMOVED_CLASSES = {('trueq.operations', 'Block')}

A list of tuples containing the modules and names of removed classed which may be needed for backwards compatibility. Any newly removed classes which may have been saved to file in older versions of True-Q™ should be added to this list in the form of (module, name).

add_cycle_loader()

Adds a class overload to this unpickler that causes any Cycle objects found during unpickling to be constructed with a special class that handles legacy cycle formats.

add_key_loader()

Adds a class overload to this unpickler that causes any Key objects found during unpickling to be constructed with a special class that handles legacy key formats.

add_native_gate_loader()

Adds a class overload to this unpickler that causes any NativeGate objects found during unpickling to be constructed with a special class that handles legacy native gate formats.

find_class(module, name)

Returns a type object name which is imported from module. If the pair (module, name) is in REMOVED_CLASSES, a placeholder object type is returned instead of trying to import the removed class, and warns the user that the class has been removed. See also add_cycle_loader(), add_key_loader(), and add_native_gate_loader() which are called at instantiation.

Parameters:
  • module (str) – The module containing the desired class or function to import.

  • name (str) – The name of the desired class or function to be imported.

Returns:

The class or function type, module.name.

Return type:

type

class trueq.utils.UpgradePath(stages, default=None, values=None)

A class that abstracts the logic of upgrading a set of values, each of which act on some qubit labels, into increasingly complex representations, while also providing consistency checks on quantities like dimension. For example, we can upgrade a probability into a probability vector, and a probability vector into a confusion matrix, and a confusion matrix into a POVM. In general, the upgrade structure can be a connected directed acyclic graph; the only strict requirement is that any two representations can be upgraded into some common representation.

Parameters:
  • stages (list) – A list of one or more Stages, each representing a stage in the upgrade path.

  • default (NoneType | object) – A value acting on one subsystem with no labels.

  • values (dict) – A dictionary mapping labels to values.

class Stage(check, shape, shape_strict, upgrade, next_stage)

Represents the stage of a value inside of an upgrade path.

Parameters:
  • check (function) – Accepts a value and returns whether or not it matches this stage.

  • shape (function) – Accepts a value and its n_sys and returns a compatible shape.

  • shape_strict (bool) – Whether returns from shape are strict or just suggestions.

  • upgrade (function | NoneType) – Either None, if there is no upgrade beyond the current stage, or is a function that accepts a value, its n_sys, the output of shape, and returns a value that will pass the check function of the next stage.

  • next_stage (Stage | NoneType) – The Stage that follows this one in the upgrade path, or None if this is the most advanced stage.

check

Alias for field number 0

next_stage

Alias for field number 4

shape

Alias for field number 1

shape_strict

Alias for field number 2

upgrade

Alias for field number 3

property common_stage

The least-upgraded stage that all current values can be upgraded to.

Type:

int

property max_stage

The maximum possible stage.

Type:

Stage

property shape

The shape of the most upgraded value.

Type:

object

Raises:

ValueError – If there is a conflict in shape between the shapes of the most upgraded or strict_shape=True values.

property values

A dictionary mapping labels to their current values.

Type:

dict

get_default(default=None)

Returns the default single-system value.

Parameters:

default (object) – The value to return if no default was given during construction.

Return type:

object

upgrade_to(stage)

Upgrades all values until every is equal to or more upgraded than the given stage.

Parameters:

stage (int) – The minimum desired stage across all values.