"""Utility functions for geometry.
"""
import numpy as np
import logging
logger = logging.getLogger('lavaflow')
# -----------------------------------------------------------------------------
# Geometry helpers
[docs]def roundPoint(p):
"""Function to round a point to the nearest integer.
Args:
p (tuple): point to round
Returns:
p (tuple): point with rounding applied
"""
return tuple([int(x) for x in p])
[docs]def distance(a, b):
"""Compute the distance between two points.
Args:
a (tuple): point 1
b (tuple): point 2
Returns:
dist (float): distance between two points
"""
return np.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
[docs]def line_proximity(p, a, b):
"""Compute the shortest distance between the point p and the line passing through two points (a - b)
Args:
p (tuple): point to compute proximity
a (tuple): line point 1
b (tuple): line point 2
Returns:
dist (float): the shortest distance
"""
p = np.array(p)
a = np.array(a)
b = np.array(b)
n = np.flip(a - b)
n[1] = -n[1]
s, t = np.linalg.solve(np.hstack([n.reshape(-1, 1), (a - b).reshape(-1, 1)]), (a - p).reshape(-1, 1)).flatten()
if t <= 0:
return np.linalg.norm(a - p)
elif 0 < t < 1:
return np.linalg.norm(s * n)
elif t >= 1:
return np.linalg.norm(b - p)