dit.utils

Module providing miscellaneous functionality.

Functions

basic_logger

Return a loguru-bound logger for backward compatibility.

bindcallargs

build_table

Construct a PrettyTable with style set.

cd

Change the current working directory to newpath, temporarily.

default_opener

Opens filename using system's default program.

digits

Returns n as a sequence of indexes into an alphabet.

extended_partition

Expand a partition over a subset of outcome indices to the entire outcome.

flatten

Flatten an irregular list of lists.

get_fobj

Obtain a proper file object.

is_string_like

Returns True if obj is string-like, and False otherwise.

named_tempfile

Calls tempfile.NamedTemporaryFile(*args, **kwargs) with delete=False.

ordered_partitions

Generates ordered partitions of elements in seq.

partition_set

Returns the equivlence classes from elements.

partitions

Generates all partitions of seq.

pmf_to_latex

Convert an array-like object into a LaTeX array.

pmf_to_pdf

Converts a NumPy array to a LaTeX array, compiles and displays it.

powerset

product_maker

Returns a customized product function.

quasilexico_key

Returns a key suitable for a quasi-lexicographic sort [1].

require_keys

Verifies that keys appear in the specified dictionary.

str_product

tempdir

Calls tempfile.mkdtemp() and deletes the directory after the context.

unitful

Report the wrapped measure's value in the base of its distribution.

Reference

basic_logger(name, level)[source]

Return a loguru-bound logger for backward compatibility.

Parameters:
  • name (str) – The name to bind to log messages.

  • level (int, bool, None) – If None or False, logging is effectively silenced. If True or a positive integer, logging is enabled.

Returns:

logger – A loguru logger instance bound to name.

Return type:

loguru.Logger

bindcallargs(_fUnCtIoN_, *args, **kwargs)[source]
build_table(field_names=None, title=None)[source]

Construct a PrettyTable with style set.

Parameters:
  • field_names (list) – List of field names.

  • title (str) – Title for the table.

Returns:

table – A new table.

Return type:

PrettyTable

cd(newpath)[source]

Change the current working directory to newpath, temporarily.

If the old current working directory no longer exists, do not return back.

default_opener(filename)[source]

Opens filename using system’s default program.

Parameters:

filename (str) – The path of the file to be opened.

digits(n, base, alphabet=None, pad=0, big_endian=True)[source]

Returns n as a sequence of indexes into an alphabet.

Parameters:
  • n (int) – The number to convert into a sequence of indexes.

  • base (int) – The desired base of the sequence representation. The base must be greater than or equal to 2.

  • alphabet (iterable) – If specified, then the indexes are converted into symbols using the specified alphabet.

  • pad (int) – If True, the resultant sequence is padded with zeros.

  • big_endian (bool) – If True, then the resultant sequence has the least significant digits at the end. This is standard for Western culture.

Returns:

sequence – The digits representation of n.

Return type:

list

Examples

>>> digits(6, base=2, pad=4)
[0, 1, 1, 0]
>>> ''.join(digits(6, base=2, pad=4, alphabet='xo'))
'xoox'
extended_partition(outcomes, indices, part, ctr)[source]

Expand a partition over a subset of outcome indices to the entire outcome.

Parameters:
  • outcomes (list) – List of outcomes.

  • indices ([int]) – A list of indices corresponding to which indices of each outcome an element of part corresponds to.

  • part (frozenset[frozenset]) – A partition on some subset of indices of the outcomes.

  • ctr (func) – The constructor to build sub-outcomes from.

Returns:

partition – The expanded partition.

Return type:

frozenset[frozenset]

flatten(l)[source]

Flatten an irregular list of lists.

Parameters:

l (iterable) – The object to be flattened.

Yields:

el (object) – The non-iterable items in l.

get_fobj(fname, mode='w+')[source]

Obtain a proper file object.

Parameters:
  • fname (string, file object, file descriptor) – If a string or file descriptor, then we create a file object. If fname is a file object, then we do nothing and ignore the specified mode parameter.

  • mode (str) – The mode of the file to be opened.

Returns:

  • fobj (file object) – The file object.

  • close (bool) – If fname was a string or file descriptor, then close will be True to signify that the file object should be closed. Otherwise, close will be False signifying that the user has opened the file object and that we should not close it.

is_string_like(obj)[source]

Returns True if obj is string-like, and False otherwise.

named_tempfile(*args, **kwargs)[source]

Calls tempfile.NamedTemporaryFile(*args, **kwargs) with delete=False.

The file is deleted after the context.

ordered_partitions(seq, tuples=False)[source]

Generates ordered partitions of elements in seq.

Parameters:
  • seq (iterable) – Any iterable. Used to generate the partitions.

  • tuples (bool) – If True, yields tuple of tuples. Otherwise, yields tuple of frozensets.

Yields:

partition (tuple) – A tuple of frozensets, or a tuple of sorted tuples.

partition_set(elements, relation=None, innerset=False, reflexive=False, transitive=False)[source]

Returns the equivlence classes from elements.

Given relation, we test each element in elements against the other elements and form the equivalence classes induced by relation. By default, we assume the relation is symmetric. Optionally, the relation can be assumed to be reflexive and transitive as well. All three properties are required for relation to be an equivalence relation.

However, there are times when a relation is not reflexive or transitive. For example, floating point comparisons do not have these properties. In this instance, it might be desirable to force reflexivity and transitivity on the elements and then, work with the resulting partition.

Parameters:
  • elements (iterable) – The elements to be partitioned.

  • relation (function, None) – A function accepting two elements, which returns True iff the two elements are related. The relation need not be an equivalence relation, but if reflexive and transitive are not set to False, then the resulting partition will not be unique. If None, then == is used.

  • innerset (bool) – If True, then the equivalence classes will be returned as frozensets. This means that duplicate elements (according to __eq__ not relation) will appear only once in the equivalence class. If False, then the equivalence classes will be returned as lists. This means that duplicate elements will appear multiple times in an equivalence class.

  • reflexive (bool) – If True, then relation is assumed to be reflexive. If False, then reflexivity will be enforced manually. Effectively, a new relation is considered: relation(a,b) AND relation(b,a).

  • transitive (bool) – If True, then relation is assumed to be transitive. If False, then transitivity will be enforced manually. Effectively, a new relation is considered: relation(a,b) for all b in the class.

Returns:

  • eqclasses (list) – The collection of equivalence classes.

  • lookup (list) – A list relating where lookup[i] contains the index of the eqclass that elements[i] was mapped to in eqclasses.

partitions(seq, tuples=False)[source]

Generates all partitions of seq.

Parameters:
  • seq (iterable) – Any iterable. Used to generate the partitions.

  • tuples (bool) – If True, yields tuple of tuples. Otherwise, yields frozenset of frozensets.

Yields:

partition (frozenset or tuple) – A frozenset of frozensets, or a sorted tuple of sorted tuples.

pmf_to_latex(a, exact=False, decimals=3, tab='  ')

Convert an array-like object into a LaTeX array.

Parameters:
  • a (array-like) – A list, tuple, NumPy array, etc. The elements are written into a LaTeX array environment.

  • exact (bool) –

    When exact is False, the elements of each column are aligned on the decimal, if present. Spacing is automatically adjusted depending on if a contains negative numbers or not. For float data, trailing zeros are included so that array output is uniform.

    When exact is True, then each float is turned into a fraction and placed in a column. One may specify exact as a small float to be used as the tolerance while converting to a fraction.

  • decimals (int) – The number of decimal places to round to before writing to LaTeX.

  • tab (str) – The tab character to use for indentation within LaTeX.

Examples

>>> x = [1,2,-3]
>>> print to_latex(x)
\newcolumntype{X}{D{.}{.}{2,0}}
\begin{array}{*{3}{X}}
  1 & 2 & -3
\end{array}
>>> import numpy as np
>>> np.random.seed(0)
>>> y = np.random.rand(12).reshape(4,3) - 0.5
>>> print to_latex(y, decimals=2)
\newcolumntype{X}{D{.}{.}{2,2}}
\begin{array}{*{3}{X}}
  0.05 & 0.22 & 0.10 \\
  0.04 & -0.08 & 0.15 \\
  -0.06 & 0.39 & 0.46 \\
  -0.12 & 0.29 & 0.03
\end{array}

Notes

The resultant array environment should be used within LaTeX’s mathmode, and the following should appear in the preamble:

usepackage{array} usepackage{dcolumn}

pmf_to_pdf(a, exact=False, decimals=3, line='p(x) = \\left[\n{0}\n\\right]', show=True)

Converts a NumPy array to a LaTeX array, compiles and displays it.

Examples

>>> a = np.array([[.1, .23, -1.523],[2.1, .23, .523]])
>>> to_pdf(a) # pragma: no cover
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)[source]
product_maker(func)[source]

Returns a customized product function.

itertools.product yields tuples. Sometimes, one desires some other type of object—for example, strings. This function transforms the output of itertools.product, returning a customized product function.

Parameters:

func (callable) – Any function which accepts an iterable as the single input argument. The iterates of itertools.product are transformed by this callable.

Returns:

_product – A customized itertools.product function.

Return type:

callable

quasilexico_key(x)[source]

Returns a key suitable for a quasi-lexicographic sort [1].

Objects are sorted by length first, then lexicographically.

Examples

>>> L = ['a', 'aa', 'b']
>>> sorted(L, key=quasilexico_key)
['a', 'b', 'aa']

References

require_keys(keys, dikt)[source]

Verifies that keys appear in the specified dictionary.

Parameters:
  • keys (list of str) – List of required keys.

  • dikt (dict) – The dictionary that is checked for keys.

Return type:

None

Raises:

Exception – Raised when a required key is not present.

str_product(*args, **kwargs)
tempdir(*args, **kwargs)[source]

Calls tempfile.mkdtemp() and deletes the directory after the context.

unitful(f)[source]

Report the wrapped measure’s value in the base of its distribution.

Parameters:

f (func) – The function to wrap. It must compute its result in bits from linear-probability distributions.

Returns:

wrapper – A function whose distribution arguments are linearized and whose (first) return value is expressed in the base of the first distribution argument, optionally with units attached.

Return type:

func