Keys and Parameters

Keys

class trueq.keys.Key(**kwargs)

A hashable unordered map, whose primary purpose is to enable convenient subset lookups in dictionaries which use instances of this class as keys.

k1 = Key(apple=0, banana=1)
k2 = Key(banana=1, apple=0)
k1 == k2
True
hash(k1) == hash(k2)
True
Parameters

kwargs – key/value pairs to store in the Key

match(**filter)

Returns True whenever all of the given filter keys exist as names in this Key, and all the given filter values match this Key’s corresponding values. A match occurs if the values are equal, or if a value in the filter is set and the Keys value is in the set.

k = Key(apple=0, banana=1)
k.match(cranberry=1)
False
k.match(apple=0)
True
k.match(apple=0, banana=0)
False
k.match(apple=0, banana=1)
True
k.match(apple={0, 1, 2})
True
k.match(apple={1, 2, 3})
False
Parameters

filter – A filter to apply to the Key to match based on key/value pair(s).

Return type

bool

hash_match(must_have, any_of, cannot_have)

A lower-level interface to Key.match() where hashes of key-value pairs are passed in, instead of the key-value pairs themselves.

Parameters
  • must_have – An iterable of hashes that this key must contain to return True.

  • any_of – An iterable of iterables. For each inner iterable, at least one of the hashes must match something in this key’s hashset in order for this method to return True.

  • cannot_have – An iterable of hashes, which cannot intersect with the hashset of this key in order for this method to return True.

Return type

bool

property names

The names of this Key.

Type

tuple

property values

The values of this Key.

Type

tuple

property items

Returns a tuple containing (name, value) pairs

Type

tuple

get(name, *default)

Gets the value corresponding to the given name.

Parameters
  • name (str) – A name present in this Key.

  • default – A value to return if the name is not found.

Raises

KeyError – If the name is not found, and the default is not present.

to_dict()

Returns a dictionary representation of the py:class:trueq.Key.

Return type

dict

static from_dict(dic)

Returns a py:class:trueq.Key constructed from a dictionary representation.

Parameters

values (dict) – Constructs a new key from a dictionary.

Return type

trueq.Key

copy(keep=None, remove=None, new=None)

Returns a copy of the Key.

Which names to be kept or removed can be specified during the copy.

>>> Key(apple=5, coffee=True).copy()
Key(apple=5, coffee=True)
>>> Key(apple=5, coffee=True).copy(keep='coffee')
Key(coffee=True)
>>> Key(apple=5, coffee=True).copy(remove='apple')
Key(coffee=True)
>>> Key(apple=5, coffee=True, sleep=False).copy(remove=['apple', 'sleep'])
Key(coffee=True)
>>> Key(apple=5, coffee=True).copy(remove='copy', new=dict(tea=True))
Key(apple=5, tea=True)
Parameters
  • keep (str | list) – A string or list of strings specifying which names in the key are to be kept during the copy.

  • remove (str | list) – A string or list of strings specifying which names in the key are to be removed during the copy.

  • new (dict) – A dictionary specifying new names and values to be added to the new copy.

Raises

ValueError – If the mutally exclusive keep and remove are both set to True.

Return type

Key

class trueq.keys.KeySet(*keysets)

An immutable set of Keys, with the feature of fancy attribute fetching; when asked for an attribute whose name is present in at least one of the keys, a set is returned containing all values of keys corresponding to that name.

KeySet(Key(fruit="apple"), [Key(fruit="banana"), Key(fruit="kiwi")])
Parameters

keyset – Any mixture of Keys and iterables of Keys. Note that for efficiency, no type checking is done on the input.

property names

A set of the names present in all Key objects in the KeySet.

Type

set

match(**filter)

Returns all Key objects in the KeySet which match the keyword arguments provided. See Key.match() for details on how matches work.

Parameters

filter – A filter applied to the KeySet, which matches Keys based on the filter’s key/value pair.

Return type

KeySet

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.

keys = KeySet(
    Key(a=4, b='x'),
    Key(a=10, b='y'),
    Key('a=10, b='x')
)
for keys in circuits.similar_keys("a"):
    print(keys)
KeySet(Key(a=4, b='x'), Key(a=10, b='x'))
KeySet(Key(a=10, b='y'))
Parameters
  • names – An iterable of names.

  • invert (bool) – Whether the list of names to use should be those presented, or all names except those presented. It does not apply to the filter.

  • filter – A filter to apply to the KeySet before the process of finding disjoint subsets begins.

Return type

generator

copy(keep=None, remove=None, new=None)

Returns a copy of the KeySet with copies Key. Which names to be kept or removed can be specified during the copy, see Key.copy().

Parameters
  • keep (str | list) – A string or list of strings specifying which names in the set are to be kept during the copy.

  • remove (str | list) – A string or list of strings specifying which names in the key are to be removed during the copy.

  • new (dict) – A dictionary specifying new names and values to be added to the new set.

Return type

KeySet

sorted(*names)

Sorts this set lexicographically by value, using this set’s (sorted) names as the order to place values in. This order of names can be overridden by providing one or more names that you would like to appear first.

Parameters

names (str) – One or more names that should take priority in sorting.

Return type

list

class trueq.keys.KeyMap(*args)

A mutable mapping object whose keys are Key instances.

Parameters

args – An OrderedDict mapping Keys to arbitrary values.

keys(**filter)

Retrieves all unique Keys from the KeyMap that match the given name/values present in the filter dictionary. See Key.match() for details on how matches work.

Parameters

filter – A filter to apply to the KeyMap, which returns a KeySet based on the values in the filter.

Return type

KeySet

pop(key)

Removes a Key from a KeyMap and returns its corresponding value.

Parameters

key (Key) – The Key to remove from a KeyMap (if it exists).

Return type

Key

update(other)

Updates a KeyMap with a new Key/value pair. This method changes the mapped value of an existing Key or adds a new key/value pair entirely.

Parameters

other (dict) – The dict containing Keys and their arbitrarily mapped values.

values(**filter)

Returns a generator of a KeyMap’s values. See Key.match() for details on how matches work.

Parameters

filter – A filter to apply to the KeyMap, which returns a generator of values based on the values in the filter.

Return type

generator

items(**filter)

Returns a generator of a KeyMap’s Key’s’.

Parameters

filter (dict) – A filter to apply to the KeyMap, which returns a generator of keys based on the values in the filter.

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([0], [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 – An iterable of names.

  • invert (bool) – Whether the list of names to use should be those presented, or all names except those presented. It does not apply to the filter.

  • filter – A filter to apply to the KeyMap, which matches Keys based on their key and value.

Return type

generator

Parameters

class trueq.parameters.Parameter(name, estimate, std, description=None, ideal_value=None)

Represents the analysis results of a single parameter.

Parameters
  • name (str) – Name of the parameter, must be a valid python name.

  • estimate (float) – Value of the estimate for this parameter.

  • std (float) – Standard deviation of the estimator for this parameter.

  • description (str) – A brief description of the estimator used.

  • ideal_value (float) – The ideal value of this parameter.

property name

Name of the Parameter.

Type

str

property estimate

Estimate of the Parameter.

Type

float

property std

Standard deviation of the estimator.

Type

float

property description

A brief description of this Parameter’s meaning.

Type

str

property ideal_value

The ideal value of this Parameter, or None when not specified.

Type

float

get_bound(confidence_levels=None)

Gets the value of the bound on this Parameter at each of the given confidence level(s).

parameter.get_bound([0.025, 0.975])
[0.9921, 0.9973]

Returns a bound for Parameter at confidence levels 2.5% and 97.5%.

Parameters

confidence_levels (list | float) – A number or iterable of numbers in \([0,1]\) at which to extract a bound.

Return type

numpy.ndarray, with same shape as input.

sample(n=100)

Sample points from a normal distribution with mean and standard deviation equal to this Parameter’s estimate and standard deviation.

Parameters

n (int) – The number of points to sample.

Return type

numpy.ndarray

matches(pattern)

Returns whether the name of this Parameter matches the given pattern. The pattern can contain one wildcard * which matches any number of contiguous characters.

p = Parameter("p_XXY", 0.1, 0.01)
p.matches("p")
False
p.matches("p*")
True
p.matches("p_*Y")
True
Parameters

pattern (str) – A string pattern to match by.

Return type

bool

class trueq.parameters.ParameterList(parameters=None, **meta)

Represents a list of Parameters, usually to be used as values in the ParameterCollection class.

Parameters
  • parameters (list) – A list of Parameter instances.

  • meta (dict) – Meta-information to assign to this list, stored as key value pairs. This meta information is retrievable using attribute fetching (e.g. parameter_list.meta_name) and item getting (e.g. parameter_list["meta_name"]).

property names

A list of names for each Parameter in this collection.

Type

list

hasmeta(*names)

Returns True if meta information exists. If specific meta names are given, returns True if all of them have values.

Parameters

names – Some meta key names to check.

Return type

bool

matches(pattern)

Returns a generator over all Parameters in this list whose name matches the given pattern, see also Parameter.matches().

Parameters

pattern (str) – A string pattern to match by.

Return type

generator

update_meta(**meta)

Updates meta information with that which is provided.

Parameters

meta – Names and values of meta information to update with.

sort()

Sorts this ParameterList in-place by name.

class trueq.parameters.ParameterCollection(parameters=None, **kwargs)

Represents a collection of Parameter instances. These parameters are stored in a dictionary format, where individual keys are mapped to a list of parameters, a ParameterList. Keys are instances of Key.

There are several ways of accessing particular parameters. If you know the specific key of the parameter list containing your parameter, you can access it as follows:

# get the parameter with name 'p' out of the list attached to the known key
params[key].p
Parameter('p', 0.1, 0.01)

You can look at all the keys, and optionally filter over desired attributes:

# get all the keys in this collection
params.keys()
KeySet({Key(...), ...})
# get all the keys in the collection where protocol is SRB
params.keys(protocol="SRB")
KeySet({Key(...), ...})

You can iterate over all parameters in the collection whose names match a given pattern:

# get all parameters that start with 'p' and whose protocol is SRB
[param.std for param in params.subset('p*', protocol="SRB")]

Similarly, you can iterate over all key,parameter tuples:

# get all parameters that start with 'p' and whose protocol is SRB
{key: param.std for key, param in params.flat_items('p*', protocol="SRB")}
Parameters

parameters – A dictionary-like structure of Parameter instances, where keys are Keys.

plot = None

An object that stores all plotting functions deemed relevant to this collection of parameters.

Note

If there is a plotting function that you expected to be present but is not, double check which parameters are actually present in this collection.

Type

PlottingSuite

keys(**filter)

Returns the set of all keys of this parameter collection matching the given filter.

parameter_collection.keys(protocol="SRB")
KeySet(Key(...,protocol="SRB"), ...)
Parameters

filter – The filter on keys.

Return type

KeySet

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. See similar_keys() for some more details.

Parameters
  • names – Any number of name strings.

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

subset(pattern='*', **filter)

Returns a generator over all parameters in this collection that match the filter on keys, and whose parameter names match the given pattern. The pattern can contain a wildcard character ‘*’, see Parameter.matches() .

# get all estimates of parameters from CB that start with 'p'
estimates = [param.estimate for param in params.subset('p*', protocol="CB")]
Parameters
  • pattern (str) – A string pattern to match by.

  • filter – The filter on keys.

Return type

generator

flat_items(pattern='*', **filter)

Returns a generator over all tuples (key, param) in this collection that match the filter on keys, and whose parameter names match the given pattern. The pattern can contain a wildcard character ‘*’, see Parameter.matches(). Here, param is a Parameter and key is the Key that owns the corresponding parameter.

# make a dictionary of standard deviations for all those parameters that
# start with 'p' and have protocol of CB
stds = {
    key.pauli_decay: param.std
    for key, param in params.flat_items("p*", protocol="CB")
}
Parameters
  • pattern (str) – A string pattern to match by.

  • filter – The filter on keys.

Return type

generator

items(**filter)

Returns a generator over key, value pairs of this collection. Each key is a Key instance, and each value is a ParameterList instance.

Parameters

filter – The filter on keys.

append(key, parameter, **meta)

Appends a parameter to this collection categorized by the given key.

Parameters
  • key (Key) – A Key instance.

  • parameter (Parameter) – A Parameter instance.

  • meta – Any meta information to attach to the given key.

combine(parameters)

Adds all of the keys/parameters from the given parameter collection to this parameter collection. Meta information is only updated for a given key in this collection if it is not already present.

Parameters

parameters (ParameterCollection) – Another ParameterCollection.

summarize()

Prints a multi-line text summary of the parameters in this collection.