forked from astropy/astropy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.py
More file actions
188 lines (150 loc) · 5.14 KB
/
diff.py
File metadata and controls
188 lines (150 loc) · 5.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import difflib
import functools
import math
import sys
from textwrap import indent
import numpy as np
__all__ = [
"diff_values",
"report_diff_values",
"where_not_allclose",
]
def diff_values(a, b, rtol=0.0, atol=0.0):
"""
Diff two scalar values. If both values are floats, they are compared to
within the given absolute and relative tolerance.
Parameters
----------
a, b : int, float, str
Scalar values to compare.
rtol, atol : float
Relative and absolute tolerances as accepted by
:func:`numpy.allclose`.
Returns
-------
is_different : bool
`True` if they are different, else `False`.
"""
if isinstance(a, float) and isinstance(b, float):
if math.isfinite(b):
return not abs(a - b) <= atol + rtol * abs(b)
if math.isnan(a) and math.isnan(b):
return False
return a != b
def _ignore_astropy_terminal_size(func):
@functools.wraps(func)
def inner(*args, **kwargs):
from astropy import conf
with conf.set_temp("max_width", -1), conf.set_temp("max_lines", -1):
return func(*args, **kwargs)
return inner
@_ignore_astropy_terminal_size
def report_diff_values(a, b, fileobj=sys.stdout, indent_width=0, rtol=0.0, atol=0.0):
"""
Write a diff report between two values to the specified file-like object.
Parameters
----------
a, b
Values to compare. Anything that can be turned into strings
and compared using :py:mod:`difflib` should work.
fileobj : object
File-like object to write to.
The default is ``sys.stdout``, which writes to terminal.
indent_width : int
Character column(s) to indent.
rtol, atol : float
Relative and absolute tolerances as accepted by
:func:`numpy.allclose`.
Returns
-------
identical : bool
`True` if no diff, else `False`.
"""
indent_prefix = indent_width * " "
if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
if a.shape != b.shape:
fileobj.write(indent(" Different array shapes:\n", indent_prefix))
report_diff_values(
str(a.shape),
str(b.shape),
fileobj=fileobj,
indent_width=indent_width + 1,
)
return False
if np.issubdtype(a.dtype, np.floating) and np.issubdtype(b.dtype, np.floating):
diff_indices = np.transpose(where_not_allclose(a, b, rtol=rtol, atol=atol))
else:
diff_indices = np.transpose(np.where(a != b))
num_diffs = diff_indices.shape[0]
for idx in diff_indices[:3]:
lidx = idx.tolist()
fileobj.write(indent(f" at {lidx!r}:\n", indent_prefix))
report_diff_values(
a[tuple(idx)],
b[tuple(idx)],
fileobj=fileobj,
indent_width=indent_width + 1,
rtol=rtol,
atol=atol,
)
if num_diffs > 3:
fileobj.write(
indent(f" ...and at {num_diffs - 3:d} more indices.\n", indent_prefix)
)
return False
return num_diffs == 0
typea = type(a)
typeb = type(b)
if typea == typeb:
lnpad = " "
sign_a = "a>"
sign_b = "b>"
a = str(a)
b = str(b)
else:
padding = max(len(typea.__name__), len(typeb.__name__)) + 3
lnpad = (padding + 1) * " "
sign_a = ("(" + typea.__name__ + ") ").rjust(padding) + "a>"
sign_b = ("(" + typeb.__name__ + ") ").rjust(padding) + "b>"
is_a_str = isinstance(a, str)
is_b_str = isinstance(b, str)
a = repr(a) if is_a_str and not is_b_str else str(a)
b = repr(b) if is_b_str and not is_a_str else str(b)
identical = True
for line in difflib.ndiff(a.splitlines(), b.splitlines()):
if line[0] == "-":
identical = False
line = sign_a + line[1:]
elif line[0] == "+":
identical = False
line = sign_b + line[1:]
else:
line = lnpad + line
fileobj.write(indent(" {}\n".format(line.rstrip("\n")), indent_prefix))
return identical
def where_not_allclose(a, b, rtol=1e-5, atol=1e-8):
"""
A version of :func:`numpy.allclose` that returns the indices
where the two arrays differ, instead of just a boolean value.
Parameters
----------
a, b : array-like
Input arrays to compare.
rtol, atol : float
Relative and absolute tolerances as accepted by
:func:`numpy.allclose`.
Returns
-------
idx : tuple of array
Indices where the two arrays differ.
"""
# Create fixed mask arrays to handle INF and NaN; currently INF and NaN
# are handled as equivalent
if not np.all(np.isfinite(a)):
a = np.ma.fix_invalid(a).data
if not np.all(np.isfinite(b)):
b = np.ma.fix_invalid(b).data
if atol == 0.0 and rtol == 0.0:
# Use a faster comparison for the most simple (and common) case
return np.where(a != b)
return np.where(np.abs(a - b) > (atol + rtol * np.abs(b)))