From 03001717467d73b83dcf7f7ec9fece9ca90cfb86 Mon Sep 17 00:00:00 2001 From: Abdulmalik Alquwayfili Date: Thu, 8 Oct 2026 13:20:56 +0300 Subject: [PATCH 1/2] Fix integer overflow in geographic distance features --- feature_engine/creation/geo_features.py | 10 +++++--- tests/test_creation/test_geo_features.py | 32 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/feature_engine/creation/geo_features.py b/feature_engine/creation/geo_features.py index 57b54da60..a275face1 100644 --- a/feature_engine/creation/geo_features.py +++ b/feature_engine/creation/geo_features.py @@ -407,8 +407,9 @@ def _euclidean_distance( # Simple Euclidean distance (approximate, best for short distances) # Convert to approximate km then to requested unit - dlat = lat2 - lat1 - dlon = lon2 - lon1 + # Promote before subtraction to avoid overflow with integer coordinates. + dlat = np.subtract(lat2, lat1, dtype=np.float64) + dlon = np.subtract(lon2, lon1, dtype=np.float64) # Approximate degrees to km (at equator) km_per_degree = 111.0 @@ -427,8 +428,9 @@ def _manhattan_distance( ) -> np.ndarray: """Calculate Manhattan (taxicab) distance in coordinate space.""" - dlat = np.abs(lat2 - lat1) - dlon = np.abs(lon2 - lon1) + # Keep both the differences and their sum out of the integer dtype. + dlat = np.abs(np.subtract(lat2, lat1, dtype=np.float64)) + dlon = np.abs(np.subtract(lon2, lon1, dtype=np.float64)) # Approximate degrees to km (at equator) km_per_degree = 111.0 diff --git a/tests/test_creation/test_geo_features.py b/tests/test_creation/test_geo_features.py index f137e4ef1..8b5d8977a 100644 --- a/tests/test_creation/test_geo_features.py +++ b/tests/test_creation/test_geo_features.py @@ -123,6 +123,38 @@ def test_manhattan_method(make_df): ) +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +@pytest.mark.parametrize("method", ["euclidean", "manhattan"]) +@pytest.mark.parametrize( + "dtype, coordinates, deltas", + [ + (nw.UInt8, [1, 2, 0, 1], [1, 1]), + (nw.Int8, [-80, -120, 80, 120], [160, 240]), + (nw.Int8, [0, 0, 80, 80], [80, 80]), + (nw.Float64, [1, 2, 0, 1], [1, 1]), + ], +) +def test_distance_does_not_overflow(make_df, method, dtype, coordinates, deltas): + """Integer coordinates give the same distance in both directions.""" + lat1, lon1, lat2, lon2 = coordinates + data = { + "lat1": [lat1, lat2], + "lon1": [lon1, lon2], + "lat2": [lat2, lat1], + "lon2": [lon2, lon1], + } + X = nw.from_native(make_df(data)).with_columns(nw.all().cast(dtype)).to_native() + transformer = GeoDistanceFeatures( + lat1="lat1", lon1="lon1", lat2="lat2", lon2="lon2", method=method + ) + + X_tr = transformer.fit_transform(X) + + distance = np.hypot(*deltas) if method == "euclidean" else sum(deltas) + assert isinstance(X_tr, make_df) + assert_df_equal(X_tr, {**data, "geo_distance": [distance * 111.0] * 2}) + + @pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) def test_custom_output_column_name(make_df): """Test custom output column name.""" From 0ee0afad6ef64f17787d0899ef99235d9d02944f Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Sun, 29 Nov 2026 11:43:43 +0100 Subject: [PATCH 2/2] Cast coordinates to float64 once, fix range checks on int minimums Converting the coordinates to float64 in transform fixes the overflow for all methods, and haversine no longer computes in float16 or float32 with small integer dtypes. The range checks compare against both bounds, since np.abs overflows on the minimum of signed integer dtypes. Co-Authored-By: Claude Opus 5.5 --- feature_engine/creation/geo_features.py | 22 ++++++---- tests/test_creation/test_geo_features.py | 54 ++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/feature_engine/creation/geo_features.py b/feature_engine/creation/geo_features.py index a275face1..7fb7a90a9 100644 --- a/feature_engine/creation/geo_features.py +++ b/feature_engine/creation/geo_features.py @@ -311,13 +311,14 @@ def _validate_coordinate_ranges( """Raise if any latitude/longitude value falls outside its valid range.""" lat_cols = [self.lat1, self.lat2] for lat_col, values in zip(lat_cols, to_numpy(X, lat_cols)): - if (np.abs(values) > 90).any(): + # np.abs overflows on the minimum of signed integer dtypes. + if ((values < -90) | (values > 90)).any(): raise ValueError( f"Latitude values in '{lat_col}' must be between -90 and 90." ) lon_cols = [self.lon1, self.lon2] for lon_col, values in zip(lon_cols, to_numpy(X, lon_cols)): - if (np.abs(values) > 180).any(): + if ((values < -180) | (values > 180)).any(): raise ValueError( f"Longitude values in '{lon_col}' must be between -180 and 180." ) @@ -350,7 +351,12 @@ def transform(self, X: IntoDataFrame) -> IntoDataFrame: # reorder variables to match train set X = subset_df(X, self.feature_names_in_) - lat1, lon1, lat2, lon2 = to_numpy(X, self.variables_) + # Small integer dtypes overflow when subtracted and become float16 in + # trigonometric functions. + lat1, lon1, lat2, lon2 = [ + np.asarray(values, dtype=np.float64) + for values in to_numpy(X, self.variables_) + ] # Calculate distance based on method if self.method == "haversine": @@ -407,9 +413,8 @@ def _euclidean_distance( # Simple Euclidean distance (approximate, best for short distances) # Convert to approximate km then to requested unit - # Promote before subtraction to avoid overflow with integer coordinates. - dlat = np.subtract(lat2, lat1, dtype=np.float64) - dlon = np.subtract(lon2, lon1, dtype=np.float64) + dlat = lat2 - lat1 + dlon = lon2 - lon1 # Approximate degrees to km (at equator) km_per_degree = 111.0 @@ -428,9 +433,8 @@ def _manhattan_distance( ) -> np.ndarray: """Calculate Manhattan (taxicab) distance in coordinate space.""" - # Keep both the differences and their sum out of the integer dtype. - dlat = np.abs(np.subtract(lat2, lat1, dtype=np.float64)) - dlon = np.abs(np.subtract(lon2, lon1, dtype=np.float64)) + dlat = np.abs(lat2 - lat1) + dlon = np.abs(lon2 - lon1) # Approximate degrees to km (at equator) km_per_degree = 111.0 diff --git a/tests/test_creation/test_geo_features.py b/tests/test_creation/test_geo_features.py index 8b5d8977a..ae01d0793 100644 --- a/tests/test_creation/test_geo_features.py +++ b/tests/test_creation/test_geo_features.py @@ -1,3 +1,5 @@ +import re + import narwhals as nw import numpy as np import pandas as pd @@ -155,6 +157,26 @@ def test_distance_does_not_overflow(make_df, method, dtype, coordinates, deltas) assert_df_equal(X_tr, {**data, "geo_distance": [distance * 111.0] * 2}) +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +@pytest.mark.parametrize("method", ["haversine", "euclidean", "manhattan"]) +@pytest.mark.parametrize("dtype", [nw.Int8, nw.UInt8, nw.Int16]) +def test_integer_coordinates_match_float_coordinates(make_df, method, dtype): + """Small integer dtypes give the same float64 distances as float coordinates.""" + data = {"lat1": [40, 10], "lon1": [74, 20], "lat2": [34, 11], "lon2": [118, 21]} + X = make_df(data) + X_int = nw.from_native(X).with_columns(nw.all().cast(dtype)).to_native() + X_float = nw.from_native(X).with_columns(nw.all().cast(nw.Float64)).to_native() + transformer = GeoDistanceFeatures( + lat1="lat1", lon1="lon1", lat2="lat2", lon2="lon2", method=method + ) + + distance = nw.from_native(transformer.fit_transform(X_int))["geo_distance"] + expected = nw.from_native(transformer.fit_transform(X_float))["geo_distance"] + + assert distance.dtype == nw.Float64 + assert distance.to_list() == pytest.approx(expected.to_list(), rel=1e-12) + + @pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) def test_custom_output_column_name(make_df): """Test custom output column name.""" @@ -284,6 +306,38 @@ def test_invalid_longitude_range_raises_error(make_df, invalid_lon): transformer.fit(X) +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +@pytest.mark.parametrize( + "column, dtype, value, msg", + [ + ( + "lat1", + nw.Int8, + -128, + "Latitude values in 'lat1' must be between -90 and 90.", + ), + ( + "lon1", + nw.Int16, + -32768, + "Longitude values in 'lon1' must be between -180 and 180.", + ), + ], +) +def test_invalid_range_at_integer_minimum_raises_error( + make_df, column, dtype, value, msg +): + """The minimum of a signed integer dtype is out of range, despite np.abs.""" + data = {"lat1": [0], "lon1": [0], "lat2": [0], "lon2": [0]} + data[column] = [value] + X = nw.from_native(make_df(data)).with_columns(nw.all().cast(dtype)).to_native() + transformer = GeoDistanceFeatures( + lat1="lat1", lon1="lon1", lat2="lat2", lon2="lon2" + ) + with pytest.raises(ValueError, match=re.escape(msg)): + transformer.fit(X) + + @pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) def test_validate_ranges_disabled(make_df): """Test that invalid coordinates don't raise error when validate_ranges=False."""