@@ -190,15 +190,6 @@ def _compare_xarray_dataarray_xy(
190190 return issues
191191
192192
193- def _check_pixel_tolerance (
194- actual : xarray .DataArray , expected : xarray .DataArray , pixel_tolerance : float = _DEFAULT_PIXELTOL
195- ):
196- """check if the percentage of pixels that are different is below the threshold"""
197- assert (
198- actual != expected
199- ).mean ().item () * 100 <= pixel_tolerance , "Percentage number of pixels that are different is above the threshold"
200-
201-
202193def _compare_xarray_dataarray (
203194 actual : Union [xarray .DataArray , str , Path ],
204195 expected : Union [xarray .DataArray , str , Path ],
@@ -241,24 +232,23 @@ def _compare_xarray_dataarray(
241232 if actual .shape != expected .shape :
242233 issues .append (f"Shape mismatch: { actual .shape } != { expected .shape } " )
243234 compatible = len (issues ) == 0
244- _pixel_tolerance_satisfied = True # flag for pixel tolerance test
245235 try :
246- xarray .testing .assert_allclose (a = actual , b = expected , rtol = rtol , atol = atol )
236+ if (pixel_tolerance > _DEFAULT_PIXELTOL ) and compatible :
237+ _bad_pixels = (actual * 1.0 - expected * 1.0 ) > atol
238+ assert (
239+ _bad_pixels .mean ().item () * 100 <= pixel_tolerance
240+ ), "Percentage number of pixels that are different is above the threshold"
241+ xarray .testing .assert_allclose (
242+ a = actual .where (~ _bad_pixels ), b = expected .where (~ _bad_pixels ), rtol = rtol , atol = atol
243+ )
244+ else :
245+ xarray .testing .assert_allclose (a = actual , b = expected , rtol = rtol , atol = atol )
247246 except AssertionError as e :
248- if (pixel_tolerance > _DEFAULT_PIXELTOL ) and compatible : # skip if there are issues
249- try :
250- _check_pixel_tolerance (actual , expected , pixel_tolerance )
251- except AssertionError as e1 :
252- issues .append (str (e1 ))
253- # Used to add the assertion error from assert_allclose to issues
254- _pixel_tolerance_satisfied = False
255- elif not _pixel_tolerance_satisfied :
256- # TODO: message of `assert_allclose` is typically multiline, split it again or make it one line?
257- issues .append (str (e ).strip ())
258- if compatible and {"x" , "y" } <= set (expected .dims ):
259- issues .extend (
260- _compare_xarray_dataarray_xy (actual = actual , expected = expected , rtol = rtol , atol = atol , name = name )
261- )
247+ issues .append (str (e ).strip ())
248+ if compatible and {"x" , "y" } <= set (expected .dims ):
249+ issues .extend (
250+ _compare_xarray_dataarray_xy (actual = actual , expected = expected , rtol = rtol , atol = atol , name = name )
251+ )
262252 return issues
263253
264254
0 commit comments