# pylint: disable=too-many-lines
# (Yes, it has a point!)
from __future__ import division, absolute_import, print_function
__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from functools import reduce
import operator
import sys
import logging
from typing import (
Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, TypeVar)
import six
from six.moves import range, zip, intern, input
decorator_module = __import__("decorator", level=0)
my_decorator = decorator_module.decorator
__doc__ = """
A Collection of Utilities
=========================
Math
----
.. autofunction:: levi_civita
.. autofunction:: perm
.. autofunction:: comb
Assertive accessors
-------------------
.. autofunction:: one
.. autofunction:: is_single_valued
.. autofunction:: all_roughly_equal
.. autofunction:: single_valued
Memoization
-----------
.. autofunction:: memoize
.. autofunction:: memoize_on_first_arg
.. autofunction:: memoize_method
.. autofunction:: memoize_in
.. autofunction:: keyed_memoize_on_first_arg
.. autofunction:: keyed_memoize_method
Argmin/max
----------
.. autofunction:: argmin2
.. autofunction:: argmax2
.. autofunction:: argmin
.. autofunction:: argmax
Cartesian products
------------------
.. autofunction:: cartesian_product
.. autofunction:: distinct_pairs
Permutations, Tuples, Integer sequences
---------------------------------------
.. autofunction:: wandering_element
.. autofunction:: generate_nonnegative_integer_tuples_below
.. autofunction:: generate_nonnegative_integer_tuples_summing_to_at_most
.. autofunction:: generate_all_nonnegative_integer_tuples
.. autofunction:: generate_all_integer_tuples_below
.. autofunction:: generate_all_integer_tuples
.. autofunction:: generate_permutations
.. autofunction:: generate_unique_permutations
Formatting
----------
.. autoclass:: Table
.. autofunction:: string_histogram
.. autofunction:: word_wrap
Debugging
---------
.. autofunction:: typedump
.. autofunction:: invoke_editor
Progress bars
-------------
.. autoclass:: ProgressBar
Name generation
---------------
.. autofunction:: generate_unique_names
.. autofunction:: generate_numbered_unique_names
.. autoclass:: UniqueNameGenerator
Functions for dealing with (large) auxiliary files
--------------------------------------------------
.. autofunction:: download_from_web_if_not_present
Helpers for :mod:`numpy`
------------------------
.. autofunction:: reshaped_view
Timing data
-----------
.. data:: SUPPORTS_PROCESS_TIME
A :class:`bool` indicating whether :class:`ProcessTimer` measures elapsed
process time (available on Python 3.3+).
.. autoclass:: ProcessTimer
Log utilities
-------------
.. autoclass:: ProcessLogger
.. autoclass:: DebugProcessLogger
.. autoclass:: log_process
Sorting in natural order
------------------------
.. autofunction:: natorder
.. autofunction:: natsorted
"""
# {{{ type variables
T = TypeVar("T")
F = TypeVar('F', bound=Callable[..., Any])
# }}}
# {{{ math --------------------------------------------------------------------
def delta(x, y):
if x == y:
return 1
else:
return 0
def levi_civita(tup):
"""Compute an entry of the Levi-Civita tensor for the indices *tuple*."""
if len(tup) == 2:
i, j = tup
return j-i
if len(tup) == 3:
i, j, k = tup
return (j-i)*(k-i)*(k-j)/2
else:
raise NotImplementedError
def factorial(n):
from operator import mul
assert n == int(n)
return reduce(mul, (i for i in range(1, n+1)), 1)
def perm(n, k):
"""Return P(n, k), the number of permutations of length k drawn from n
choices.
"""
result = 1
assert k > 0
while k:
result *= n
n -= 1
k -= 1
return result
def comb(n, k):
"""Return C(n, k), the number of combinations (subsets)
of length k drawn from n choices.
"""
return perm(n, k)//factorial(k)
def norm_1(iterable):
return sum(abs(x) for x in iterable)
def norm_2(iterable):
return sum(x**2 for x in iterable)**0.5
def norm_inf(iterable):
return max(abs(x) for x in iterable)
def norm_p(iterable, p):
return sum(i**p for i in iterable)**(1/p)
class Norm(object):
def __init__(self, p):
self.p = p
def __call__(self, iterable):
return sum(i**self.p for i in iterable)**(1/self.p)
# }}}
# {{{ data structures
# {{{ record
class RecordWithoutPickling(object):
"""An aggregate of named sub-variables. Assumes that each record sub-type
will be individually derived from this class.
"""
__slots__: List[str] = []
def __init__(self, valuedict=None, exclude=None, **kwargs):
assert self.__class__ is not Record
if exclude is None:
exclude = ["self"]
try:
fields = self.__class__.fields
except AttributeError:
self.__class__.fields = fields = set()
if valuedict is not None:
kwargs.update(valuedict)
for key, value in six.iteritems(kwargs):
if key not in exclude:
fields.add(key)
setattr(self, key, value)
def get_copy_kwargs(self, **kwargs):
for f in self.__class__.fields:
if f not in kwargs:
try:
kwargs[f] = getattr(self, f)
except AttributeError:
pass
return kwargs
def copy(self, **kwargs):
return self.__class__(**self.get_copy_kwargs(**kwargs))
def __repr__(self):
return "%s(%s)" % (
self.__class__.__name__,
", ".join("%s=%r" % (fld, getattr(self, fld))
for fld in self.__class__.fields
if hasattr(self, fld)))
def register_fields(self, new_fields):
try:
fields = self.__class__.fields
except AttributeError:
self.__class__.fields = fields = set()
fields.update(new_fields)
def __getattr__(self, name):
# This method is implemented to avoid pylint 'no-member' errors for
# attribute access.
raise AttributeError(
"'%s' object has no attribute '%s'" % (
self.__class__.__name__, name))
class Record(RecordWithoutPickling):
__slots__: List[str] = []
def __getstate__(self):
return dict(
(key, getattr(self, key))
for key in self.__class__.fields
if hasattr(self, key))
def __setstate__(self, valuedict):
try:
fields = self.__class__.fields
except AttributeError:
self.__class__.fields = fields = set()
for key, value in six.iteritems(valuedict):
fields.add(key)
setattr(self, key, value)
def __eq__(self, other):
return (self.__class__ == other.__class__
and self.__getstate__() == other.__getstate__())
def __ne__(self, other):
return not self.__eq__(other)
class ImmutableRecordWithoutPickling(RecordWithoutPickling):
"Hashable record. Does not explicitly enforce immutability."
def __init__(self, *args, **kwargs):
RecordWithoutPickling.__init__(self, *args, **kwargs)
self._cached_hash = None
def __hash__(self):
if self._cached_hash is None:
self._cached_hash = hash(
(type(self),) + tuple(getattr(self, field)
for field in self.__class__.fields))
return self._cached_hash
Loading ...