Skip to content

ENH: add "max difference" messages to np.testing.assert_array_equal - #12591

Merged
shoyer merged 12 commits into
numpy:masterfrom
shoyer:assert-max-difference
Jan 2, 2019
Merged

shoyer merged 12 commits into
numpy:masterfrom
shoyer:assert-max-difference

Conversation

@shoyer

@shoyer shoyer commented Dec 19, 2018 •

Copy link
Copy Markdown
Member

Example behavior:

>>> x = np.array([1, 2, 3])
>>> y = np.array([1, 2, 3.0001])
>>> np.testing.assert_allclose(x, y)
AssertionError:
Not equal to tolerance rtol=1e-07, atol=0

Mismatch: 33.3%
Max absolute difference: 0.0001
Max relative difference: 3.33322223e-05
 x: array([1, 2, 3])
 y: array([1.    , 2.    , 3.0001])

Motivation: when writing numerical algorithms, I frequently find myself experimenting to pick the right value of atol and rtol for np.testing.assert_allclose(). If I make the tolerance too generous, I risk missing regressions in accuracy, so I usually try to pick the smallest values for which tests pass. This change immediately reveals appropriate values to use for these parameters, so I don't need to guess and check.

If others like this idea, I will run it by the mailing list.

…_equal

Example behavior:

    >>> x = np.array([1, 2, 3])
    >>> y = np.array([1, 2, 3.0001])
    >>> np.testing.assert_allclose(x, y)
    AssertionError:
    Not equal to tolerance rtol=1e-07, atol=0

    (mismatch 33.333333333333336%, maximum difference 0.00010000000000021103)
     x: array([1, 2, 3])
     y: array([1.    , 2.    , 3.0001])

Motivation: when writing numerical algorithms, I frequently find myself
experimenting to pick the right value of `atol` and `rtol` for
`np.testing.assert_allclose()`. If I make the tolerance too generous, I risk
missing regressions in accuracy, so I usually try to pick the smallest values
for which tests pass. This change immediately reveals appropriate values to
use for these parameters, so I don't need to guess and check.
@rgommers

Copy link
Copy Markdown
Member

I like this idea

Comment thread numpy/testing/tests/test_utils.py Resolved

@eric-wieser eric-wieser left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally looks good, but I don't understand the existing tests that you tweaked

@mhvk

mhvk commented Dec 19, 2018

Copy link
Copy Markdown
Contributor

Nice little enhancement; I've definitely done the same.

@shoyer

shoyer commented Dec 19, 2018

Copy link
Copy Markdown
Member Author

Note that this definitely needs more extensive tests. I'll remove "WIP" from the title when that's done.

@shoyer shoyer changed the title ENH: add "maximum difference" message to np.testing.assert_array_equal WIP: ENH: add "maximum difference" message to np.testing.assert_array_equal Dec 19, 2018
@shoyer
shoyer force-pushed the assert-max-difference branch from a138ffd to baed612 Compare December 20, 2018 05:52
@shoyer

shoyer commented Dec 20, 2018

Copy link
Copy Markdown
Member Author

Per the mailing list discussion, I've added relative error as well. Here's what it looks like currently:

>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
...                               [1, np.sqrt(np.pi)**2, np.nan])
AssertionError:
Arrays are not equal

(mismatch 33.3%, max abs error 4.4408921e-16, max rel error 1.41357986e-16)
 x: array([1.      , 3.141593,      nan])
 y: array([1.      , 3.141593,      nan])

@shoyer

shoyer commented Dec 20, 2018

Copy link
Copy Markdown
Member Author

It's not entirely clear to me what the right description for these error levels is. Currently I have "max abs error" and "max rel error", which is a compromise between explicitness and succinctness (i.e., fitting on one line). Other possible choices:

  • Don't abbreviate, i.e., max -> maximum, abs -> absolute, rel -> relative
  • Remove "max" as redundant, i.e., just "abs error" and "rel error"
  • "diff" or "difference" instead of "error", i.e., "max abs diff" and "max rel diff"

I think we're at about the maximum description length for fitting cleanly on one line within parentheses with "max abs error". If we want a longer or non-abbreviate description, we should figure out how to make this look good with line breaks, e.g., something like:

Mismatch: 33.3%
Maximum absolute error: 4.4408921e-16
Maximum relative error: 1.41357986e-16
 x: array([1.      , 3.141593,      nan])
 y: array([1.      , 3.141593,      nan])


with errstate(invalid='ignore', divide='ignore'):
# ignore errors for non-numeric types
with contextlib.suppress(TypeError):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do I get a prize for using the first Python 3 only feature in NumPy? :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use a 2.7 feature here too, and combine both withs into a single with?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could, but then I need an ugly explicit continuation character \, e.g.,

            with errstate(invalid='ignore', divide='ignore'), \
                    contextlib.suppress(TypeError):
                # ignore errors for non-numeric types

@mhvk

mhvk commented Dec 20, 2018

Copy link
Copy Markdown
Contributor

I would do your suggested error -> diff change. If you want to shorten even more max adiff, max rdiff.

Your version split over multiple lines is probably better, though (would still replace "error" with "difference").

@shoyer

shoyer commented Dec 20, 2018 •

Copy link
Copy Markdown
Member Author

OK, so perhaps:

Mismatch: 33.3%
Max absolute difference: 4.4408921e-16
Max relative difference: 1.41357986e-16
 x: array([1.      , 3.141593,      nan])
 y: array([1.      , 3.141593,      nan])

@mhvk

mhvk commented Dec 20, 2018

Copy link
Copy Markdown
Contributor

Last suggestion looks great to me!

@shoyer shoyer changed the title WIP: ENH: add "maximum difference" message to np.testing.assert_array_equal ENH: add "max difference" messages to np.testing.assert_array_equal Dec 23, 2018
Comment thread doc/release/1.17.0-notes.rst Outdated

Array comparison assertions include maximum differneces
-------------------------------------------------------

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: remove this blank line, which probably also makes git behave better in future merges.

Comment thread numpy/testing/_private/utils.py Outdated
Arrays are not almost equal to 5 decimals
x and y nan location mismatch:
x: array([1. , 2.33333, nan])
y: array([1. , 2.33339, 5. ])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tylerjereddy, are these now being run through refguide? If so, why was the old error type not causing a failure?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refguide is opt-in so if @shoyer thinks we should be running the checker on these docstrings then:

diff --git a/tools/refguide_check.py b/tools/refguide_check.py
index 3d885e3..fec715f 100644
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -76,6 +76,7 @@ PUBLIC_SUBMODULES = [
     'polynomial',
     'matrixlib',
     'random',
+    'testing',
 ]

Testing locally (python runtests.py -g --refguide-check >& refguide_results.txt), this causes various failures, some for the docstrings touched here, but also for other testing/_private/utils.py docstrings with things like suppress_warnings is not defined.

I wonder if there's an extra layer of complexity given that we are testing the testing utilities' docstrings. Normally refguide failures will produce an expected and got set of values, but many of the problems here seem to complain about the desired assertion actually happening (something not being caught when it should be maybe).

My initial bet is that this is the design issue observed with refguide here:

    def _do_check(self, want, got):
        # This should be done exactly as written to correctly handle all of
        # numpy-comparable objects, strings, and heterogeneous tuples
        try:
            if want == got:
                return True
        except Exception:
            pass
        return np.allclose(want, got, atol=self.atol, rtol=self.rtol)

In particular, I suppose we'd want a way to check if allclose and / or similar are the actual function under test in the docstring and then perform a meta-assessment from there. I find this slightly mind-bending, but maybe obvious to other devs.

That said, is this something for a separate issue / wish-list? Or maybe simpler than I'm thinking here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was able to successfully enable refguide checking on np.testing with a few docstring fixes. It appears the trick is add to include lines for the trraceback at the start of each error message:

Traceback (most recent call last):
    ...

Otherwise doctests don't recognize the exception.

Comment thread numpy/testing/tests/test_utils.py Outdated
' x: array([1.00000000001, 2.00000000002, 3.00003 ])')
assert_equal(
msgs[7],
' y: array([1.00000000002, 2.00000000003, 3.00004 ])')

@eric-wieser eric-wieser Dec 23, 2018 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should have at the end a

else:
    assert_(False)

Or perhaps better as:

with pytest.raises(AssertionError) as exc_info:
    self._assert_func(x, y, decimal=12)
e = exc_info.value
# rest as you have it

Same in all the cases below - the test is not actually checking that the error happens at all.

@charris

charris commented Dec 25, 2018

Copy link
Copy Markdown
Member

Needs rebase and (partial?) squashing.

@shoyer

shoyer commented Dec 25, 2018 via email

Copy link
Copy Markdown
Member Author

@charris

charris commented Dec 26, 2018

Copy link
Copy Markdown
Member

I think it is about to get merged.

@charris

charris commented Dec 31, 2018

Copy link
Copy Markdown
Member

Needs rebase.

@mattip

mattip commented Jan 1, 2019

Copy link
Copy Markdown
Member

Test failure unrelated to this PR.

LGTM.

@tylerjereddy tylerjereddy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great that refguide has been activated for the docstrings touched here now. For exceptions, it looks like the "actual" and "desired" values (and probably also the error message itself) aren't checked.

I found one obvious typo that refguide misses as a result, but otherwise a net improvement.

Comment thread numpy/testing/_private/utils.py Outdated
AssertionError:
Arrays are not almost equal to 10 decimals
ACTUAL: 2.3333333333333
DESIRED: 2.2.33333334

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The desired value looks wrong with two decimals--probably a typo. I think you're right that refguide is now working as intended for the modules you've touched, but it will only be sensitive to the "type" of exception object, and apparently not to much beyond that.

I think @mattip recently observed this too. Maybe this is ok, but maybe our wish-list may include a bit more stringency than just checking the category of the error.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, fixed. We should definitely disable IGNORE_EXECPTION_DETAIL in refguide, but let's save that for another PR.

@charris charris mentioned this pull request Jan 1, 2019
@charris charris added this to the 1.16.1 release milestone Jan 1, 2019
@charris charris added the 09 - Backport-Candidate PRs tagged should be backported label Jan 1, 2019
@charris

charris commented Jan 1, 2019

Copy link
Copy Markdown
Member

Whoever merges this, please squash as it will make a backport much easier.

@shoyer

shoyer commented Jan 2, 2019

Copy link
Copy Markdown
Member Author

I'm going to merge this (via squashing) when tests pass.

@shoyer
shoyer merged commit a16fc94 into numpy:master Jan 2, 2019
@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label Jan 17, 2019
@charris charris removed this from the 1.16.1 release milestone Jan 17, 2019
charris pushed a commit to charris/numpy that referenced this pull request Jan 17, 2019
…umpy#12591)

Example behavior:

>>> x = np.array([1, 2, 3])
>>> y = np.array([1, 2, 3.0001])
>>> np.testing.assert_allclose(x, y)
AssertionError:
Not equal to tolerance rtol=1e-07, atol=0

Mismatch: 33.3%
Max absolute difference: 0.0001
Max relative difference: 3.33322223e-05
 x: array([1, 2, 3])
 y: array([1.    , 2.    , 3.0001])

Motivation: when writing numerical algorithms, I frequently find myself
experimenting to pick the right value of `atol` and `rtol` for
`np.testing.assert_allclose()`. If I make the tolerance too generous, I risk
missing regressions in accuracy, so I usually try to pick the smallest values
for which tests pass. This change immediately reveals appropriate values to
use for these parameters, so I don't need to guess and check.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants