Skip to content

Commit

Permalink
MAINT: Raise TypeError with error inputting type (#705)
Browse files Browse the repository at this point in the history
* Raise type error while the type is not right

* Test type error

* test inputting None

* Add necessary importing

* use y-x instead of x-y

* copy it if input None

* test inputting None

* use s.index instead of other.index
  • Loading branch information
Zeroto521 committed Sep 9, 2022
1 parent b9654b8 commit 6dfe26f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
16 changes: 11 additions & 5 deletions dtoolkit/geoaccessor/geoseries/geodistance_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ def geodistance_matrix(
ValueError
If the CRS is not ``ESGP:4326``.
TypeError
If the other is not a GeoSeries, GeoDataFrame, or None type.
See Also
--------
sklearn.metrics.pairwise.haversine_distances
Expand All @@ -72,6 +75,7 @@ def geodistance_matrix(
Examples
--------
>>> import dtoolkit.geoaccessor
>>> import pandas as pd
>>> df = pd.DataFrame(
... {
... "x": [120, 122, 100],
Expand Down Expand Up @@ -104,17 +108,19 @@ def geodistance_matrix(
if s.crs != 4326:
raise ValueError(f"Only support 'EPSG:4326' CRS, but got {s.crs!r}.")

if isinstance(other, gpd.base.GeoPandasBase):
if other is None:
Y = None
elif isinstance(other, gpd.base.GeoPandasBase):
if other.crs != 4326:
raise ValueError(f"Only support 'EPSG:4326' CRS, but got {other.crs!r}.")

# Force convert to GeoSeries
other = other.geometry
Y = np.radians(np.stack((other.geometry.y, other.geometry.x), axis=1))
else:
raise TypeError(f"Unknown type: {type(other).__name__!r}.")

X = np.radians(np.stack((s.y, s.x), axis=1))
Y = np.radians(np.stack((other.y, other.x), axis=1)) if other is not None else other
return pd.DataFrame(
radius * haversine_distances(X, Y),
index=s.index,
columns=other.index,
columns=other.index if other is not None else s.index,
)
19 changes: 19 additions & 0 deletions test/geoaccessor/geoseries/test_geodistance_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@
gpd.GeoSeries([Point(120, 30), Point(122, 55), Point(100, 1)]),
ValueError,
),
(
gpd.GeoSeries([Point(120, 30), Point(110, 40)], crs=4326),
Point(1, 1),
TypeError,
),
(
gpd.GeoSeries([Point(120, 30), Point(110, 40)], crs=4326),
"string",
TypeError,
),
],
)
def test_error(s, other, error):
Expand All @@ -36,3 +46,12 @@ def test_geodataframe():
expected = pd.DataFrame([[0, 6.3275778074520295], [6.3275778074520295, 0]])

assert_frame_equal(result, expected)


def test_none():
s = gpd.GeoSeries([Point(122, 55), Point(100, 1)], crs=4326)

result = s.geodistance_matrix()
expected = pd.DataFrame([[0, 6327577.80745203], [6327577.80745203, 0]])

assert_frame_equal(result, expected)

0 comments on commit 6dfe26f

Please sign in to comment.