Skip to content

Instantly share code, notes, and snippets.

@surajRathi
Created January 16, 2022 05:57
Show Gist options
  • Save surajRathi/f98439330bcc16efe90db1b41afcf57e to your computer and use it in GitHub Desktop.
Save surajRathi/f98439330bcc16efe90db1b41afcf57e to your computer and use it in GitHub Desktop.
Helper class for dealing with points and line segments
import numpy as np
# https://www.desmos.com/calculator/acagoky1yo
Point2 = np.ndarray # np.ndarray[2,]
def dist(p1: Point2, p2: Point2):
return np.linalg.norm(p2 - p1)
class LineSegment:
def __init__(self, p1: Point2, p2: Point2):
# Line segment from `p1` to `p2`
self.p1 = p1
self.p2 = p2
self.v = p2 - p1 # Direction Vector
factor = np.linalg.norm(self.v)
if factor == 0:
raise ValueError("Cannot make line segment from two coincident points.")
self.v /= factor
self.L = self.horiz_dist(self.p2) # Length of the segment
def perp_dist(self, p: Point2): # Rename -> perp_dist
# Perpendicular distance of `p` from the line
return np.cross(self.v, p - self.p1)
def horiz_dist(self, p: Point2):
# Distance from `p1` to the projection of `p` onto the line
return np.dot(self.v, p - self.p1)
def parametric(self, horiz_dist: float):
# The point `horiz_dist` away from `p1` on the line
return self.p1 + self.v * horiz_dist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment