diff --git a/harmonica/_io/oasis_montaj_grd.py b/harmonica/_io/oasis_montaj_grd.py index 80eb2f067..b9f7c65ce 100644 --- a/harmonica/_io/oasis_montaj_grd.py +++ b/harmonica/_io/oasis_montaj_grd.py @@ -107,6 +107,14 @@ def load_oasis_montaj_grid(fname): order = "F" shape = (header["shape_e"], header["shape_v"]) spacing = (header["spacing_e"], header["spacing_v"]) + # Check that the number of elements matches the expected shape + expected_size = shape[0] * shape[1] + actual_size = grid.size + if actual_size != expected_size: + raise ValueError( + f"Grid data size mismatch: found {actual_size} elements, expected {expected_size} (shape {shape}). " + "The file may be corrupted or incomplete." + ) grid = grid.reshape(shape, order=order) # Build coords if header["rotation"] == 0: diff --git a/harmonica/tests/data/incomplete_grid.grd b/harmonica/tests/data/incomplete_grid.grd new file mode 100644 index 000000000..531ecc0e5 Binary files /dev/null and b/harmonica/tests/data/incomplete_grid.grd differ diff --git a/harmonica/tests/test_oasis.py b/harmonica/tests/test_oasis.py index b1193acfe..041ed87e7 100644 --- a/harmonica/tests/test_oasis.py +++ b/harmonica/tests/test_oasis.py @@ -107,3 +107,9 @@ def test_rotated_grid(self): npt.assert_allclose( grid.rotation, np.degrees(np.arctan((north - south) / (east - west))) ) + + +def test_incomplete_grid_raises_error(): + corrupted_file = "harmonica/tests/data/incomplete_grid.grd" + with pytest.raises(ValueError, match="Grid data size mismatch"): + load_oasis_montaj_grid(corrupted_file)