BenchMatcha 0.0.1__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.
- BenchMatcha/__init__.py +32 -0
- BenchMatcha/complexity.py +208 -0
- BenchMatcha/config.py +108 -0
- BenchMatcha/errors.py +89 -0
- BenchMatcha/handlers.py +154 -0
- BenchMatcha/plotting.py +247 -0
- BenchMatcha/py.typed +0 -0
- BenchMatcha/runner.py +339 -0
- BenchMatcha/sifter.py +89 -0
- BenchMatcha/structure.py +362 -0
- BenchMatcha/utils.py +83 -0
- benchmatcha-0.0.1.dist-info/METADATA +147 -0
- benchmatcha-0.0.1.dist-info/RECORD +17 -0
- benchmatcha-0.0.1.dist-info/WHEEL +5 -0
- benchmatcha-0.0.1.dist-info/entry_points.txt +2 -0
- benchmatcha-0.0.1.dist-info/licenses/LICENSE +28 -0
- benchmatcha-0.0.1.dist-info/top_level.txt +1 -0
BenchMatcha/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# BSD 3-Clause License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2025, Spill-Tea
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
# list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
# contributors may be used to endorse or promote products derived from
|
|
17
|
+
# this software without specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
29
|
+
|
|
30
|
+
"""BenchMatcha Project."""
|
|
31
|
+
|
|
32
|
+
__version__: str = "v0.0.1"
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# BSD 3-Clause License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2025, Spill-Tea
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
# list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
# contributors may be used to endorse or promote products derived from
|
|
17
|
+
# this software without specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
29
|
+
|
|
30
|
+
"""Complexity calculations."""
|
|
31
|
+
|
|
32
|
+
from collections.abc import Callable
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
|
|
35
|
+
import google_benchmark as gbench
|
|
36
|
+
import numpy as np
|
|
37
|
+
from scipy.optimize import curve_fit # type: ignore[import-untyped]
|
|
38
|
+
|
|
39
|
+
from .utils import _simple_stats
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class FitResult:
|
|
44
|
+
"""Curve fit result.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
bigo (str): Big O notation string identifier.
|
|
48
|
+
params (np.ndarray): coefficient value(s).
|
|
49
|
+
cov (np.ndarray): covariance std of coefficients
|
|
50
|
+
rms (float): root mean square error of fit.
|
|
51
|
+
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
bigo: str
|
|
55
|
+
params: np.ndarray
|
|
56
|
+
cov: np.ndarray
|
|
57
|
+
rms: float
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def _handle(x: np.ndarray) -> str:
|
|
61
|
+
a = " ".join([f"{j:.3E}" for j in x.tolist()])
|
|
62
|
+
|
|
63
|
+
return f"[{a}]"
|
|
64
|
+
|
|
65
|
+
def __repr__(self) -> str:
|
|
66
|
+
return (
|
|
67
|
+
f"FitResult(bigo={self.bigo},params={self._handle(self.params)}"
|
|
68
|
+
f",cov={self._handle(self.cov)},rms={self.rms:.3f})"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# Define common complexity functions with all coefficients and intercept
|
|
73
|
+
Equation = (
|
|
74
|
+
Callable[[np.ndarray, float, float], np.ndarray]
|
|
75
|
+
| Callable[[np.ndarray, float, float, float], np.ndarray]
|
|
76
|
+
| Callable[[np.ndarray, float, float, float, float], np.ndarray]
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def constant(n: np.ndarray, a: float, b: float) -> np.ndarray:
|
|
81
|
+
"""Constant O(1) equation."""
|
|
82
|
+
return a * np.ones_like(n) + b
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def logn(n: np.ndarray, a: float, b: float) -> np.ndarray:
|
|
86
|
+
"""Log O(logN) equation."""
|
|
87
|
+
return a * np.log2(n) + b
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def linear(n: np.ndarray, a: float, b: float) -> np.ndarray:
|
|
91
|
+
"""Linear O(N) equation."""
|
|
92
|
+
return a * n + b
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def nlogn(n: np.ndarray, a: float, b: float) -> np.ndarray:
|
|
96
|
+
"""Log linear O(NlogN) equation."""
|
|
97
|
+
return a * n * np.log2(n) + b
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def quadratic(n: np.ndarray, a: float, b: float, c: float) -> np.ndarray:
|
|
101
|
+
"""Quadratic O(N^2) equation."""
|
|
102
|
+
return a * np.power(n, 2) + linear(n, b, c)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def cubic(n: np.ndarray, a: float, b: float, c: float, d: float) -> np.ndarray:
|
|
106
|
+
"""Cubic O(N^3) equation."""
|
|
107
|
+
return a * np.power(n, 3) + quadratic(n, b, c, d)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
complexity_functions: dict[str, Equation] = {
|
|
111
|
+
# gbench.oNone.name: "",
|
|
112
|
+
gbench.o1.name: constant,
|
|
113
|
+
gbench.oLogN.name: logn,
|
|
114
|
+
gbench.oN.name: linear,
|
|
115
|
+
gbench.oNLogN.name: nlogn,
|
|
116
|
+
gbench.oNSquared.name: quadratic,
|
|
117
|
+
gbench.oNCubed.name: cubic,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def compute_rmsd(y_true: np.ndarray, y_pred: np.ndarray, k: int) -> float:
|
|
122
|
+
r"""Mean normalized root mean square deviation (RMSD).
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
y_true (np.ndarray): observed y values.
|
|
126
|
+
y_pred (np.ndarray): predicted y values.
|
|
127
|
+
k (int): number of parameters used to estimate predicted values.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
(float): normalized RMSD
|
|
131
|
+
|
|
132
|
+
Equations:
|
|
133
|
+
$\frac{1}{\bar{y}} \sqrt{\frac{\sum_{i=0}^{N} (y_i - \hat{y}_i)^2}{N - k}}$
|
|
134
|
+
|
|
135
|
+
"""
|
|
136
|
+
residuals: np.ndarray = y_true - y_pred
|
|
137
|
+
sum_square_error: np.float64 = (residuals * residuals).sum()
|
|
138
|
+
dof: np.int64 = np.prod(y_pred.size) - k
|
|
139
|
+
|
|
140
|
+
return float(np.sqrt(sum_square_error / dof) / y_true.mean())
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def fit(
|
|
144
|
+
func: Callable,
|
|
145
|
+
label: str,
|
|
146
|
+
x: np.ndarray,
|
|
147
|
+
y: np.ndarray,
|
|
148
|
+
sigma: np.ndarray,
|
|
149
|
+
) -> FitResult | None:
|
|
150
|
+
"""Fit observed data to an equation.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
func (Callable): equation to fit.
|
|
154
|
+
label (str): complexity label
|
|
155
|
+
x (np.ndarray): x input values
|
|
156
|
+
y (np.ndarray): observed y values
|
|
157
|
+
sigma (np.ndarray): observed error in y values
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
(FitResult | None) returns fit result if converged.
|
|
161
|
+
|
|
162
|
+
"""
|
|
163
|
+
popt: np.ndarray
|
|
164
|
+
pcov: np.ndarray
|
|
165
|
+
try:
|
|
166
|
+
popt, pcov, *_ = curve_fit(
|
|
167
|
+
func,
|
|
168
|
+
x,
|
|
169
|
+
y,
|
|
170
|
+
sigma=sigma,
|
|
171
|
+
absolute_sigma=True,
|
|
172
|
+
)
|
|
173
|
+
pred = func(x, *popt)
|
|
174
|
+
cov = np.sqrt(pcov.diagonal())
|
|
175
|
+
rms = compute_rmsd(y, pred, len(popt))
|
|
176
|
+
|
|
177
|
+
return FitResult(
|
|
178
|
+
bigo=label,
|
|
179
|
+
params=popt,
|
|
180
|
+
cov=cov,
|
|
181
|
+
rms=rms,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
except RuntimeError:
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def fit_complexity(x: np.ndarray, y: np.ndarray, sigma: np.ndarray) -> list[FitResult]:
|
|
189
|
+
"""Perform curve fitting to available complexity algorithms."""
|
|
190
|
+
results: list[FitResult] = []
|
|
191
|
+
|
|
192
|
+
for label, func in complexity_functions.items():
|
|
193
|
+
if (res := fit(func, label, x, y, sigma)) is not None:
|
|
194
|
+
results.append(res)
|
|
195
|
+
|
|
196
|
+
return results
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def analyze_complexity(x: np.ndarray, y: np.ndarray) -> list[FitResult]:
|
|
200
|
+
"""Analyze algorithmic complexity."""
|
|
201
|
+
mean, std = _simple_stats(y)
|
|
202
|
+
|
|
203
|
+
return sorted(fit_complexity(x, mean, std), key=lambda x: x.rms)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def get_best_fit(fits: list[FitResult]) -> FitResult:
|
|
207
|
+
"""Return best fit by minimizing RMSD."""
|
|
208
|
+
return min(fits, key=lambda x: x.rms)
|
BenchMatcha/config.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# BSD 3-Clause License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2025, Spill-Tea
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
# list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
# contributors may be used to endorse or promote products derived from
|
|
17
|
+
# this software without specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
29
|
+
|
|
30
|
+
"""Default runner configuration."""
|
|
31
|
+
|
|
32
|
+
import logging
|
|
33
|
+
|
|
34
|
+
import toml # type: ignore[import-untyped]
|
|
35
|
+
|
|
36
|
+
from . import plotting
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Config:
|
|
43
|
+
"""default configuration.
|
|
44
|
+
|
|
45
|
+
Attributes:
|
|
46
|
+
color (str): plot marker color.
|
|
47
|
+
line_color (str): plot line color.
|
|
48
|
+
font (str): plot font family style.
|
|
49
|
+
x_axis (int): Maximum number of line ticks on x-axis.
|
|
50
|
+
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
color: str = plotting.Prism[3]
|
|
54
|
+
line_color: str = plotting.Prism[4]
|
|
55
|
+
font: str = "Space Grotesk Light, Courier New, monospace"
|
|
56
|
+
x_axis: int = 13
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ConfigUpdater:
|
|
60
|
+
"""Configuration updater through pyproject config file.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
path (str): path to valid configuration file.
|
|
64
|
+
config (Config): configuration class to update.
|
|
65
|
+
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
path: str
|
|
69
|
+
config: type[Config]
|
|
70
|
+
|
|
71
|
+
def __init__(self, path: str, config: type[Config] = Config) -> None:
|
|
72
|
+
self.path = path
|
|
73
|
+
self.config = config
|
|
74
|
+
|
|
75
|
+
def load(self) -> dict:
|
|
76
|
+
"""Load toml data from path."""
|
|
77
|
+
return toml.load(self.path)
|
|
78
|
+
|
|
79
|
+
def _update(self, data: dict) -> None:
|
|
80
|
+
for key, value in data.get("tool", {}).get("BenchMatcha", {}).items():
|
|
81
|
+
if not hasattr(self.config, key):
|
|
82
|
+
log.info("Unsupported tool key: %s", key)
|
|
83
|
+
continue
|
|
84
|
+
|
|
85
|
+
setattr(self.config, key, value)
|
|
86
|
+
|
|
87
|
+
def update(self) -> None:
|
|
88
|
+
"""Parse toml path and update default configuration."""
|
|
89
|
+
data: dict = self.load()
|
|
90
|
+
self._update(data)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def update_config_from_pyproject(path: str) -> None:
|
|
94
|
+
"""Update default config from pyproject toml file.
|
|
95
|
+
|
|
96
|
+
Example:
|
|
97
|
+
|
|
98
|
+
.. code-block: toml
|
|
99
|
+
|
|
100
|
+
[tool.BenchMatcha]
|
|
101
|
+
color="#FFF"
|
|
102
|
+
line_color="#333"
|
|
103
|
+
font="Courier"
|
|
104
|
+
x_axis=5
|
|
105
|
+
|
|
106
|
+
"""
|
|
107
|
+
cu = ConfigUpdater(path)
|
|
108
|
+
cu.update()
|
BenchMatcha/errors.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# BSD 3-Clause License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2025, Spill-Tea
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
# list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
# contributors may be used to endorse or promote products derived from
|
|
17
|
+
# this software without specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
29
|
+
|
|
30
|
+
"""Custom BenchMatcha exception definitions.
|
|
31
|
+
|
|
32
|
+
Considerations:
|
|
33
|
+
* All custom exceptions should be defined within this module for better project
|
|
34
|
+
organization. This also prevents proliferation of custom errors as project scales.
|
|
35
|
+
* Custom exceptions should define a class method named `response` to construct and
|
|
36
|
+
standardize verbiage of output message. It has the nice side effect of providing
|
|
37
|
+
example context for usage.
|
|
38
|
+
* Before creating a custom error, determine if available exceptions can be used
|
|
39
|
+
instead.
|
|
40
|
+
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
from json import JSONDecodeError
|
|
46
|
+
from typing import Self, TypeVar
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
E = TypeVar("E", bound=Exception)
|
|
50
|
+
|
|
51
|
+
_exception_register: set[type[Exception]] = {
|
|
52
|
+
TypeError,
|
|
53
|
+
ValueError,
|
|
54
|
+
RuntimeError,
|
|
55
|
+
JSONDecodeError,
|
|
56
|
+
FileNotFoundError,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def register_custom_exception(cls: type[E]) -> type[E]:
|
|
61
|
+
"""Register custom exceptions."""
|
|
62
|
+
_exception_register.add(cls)
|
|
63
|
+
|
|
64
|
+
return cls
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@register_custom_exception
|
|
68
|
+
class SchemaError(Exception):
|
|
69
|
+
"""Unsupported json schema."""
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def response(cls, version: str) -> Self:
|
|
73
|
+
"""Define standard response message."""
|
|
74
|
+
msg: str = f"Unsupported json schema version: {version}"
|
|
75
|
+
|
|
76
|
+
return cls(msg)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@register_custom_exception
|
|
80
|
+
class ParsingError(Exception):
|
|
81
|
+
"""Failed to parse json output (from Google Benchmark)."""
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def response(cls) -> Self:
|
|
85
|
+
"""Define standard response message."""
|
|
86
|
+
return cls(
|
|
87
|
+
"Failed to parse json data. Please confirm benchmarks do not contain "
|
|
88
|
+
"print statements or write to stdout, which can interfere with output."
|
|
89
|
+
)
|
BenchMatcha/handlers.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# BSD 3-Clause License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2025, Spill-Tea
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
# list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
# contributors may be used to endorse or promote products derived from
|
|
17
|
+
# this software without specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
29
|
+
|
|
30
|
+
"""IO handlers to transform using json library."""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import json
|
|
35
|
+
import os
|
|
36
|
+
from abc import ABC, abstractmethod
|
|
37
|
+
from io import IOBase
|
|
38
|
+
from typing import IO, Any
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_readable_io_protocol(obj: object) -> bool:
|
|
42
|
+
"""Determine if object implements readable IO interface."""
|
|
43
|
+
methods: set[str] = {
|
|
44
|
+
"read",
|
|
45
|
+
"readable",
|
|
46
|
+
"write",
|
|
47
|
+
# "writeable", # temporary file handler does not have this method.
|
|
48
|
+
"seek",
|
|
49
|
+
"seekable",
|
|
50
|
+
"tell",
|
|
51
|
+
"close",
|
|
52
|
+
"closed", # property
|
|
53
|
+
"flush",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return (
|
|
57
|
+
isinstance(obj, IO | IOBase) or all(map(lambda x: hasattr(obj, x), methods))
|
|
58
|
+
) and obj.readable() # type: ignore[attr-defined]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Handler(ABC):
|
|
62
|
+
"""Abstract Handler protocol."""
|
|
63
|
+
|
|
64
|
+
@abstractmethod
|
|
65
|
+
def handle(self) -> dict[str, Any]:
|
|
66
|
+
"""Handle parsing of object."""
|
|
67
|
+
raise NotImplementedError("Must implement.")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class HandleText(Handler):
|
|
71
|
+
"""Handle loading text (string) to json object."""
|
|
72
|
+
|
|
73
|
+
text: str
|
|
74
|
+
|
|
75
|
+
def __init__(self, text: str):
|
|
76
|
+
self.text = text
|
|
77
|
+
|
|
78
|
+
def handle(self) -> dict[str, Any]:
|
|
79
|
+
return json.loads(self.text)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class HandleBytes(Handler):
|
|
83
|
+
"""Handle loading bytes to json object."""
|
|
84
|
+
|
|
85
|
+
text: bytes
|
|
86
|
+
encoding: str
|
|
87
|
+
|
|
88
|
+
def __init__(self, text: bytes, encoding: str = "utf8"):
|
|
89
|
+
self.text = text
|
|
90
|
+
self.encoding = encoding
|
|
91
|
+
|
|
92
|
+
def handle(self) -> dict[str, Any]:
|
|
93
|
+
return HandleText(self.text.decode(self.encoding)).handle()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class HandleIO(Handler):
|
|
97
|
+
"""Handle loading io data to json object."""
|
|
98
|
+
|
|
99
|
+
stream: IOBase
|
|
100
|
+
encoding: str
|
|
101
|
+
|
|
102
|
+
def __init__(self, stream: IOBase, encoding: str = "utf8"):
|
|
103
|
+
self.stream = stream
|
|
104
|
+
if not self.stream.readable():
|
|
105
|
+
raise TypeError("Unreadable stream.")
|
|
106
|
+
|
|
107
|
+
self.encoding = encoding
|
|
108
|
+
|
|
109
|
+
def handle(self) -> dict[str, Any]:
|
|
110
|
+
text = self.stream.read()
|
|
111
|
+
if isinstance(text, bytes):
|
|
112
|
+
handler: Handler = HandleBytes(text, self.encoding)
|
|
113
|
+
|
|
114
|
+
else:
|
|
115
|
+
handler = HandleText(text)
|
|
116
|
+
|
|
117
|
+
return handler.handle()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class HandlePath(Handler):
|
|
121
|
+
"""Handle loading data from file to json object."""
|
|
122
|
+
|
|
123
|
+
path: str
|
|
124
|
+
encoding: str
|
|
125
|
+
|
|
126
|
+
def __init__(self, path: str, encoding: str = "utf8"):
|
|
127
|
+
self.path = path
|
|
128
|
+
self.encoding = encoding
|
|
129
|
+
|
|
130
|
+
def handle(self) -> dict[str, Any]:
|
|
131
|
+
if not os.path.exists(self.path):
|
|
132
|
+
return HandleText(self.path).handle()
|
|
133
|
+
|
|
134
|
+
with open(self.path, "r", encoding=self.encoding) as f:
|
|
135
|
+
return HandleIO(f).handle()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def dispatch(obj: object, encoding: str = "utf8") -> Handler:
|
|
139
|
+
"""Dispatch appropriate handler in response to input object type."""
|
|
140
|
+
if isinstance(obj, str):
|
|
141
|
+
return HandlePath(obj)
|
|
142
|
+
|
|
143
|
+
elif isinstance(obj, bytes):
|
|
144
|
+
return HandleBytes(obj, encoding)
|
|
145
|
+
|
|
146
|
+
elif is_readable_io_protocol(obj):
|
|
147
|
+
return HandleIO(obj, encoding) # type: ignore[arg-type]
|
|
148
|
+
|
|
149
|
+
raise TypeError(f"Unsupported object type: {type(obj)}")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def load(obj: object, encoding: str = "utf8") -> dict[str, Any]:
|
|
153
|
+
"""Load json data."""
|
|
154
|
+
return dispatch(obj, encoding).handle()
|