19"""The :mod:`~qdpy.utils` module is a collection of small functions and classes handling common patterns."""
23from collections.abc
import Iterable
24from typing
import Optional, Tuple, TypeVar, Union, Any, MutableSet, Mapping, MutableMapping, Sequence, MutableSequence, Callable, Tuple, Generator
25from typing_extensions
import runtime, Protocol
33def is_iterable(obj: Any) -> bool:
34 """Return if ``obj`` is iterable or not."""
35 return isinstance(obj, Iterable)
38def in_bounds(val: Any, domain: Any) -> bool:
39 """Check whether a scalar or vector falls inside inclusive bounds.
41 A vector may use one shared interval or one interval per coordinate.
42 Coordinate-specific bounds must have the same length as the vector.
43 A NaN comparison fails the bounds check.
46 if isinstance(val, Sequence)
or isinstance(val, np.ndarray):
47 if isinstance(domain[0], Sequence)
or isinstance(domain[0], np.ndarray):
48 if len(val) == len(domain):
49 return all((v >= d[0]
and v <= d[1]
for v, d
in zip(val, domain)))
51 raise ValueError(f
"if ``val`` is a Sequence, ``domain`` must have the same length ({len(domain)}) as ``val`` ({len(val)}).")
53 return all((v >= domain[0]
and v <= domain[1]
for v
in val))
55 if isinstance(domain[0], Sequence)
or isinstance(domain[0], np.ndarray):
56 raise ValueError(f
"if ``val`` is not a Sequence, ``domain`` must be a 2-tuple of numbers.")
58 return val >= domain[0]
and val <= domain[1]
67def tuplify(item: Union[Any, Sequence[Any]]) -> Tuple[Any, ...]:
68 """Convert a sequence to a tuple, or wrap a single value in a one-item tuple."""
69 if isinstance(item, Sequence):
75def argsort(a, **kwargs):
76 """Return indexes ordered by the values they address."""
77 return sorted(range(len(a)), key=a.__getitem__, **kwargs)
80def flatten_seq_of_seq(seq: Sequence[Sequence[Any]]) -> Sequence[Any]:
81 """Materialise elements from nested sequences in encounter order."""
82 seq_as_lists = [list(s)
for s
in seq]
83 flat_list = [i
for sublist
in seq_as_lists
for i
in sublist]
86def generator_flattened_seq_of_seq(seq: Sequence[Sequence[Any]]) -> Generator[Any,
None,
None]:
87 """Yield nested elements in encounter order without an intermediate list."""
92def catch(func, handle=lambda e: None, *args, **kwargs):
93 """Safeguard function evaluation against exceptions. Useful when calling function inside a list-comprehension."""
95 return func(*args, **kwargs)
96 except Exception
as e:
100def insert_dict(d, key, val, idx=0, in_place: bool =
True):
101 """Insert a new key at an index in mapping order, with an option to update the supplied mapping."""
102 if not 0 <= idx <= len(d):
103 raise IndexError(
"The insertion index is outside the mapping.")
105 d2 = copy.deepcopy(d)
112 for i, k
in enumerate(list(d2.keys())):
122def _dummyJit(*args, **kwargs):
124 Dummy version of jit decorator, does nothing
126 if len(args) == 1
and callable(args[0]):
134 from numba
import jit