Utilities

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() - 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:

@shelve_cache
def fib(n):
    'Memoized fibonacci function'
    if n in [0, 1]:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)

fib(100)
573147844013817084101

fib.info
{'hits': 98, 'misses': 101, 'calls': 199, 'filename': None}
Parameters

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

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

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

optional_import("qiskit", required_version="0.8.1")
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.

Return type

module

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

to_tuple_int(np.float64(7), 0)
7
to_tuple_int([0,, np.float64(5), 3], 1)
(0, 5, 3)
to_tuple_int([(0,), (np.float64(5), 3)], 2)
((0,), (5, 3))
to_tuple_int([([0],), ([np.float64(5)], [3])], 3)
(((0,),), ((5,), (3,)))
to_tuple_int([0, np.float64(5), (3,)], 2)
((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 | :py:class: 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.cycle_to_str(cycle)

Turns a cycle into a string.

Parameters

cycle (dict) – A Cycle

Return type

str

trueq.utils.temporary_file_name(extension='')

Generates a random file name with the given extension and returns the file name.

Parameters

extension (str) – The file extension to use.

Returns

The temporary file name and extension.

Return type

str

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
circuits = tq.make_srb([0, 1], [4, 50, 100], 30)
tq.utils.save(circuits, "mycircuits.data")
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.

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

Creates a new instance of a True-Qᵀᴹ object that was saved to disk in the Pickle format.

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

loaded = tq.load("mycircuits.data")
Parameters
  • filename (str) – Where to find the files.

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

Returns

object

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.twirls_equal(twirl1, twirl2)

Returns True iff the two given twirling groups are equal.

twirls_equal((("P", 0), ("SU", 1,2)), (("SU", 2,1), ("P", 0) ))
# True

twirls_equal((("P", 0), ("SU", 1,2)), (("P", 0), ("C", 1,2)))
# False
Parameters
  • twirl1 – The first twirling group.

  • twirl2 – The second twirling group.

Return type

bool

trueq.utils.cycle_labels(cycle)

Returns the sorted unique qubit labels contained in the given Cycle object.

Return type

list

trueq.utils.auto_labels(obj, labels, filter)

Constructs a list of labels based on the “twirl” attribute of Keys in the given obj if no labels are given.

Parameters
  • obj (KeyMap) – Some object with a keys() method.

  • labels (list) – A list of labels to override with.

  • filter (dict) – Something to filter obj with.

Return type

list

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.

list(riffle_flatten([1] * 4, [2] * 4, [3] * 4))
# [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

list(riffle_flatten([1] * 6, [2] * 5, [3] * 2))
# [1, 1, 1, 2, 2, 3, 1, 1, 1, 2, 2, 3, 2]
Parameters

iterables – A sequence of iterable objects with a len attribute.

Return type

generator

class trueq.utils.HTMLTable(widths)

Helper class to build HTML tables.

Parameters

widths (list) – Default widths, in percent, of columns of the table. These should add up to 100.

static tooltip(content, mouseovertext)

Returns an HTML string that places the given content in a div tag whose mouse-over text is as provided.

Parameters
  • content – The content to display.

  • mouseovertext – The tooltip of the content.

Return type

str

add_headers(headers, widths=None, legalize=True)

Adds a row of headers to the table.

Parameters
  • headers (Iterable) – An iterable of strs to use as headers.

  • widths (list) – A list of widths, in percent, to override the default widths with. Should have the same length as headers and add up to 100.

  • legalize (bool) – Whether to legalize each of the cell contents.

add_subheaders(headers, widths=None, legalize=True)

Adds a row of sub-headers to the table.

Parameters
  • headers (Iterable) – An iterable of strings to use as sub-headers.

  • widths (list) – A list of widths, in percent, to override the default widths with. Should have the same length as headers and add up to 100.

  • legalize (bool) – Whether to legalize each of the cell contents.

add_row(row, widths=None, legalize=True)

Adds a row of cells to the table.

Parameters
  • headers (Iterable) – An iterable of strings to use as cell content.

  • widths (list) – A list of widths, in percent, to override the default widths with. Should have the same length as headers and add up to 100.

  • legalize (bool) – Whether to legalize each of the cell contents.

property html

HTML of the entire table as it currently exists. If this class itself is being used as a context manager (ie with HTMLTable as table: ...) make sure to call this after you leave the context, to get the final </div> of the table.

Return type

str

class trueq.utils.TextTable(widths, align=None)

Helper class to build ASCII text tables.

Parameters
  • widths (list) – Default widths, in characters, of the columns of the table.

  • align (str) – Default alignments, in characters, of the columns of the table. For example, ">>>><^".

add_banner(text)

Adds a row of headers to the table.

Parameters

headers (Iterable) – An iterable of strings to use as headers.

add_row(row, widths=None, align=None)

Adds a row of cells to the table.

Parameters
  • headers (Iterable) – An iterable of strings to use as cell content.

  • widths (list) – A list specifying the width, in characters, of each item in the row, overriding the default values.

  • align (str) – A string specifying alignment of each item in the row, overriding the default values.

property text

Text of the entire table as it currently exists.

Return type

str