A Collection of Utilities

Math

pytools.levi_civita(tup)[source]

Compute an entry of the Levi-Civita tensor for the indices tuple.

pytools.perm(n, k)[source]

Return P(n, k), the number of permutations of length k drawn from n choices.

pytools.comb(n, k)[source]

Return C(n, k), the number of combinations (subsets) of length k drawn from n choices.

Assertive accessors

pytools.one(iterable)[source]

Return the first entry of iterable. Assert that iterable has only that one entry.

pytools.is_single_valued(iterable, equality_pred=<built-in function eq>)[source]
pytools.all_roughly_equal(iterable, threshold)[source]
pytools.single_valued(iterable, equality_pred=<built-in function eq>)[source]

Return the first entry of iterable; Assert that other entries are the same with the first entry of iterable.

Memoization

pytools.memoize(*args, **kwargs)[source]

Stores previously computed function values in a cache.

Two keyword-only arguments are supported:

Parameters
  • use_kwargs – Allows the caller to use keyword arguments. Defaults to False. Setting this to True has a non-negligible performance impact.

  • key – A function receiving the same arguments as the decorated function which computes and returns the cache key.

pytools.memoize_on_first_arg(function, cache_dict_name=None)[source]

Like memoize_method(), but for functions that take the object to do memoization as first argument.

Supports cache deletion via function_name.clear_cache(self).

Note

clear_cache support requires Python 2.5 or newer.

pytools.memoize_method(method)[source]

Supports cache deletion via method_name.clear_cache(self).

Note

clear_cache support requires Python 2.5 or newer.

pytools.memoize_method_with_uncached(uncached_args=None, uncached_kwargs=None)[source]

Supports cache deletion via method_name.clear_cache(self).

Parameters

uncached_args – a list of argument numbers (0-based, not counting ‘self’ argument)

pytools.memoize_in(container, identifier)[source]

Adds a cache to a function nested inside a method. The cache is attached to object.

Requires Python 2.5 or newer.

Argmin/max

pytools.argmin2(iterable, return_value=False)[source]
pytools.argmax2(iterable, return_value=False)[source]
pytools.argmin(iterable)[source]
pytools.argmax(iterable)[source]

Cartesian products

pytools.cartesian_product(list1, list2)[source]
pytools.distinct_pairs(list1, list2)[source]

Permutations, Tuples, Integer sequences

pytools.wandering_element(length, wanderer=1, landscape=0)[source]
pytools.indices_in_shape(shape)[source]
pytools.generate_nonnegative_integer_tuples_below(n, length=None, least=0)[source]

n may be a sequence, in which case length must be None.

pytools.generate_nonnegative_integer_tuples_summing_to_at_most(n, length)[source]

Enumerate all non-negative integer tuples summing to at most n, exhausting the search space by varying the first entry fastest, and the last entry the slowest.

pytools.generate_all_nonnegative_integer_tuples(length, least=0)[source]
pytools.generate_all_integer_tuples_below(n, length, least_abs=0)[source]
pytools.generate_all_integer_tuples(length, least_abs=0)[source]
pytools.generate_permutations(original)[source]

Generate all permutations of the list original.

Nicked from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252178

pytools.generate_unique_permutations(original)[source]

Generate all unique permutations of the list original.

Graph Algorithms

pytools.a_star(initial_state, goal_state, neighbor_map, estimate_remaining_cost=None, get_step_cost=<function <lambda>>)[source]

With the default cost and heuristic, this amounts to Dijkstra’s algorithm.

Formatting

class pytools.Table[source]

An ASCII table generator.

add_row(row)[source]
__str__()[source]

Return str(self).

latex(skip_lines=0, hline_after=None)[source]
pytools.string_histogram(iterable, min_value=None, max_value=None, bin_count=20, width=70, bin_starts=None, use_unicode=True)[source]
pytools.word_wrap(text, width, wrap_using='\n')[source]

A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines (\n).

Debugging

pytools.typedump(val, max_seq=5, special_handlers=None)[source]
pytools.invoke_editor(s, filename='edit.txt', descr='the file')[source]

Progress bars

class pytools.ProgressBar(descr, total, initial=0, length=40)[source]
draw()[source]
progress(steps=1)[source]
set_progress(done)[source]
finished()[source]
__enter__()[source]
__exit__(exc_type, exc_val, exc_tb)[source]

Name generation

pytools.generate_unique_names(prefix)[source]
pytools.generate_numbered_unique_names(prefix, num=None)[source]
class pytools.UniqueNameGenerator(existing_names=None, forced_prefix='')[source]
is_name_conflicting(name)[source]
add_name(name)[source]
add_names(names)[source]
__call__(based_on='id')[source]

Call self as a function.

Functions for dealing with (large) auxiliary files

pytools.download_from_web_if_not_present(url, local_name=None)[source]

New in version 2017.5.

Helpers for numpy

pytools.reshaped_view(a, newshape)[source]

Create a new view object with shape newshape without copying the data of a. This function is different from numpy.reshape by raising an exception when data copy is necessary.

Parameters
  • a – a numpy.ndarray object.

  • newshape – an int object or a tuple of int objects.

New in version 2018.4.

Timing data

pytools.SUPPORTS_PROCESS_TIME

A bool indicating whether ProcessTimer measures elapsed process time (available on Python 3.3+).

class pytools.ProcessTimer[source]

Measures elapsed wall time and process time.

__enter__()[source]
__exit__(exc_type, exc_val, exc_tb)[source]
done()[source]

Timing data attributes:

wall_elapsed
process_elapsed

Only available in Python 3.3+.

New in version 2018.5.

Log utilities

class pytools.ProcessLogger(logger, description, silent_level=None, noisy_level=None, long_threshold_seconds=None)[source]

Logs the completion time of a (presumably) lengthy process to logging. Only uses a high log level if the process took perceptible time.

__init__(logger, description, silent_level=None, noisy_level=None, long_threshold_seconds=None)[source]

Initialize self. See help(type(self)) for accurate signature.

done(extra_msg=None, *extra_fmt_args)[source]
__enter__()[source]
__exit__(exc_type, exc_val, exc_tb)[source]
class pytools.DebugProcessLogger(logger, description, silent_level=None, noisy_level=None, long_threshold_seconds=None)[source]
class pytools.log_process(logger, description=None)[source]

A decorator that uses ProcessLogger to log data about calls to the wrapped function.