Skip to content

Commit

Permalink
Use iloc in nearest - STRTree returns array index
Browse files Browse the repository at this point in the history
Closes #49
  • Loading branch information
tomalrussell committed Nov 13, 2023
1 parent c6d3190 commit a26a02e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/snkit/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,7 @@ def nearest(geom: Geometry, gdf: GeoDataFrame) -> "pandas.Series[Any]":
"""Find the element of a GeoDataFrame nearest a shapely geometry"""
try:
match_idx = gdf.sindex.nearest(geom, return_all=False)[1][0]
nearest_geom: "pandas.Series[Any]" = gdf.loc[match_idx]
nearest_geom: "pandas.Series[Any]" = gdf.iloc[match_idx]
return nearest_geom

except TypeError:
Expand Down
28 changes: 28 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -846,3 +846,31 @@ def test_matching_gdf_from_geoms(edge_only):
gdf["b"] = "abc"
actual = snkit.network.matching_gdf_from_geoms(gdf, geoms)
assert_frame_equal(actual, expected)


def test_nearest():
a = Point((0, 0))
b = Point((0, 2))
c = Point((0, 1))
d = Point((1, 1))
ab = LineString([a, b])
cd = LineString([c, d])
gdf = GeoDataFrame(geometry=[ab, cd])

# default RangeIndex
actual = snkit.network.nearest(Point(0.1, -0.1), gdf)
assert actual.geometry == LineString([Point(0, 0), Point(0, 2)])

# set integer index, not running from 0..n
gdf["edge_id"] = [1, 4]
gdf.set_index("edge_id", inplace=True)
actual = snkit.network.nearest(Point(1.0, 0.9), gdf)
assert actual.name == 4
assert actual.geometry == LineString([Point(0, 1), Point(1, 1)])

# set a non-integer index
gdf["edge_id"] = ["ab", "cd"]
gdf.set_index("edge_id", inplace=True)
actual = snkit.network.nearest(Point(1.1, 1.1), gdf)
assert actual.name == "cd"
assert actual.geometry == LineString([Point(0, 1), Point(1, 1)])

0 comments on commit a26a02e

Please sign in to comment.