Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize LineCollection #206

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 30 additions & 56 deletions src/data_morph/shapes/bases/line_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ class LineCollection(Shape):
"""

def __init__(self, *lines: Iterable[Iterable[Number]]) -> None:
self.lines = lines
# check that lines that have the same starting and ending points raise an error
for line in lines:
start, end = line
if np.allclose(start, end):
raise ValueError(f'Line {line} has the same start and end point')
self.lines = np.array(lines)
"""Iterable[Iterable[numbers.Number]]: An iterable
of two (x, y) pairs representing the endpoints of a line."""

Expand All @@ -45,66 +50,35 @@ def distance(self, x: Number, y: Number) -> float:
float
The minimum distance from the lines of this shape to the
point (x, y).
"""
return min(
self._distance_point_to_line(point=(x, y), line=line) for line in self.lines
)

def _distance_point_to_line(
self,
point: Iterable[Number],
line: Iterable[Iterable[Number]],
) -> float:
"""
Calculate the minimum distance between a point and a line.

Parameters
----------
point : Iterable[numbers.Number]
Coordinates of a point in 2D space.
line : Iterable[Iterable[numbers.Number]]
Coordinates of the endpoints of a line in 2D space.

Returns
-------
float
The minimum distance between the point and the line.

Notes
-----
Implementation based on `this VBA code`_.
Implementation based on `this Stack Overflow answer`_.

.. _this VBA code: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
.. _this Stack Overflow answer: https://stackoverflow.com/a/58781995
"""
start, end = np.array(line)
line_mag = self._euclidean_distance(start, end)
point = np.array(point)

if line_mag < 0.00000001:
# Arbitrarily large value
return 9999

px, py = point
x1, y1 = start
x2, y2 = end

u1 = ((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))
u = u1 / (line_mag * line_mag)

if (u < 0.00001) or (u > 1):
# closest point does not fall within the line segment, take the shorter
# distance to an endpoint
distance = min(
self._euclidean_distance(point, start),
self._euclidean_distance(point, end),
)
else:
# Intersecting point is on the line, use the formula
ix = x1 + u * (x2 - x1)
iy = y1 + u * (y2 - y1)
distance = self._euclidean_distance(point, np.array((ix, iy)))

return distance
p = np.array([x, y])
stefmolin marked this conversation as resolved.
Show resolved Hide resolved

a = self.lines[:, 0, :]
b = self.lines[:, 1, :]

d_ba = b - a
d = np.divide(d_ba, (np.hypot(d_ba[:, 0], d_ba[:, 1]).reshape(-1, 1)))

# signed parallel distance components
# rowwise dot products of 2D vectors
s = np.multiply(a - p, d).sum(axis=1)
t = np.multiply(p - b, d).sum(axis=1)

# clamped parallel distance
h = np.maximum.reduce([s, t, np.zeros(len(s))])

# perpendicular distance component
# rowwise cross products of 2D vectors
d_pa = p - a
c = d_pa[:, 0] * d[:, 1] - d_pa[:, 1] * d[:, 0]
stefmolin marked this conversation as resolved.
Show resolved Hide resolved

return np.min(np.hypot(h, c))

@plot_with_custom_style
def plot(self, ax: Axes = None) -> Axes:
Expand Down
29 changes: 13 additions & 16 deletions tests/shapes/bases/test_line_collection.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Test line_collection module."""

import itertools
import re

import pytest

Expand Down Expand Up @@ -35,21 +34,19 @@ def test_distance_nonzero(self, line_collection, point, expected_distance):
assert pytest.approx(line_collection.distance(*point)) == expected_distance

@pytest.mark.parametrize('line', [[(0, 0), (0, 0)], [(-1, -1), (-1, -1)]], ids=str)
def test_distance_to_small_line_magnitude(self, line_collection, line):
"""Test _distance_point_to_line() for small line magnitudes."""
distance = line_collection._distance_point_to_line((30, 50), line)
assert distance == 9999
def test_line_as_point(self, line):
"""Test LineCollection raises a ValueError for small line magnitudes."""
with pytest.raises(ValueError):
LineCollection(line)

def test_repr(self, line_collection):
"""Test that the __repr__() method is working."""
lines = r'\n '.join(
[r'\[\[\d+\.*\d*, \d+\.*\d*\], \[\d+\.*\d*, \d+\.*\d*\]\]']
* len(line_collection.lines)
)
assert (
re.match(
(r'^<LineCollection>\n lines=\n ' + lines),
repr(line_collection),
)
is not None
)
lines = r"""<LineCollection>
lines=
array([[0., 0.],
[0., 1.]])
array([[1., 0.],
[1., 1.]])
array([[10.5, 11.5],
[11. , 10. ]])"""
assert repr(line_collection) == lines
JCGoran marked this conversation as resolved.
Show resolved Hide resolved
Loading