-
Notifications
You must be signed in to change notification settings - Fork 240
/
assert_utils.py
543 lines (457 loc) · 18.9 KB
/
assert_utils.py
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
"""
Functions for making assertions about OpenMDAO Systems.
"""
import numpy as np
from math import isnan
import warnings
import unittest
from contextlib import contextmanager
from functools import wraps
from openmdao.core.component import Component
from openmdao.core.group import Group
from openmdao.jacobians.dictionary_jacobian import DictionaryJacobian
from openmdao.utils.general_utils import pad_name, reset_warning_registry
from openmdao.utils.general_utils import warn_deprecation
@contextmanager
def assert_warning(category, msg):
"""
Context manager asserting that a warning is issued.
Parameters
----------
category : class
The class of the expected warning.
msg : str
The text of the expected warning.
Raises
------
AssertionError
If the expected warning is not raised.
"""
with reset_warning_registry():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
yield
for warn in w:
if (issubclass(warn.category, category) and str(warn.message) == msg):
break
else:
raise AssertionError("Did not see expected %s: %s" % (category.__name__, msg))
@contextmanager
def assert_warnings(expected_warnings):
"""
Context manager asserting that expected warnings are issued.
Parameters
----------
expected_warnings : iterable of (class, str)
The category and text of the expected warnings.
Raises
------
AssertionError
If all the expected warnings are not raised.
"""
with reset_warning_registry():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
yield
for category, msg in expected_warnings:
for warn in w:
if (issubclass(warn.category, category) and str(warn.message) == msg):
break
else:
raise AssertionError("Did not see expected %s: %s" % (category.__name__, msg))
@contextmanager
def assert_no_warning(category, msg=None):
"""
Context manager asserting that a warning is not issued.
Parameters
----------
category : class
The class of the warning.
msg : str or None
The text of the warning. If None then only the warning class will be checked.
Raises
------
AssertionError
If the warning is raised.
"""
with reset_warning_registry():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
yield
for warn in w:
if issubclass(warn.category, category):
if msg is None:
raise AssertionError(f"Found warning: {category} {str(warn.message)}")
elif str(warn.message) == msg:
raise AssertionError(f"Found warning: {category} {msg}")
def assert_check_partials(data, atol=1e-6, rtol=1e-6):
"""
Raise assertion if any entry from the return from check_partials is above a tolerance.
Parameters
----------
data : dict of dicts of dicts
First key:
is the component name;
Second key:
is the (output, input) tuple of strings;
Third key:
is one of ['rel error', 'abs error', 'magnitude', 'J_fd', 'J_fwd', 'J_rev'];
For 'rel error', 'abs error', 'magnitude' the value is: A tuple containing norms for
forward - fd, adjoint - fd, forward - adjoint.
For 'J_fd', 'J_fwd', 'J_rev' the value is: A numpy array representing the computed
Jacobian for the three different methods of computation.
atol : float
absolute error. Default is 1e-6.
rtol : float
relative error. Default is 1e-6.
"""
error_string = ''
absrel_header = 'abs/rel'
wrt_header = '< output > wrt < variable >'
norm_value_header = 'norm value'
len_absrel_width = len(absrel_header)
norm_types = ['fwd-fd', 'rev-fd', 'fd-rev']
len_norm_type_width = max(len(s) for s in norm_types)
for comp in data:
len_wrt_width = len(wrt_header)
len_norm_width = len(norm_value_header)
bad_derivs = []
# Find all derivatives whose errors exceed tolerance.
# Also, size the output to precompute column extents.
for (var, wrt) in data[comp]:
pair_data = data[comp][var, wrt]
for error_type, tolerance in [('abs error', atol), ('rel error', rtol), ]:
actual = pair_data[error_type]
for error_val, mode in zip(actual, norm_types):
in_error = False
if error_val is None:
# Reverse derivatives only computed on matrix free comps.
continue
if not np.isnan(error_val):
if not np.allclose(error_val, 0.0, atol=tolerance):
if error_type == 'rel error' and mode == 'fwd-fd' and \
np.allclose(pair_data['J_fwd'], 0.0, atol=atol) and \
np.allclose(pair_data['J_fd'], 0.0, atol=atol):
# Special case: both fd and fwd are really tiny, so we want to
# ignore the rather large relative errors.
in_error = False
else:
# This is a bona-fide error.
in_error = True
elif error_type == 'abs error' and mode == 'fwd-fd':
# Either analytic or approximated derivatives contain a NaN.
in_error = True
if in_error:
wrt_string = '{0} wrt {1}'.format(var, wrt)
norm_string = '{}'.format(error_val)
bad_derivs.append((wrt_string, norm_string, error_type, mode))
len_wrt_width = max(len_wrt_width, len(wrt_string))
len_norm_width = max(len_norm_width, len(norm_string))
if bad_derivs:
comp_error_string = ''
for wrt_string, norm_string, error_type, mode in bad_derivs:
err_msg = '{0} | {1} | {2} | {3}'.format(
pad_name(wrt_string, len_wrt_width),
pad_name(error_type.split()[0], len_absrel_width),
pad_name(mode, len_norm_type_width),
pad_name(norm_string, len_norm_width)) + '\n'
comp_error_string += err_msg
name_header = 'Component: {}\n'.format(comp)
len_name_header = len(name_header)
header = len_name_header * '-' + '\n'
header += name_header
header += len_name_header * '-' + '\n'
header += '{0} | {1} | {2} | {3}'.format(
pad_name(wrt_header, len_wrt_width),
pad_name(absrel_header, len_absrel_width),
pad_name('norm', len_norm_type_width),
pad_name(norm_value_header, len_norm_width),
) + '\n'
header += '{0} | {1} | {2} | {3}'.format(
len_wrt_width * '-',
len_absrel_width * '-',
len_norm_type_width * '-',
len_norm_width * '-',
) + '\n'
comp_error_string = header + comp_error_string
error_string += comp_error_string
# if error string then raise error with that string
if error_string:
header_line1 = 'Assert Check Partials failed for the following Components'
header_line2 = 'with absolute tolerance = {} and relative tolerance = {}'.format(atol, rtol)
header_width = max(len(header_line1), len(header_line2))
header = '\n' + header_width * '=' + '\n'
header += header_line1 + '\n'
header += header_line2 + '\n'
header += header_width * '=' + '\n'
error_string = header + error_string
raise ValueError(error_string)
def assert_no_approx_partials(system, include_self=True, recurse=True):
"""
Raise assertion error if any component within system is using approximated partials.
Parameters
----------
system : System
The system under which to search for approximated partials.
include_self : bool
If True, include this system in the iteration.
recurse : bool
If True, iterate over the whole tree under this system.
Raises
------
AssertionError
If a subsystem of group is found to be using approximated partials.
"""
has_approx_partials = False
msg = 'The following components use approximated partials:\n'
for s in system.system_iter(include_self=include_self, recurse=recurse):
if isinstance(s, Component):
if s._approx_schemes:
has_approx_partials = True
approx_partials = [(k, v['method']) for k, v in s._declared_partials.items()
if 'method' in v and v['method']]
msg += ' ' + s.pathname + '\n'
for key, method in approx_partials:
msg += ' of={0:12s} wrt={1:12s} method={2:2s}\n'.format(key[0],
key[1],
method)
if has_approx_partials:
raise AssertionError(msg)
def assert_no_dict_jacobians(system, include_self=True, recurse=True):
"""
Raise an assertion error if any Group within system is found to be using dictionary jacobians.
Parameters
----------
system : System
The system under which to search for approximated partials.
include_self : bool
If True, include this system in the iteration.
recurse : bool
If True, iterate over the whole tree under this system.
Raises
------
AssertionError
If a subsystem of group is found to be using approximated partials.
"""
parts = ['The following groups use dictionary jacobians:\n']
for s in system.system_iter(include_self=include_self, recurse=recurse, typ=Group):
if isinstance(s._jacobian, DictionaryJacobian):
parts.append(' ' + s.pathname)
if len(parts) > 1:
raise AssertionError('\n'.join(parts))
def assert_rel_error(test_case, actual, desired, tolerance=1e-15):
"""
Check relative error.
Determine that the relative error between `actual` and `desired`
is within `tolerance`. If `desired` is zero, then use absolute error.
Parameters
----------
test_case : :class:`unittest.TestCase`
TestCase instance used for assertions.
actual : float, array-like, dict
The value from the test.
desired : float, array-like, dict
The value expected.
tolerance : float
Maximum relative error ``(actual - desired) / desired``.
Returns
-------
float
The error.
"""
warn_deprecation("'assert_rel_error' has been deprecated. Use "
"'assert_near_equal' instead.")
if isinstance(actual, dict) and isinstance(desired, dict):
actual_keys = set(actual.keys())
desired_keys = set(desired.keys())
if actual_keys.symmetric_difference(desired_keys):
msg = 'Actual and desired keys differ. Actual extra keys: {}, Desired extra keys: {}'
actual_extra = actual_keys.difference(desired_keys)
desired_extra = desired_keys.difference(actual_keys)
test_case.fail(msg.format(actual_extra, desired_extra))
error = 0.
for key in actual_keys:
try:
new_error = assert_rel_error(test_case, actual[key], desired[key], tolerance)
error = max(error, new_error)
except test_case.failureException as exception:
msg = '{}: '.format(key) + str(exception)
raise test_case.failureException(msg) from None
elif isinstance(actual, float) and isinstance(desired, float):
if isnan(actual) and not isnan(desired):
test_case.fail('actual nan, desired %s' % desired)
if desired != 0:
error = (actual - desired) / desired
else:
error = actual
if abs(error) > tolerance:
test_case.fail('actual %s, desired %s, rel error %s, tolerance %s'
% (actual, desired, error, tolerance))
# array values
else:
actual = np.atleast_1d(actual)
desired = np.atleast_1d(desired)
if actual.shape != desired.shape:
test_case.fail(
'actual and desired have differing shapes.'
' actual {}, desired {}'.format(actual.shape, desired.shape))
if not np.all(np.isnan(actual) == np.isnan(desired)):
if actual.size == 1 and desired.size == 1:
test_case.fail('actual %s, desired %s' % (actual, desired))
else:
test_case.fail('actual and desired values have non-matching nan'
' values')
if np.linalg.norm(desired) == 0:
error = np.linalg.norm(actual)
else:
error = np.linalg.norm(actual - desired) / np.linalg.norm(desired)
if abs(error) > tolerance:
if actual.size < 10 and desired.size < 10:
test_case.fail('actual %s, desired %s, rel error %s, tolerance %s'
% (actual, desired, error, tolerance))
else:
test_case.fail('arrays do not match, rel error %.3e > tol (%.3e)' %
(error, tolerance))
return error
def assert_near_equal(actual, desired, tolerance=1e-15):
"""
Check relative error.
Determine that the relative error between `actual` and `desired`
is within `tolerance`. If `desired` is zero, then use absolute error.
Parameters
----------
actual : float, array-like, dict
The value from the test.
desired : float, array-like, dict
The value expected.
tolerance : float
Maximum relative error ``(actual - desired) / desired``.
Returns
-------
float
The error.
"""
if isinstance(actual, dict) and isinstance(desired, dict):
actual_keys = set(actual.keys())
desired_keys = set(desired.keys())
if actual_keys.symmetric_difference(desired_keys):
msg = 'Actual and desired keys differ. Actual extra keys: {}, Desired extra keys: {}'
actual_extra = actual_keys.difference(desired_keys)
desired_extra = desired_keys.difference(actual_keys)
raise KeyError(msg.format(actual_extra, desired_extra))
error = 0.
for key in actual_keys:
try:
new_error = assert_near_equal(
actual[key], desired[key], tolerance)
error = max(error, new_error)
except ValueError as exception:
msg = '{}: '.format(key) + str(exception)
raise ValueError(msg) from None
except KeyError as exception:
msg = '{}: '.format(key) + str(exception)
raise KeyError(msg) from None
elif isinstance(actual, float) and isinstance(desired, float):
if isnan(actual) and not isnan(desired):
raise ValueError('actual nan, desired %s' % desired)
if desired != 0:
error = (actual - desired) / desired
else:
error = actual
if abs(error) > tolerance:
raise ValueError('actual %s, desired %s, rel error %s, tolerance %s'
% (actual, desired, error, tolerance))
# array values
else:
actual = np.atleast_1d(actual)
desired = np.atleast_1d(desired)
if actual.shape != desired.shape:
raise ValueError(
'actual and desired have differing shapes.'
' actual {}, desired {}'.format(actual.shape, desired.shape))
if not np.all(np.isnan(actual) == np.isnan(desired)):
if actual.size == 1 and desired.size == 1:
raise ValueError('actual %s, desired %s' % (actual, desired))
else:
raise ValueError('actual and desired values have non-matching nan'
' values')
if np.linalg.norm(desired) == 0:
error = np.linalg.norm(actual)
else:
error = np.linalg.norm(actual - desired) / np.linalg.norm(desired)
if abs(error) > tolerance:
if actual.size < 10 and desired.size < 10:
raise ValueError('actual %s, desired %s, rel error %s, tolerance %s'
% (actual, desired, error, tolerance))
else:
raise ValueError('arrays do not match, rel error %.3e > tol (%.3e)' %
(error, tolerance))
return error
def assert_equal_arrays(a1, a2):
"""
Check that two arrays are equal.
This is a simplified method useful when the arrays to be compared may
not be numeric. It simply compares the shapes of the two arrays and then
does a value by value comparison.
Parameters
----------
a1 : array
The first array to compare.
a2 : array
The second array to compare.
"""
assert a1.shape == a2.shape
for x, y in zip(a1.flat, a2.flat):
assert x == y
def skip_helper(msg):
"""
Raise a SkipTest.
Parameters
----------
msg : str
The skip messaage.
Raises
------
SkipTest
"""
raise unittest.SkipTest(msg)
class SkipParameterized(object):
"""
Replaces the parameterized class, skipping decorated test cases.
"""
@classmethod
def expand(cls, input, name_func=None, doc_func=None, skip_on_empty=False, **legacy):
"""
Decorate a test so that it raises a SkipTest.
Parameters
----------
input : iterable
Not used (part of parameterized API).
name_func : function
Not used (part of parameterized API).
doc_func : function
Not used (part of parameterized API).
skip_on_empty : bool
Not used (part of parameterized API).
**legacy : dict
Not used (part of parameterized API).
Returns
-------
function
The wrapper function.
"""
skip_msg = "requires 'parameterized' (install openmdao[test])"
def parameterized_expand_wrapper(f, instance=None):
"""
Wrap a function so that it raises a SkipTest.
f : function
Function to be wrapped.
instance : None
Not used (part of parameterized API).
Returns
-------
function
The wrapped function.
"""
return wraps(f)(lambda f: skip_helper(skip_msg))
return parameterized_expand_wrapper