Debian Codegraph @

src/pytest_regressions/num_regression.py

raw symbols SCIP
1 import os
2 from typing import Any
3 from typing import Dict
4 from typing import Optional
5 from typing import Sequence
6
7 from .common import import_error_message
8 from .dataframe_regression import DataFrameRegressionFixture
9
10
11 class NumericRegressionFixture(DataFrameRegressionFixture):
12 """
13 Numeric Data Regression fixture implementation used on num_regression fixture.
14 """
15
16 def check(
17 self,
18 data_dict: Dict[str, Any],
19 basename: Optional[str] = None,
20 fullpath: Optional["os.PathLike[str]"] = None,
21 tolerances: Optional[Dict[str, Dict[str, float]]] = None,
22 default_tolerance: Optional[Dict[str, float]] = None,
23 data_index: Optional[Sequence[int]] = None,
24 fill_different_shape_with_nan: bool = True,
25 ) -> None:
26 """
27 Checks the given dict against a previously recorded version, or generate a new file.
28 The dict must map from user-defined keys to 1d numpy arrays or array-like values.
29
30 Example::
31
32 num_regression.check({
33 'U_gas': U[0][positions],
34 'U_liquid': U[1][positions],
35 'gas_vol_frac [-]': vol_frac[0][positions],
36 'liquid_vol_frac [-]': vol_frac[1][positions],
37 'P': Pa_to_bar(P)[positions],
38 })
39
40 :param data_dict: dict mapping keys to numpy arrays, or objects that can be
41 coerced to 1d numpy arrays with a numeric dtype (e.g. list, tuple, etc).
42
43 :param basename: basename of the file to test/record. If not given the name
44 of the test is used.
45
46 :param fullpath: complete path to use as a reference file. This option
47 will ignore embed_data completely, being useful if a reference file is located
48 in the session data dir for example.
49
50 :param tolerances: dict mapping keys from the data_dict to tolerance settings for the
51 given data. Example::
52
53 tolerances={'U': Tolerance(atol=1e-2)}
54
55 :param default_tolerance: dict mapping the default tolerance for the current check
56 call. Example::
57
58 default_tolerance=dict(atol=1e-7, rtol=1e-18).
59
60 If not provided, will use defaults from numpy's ``isclose`` function.
61
62 :param data_index: If set, will override the indexes shown in the outputs. Default
63 is panda's default, which is ``range(0, len(data))``.
64
65 :param fill_different_shape_with_nan: If set, all the data provided in the data_dict
66 that has size lower than the bigger size will be filled with ``np.NaN``, in order to save
67 the data in a CSV file.
68
69 ``basename`` and ``fullpath`` are exclusive.
70 """
71
72 try:
73 import numpy as np
74 except ModuleNotFoundError:
75 raise ModuleNotFoundError(import_error_message("Numpy"))
76 try:
77 import pandas as pd
78 except ModuleNotFoundError:
79 raise ModuleNotFoundError(import_error_message("Pandas"))
80
81 __tracebackhide__ = True
82
83 for k, obj in data_dict.items():
84 if not isinstance(obj, np.ndarray):
85 arr = np.atleast_1d(np.asarray(obj))
86 if np.issubdtype(arr.dtype, np.number):
87 data_dict[k] = arr
88
89 data_shapes1 = []
90 for obj in data_dict.values():
91 assert type(obj) in [
92 np.ndarray
93 ], "Only objects that can be coerced to numpy arrays are valid for numeric_data_regression fixture.\n"
94 shape = obj.shape
95
96 assert len(shape) == 1, (
97 "Only 1D arrays are supported on num_data_regression fixture.\n"
98 "Array with shape %s was given.\n" % (shape,)
99 )
100 data_shapes1.append(shape[0])
101
102 data_shapes2 = np.array(data_shapes1)
103 if not np.all(data_shapes2 == data_shapes2[0]):
104 if not fill_different_shape_with_nan:
105 assert (
106 False
107 ), "Data dict with different array lengths will not be accepted. Try setting fill_different_shape_with_nan=True."
108 elif len(data_dict) > 1 and not all(
109 np.issubdtype(a.dtype, np.floating) for a in data_dict.values()
110 ):
111 raise TypeError(
112 "Checking multiple arrays with different shapes are not supported for non-float arrays"
113 )
114 else:
115 max_size = max(data_shapes2)
116 for k, obj in data_dict.items():
117 new_data = np.empty(shape=(max_size,), dtype=obj.dtype)
118 new_data[: len(obj)] = obj
119 new_data[len(obj) :] = np.nan
120 data_dict[k] = new_data
121
122 data_frame = pd.DataFrame(data_dict, index=data_index)
123
124 DataFrameRegressionFixture.check(
125 self, data_frame, basename, fullpath, tolerances, default_tolerance
126 )