QDpy
Loading...
Searching...
No Matches
utils.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""The :mod:`~qdpy.utils` module is a collection of small functions and classes handling common patterns."""
20
21#__all__ = ["jit"]
22
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
26import inspect
27import copy
28import numpy as np
29
30
31
32
33def is_iterable(obj: Any) -> bool:
34 """Return if ``obj`` is iterable or not."""
35 return isinstance(obj, Iterable)
36
37#def in_bounds(val: Union[float, Sequence[float]], domain: Union[DomainLike, Sequence[DomainLike]]) -> bool:
38def in_bounds(val: Any, domain: Any) -> bool:
39 """Check whether a scalar or vector falls inside inclusive bounds.
40
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.
44 """
45 #assert len(domain) >= 2, f"``domain`` must be a 2-tuple of numbers or a sequence of 2-tuples of numbers."
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)))
50 else:
51 raise ValueError(f"if ``val`` is a Sequence, ``domain`` must have the same length ({len(domain)}) as ``val`` ({len(val)}).")
52 else:
53 return all((v >= domain[0] and v <= domain[1] for v in val))
54 else:
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.")
57 else:
58 return val >= domain[0] and val <= domain[1]
59
60#def _hashify(item):
61# """Verify if *item* is hashable, if not, try and return it as a tuple."""
62# if isinstance(item, collections.abc.Hashable):
63# return item
64# else:
65# return tuple(item)
66
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):
70 return tuple(item)
71 else:
72 return (item,)
73
74
75def argsort(a, **kwargs):
76 """Return indexes ordered by the values they address."""
77 return sorted(range(len(a)), key=a.__getitem__, **kwargs)
78
79
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]
84 return flat_list
85
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."""
88 for s in seq:
89 for i in s:
90 yield i
91
92def catch(func, handle=lambda e: None, *args, **kwargs):
93 """Safeguard function evaluation against exceptions. Useful when calling function inside a list-comprehension."""
94 try:
95 return func(*args, **kwargs)
96 except Exception as e:
97 return handle(e)
98
99# Since Python 3.6+, dict are ordered (by order of insertion)
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.")
104 if in_place:
105 d2 = copy.deepcopy(d)
106 new_d = d
107 new_d.clear()
108 else:
109 d2 = d
110 new_d = {}
111
112 for i, k in enumerate(list(d2.keys())):
113 if i == idx:
114 new_d[key] = val
115 new_d[k] = d2[k]
116 if idx == len(d2):
117 new_d[key] = val
118 return new_d
119
120
121
122def _dummyJit(*args, **kwargs):
123 """
124 Dummy version of jit decorator, does nothing
125 """
126 if len(args) == 1 and callable(args[0]):
127 return args[0]
128 else:
129 def wrap(func):
130 return func
131 return wrap
132try:
133 import numba
134 from numba import jit
135except ImportError:
136 jit = _dummyJit
137
138
139
140# MODELINE "{{{1
141# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
142# vim:foldmethod=marker