Debian Codegraph @

src/pytest_regressions/dataframe_regression.py

raw symbols SCIP
1 import os
2 from pathlib import Path
3 from typing import Any
4 from typing import Dict
5 from typing import Optional
6
7 import pytest
8
9 from .common import import_error_message
10 from .common import perform_regression_check
11
12
13 class DataFrameRegressionFixture:
14 """
15 Pandas DataFrame Regression fixture implementation used on dataframe_regression fixture.
16 """
17
18 DISPLAY_PRECISION = 17 # Decimal places
19 DISPLAY_WIDTH = 1000 # Max. Chars on outputs
20 DISPLAY_MAX_COLUMNS = 1000 # Max. Number of columns (see #3)
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 self._pandas_display_options = (
35 "display.precision",
36 DataFrameRegressionFixture.DISPLAY_PRECISION,
37 "display.width",
38 DataFrameRegressionFixture.DISPLAY_WIDTH,
39 "display.max_columns",
40 DataFrameRegressionFixture.DISPLAY_MAX_COLUMNS,
41 )
42
43 def _check_data_types(
44 self, key: Any, obtained_column: Any, expected_column: Any
45 ) -> None:
46 """
47 Check if data type of obtained and expected columns are the same. Fail if not.
48 Helper method used in _check_fn method.
49 """
50 try:
51 import numpy as np
52 except ModuleNotFoundError:
53 raise ModuleNotFoundError(import_error_message("NumPy"))
54
55 __tracebackhide__ = True
56 obtained_data_type = obtained_column.values.dtype
57 expected_data_type = expected_column.values.dtype
58 if obtained_data_type != expected_data_type:
59 # Check if both data types are comparable as numbers (float, int, short, bytes, etc...)
60 if np.issubdtype(obtained_data_type, np.number) and np.issubdtype(
61 expected_data_type, np.number
62 ):
63 return
64
65 # In case they are not, assume they are not comparable
66 error_msg = (
67 "Data type for data %s of obtained and expected are not the same.\n"
68 "Obtained: %s\n"
69 "Expected: %s\n" % (key, obtained_data_type, expected_data_type)
70 )
71 raise AssertionError(error_msg)
72
73 def _check_data_shapes(self, obtained_column: Any, expected_column: Any) -> None:
74 """
75 Check if obtained and expected columns have the same size.
76 Helper method used in _check_fn method.
77 """
78 __tracebackhide__ = True
79
80 obtained_data_shape = obtained_column.values.shape
81 expected_data_shape = expected_column.values.shape
82 if obtained_data_shape != expected_data_shape:
83 error_msg = (
84 "Obtained and expected data shape are not the same.\n"
85 "Obtained: %s\n"
86 "Expected: %s\n" % (obtained_data_shape, expected_data_shape)
87 )
88 raise AssertionError(error_msg)
89
90 def _check_fn(self, obtained_filename: Path, expected_filename: Path) -> None:
91 """
92 Check if dict contents dumped to a file match the contents in expected file.
93 """
94 try:
95 import numpy as np
96 except ModuleNotFoundError:
97 raise ModuleNotFoundError(import_error_message("NumPy"))
98 try:
99 import pandas as pd
100 except ModuleNotFoundError:
101 raise ModuleNotFoundError(import_error_message("Pandas"))
102
103 __tracebackhide__ = True
104
105 obtained_data = pd.read_csv(str(obtained_filename))
106 expected_data = pd.read_csv(str(expected_filename))
107
108 comparison_tables_dict = {}
109 for k in obtained_data.keys():
110 obtained_column = obtained_data[k]
111 expected_column = expected_data.get(k)
112
113 if expected_column is None:
114 error_msg = f"Could not find key '{k}' in the expected results.\n"
115 error_msg += "Keys in the obtained data table: ["
116 for k in obtained_data.keys():
117 error_msg += f"'{k}', "
118 error_msg += "]\n"
119 error_msg += "Keys in the expected data table: ["
120 for k in expected_data.keys():
121 error_msg += f"'{k}', "
122 error_msg += "]\n"
123 error_msg += "To update values, use --force-regen option.\n\n"
124 raise AssertionError(error_msg)
125
126 tolerance_args = self._tolerances_dict.get(k, self._default_tolerance)
127
128 self._check_data_types(k, obtained_column, expected_column)
129 self._check_data_shapes(obtained_column, expected_column)
130
131 if np.issubdtype(obtained_column.values.dtype, np.inexact):
132 not_close_mask = ~np.isclose(
133 obtained_column.values,
134 expected_column.values,
135 equal_nan=True,
136 **tolerance_args,
137 )
138 else:
139 not_close_mask = obtained_column.values != expected_column.values
140 # If Empty/NaN data is expected, then the values are equal:
141 not_close_mask[
142 np.logical_and(
143 pd.isna(obtained_column.values), pd.isna(expected_column.values)
144 )
145 ] = False
146
147 if np.any(not_close_mask):
148 diff_ids = np.where(not_close_mask)[0]
149 diff_obtained_data = obtained_column[diff_ids]
150 diff_expected_data = expected_column[diff_ids]
151 if obtained_column.values.dtype == bool:
152 diffs = np.logical_xor(obtained_column, expected_column)[diff_ids]
153 elif obtained_column.values.dtype == object:
154 diffs = diff_obtained_data.copy()
155 diffs[:] = "?"
156 else:
157 diffs = np.abs(obtained_column - expected_column)[diff_ids]
158
159 comparison_table = pd.concat(
160 [diff_obtained_data, diff_expected_data, diffs], axis=1
161 )
162 comparison_table.columns = [f"obtained_{k}", f"expected_{k}", "diff"]
163 comparison_tables_dict[k] = comparison_table
164
165 if len(comparison_tables_dict) > 0:
166 error_msg = "Values are not sufficiently close.\n"
167 error_msg += "To update values, use --force-regen option.\n\n"
168 for k, comparison_table in comparison_tables_dict.items():
169 error_msg += f"{k}:\n{comparison_table}\n\n"
170 if obtained_column.values.dtype == object:
171 error_msg += (
172 "WARNING: diffs for this kind of data type cannot be computed."
173 )
174 raise AssertionError(error_msg)
175
176 def _dump_fn(self, data_object: Any, filename: Path) -> None:
177 """
178 Dump dict contents to the given filename
179 """
180 data_object.to_csv(
181 str(filename),
182 float_format=f"%.{DataFrameRegressionFixture.DISPLAY_PRECISION}g",
183 )
184
185 def check(
186 self,
187 data_frame: Any,
188 basename: Optional[str] = None,
189 fullpath: Optional["os.PathLike[str]"] = None,
190 tolerances: Optional[Dict[str, Dict[str, float]]] = None,
191 default_tolerance: Optional[Dict[str, float]] = None,
192 ) -> None:
193 """
194 Checks a pandas dataframe, containing only numeric data, against a previously recorded version, or generate a new file.
195
196 Example::
197
198 data_frame = pandas.DataFrame.from_dict({
199 'U_gas': U[0][positions],
200 'U_liquid': U[1][positions],
201 'gas_vol_frac [-]': vol_frac[0][positions],
202 'liquid_vol_frac [-]': vol_frac[1][positions],
203 'P': Pa_to_bar(P)[positions],
204 })
205 dataframe_regression.check(data_frame)
206
207 :param data_frame: pandas DataFrame containing data for regression check.
208
209 :param basename: basename of the file to test/record. If not given the name
210 of the test is used.
211
212 :param fullpath: complete path to use as a reference file. This option
213 will ignore embed_data completely, being useful if a reference file is located
214 in the session data dir for example.
215
216 :param tolerances: dict mapping keys from the data_frame to tolerance settings for the
217 given data. Example::
218
219 tolerances={'U': dict(atol=1e-2)}
220
221 :param default_tolerance: dict mapping the default tolerance for the current check
222 call. Example::
223
224 default_tolerance=dict(atol=1e-7, rtol=1e-18).
225
226 If not provided, will use defaults from numpy's ``isclose`` function.
227
228 ``basename`` and ``fullpath`` are exclusive.
229 """
230 try:
231 import pandas as pd
232 except ModuleNotFoundError:
233 raise ModuleNotFoundError(import_error_message("Pandas"))
234
235 import functools
236
237 __tracebackhide__ = True
238
239 assert isinstance(data_frame, pd.DataFrame), (
240 "Only pandas DataFrames are supported on dataframe_regression fixture.\n"
241 "Object with type '%s' was given." % (str(type(data_frame)),)
242 )
243
244 for column in data_frame.columns:
245 array = data_frame[column]
246 # Skip assertion if an array of strings
247 if (array.dtype == "O") and (type(array.iloc[0]) is str):
248 continue
249 # Rejected: timedelta, datetime, objects, zero-terminated bytes, unicode strings and raw data
250 assert array.dtype not in ["m", "M", "O", "S", "a", "U", "V"], (
251 "Only numeric data is supported on dataframe_regression fixture.\n"
252 "Array with type '%s' was given." % (str(array.dtype),)
253 )
254
255 if tolerances is None:
256 tolerances = {}
257 self._tolerances_dict = tolerances
258
259 if default_tolerance is None:
260 default_tolerance = {}
261 self._default_tolerance = default_tolerance
262
263 dump_fn = functools.partial(self._dump_fn, data_frame)
264
265 with pd.option_context(*self._pandas_display_options):
266 perform_regression_check(
267 datadir=self.datadir,
268 original_datadir=self.original_datadir,
269 request=self.request,
270 check_fn=self._check_fn,
271 dump_fn=dump_fn,
272 extension=".csv",
273 basename=basename,
274 fullpath=fullpath,
275 force_regen=self._force_regen,
276 with_test_class_names=self._with_test_class_names,
277 )