Skip to content

Commit

Permalink
Implement, test find_intersection helper
Browse files Browse the repository at this point in the history
  • Loading branch information
mmore500 committed Dec 10, 2023
1 parent e9d7f4e commit c45788d
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/outset/_auxlib/find_intersection_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import math
import typing


def find_intersection(
p1: typing.Tuple[float, float],
p2: typing.Tuple[float, float],
p3: typing.Tuple[float, float],
p4: typing.Tuple[float, float],
) -> typing.Tuple[float, float]:
"""Finds the intersection of two lines (p1 to p2 and p3 to p4).
Points are represented a tuple of (x, y).
Returns
-------
Tuple[float, float]
The intersection point, (x, y).
If lines do not intersect or are underspecified, result is (nan, nan).
"""

# Unpack points
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
x4, y4 = p4

denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if denominator == 0:
return (math.nan, math.nan)

# adapted from https://stackoverflow.com/a/51127674
px = (
(x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)
) / denominator
py = (
(x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)
) / denominator

return (px, py)
26 changes: 26 additions & 0 deletions tests/test_auxlib/test_find_intersection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import math

from outset._auxlib.find_intersection_ import find_intersection


def test_intersection_typical():
# Test a typical case where two lines intersect
assert find_intersection((0, 0), (1, 1), (0, 1), (1, 0)) == (0.5, 0.5)


def test_intersection_parallel():
# Test a case where two lines are parallel and don't intersect
assert math.isnan(find_intersection((0, 0), (1, 1), (0, 1), (1, 2))[0])
assert math.isnan(find_intersection((0, 0), (1, 1), (0, 1), (1, 2))[1])


def test_intersection_collinear():
# Test a case where two lines are collinear
assert math.isnan(find_intersection((0, 0), (1, 1), (2, 2), (3, 3))[0])
assert math.isnan(find_intersection((0, 0), (1, 1), (2, 2), (3, 3))[1])


def test_intersection_points_underspecified():
# Test a case where lines are underspecified (e.g., points are identical)
assert math.isnan(find_intersection((0, 0), (0, 0), (1, 1), (1, 1))[0])
assert math.isnan(find_intersection((0, 0), (0, 0), (1, 1), (1, 1))[1])

0 comments on commit c45788d

Please sign in to comment.