Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Avoid loss of precision when casting in packet loading #781

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions imap_processing/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,26 @@ def test_packet_file_to_datasets(use_derived_value, expected_mode):
np.testing.assert_array_equal(data["mode"], [expected_mode] * len(data["mode"]))


def test__create_minimum_dtype_array():
@pytest.mark.parametrize(
("arr", "dtype", "expected_dtype"),
[
# Expected basic case
([1, 2, 3], "uint8", "uint8"),
# We shouldn't go lower than requested either
([1, 2, 3], "uint16", "uint16"),
# Can't cast negative, fallback to default
([-1, 2, 3], "uint8", int),
# Small signed ints should be good
([-1, 2, 3], "int8", "int8"),
# Can't cast strings to ints, fallback to default
(["a", "b", "c"], "uint8", "<U1"),
# Can't cast floats to ints, fallback to default
([1, 2.5, 3], "uint8", float),
# Can't cast larger ints, fallback to default
([1, 1000, 2000], "uint8", int),
],
)
def test__create_minimum_dtype_array(arr, dtype, expected_dtype):
"""Test expected return types for minimum data types."""
result = utils._create_minimum_dtype_array([1, 2, 3], "uint8")
assert result.dtype == np.dtype("uint8")
# fallback to a generic array if the requested dtype can't be satisfied
result = utils._create_minimum_dtype_array(["a", "b", "c"], "uint8")
assert result.dtype == np.dtype("<U1")
result = utils._create_minimum_dtype_array(arr, dtype)
assert result.dtype == np.dtype(expected_dtype)
12 changes: 10 additions & 2 deletions imap_processing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,18 @@ def _create_minimum_dtype_array(values: list, dtype: str) -> npt.NDArray:
array : np.array
The array of values.
"""
# Create an initial array and then try to safely cast it to the desired dtype
x = np.asarray(values)
try:
return np.array(values, dtype=dtype)
# ValueError: when trying to cast strings (enum states) to ints
y = x.astype(dtype, copy=False)
# We need to compare the arrays to see if we trimmed any values by
# casting to a smaller datatype (e.g. float64 to uint8, 2.1 to 2)
if np.array_equal(x, y):
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This is all somewhat unfortunate in how many "arrays" we'll be creating here. If anyone has ideas for a better way to do this I'm interested in hearing it.

We are potentially creating 3 separate arrays:

  1. initial asarray from a list -> creates an int64
  2. Trying to cast to a smaller dtype -> creates a uint8
  3. Doing this array comparison in a higher-order dtype space.

They are all happening in numpy c-level functions so shouldn't be a huge hit, but it would be nice to not do this array comparison just to check loss of precision.

Copy link
Contributor

Choose a reason for hiding this comment

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

My thought would be to modify the _get_minimum_numpy_datatype function to take the derived value logic into account and return the appropriate datatype.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Really good suggestion, thanks.

I opened up: #786
with an alternative approach, which is actually able to get rid of the numpy try/except array creation too. The one downside is there isn't a great way to test all of the XTCE stuff currently :-/ I did test it on the new SWE XTCE file that was failing and it looks good, but I don't have a great way to parameterize that PR like we do with this one.

return y
except ValueError:
return np.array(values)
pass
return x


def packet_file_to_datasets(
Expand Down
Loading