bs-python-utils 1.1.1__py3-none-any.whl → 1.1.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bs_python_utils/__init__.py +2 -1
- bs_python_utils/bs_derivs.py +1 -0
- bs_python_utils/core/Timer.py +135 -40
- bs_python_utils/numerical/bs_derivs.py +49 -0
- {bs_python_utils-1.1.1.dist-info → bs_python_utils-1.1.3.dist-info}/METADATA +5 -1
- {bs_python_utils-1.1.1.dist-info → bs_python_utils-1.1.3.dist-info}/RECORD +9 -7
- {bs_python_utils-1.1.1.dist-info → bs_python_utils-1.1.3.dist-info}/WHEEL +0 -0
- {bs_python_utils-1.1.1.dist-info → bs_python_utils-1.1.3.dist-info}/licenses/LICENSE +0 -0
- {bs_python_utils-1.1.1.dist-info → bs_python_utils-1.1.3.dist-info}/top_level.txt +0 -0
bs_python_utils/__init__.py
CHANGED
|
@@ -6,7 +6,8 @@ programming.
|
|
|
6
6
|
* `bs_logging` has customized logging
|
|
7
7
|
* `bs_mathstr` has Unicode for math strings
|
|
8
8
|
* `bs_mem` reports memory usage
|
|
9
|
-
* `Timer` has a `Timer`
|
|
9
|
+
* `Timer` has a `Timer` context manager to time code execution.
|
|
10
|
+
* `bs_derivs` has Richardson derivatives
|
|
10
11
|
* `bsnputils` has Numpy functions
|
|
11
12
|
* `bssputils` has Scipy functions
|
|
12
13
|
* `sklearn_utils` has Sklearn functions
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from bs_python_utils.numerical.bs_derivs import * # noqa: F401, F403
|
bs_python_utils/core/Timer.py
CHANGED
|
@@ -6,13 +6,30 @@ Utilities to time code:
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
import time
|
|
9
|
+
from collections.abc import Callable, Iterable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
9
11
|
from functools import wraps
|
|
10
|
-
from typing import Any,
|
|
12
|
+
from typing import Any, ClassVar, Self
|
|
11
13
|
|
|
12
14
|
|
|
13
15
|
def timeit(func: Callable) -> Callable:
|
|
14
|
-
"""
|
|
15
|
-
|
|
16
|
+
"""Decorator to measure and print execution time of a function.
|
|
17
|
+
|
|
18
|
+
Wraps a function to measure its execution time using perf_counter()
|
|
19
|
+
for high precision, and prints the elapsed time to stdout.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
func: The function to be timed.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
A wrapped function that prints the execution time when called.
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
>>> @timeit
|
|
29
|
+
... def slow_function():
|
|
30
|
+
... time.sleep(0.1) # doctest: +SKIP
|
|
31
|
+
>>> slow_function() # doctest: +SKIP
|
|
32
|
+
slow_function executed in 0.100 seconds
|
|
16
33
|
"""
|
|
17
34
|
|
|
18
35
|
@wraps(func)
|
|
@@ -26,56 +43,134 @@ def timeit(func: Callable) -> Callable:
|
|
|
26
43
|
return wrapper
|
|
27
44
|
|
|
28
45
|
|
|
46
|
+
class TimerError(Exception):
|
|
47
|
+
"""A custom exception used to report errors in use of Timer class"""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
29
51
|
class Timer:
|
|
52
|
+
"""A flexible timer class for measuring execution time.
|
|
53
|
+
|
|
54
|
+
This class can be used in three ways:
|
|
55
|
+
|
|
56
|
+
1. **As a context manager**: automatically starts and stops timing
|
|
57
|
+
2. **With manual calls**: call start() and stop() explicitly
|
|
58
|
+
3. **As a named timer**: accumulate timing across multiple calls using the `name` attribute
|
|
59
|
+
|
|
60
|
+
Attributes:
|
|
61
|
+
name: Optional name for the timer. If provided, cumulative elapsed time is stored
|
|
62
|
+
in the class-level `timers` dict. Use None for one-off timings.
|
|
63
|
+
text: Format string for displaying elapsed time. Defaults to "Elapsed time: {:0.4f} seconds".
|
|
64
|
+
The string is formatted with a single float representing elapsed seconds.
|
|
65
|
+
logger: Callable to handle output. Defaults to print(). Set to None to suppress output.
|
|
66
|
+
timers: Class-level dictionary storing cumulative times for all named timers.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
TimerError: If stop() is called without start(), or start() is called on a running timer.
|
|
70
|
+
|
|
71
|
+
Example:
|
|
72
|
+
>>> # As a context manager (recommended for simple use cases)
|
|
73
|
+
>>> with Timer():
|
|
74
|
+
... time.sleep(0.1) # doctest: +SKIP
|
|
75
|
+
Elapsed time: 0.1000 seconds
|
|
76
|
+
|
|
77
|
+
>>> # With a custom message
|
|
78
|
+
>>> with Timer(text="My code took {:0.2f}s"):
|
|
79
|
+
... time.sleep(0.05) # doctest: +SKIP
|
|
80
|
+
My code took 0.05s
|
|
81
|
+
|
|
82
|
+
>>> # Suppress output
|
|
83
|
+
>>> with Timer(logger=None):
|
|
84
|
+
... time.sleep(0.1) # doctest: +SKIP
|
|
85
|
+
|
|
86
|
+
>>> # Suppress output and capture elapsed time
|
|
87
|
+
>>> with Timer(logger=None) as t:
|
|
88
|
+
... time.sleep(0.1) # doctest: +SKIP
|
|
89
|
+
>>> elapsed = t.stop()
|
|
90
|
+
|
|
91
|
+
>>> # Manual start/stop
|
|
92
|
+
>>> timer = Timer()
|
|
93
|
+
>>> timer.start() # doctest: +SKIP
|
|
94
|
+
>>> time.sleep(0.1) # doctest: +SKIP
|
|
95
|
+
>>> elapsed = timer.stop() # doctest: +SKIP
|
|
96
|
+
Elapsed time: 0.1000 seconds
|
|
97
|
+
|
|
98
|
+
>>> # Named timer for cumulative timing
|
|
99
|
+
>>> Timer(name="db_queries").start() # doctest: +SKIP
|
|
100
|
+
>>> time.sleep(0.05) # doctest: +SKIP
|
|
101
|
+
>>> Timer(name="db_queries").stop() # doctest: +SKIP
|
|
102
|
+
Elapsed time: 0.0500 seconds
|
|
103
|
+
>>> Timer.timers # doctest: +SKIP
|
|
104
|
+
{'db_queries': 0.05}
|
|
30
105
|
"""
|
|
31
|
-
A timer that can be started, stopped, and reset as needed by the user.
|
|
32
|
-
It keeps track of the total elapsed time in the `elapsed` attribute::
|
|
33
106
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
107
|
+
timers: ClassVar = {}
|
|
108
|
+
name: Any = None
|
|
109
|
+
text: Any = "Elapsed time: {:0.4f} seconds"
|
|
110
|
+
logger: Any = print
|
|
111
|
+
_start_time: Any = field(default=None, init=False, repr=False)
|
|
38
112
|
|
|
39
|
-
|
|
113
|
+
def __post_init__(self):
|
|
114
|
+
"""Initialize the timer and register it if named.
|
|
40
115
|
|
|
41
|
-
|
|
116
|
+
For named timers, creates an entry in the class-level `timers` dict
|
|
117
|
+
to accumulate elapsed time across multiple start/stop cycles.
|
|
118
|
+
"""
|
|
119
|
+
if self.name is not None:
|
|
120
|
+
self.timers.setdefault(self.name, 0)
|
|
42
121
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
>>> t.start()
|
|
46
|
-
>>> t.stop()
|
|
47
|
-
>>> t.start() # will add to the same counter
|
|
48
|
-
>>> t.stop()
|
|
49
|
-
>>> print(f"{t.elapsed} seconds total")
|
|
50
|
-
"""
|
|
122
|
+
def start(self):
|
|
123
|
+
"""Start the timer.
|
|
51
124
|
|
|
52
|
-
|
|
53
|
-
self.elapsed = 0.0
|
|
54
|
-
self._func = func
|
|
55
|
-
self._start = None
|
|
125
|
+
Records the current time using perf_counter() for high precision.
|
|
56
126
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
self.
|
|
127
|
+
Raises:
|
|
128
|
+
TimerError: If the timer is already running.
|
|
129
|
+
"""
|
|
130
|
+
if self._start_time is not None:
|
|
131
|
+
raise TimerError("Timer is running. Use .stop() to stop it")
|
|
61
132
|
|
|
62
|
-
|
|
63
|
-
if self._start is None:
|
|
64
|
-
raise RuntimeError("Not started")
|
|
65
|
-
end = self._func()
|
|
66
|
-
self.elapsed += end - self._start
|
|
67
|
-
self._start = None
|
|
133
|
+
self._start_time = time.perf_counter()
|
|
68
134
|
|
|
69
|
-
def
|
|
70
|
-
|
|
135
|
+
def stop(self) -> float:
|
|
136
|
+
"""Stop the timer and report elapsed time.
|
|
71
137
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
return self._start is not None
|
|
138
|
+
Calculates elapsed time since start() was called, sends output to the logger
|
|
139
|
+
if configured, and accumulates the time if this is a named timer.
|
|
75
140
|
|
|
76
|
-
|
|
141
|
+
Returns:
|
|
142
|
+
Elapsed time in seconds as a float.
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
TimerError: If the timer is not running.
|
|
146
|
+
"""
|
|
147
|
+
if self._start_time is None:
|
|
148
|
+
raise TimerError("Timer is not running. Use .start() to start it")
|
|
149
|
+
|
|
150
|
+
# Calculate elapsed time
|
|
151
|
+
elapsed_time: float = time.perf_counter() - self._start_time
|
|
152
|
+
self._start_time = None
|
|
153
|
+
|
|
154
|
+
# Report elapsed time
|
|
155
|
+
if self.logger:
|
|
156
|
+
self.logger(self.text.format(elapsed_time))
|
|
157
|
+
if self.name:
|
|
158
|
+
self.timers[self.name] += elapsed_time
|
|
159
|
+
|
|
160
|
+
return elapsed_time
|
|
161
|
+
|
|
162
|
+
def __enter__(self) -> Self:
|
|
163
|
+
"""Enter context manager: start the timer.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
self: The Timer instance.
|
|
167
|
+
"""
|
|
77
168
|
self.start()
|
|
78
169
|
return self
|
|
79
170
|
|
|
80
|
-
def __exit__(self, *
|
|
171
|
+
def __exit__(self, *exc_info):
|
|
172
|
+
"""Exit context manager: stop the timer.
|
|
173
|
+
|
|
174
|
+
Stops the timer regardless of whether an exception occurred in the with block.
|
|
175
|
+
"""
|
|
81
176
|
self.stop()
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def richardson_derivative(
|
|
5
|
+
f: Callable[[float, list], float], x: float, args: list, h: float
|
|
6
|
+
) -> float:
|
|
7
|
+
"""Compute the first derivative of $f(x, args)$ at $x$ via Richardson extrapolation.
|
|
8
|
+
|
|
9
|
+
Uses a 5-point central-difference stencil (step `h` and `2h`) that is
|
|
10
|
+
fourth-order accurate.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
f: The function to differentiate, called as `f(x, args)`.
|
|
14
|
+
x: The point at which to differentiate.
|
|
15
|
+
args: Other arguments passed through to `f`.
|
|
16
|
+
h: The step size.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
An approximation of the first derivative of `f` at `x`.
|
|
20
|
+
"""
|
|
21
|
+
f1 = f(x + h, args)
|
|
22
|
+
f2 = f(x - h, args)
|
|
23
|
+
f3 = f(x + 2.0 * h, args)
|
|
24
|
+
f4 = f(x - 2.0 * h, args)
|
|
25
|
+
return (8.0 * (f1 - f2) - (f3 - f4)) / (12.0 * h)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def richardson_second_derivative(
|
|
29
|
+
f: Callable[[float, list], float], x: float, args: list, h: float
|
|
30
|
+
) -> float:
|
|
31
|
+
"""Compute the second derivative of $f(x, args)$ at $x$ via Richardson extrapolation.
|
|
32
|
+
|
|
33
|
+
Applies `richardson_derivative` to the (Richardson-extrapolated) first
|
|
34
|
+
derivative of `f`.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
f: The function to differentiate, called as `f(x, args)`.
|
|
38
|
+
x: The point at which to differentiate.
|
|
39
|
+
args: Other arguments passed through to `f`.
|
|
40
|
+
h: The step size.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
An approximation of the second derivative of `f` at `x`.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def fprime(y, a):
|
|
47
|
+
return richardson_derivative(f, y, a, h)
|
|
48
|
+
|
|
49
|
+
return richardson_derivative(fprime, x, args, h)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bs-python-utils
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.3
|
|
4
4
|
Summary: Utilities programs for my Python code
|
|
5
5
|
Requires-Python: >=3.13
|
|
6
6
|
Description-Content-Type: text/markdown
|
|
@@ -50,6 +50,10 @@ Dynamic: license-file
|
|
|
50
50
|
|
|
51
51
|
### Release notes
|
|
52
52
|
|
|
53
|
+
#### 1.1.2 and 1.1.3(September 11, 2026)
|
|
54
|
+
- Improved the `Timer` class.
|
|
55
|
+
- added `bs_derivs` with Richardson derivatives.
|
|
56
|
+
|
|
53
57
|
#### 1.1.1 (September 04, 2026)
|
|
54
58
|
Added simulation-based bivariate ranks.
|
|
55
59
|
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
bs_python_utils/Timer.py,sha256=ozGneYNy-P9hKG71Q_Uu0aZfbGSilpUNVXIPglCNqhw,61
|
|
2
|
-
bs_python_utils/__init__.py,sha256=
|
|
2
|
+
bs_python_utils/__init__.py,sha256=1ozvLCSGvCGRIEgqdBD6ejQdk_JPs_ainW3k_mssVE0,1404
|
|
3
3
|
bs_python_utils/bivariate_quantiles.py,sha256=juI48flnsTs8TJYLRi5DwGIfQv-q5ZxN3TXyvtUeDRI,76
|
|
4
4
|
bs_python_utils/bs_altair.py,sha256=jt5z4QDYVzg4lt5QlX8CZDbpOJrn4YDFpQavZNrKXC8,64
|
|
5
|
+
bs_python_utils/bs_derivs.py,sha256=q3sZpeiCJMZ0jPZrpnk2pfOKGJ799hCpnw3mUSdgo7o,70
|
|
5
6
|
bs_python_utils/bs_logging.py,sha256=RrC9LLK6ih0P043SxgltxLvRFDKcNMD-UBKHPCK9pMk,66
|
|
6
7
|
bs_python_utils/bs_mathstr.py,sha256=WoqjCDYQw0ifVLR3BfxrnN0UMMyConADeVeMAtUHNkI,66
|
|
7
8
|
bs_python_utils/bs_mem.py,sha256=iZAFquRisPQoSt0UsIQsECrDuL2TIYpOk6Fsn45jk2Y,62
|
|
@@ -34,7 +35,7 @@ bs_python_utils/GaussHermiteSparseGrids/GHsparseGrid4prec9.txt,sha256=pK_J0YgoWC
|
|
|
34
35
|
bs_python_utils/GaussHermiteSparseGrids/GHsparseGrid5prec13.txt,sha256=M-Zq5ZMvjIRYPbbepZ-aDgcoiZeLjtSLuhBDjrRBod4,849182
|
|
35
36
|
bs_python_utils/GaussHermiteSparseGrids/GHsparseGrid5prec17.txt,sha256=7cRuNAccbj66EJgLUyJ63CnBcVbIuNaL5HStdu05o4w,4341422
|
|
36
37
|
bs_python_utils/GaussHermiteSparseGrids/GHsparseGrid5prec9.txt,sha256=GmfUSKpvepIuy66zHgz-cB0Et-2DRR1f195zkg6a-HA,118330
|
|
37
|
-
bs_python_utils/core/Timer.py,sha256=
|
|
38
|
+
bs_python_utils/core/Timer.py,sha256=rTJ9R-0sgnc2IkPwBItyTxFTjc0AXAJiYneGUaduPvg,5708
|
|
38
39
|
bs_python_utils/core/__init__.py,sha256=4NJk4JmeQXwVre55ttL0Zo3x3qCkPYaUESiR8n4_ZEA,77
|
|
39
40
|
bs_python_utils/core/bs_logging.py,sha256=CGi_pLeBSVd7FXsoafCI9xDu9eXLMnJebgY8Ku3-qP8,5050
|
|
40
41
|
bs_python_utils/core/bs_mathstr.py,sha256=zW2ECxDD-29H81s_PNE1UKbIXJZtuhReJwcYim_4YTg,3595
|
|
@@ -52,6 +53,7 @@ bs_python_utils/examples/examples_seaborn.py,sha256=HsFWYhXVZAkqCabTGihpUEi95QjE
|
|
|
52
53
|
bs_python_utils/examples/examples_sklearn.py,sha256=nzvMREqNFf2oq32aEQLm1Bz8DbdcTvHfhJNKy2NlI38,802
|
|
53
54
|
bs_python_utils/examples/examples_sparse_gaussian.py,sha256=hVnN_p7Dfj3CQWp51bZlwQeqvhJ6VaFMyFeQ48j-pqo,922
|
|
54
55
|
bs_python_utils/numerical/__init__.py,sha256=T1I8g5rx19p8zLxo3_jr7fHf3LqTxPVwFMRF2HUR808,75
|
|
56
|
+
bs_python_utils/numerical/bs_derivs.py,sha256=m-LQJxzlWOaBpXhAu3rUGKGdQY3yizXKeKBkZGwwjiE,1515
|
|
55
57
|
bs_python_utils/numerical/bs_sparse_gaussian.py,sha256=DzfBEQmaTY2XjxqMx3suzQ4FalD-OhoyQhZ2g2t3ztg,2241
|
|
56
58
|
bs_python_utils/numerical/bsnputils.py,sha256=px5EL0M5YAY6oexzZpaJq9uH085ADRwa178E8zVReEA,38581
|
|
57
59
|
bs_python_utils/numerical/bssputils.py,sha256=JnmN-9ZMRQDNc0W_XIC-on4lKnzDhkp2YAOZNMcH404,2475
|
|
@@ -68,8 +70,8 @@ bs_python_utils/viz/bs_plots.py,sha256=-yBJ-8y4Ni8LqqQi5ceMjqOcpvLWYngkY1_FKqWTM
|
|
|
68
70
|
bs_python_utils/viz/bs_seaborn.py,sha256=wzlsByJivHLBOi_p9RLLRaXD6WhJbAfmuQPKQDheMss,5684
|
|
69
71
|
bs_python_utils/viz/bsmplutils.py,sha256=g61VrRlHW4jDSvvyfTZF_XYtrGTIV3F4FP9umIc6oOI,2900
|
|
70
72
|
bs_python_utils/viz/streamlit_utils.py,sha256=eoelTwicHPcWxC6KbGFBnofwEomGjxIcMnnp3rSsqYU,2703
|
|
71
|
-
bs_python_utils-1.1.
|
|
72
|
-
bs_python_utils-1.1.
|
|
73
|
-
bs_python_utils-1.1.
|
|
74
|
-
bs_python_utils-1.1.
|
|
75
|
-
bs_python_utils-1.1.
|
|
73
|
+
bs_python_utils-1.1.3.dist-info/licenses/LICENSE,sha256=J03S1L_wQN4qquuluScbRUE09on78nCnNRpaUpOvHcw,1073
|
|
74
|
+
bs_python_utils-1.1.3.dist-info/METADATA,sha256=mf9EQxTeoHDLiclWTCxU6fhVKnImO0tN34w9LOygmC4,4567
|
|
75
|
+
bs_python_utils-1.1.3.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
76
|
+
bs_python_utils-1.1.3.dist-info/top_level.txt,sha256=4sbCpeuqAsdWmoAmZju1vf1ZFMJrSx310eS5SCyrAeQ,16
|
|
77
|
+
bs_python_utils-1.1.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|