Skip to content

Commit

Permalink
Add NaN/Inf checks into check_numpy_array_features (#1145)
Browse files Browse the repository at this point in the history
* Add NaN/Inf checks into check_numpy_array_features

For normal scenario (and provide a killer switch to turn off the check), all numpy arrays should not have NaN or Inf.

* fix E501

also put report_failure to the end to match the style

* Update doc
  • Loading branch information
yslan authored Jan 11, 2025
1 parent 344e1f2 commit 5563310
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
3 changes: 2 additions & 1 deletion course/page/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -1263,7 +1263,8 @@ class PythonCodeQuestion(CodeQuestion, PageBaseWithoutHumanGrading):
feedback.check_numpy_array_sanity(name, num_axes, data)
feedback.check_numpy_array_features(name, ref, data, report_failure=True)
feedback.check_numpy_array_features(name, ref, data, check_finite=True,
report_failure=True)
feedback.check_numpy_array_allclose(name, ref, data,
accuracy_critical=True, rtol=1e-5, atol=1e-8,
Expand Down
10 changes: 9 additions & 1 deletion course/page/code_feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ def check_numpy_array_sanity(self, name, num_axes, data):
0, f"'{name}' does not consist of floating point numbers--"
f"got: '{data.dtype}'")

def check_numpy_array_features(self, name, ref, data, report_failure=True):
def check_numpy_array_features(self, name, ref, data, check_finite=True,
report_failure=True):

import numpy as np
assert isinstance(ref, np.ndarray)

Expand All @@ -91,6 +93,12 @@ def bad(msg):
f"'{name}' does not have correct data type--"
f"got: '{data.dtype}', expected: '{ref.dtype}'")

if check_finite:
if np.any(np.isnan(data)):
return bad(f"'{name}' contains NaN")
if np.any(np.isinf(data)):
return bad(f"'{name}' contains Inf")

return True

def check_numpy_array_allclose(self, name, ref, data, accuracy_critical=True,
Expand Down

0 comments on commit 5563310

Please sign in to comment.