cotengra.utils¶
Various utilities for cotengra.
Attributes¶
Exceptions¶
Use this to indicate that a trial contraction tree was bad. |
Classes¶
An ordered set which stores elements as the keys of dict (ordered as of |
|
Simple class to keep track of the maximum in a likely changing |
|
A simple persistent dict. The keys should be filesystem compatible |
|
Non numpy version of gumbel number generator. |
|
Built-in immutable sequence. |
Functions¶
|
Adapted from toolz. |
|
|
|
Compute the product of sequence of numbers |
|
Get a source of random numbers. |
|
Computes the product of sizes of |
|
Get the symbol corresponding to int |
|
Get a mapping of arbitrary hashable 'indices' to single unicode symbols, |
|
A more advanced version of |
|
Create a random contraction equation that corresponds to a tree. |
|
Turn a networkx graph into a cotengra style contraction, randomly |
|
Create a random contraction equation that corresponds to a random |
|
Create a weird but valid einsum equation with lots of hyper-edges, |
|
Get a random contraction tree (note, not a tree like equation). |
|
Create a random contraction equation that corresponds to a lattice. |
|
Compute the output string from the left-hand side only of an equation. |
Convert a einsum equation into an explicit list of list of characters |
|
|
Convert an explicit list of inputs and output to a str einsum equation. |
|
Convert a list of shapes and inputs to a size dictionary. |
|
Get a random size dictionary for a given set of inputs. |
|
Make example shapes to match inputs and index sizes. |
|
Make example arrays to match inputs and index sizes. |
|
Create a set of example arrays to match an einsum equation directly. |
|
Find the output indices for a given set of inputs. The outputs are |
|
Check if the optimize path is a list of indices or a single string. |
|
Return a canonicalized version of the inputs and output, with the |
|
Convert from interleaved format |
|
Check if a einsum term has exactly one ellipsis ('...') or else no |
|
|
|
Reproduce einsum input parsing, which handles both interleaved input, |
|
Save a contraction to a json file. |
|
Load a contraction from a json file. |
Module Contents¶
- class cotengra.utils.oset(it=())[source]¶
An ordered set which stores elements as the keys of dict (ordered as of python 3.6). ‘A few times’ slower than using a set directly for small sizes, but makes everything deterministic.
- __slots__ = ('_d',)¶
- _d¶
- class cotengra.utils.MaxCounter(it=None)[source]¶
Simple class to keep track of the maximum in a likely changing sequence of elements.
- Parameters:
it (None or sequence of hashable, optional) – The initial items to add.
Examples
>>> mc = MaxCounter([1, 2, 3, 3]) >>> mc.max() 3
>>> mc.discard(3) >>> mc.max() 3
>>> mc.discard(3) >>> mc.max() 2
>>> mc.add(10) >>> mc.max() 10
- __slots__ = ('_c', '_max_element')¶
- _c¶
- class cotengra.utils.BitSet(it)[source]¶
- __slots__ = ('members', 'map', 'size', 'infimum', 'supremum', 'hashkey')¶
- members¶
- map¶
- size¶
- supremum¶
- infimum¶
- hashkey¶
- class cotengra.utils.DiskDict(directory=None, max_retries=3, retry_delay=0.01)[source]¶
A simple persistent dict. The keys should be filesystem compatible strings, or tuples of strings, in which case it will be used as a sub-directory structure. The values should be picklable. The directory will be created if it does not exist. Values are loaded into memory once they are accessed.
- Parameters:
directory (str or pathlib.Path, optional) – The directory to store the files in. If None, the files will not be stored on disk and only kept in memory.
max_retries (int, optional) – The maximum number of retries to read a file if it is not completely written yet. Default is 3.
retry_delay (float, optional) – The delay between retries in seconds. Default is 0.01.
- __slots__ = ('_directory', '_mem_cache', '_path', 'max_retries', 'retry_delay')¶
- _mem_cache¶
- _directory = None¶
- max_retries = 3¶
- retry_delay¶
- cotengra.utils.get_rng(seed=None)[source]¶
Get a source of random numbers.
- Parameters:
seed (None or int or random.Random, optional) – The seed for the random number generator. If None, use the default random number generator. If an integer, use a new random number generator with the given seed. If a random.Random instance, use that instance.
- class cotengra.utils.GumbelBatchedGenerator(seed=None)[source]¶
Non numpy version of gumbel number generator.
- rng¶
- exception cotengra.utils.BadTrial[source]¶
Bases:
ExceptionUse this to indicate that a trial contraction tree was bad.
- cotengra.utils.compute_size_by_dict(indices, size_dict)[source]¶
Computes the product of sizes of
indicesbased onsize_dict.- Parameters:
- Returns:
d – The resulting product.
- Return type:
Examples
>>> compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5}) 90
- cotengra.utils._einsum_symbols_base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'¶
- cotengra.utils.get_symbol(i)[source]¶
Get the symbol corresponding to int
i- runs through the usual 52 letters before resorting to unicode characters, starting atchr(192)and skipping surrogates.Examples
get_symbol(2) #> ‘c’
get_symbol(200) #> ‘Ŕ’
get_symbol(20000) #> ‘京’
- cotengra.utils.get_symbol_map(inputs)[source]¶
Get a mapping of arbitrary hashable ‘indices’ to single unicode symbols, matching the canonicalization of the expression.
- class cotengra.utils.Contraction[source]¶
Bases:
collections.namedtuple('Contraction', ('inputs','output','shapes','size_dict'))Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.
- property eq¶
Get the einsum equation string corresponding to this contraction.
- cotengra.utils.rand_equation(n, reg, n_out=0, n_hyper_in=0, n_hyper_out=0, d_min=2, d_max=3, seed=None)[source]¶
A more advanced version of
opt_einsum.testing.rand_equationthat can also generate both inner and outer hyper-edges. Mostly useful for generating test instances covering all edge cases.- Parameters:
n (int) – The number of tensors.
reg (int) – The average number of indices per tensor if no hyper-edges, i.e. total number of inds
= n * reg // 2.n_out (int, optional) – The number of output indices.
n_hyper_in (int, optional) – The number of inner hyper-indices.
n_hyper_out (int, optional) – The number of outer hyper-indices.
d_min (int, optional) – The minimum dimension size.
d_max (int, optional) – The maximum dimension size.
seed (None or int, optional) – Seed for
np.randomfor repeatibility.
- Returns:
inputs (list[list[str]])
output (list[str])
shapes (list[tuple[int]])
size_dict (dict[str, int])
- cotengra.utils.tree_equation(n, d_min=2, d_max=3, n_outer=0, seed=None)[source]¶
Create a random contraction equation that corresponds to a tree.
- cotengra.utils.networkx_graph_to_equation(G, d_min=2, d_max=3, seed=None)[source]¶
Turn a networkx graph into a cotengra style contraction, randomly sampling index sizes for each edge.
- Parameters:
- Returns:
inputs (list[list[str]])
output (list[str])
shapes (list[tuple[int]])
size_dict (dict[str, int])
- cotengra.utils.randreg_equation(n, reg, d_min=2, d_max=3, seed=None)[source]¶
Create a random contraction equation that corresponds to a random regular graph.
- Parameters:
- Returns:
inputs (list[list[str]])
output (list[str])
shapes (list[tuple[int]])
size_dict (dict[str, int])
- cotengra.utils.perverse_equation(n, num_indices=3, min_rank=0, max_rank=6, d_min=2, d_max=3, n_outer=2, seed=None)[source]¶
Create a weird but valid einsum equation with lots of hyper-edges, repeated indices, scalars and repeated terms.
- Parameters:
n (int) – The number of tensors.
num_indices (int, optional) – The number of indices to use.
min_rank (int, optional) – The minimum rank of a tensor.
max_rank (int, optional) – The maximum rank of a tensor.
d_min (int, optional) – The minimum size of an index.
d_max (int, optional) – The maximum size of an index.
n_outer (int, optional) – The number of outer indices.
seed (None or int, optional) – Seed for
random.Randomfor repeatibility.
- cotengra.utils.rand_tree(n, reg, n_out=0, n_hyper_in=0, n_hyper_out=0, d_min=2, d_max=3, seed=None, optimize='greedy')[source]¶
Get a random contraction tree (note, not a tree like equation).
- cotengra.utils.lattice_equation(dims, cyclic=False, d_min=2, d_max=None, seed=None)[source]¶
Create a random contraction equation that corresponds to a lattice.
- Parameters:
dims (sequence of int) – The size of each dimension, with the dimensionality being the length of the sequence.
cyclic (bool or sequence of bool, optional) – Whether each dimension is cyclic or not. If a sequence, must be the same length as
dims.d_min (int, optional) – The minimum size of an index.
d_max (int, optional) – The maximum size of an index. If
None, defaults tod_min, i.e. all indices are the same size.seed (None or int, optional) – Seed for
random.Randomfor repeatibility.
- cotengra.utils.find_output_str(lhs)[source]¶
Compute the output string from the left-hand side only of an equation. This is any indices that appear only once in the left-hand side, in sorted order.
- Parameters:
lhs (str) – The comma separated list of indices on the left-hand side of an einsum equation.
- Returns:
rhs – The output string of the einsum equation.
- Return type:
Examples
>>> find_output_str('cb,ba') 'ac'
- cotengra.utils.eq_to_inputs_output(eq)[source]¶
Convert a einsum equation into an explicit list of list of characters and an output list of characters.
- Parameters:
eq (str) – The einsum equation, with or without output.
- Returns:
inputs (list[list[str]]) – The input terms.
output (list[str]) – The output term.
- cotengra.utils.inputs_output_to_eq(inputs, output, canonicalize=False)[source]¶
Convert an explicit list of inputs and output to a str einsum equation.
- cotengra.utils.shapes_inputs_to_size_dict(shapes, inputs)[source]¶
Convert a list of shapes and inputs to a size dictionary.
- cotengra.utils.make_rand_size_dict_from_inputs(inputs, d_min=2, d_max=3, seed=None)[source]¶
Get a random size dictionary for a given set of inputs.
- Parameters:
- Returns:
size_dict – The index size dictionary.
- Return type:
- cotengra.utils.make_shapes_from_inputs(inputs, size_dict)[source]¶
Make example shapes to match inputs and index sizes.
- cotengra.utils.make_arrays_from_inputs(inputs, size_dict, seed=None, dtype='float64')[source]¶
Make example arrays to match inputs and index sizes.
- Parameters:
- Returns:
arrays – The example arrays.
- Return type:
- cotengra.utils.make_arrays_from_eq(eq, d_min=2, d_max=3, seed=None, size_dict=None, dtype='float64')[source]¶
Create a set of example arrays to match an einsum equation directly.
- Parameters:
eq (str) – The einsum equation.
d_min (int, optional) – The minimum dimension, by default 2.
d_max (int, optional) – The maximum dimension, by default 3.
seed (int, optional) – The random seed, by default None.
size_dict (dict[str, int], optional) – The index size dictionary. If supplied this is used instead of generating a random one.
dtype ({'float32', 'float64', 'complex64', 'complex128'}, optional) – The dtype of the arrays, by default ‘float64’.
- Returns:
arrays – The example arrays.
- Return type:
- cotengra.utils.find_output_from_inputs(inputs)[source]¶
Find the output indices for a given set of inputs. The outputs are calculated as the set of indices that appear only once, in the order they appear in the inputs. This is different to einsum where they in sorted order since we only require the indices to be hashable.
- Parameters:
inputs (Sequence[Sequence[Hashable]]) – The input terms.
- Returns:
output
- Return type:
tuple[Hashable]
- cotengra.utils.is_edge_path(optimize)[source]¶
Check if the optimize path is a list of indices or a single string.
- cotengra.utils.canonicalize_inputs(inputs, output=None, shapes=None, size_dict=None, optimize=None)[source]¶
Return a canonicalized version of the inputs and output, with the indices labelled from ‘a’, ‘b’, ‘c’, … according to the order they appear in the equation.
If
outputis not provided, it will be computed as the set of indices that appear once, in the order they appear on the inputs (note that this is different to einsum where they in sorted order since we only require the indices to be hashable and not comparable).If either
shapesorsize_dictis provided, then also compute the corresponding canonicalizedsize_dictfor new index labels.- Parameters:
inputs (Sequence[Sequence[Hashable]]) – The input terms.
output (Sequence[Hashable], optional) – The output term. If not supplied it will be computed.
shapes (None or Sequence[tuple[int]], optional) – The shapes of each input.
size_dict (None or dict[Hashable, int], optional) – The index size dictionary.
- Returns:
new_inputs (tuple[tuple[str]]) – The canonicalized input terms.
new_output (tuple[str]) – The canonicalized output term.
new_size_dict (dict[str, int] or None) – The canonicalized index size dictionary,
Noneifsize_dictorshapeswas not provided.new_optimize (None or str or Sequence[str] or Sequence[int], optional) – The canonicalized optimize path,
Noneifoptimizewas not provided.
- cotengra.utils.convert_from_interleaved(args)[source]¶
Convert from interleaved format
array0, input0, array1, input1, ...to a single equation and list of arrays. The arrays can just be shapes.
- cotengra.utils.check_ellipsis(term)[source]¶
Check if a einsum term has exactly one ellipsis (’…’) or else no dots at all.
- cotengra.utils.parse_einsum_input(args, shapes=False, tuples=False, constants=None)[source]¶
Reproduce einsum input parsing, which handles both interleaved input, ellipsis expansions, and output calculation. The main processing is cached.