Debian Codegraph @

src/pytest_regressions/ndarrays_regression.py

raw symbols SCIP
1 import os
2 import zipfile
3 from pathlib import Path
4 from typing import Any
5 from typing import Dict
6 from typing import Optional
7
8 import pytest
9
10 from .common import import_error_message
11 from .common import perform_regression_check
12
13
14 class NDArraysRegressionFixture:
15 """
16 NumPy NPZ regression fixture implementation used on ndarrays_regression fixture.
17 """
18
19 THRESHOLD = 100
20 ROWFORMAT = "{:>15s} {:>20s} {:>20s} {:>20s}\n"
21
22 def __init__(
23 self, datadir: Path, original_datadir: Path, request: pytest.FixtureRequest
24 ) -> None:
25 self._tolerances_dict: Dict[str, Dict[str, float]] = {}
26 self._default_tolerance: Dict[str, float] = {}
27
28 self.request = request
29 self.datadir = datadir
30 self.original_datadir = original_datadir
31 self._force_regen = False
32 self._with_test_class_names = False
33
34 def _check_data_types(
35 self, key: Any, obtained_array: Any, expected_array: Any
36 ) -> None:
37 """
38 Check if data type of obtained and expected arrays are the same. Fail if not.
39 Helper method used in _check_fn method.
40 """
41 try:
42 import numpy as np
43 except ModuleNotFoundError:
44 raise ModuleNotFoundError(import_error_message("NumPy"))
45
46 __tracebackhide__ = True
47
48 if obtained_array.dtype != expected_array.dtype:
49 # Check if both data types are comparable as numbers (float, int, short, bytes, etc...)
50 if np.issubdtype(obtained_array.dtype, np.number) and np.issubdtype(
51 expected_array.dtype, np.number
52 ):
53 return
54 # Check if both data types are comparable as strings
55 if np.issubdtype(obtained_array.dtype, str) and np.issubdtype(
56 expected_array.dtype, str
57 ):
58 return
59
60 # In case they are not, assume they are not comparable
61 error_msg = (
62 "Data types are not the same.\n"
63 f" key: {key}\n"
64 f" Obtained: {obtained_array.dtype}\n"
65 f" Expected: {expected_array.dtype}\n"
66 )
67 raise AssertionError(error_msg)
68
69 def _check_data_shapes(
70 self, key: Any, obtained_array: Any, expected_array: Any
71 ) -> None:
72 """
73 Check if obtained and expected arrays have the same size.
74 Helper method used in _check_fn method.
75 """
76 __tracebackhide__ = True
77
78 if obtained_array.shape != expected_array.shape:
79 error_msg = (
80 "Shapes are not the same.\n"
81 f" Key: {key}\n"
82 f" Obtained: {obtained_array.shape}\n"
83 f" Expected: {expected_array.shape}\n"
84 )
85 raise AssertionError(error_msg)
86
87 def _check_fn(self, obtained_filename: Path, expected_filename: Path) -> None:
88 """
89 Check if dict contents dumped to a file match the contents in expected file.
90 """
91 try:
92 import numpy as np
93 except ModuleNotFoundError:
94 raise ModuleNotFoundError(import_error_message("NumPy"))
95
96 __tracebackhide__ = True
97
98 # Turn result of np.load into a dictionary, such that the files are closed immediately.
99 expected_data = self._load_fn(expected_filename)
100 obtained_data = self._load_fn(obtained_filename)
101
102 # Check mismatches in the keys.
103 if set(obtained_data) != set(expected_data):
104 error_msg = (
105 "They keys in the obtained results differ from the expected results.\n"
106 )
107 error_msg += " Matching keys: "
108 error_msg += str(list(set(obtained_data) & set(expected_data)))
109 error_msg += "\n"
110 error_msg += " New in obtained: "
111 error_msg += str(list(set(obtained_data) - set(expected_data)))
112 error_msg += "\n"
113 error_msg += " Missing from obtained: "
114 error_msg += str(list(set(expected_data) - set(obtained_data)))
115 error_msg += "\n"
116 error_msg += "To update values, use --force-regen option.\n\n"
117 raise AssertionError(error_msg)
118
119 # Compare the contents of the arrays.
120 comparison_tables_dict = {}
121 for k, obtained_array in obtained_data.items():
122 expected_array = expected_data[k]
123 tolerance_args = self._tolerances_dict.get(k, self._default_tolerance)
124
125 self._check_data_types(k, obtained_array, expected_array)
126 self._check_data_shapes(k, obtained_array, expected_array)
127
128 if np.issubdtype(obtained_array.dtype, np.inexact):
129 not_close_mask = ~np.isclose(
130 obtained_array,
131 expected_array,
132 equal_nan=True,
133 **tolerance_args,
134 )
135 else:
136 not_close_mask = obtained_array != expected_array
137
138 if np.any(not_close_mask):
139 diff_ids: Any
140 if not_close_mask.ndim == 0:
141 diff_ids = [()]
142 else:
143 diff_ids = np.array(
144 np.nonzero(not_close_mask)
145 ).T # type:ignore[unreachable]
146 comparison_tables_dict[k] = (
147 expected_array.size,
148 expected_array.shape,
149 diff_ids,
150 obtained_array[not_close_mask],
151 expected_array[not_close_mask],
152 )
153
154 if len(comparison_tables_dict) > 0:
155 error_msg = "Values are not sufficiently close.\n"
156 error_msg += "To update values, use --force-regen option.\n\n"
157 for k, (
158 size,
159 shape,
160 diff_ids,
161 obtained_array,
162 expected_array,
163 ) in comparison_tables_dict.items():
164 # Summary
165 error_msg += f"{k}:\n Shape: {shape}\n"
166 pct = 100 * len(diff_ids) / size
167 error_msg += (
168 f" Number of differences: {len(diff_ids)} / {size} ({pct:.1f}%)\n"
169 )
170 if np.issubdtype(obtained_array.dtype, np.number) and len(diff_ids) > 1:
171 error_msg += (
172 " Statistics are computed for differing elements only.\n"
173 )
174
175 abs_errors = abs(obtained_array - expected_array)
176 error_msg += " Stats for abs(obtained - expected):\n"
177 error_msg += f" Max: {abs_errors.max()}\n"
178 error_msg += f" Mean: {abs_errors.mean()}\n"
179 error_msg += f" Median: {np.median(abs_errors)}\n"
180
181 expected_nonzero = np.array(np.nonzero(expected_array)).T
182 rel_errors = abs(
183 (
184 obtained_array[expected_nonzero]
185 - expected_array[expected_nonzero]
186 )
187 / expected_array[expected_nonzero]
188 )
189 if len(rel_errors) == 0:
190 error_msg += " Relative errors are not reported because all expected values are zero.\n"
191 else:
192 error_msg += (
193 f" Stats for abs(obtained - expected) / abs(expected):\n"
194 )
195 if len(rel_errors) != len(abs_errors):
196 pct = 100 * len(rel_errors) / len(abs_errors)
197 error_msg += f" Number of (differing) non-zero expected results: {len(rel_errors)} / {len(abs_errors)} ({pct:.1f}%)\n"
198 error_msg += f" Relative errors are computed for the non-zero expected results.\n"
199 else:
200 rel_errors = abs(
201 (obtained_array - expected_array) / expected_array
202 )
203 error_msg += f" Max: {rel_errors.max()}\n"
204 error_msg += f" Mean: {rel_errors.mean()}\n"
205 error_msg += f" Median: {np.median(rel_errors)}\n"
206
207 # Details results
208 error_msg += " Individual errors:\n"
209 if len(diff_ids) > self.THRESHOLD:
210 error_msg += (
211 f" Only showing first {self.THRESHOLD} mismatches.\n"
212 )
213 diff_ids = diff_ids[: self.THRESHOLD]
214 obtained_array = obtained_array[: self.THRESHOLD]
215 expected_array = expected_array[: self.THRESHOLD]
216 error_msg += self.ROWFORMAT.format(
217 "Index",
218 "Obtained",
219 "Expected",
220 "Difference",
221 )
222 for diff_id, obtained, expected in zip(
223 diff_ids, obtained_array, expected_array
224 ):
225 diff_id_str = ", ".join(str(i) for i in diff_id)
226 if len(diff_id) != 1:
227 diff_id_str = f"({diff_id_str})"
228 error_msg += self.ROWFORMAT.format(
229 diff_id_str,
230 str(obtained),
231 str(expected),
232 str(obtained - expected)
233 if isinstance(obtained, np.number)
234 else "",
235 )
236 error_msg += "\n"
237
238 raise AssertionError(error_msg)
239
240 def _load_fn(self, filename: Path) -> Dict[str, Any]:
241 """
242 Load dict contents from the given filename.
243 """
244 try:
245 import numpy as np
246 except ModuleNotFoundError:
247 raise ModuleNotFoundError(import_error_message("NumPy"))
248
249 try:
250 # Open the file with a context manager manually, because np.load does not
251 # follow such good practices internally, causing avoidable error messages
252 # in the unit tests.
253 with open(filename, "rb") as f:
254 result = dict(np.load(f))
255 except (zipfile.BadZipFile, ValueError) as e:
256 raise OSError(
257 f"NPZ file {filename} could not be loaded. Corrupt file?"
258 ) from e
259 return result
260
261 def _dump_fn(self, data_dict: Dict[str, Any], filename: Path) -> None:
262 """
263 Dump dict contents to the given filename.
264 """
265 try:
266 import numpy as np
267 except ModuleNotFoundError:
268 raise ModuleNotFoundError(import_error_message("NumPy"))
269
270 np.savez_compressed(str(filename), **data_dict)
271
272 def check(
273 self,
274 data_dict: Dict[str, Any],
275 basename: Optional[str] = None,
276 fullpath: Optional["os.PathLike[str]"] = None,
277 tolerances: Optional[Dict[str, Dict[str, float]]] = None,
278 default_tolerance: Optional[Dict[str, float]] = None,
279 ) -> None:
280 """
281 Checks a dictionary of NumPy ndarrays, containing only numeric data, against a previously recorded version, or generate a new file.
282
283 Example::
284
285 def test_some_data(ndarrays_regression):
286 points, values = some_function()
287 ndarrays_regression.check(
288 {
289 'points': points, # array with shape (100, 3)
290 'values': values, # array with shape (100,)
291 },
292 default_tolerance=dict(atol=1e-8, rtol=1e-8)
293 )
294
295 :param data_dict: dictionary of NumPy ndarrays containing
296 data for regression check. The arrays can have any shape.
297
298 :param basename: basename of the file to test/record. If not given the name
299 of the test is used.
300
301 :param fullpath: complete path to use as a reference file. This option
302 will ignore embed_data completely, being useful if a reference file is located
303 in the session data dir for example.
304
305 :param tolerances: dict mapping keys from the data_dict to tolerance settings
306 for the given data. Example::
307
308 tolerances={'U': Tolerance(atol=1e-2)}
309
310 :param default_tolerance: dict mapping the default tolerance for the current
311 check call. Example::
312
313 default_tolerance=dict(atol=1e-7, rtol=1e-18).
314
315 If not provided, will use defaults from numpy's ``isclose`` function.
316
317 ``basename`` and ``fullpath`` are exclusive.
318 """
319 try:
320 import numpy as np
321 except ModuleNotFoundError:
322 raise ModuleNotFoundError(import_error_message("NumPy"))
323
324 import functools
325
326 __tracebackhide__ = True
327
328 if not isinstance(data_dict, dict):
329 raise TypeError(
330 "Only dictionaries with NumPy arrays or array-like objects are "
331 "supported on ndarray_regression fixture.\n"
332 "Object with type '{}' was given.".format(str(type(data_dict)))
333 )
334 for key, array in data_dict.items():
335 assert isinstance(key, str), (
336 "The dictionary keys must be strings. "
337 "Found key with type '{}'".format(str(type(key)))
338 )
339 data_dict[key] = np.asarray(array)
340
341 for key, array in data_dict.items():
342 # Accepted:
343 # - b: boolean
344 # - i: signed integer
345 # - u: unsigned integer
346 # - f: floating-point number
347 # - c: complex floating-point number
348 # - U: unicode string
349 # Rejected:
350 # - m: timedelta
351 # - M: datetime
352 # - O: objects
353 # - S: zero-terminated bytes
354 # - V: void (raw data, structured arrays)
355 if array.dtype.kind not in ["b", "i", "u", "f", "c", "U"]:
356 raise TypeError(
357 "Only numeric or unicode data is supported on ndarrays_regression "
358 f"fixture.\nArray '{key}' with type '{array.dtype}' was given."
359 )
360
361 if tolerances is None:
362 tolerances = {}
363 self._tolerances_dict = tolerances
364
365 if default_tolerance is None:
366 default_tolerance = {}
367 self._default_tolerance = default_tolerance
368
369 dump_fn = functools.partial(self._dump_fn, data_dict)
370
371 perform_regression_check(
372 datadir=self.datadir,
373 original_datadir=self.original_datadir,
374 request=self.request,
375 check_fn=self._check_fn,
376 dump_fn=dump_fn,
377 extension=".npz",
378 basename=basename,
379 fullpath=fullpath,
380 force_regen=self._force_regen,
381 with_test_class_names=self._with_test_class_names,
382 )