# Compute the distance from a point to polygon given the point and direction

I want to compute the distance from a point to a polygon given the point and direction. Currently I am using shapely and defining a "somewhat" infinite line string. This is not ideal as I can't actually create an infinite line string due to there being a maximum limit on the floating point value. Here I just use 10e10 to represent a really long line. Is there a better way to do this?

``````        def distance_between_point_and_polygon(point, polygon, direction)
"""
Args:
point: (1x2) numpy array/torch tensor
polygon: (Nx2) numpy array/torch tensor
direction: (1x2) numpy array/torch tensor
"""
polygon_shapely_linestring = LineString(polygon)

# Create infinite line string based on point and direction.
inf_line_string = LineString([point, point + direction * 10e10])

# Compute the intersecting points between the infinite line and the polygon
intersecting_points = polygon_shapely_linestring.intersection(inf_line_string)

# If there are multiple intersections, take the first one as that is the first point of intersection
# between the ray and the polygon and this is the point needed to compute the distance to the polygon
if isinstance(intersecting_points, Point):
intersecting_point = intersecting_points
elif isinstance(intersecting_points, MultiPoint):
intersecting_point = intersecting_points[0]
else:
# raise some error as there is no intersection

# Compute the distance from the point to the first intersection with the polygon
distance = LineString([point, intersecting_point]).length

return distance
``````

For example this is what I expect:

``````    polygon = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], dtype=torch.float64)

points = torch.tensor([[0.0, 0.0], [-1.0, -1.0], [-4.0, 0.0], [0.5, 0.5]], dtype=torch.float64)
directions = torch.tensor([[1.0, 1.0], [1.0, 1.0], [0.0, 1.0], [0.5, 0.5]], dtype=torch.float64)

print(distance_between_point_and_polygon(point, polygon, direction))
>>> torch.tensor([0.0, 1.4142135382, torch.nan, 0.7071067811], dtype=torch.float64)
``````