Utilities

trueq.utils.docs()

Loads True-Q documentation.

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.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.multiply_pauli_str(pauli0, pauli1)

Returns the product of two Pauli strings as a new Pauli string.

The returned string doesn’t contain any phase information, see examples below.

from trueq.utils import multiply_pauli_str

assert multiply_pauli_str("IXYZ", "XXIY") == "XIYX"
assert multiply_pauli_str("IXYZ", "ZYXI") == "ZZZZ"
Parameters
  • pauli0 (str) – A string made up of any number of IXYZ characters.

  • pauli1 (str) – A string of IXYZ characters of the same length as pauli0.

Return type

str

Raises

ValueError – If the string lengths are not the same or contain invalid chars.

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(filename)() - This sets the filename of where to save
    the cache file.

Example:

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

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.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 tmppes4y_l3 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 114423 bytes.
Parameters
  • obj – The object to Pickle.

  • filename (str) – The filename to save 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 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.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

This class has the same behaviour as 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)

This class 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