forked from OmkarPathak/pygorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathline2.py
More file actions
645 lines (471 loc) · 22.6 KB
/
line2.py
File metadata and controls
645 lines (471 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
"""
line2
Author: Timothy Moore
Defines a simple two-dimensional line segment
"""
import math
from pygorithm.geometry import (vector2, axisall)
class Line2(object):
"""
Define a two-dimensional directed line segment defined by two points.
This class is mostly used as a way to cache information that is
regularly required when working on geometrical problems.
.. caution::
Lines should be used as if they were completely immutable to ensure
correctness. All attributes of Line2 can be reconstructed from the two
points, and thus cannot be changed on their own and must be recalculated
if there were any changes to `start` or `end`.
.. tip::
To prevent unnecessary recalculations, many functions on lines accept an
'offset' argument, which is used to perform calculations on lines that
are simply shifts of other lines.
.. note::
The minimum x is guarranteed to be on either (or both) of
the start and end. However, minimum x and minimum y might not
come from the same point. The same is true for the maximum x
and maximum y.
:ivar start: the start of this line
:vartype start: :class:`pygorithm.geometry.vector2.Vector2`
:ivar end: the end of this line
:vartype end: :class:`pygorithm.geometry.vector2.Vector2`
"""
def __init__(self, start, end):
"""
Create a new line from start to end.
:param start: the start point
:type start: :class:`pygorithm.geometry.vector2.Vector2`
:param end: the end point
:type end: :class:`pygorithm.geometry.vector2.Vector2`
:raises ValueError: if start and end are at the same point
"""
if start.x == end.x and start.y == end.y:
raise ValueError('start and end are the same point')
self.start = start
self.end = end
self._delta = None
self._axis = None
self._normal = None
self._magnitude_squared = None
self._magnitude = None
self._min_x = None
self._min_y = None
self._max_x = None
self._max_y = None
self._slope = None
self._y_intercept = None
self._horizontal = None
self._vertical = None
@property
def delta(self):
"""
Get the vector from start to end, lazily initialized.
:returns: delta from start to end
:rtype: :class:`pygorithm.geometry.vector2.Vector2`
"""
if self._delta is None:
self._delta = self.end - self.start
return self._delta
@property
def axis(self):
"""
Get the normalized delta vector, lazily initialized
:returns: normalized delta
:rtype: :class:`pygorithm.geometry.vector2.Vector2`
"""
if self._axis is None:
self._axis = self.delta * (1 / self.magnitude)
return self._axis
@property
def normal(self):
"""
Get normalized normal vector to axis, lazily initialized.
Get the normalized normal vector such that the normal
vector is 90 degrees counter-clockwise from the axis.
:returns: normalized normal to axis
:rtype: :class:`pygorithm.geometry.vector2.Vector2`
"""
if self._normal is None:
self._normal = vector2.Vector2(-self.axis.y, self.axis.x)
return self._normal
@property
def magnitude_squared(self):
"""
Get the square of the magnitude of delta, lazily initialized.
:returns: square of magnitude of delta
:rtype: :class:`numbers.Number`
"""
if self._magnitude_squared is None:
self._magnitude_squared = self.delta.magnitude_squared()
return self._magnitude_squared
@property
def magnitude(self):
"""
Get the magnitude of delta, lazily initialized.
.. note::
It is substantially faster to operate on squared magnitude,
where possible.
:returns: magnitude of delta
:rtype: :class:`numbers.Number`
"""
if self._magnitude is None:
self._magnitude = math.sqrt(self.magnitude_squared)
return self._magnitude
@property
def min_x(self):
"""
Get the minimum x that this line contains, lazily initialized.
:returns: minimum x this line contains
:rtype: :class:`numbers.Number`
"""
if self._min_x is None:
self._min_x = min(self.start.x, self.end.x)
return self._min_x
@property
def min_y(self):
"""
Get the minimum y that this line contains, lazily initialized.
:returns: minimum x this line contains
:rtype: :class:`numbers.Number`
"""
if self._min_y is None:
self._min_y = min(self.start.y, self.end.y)
return self._min_y
@property
def max_x(self):
"""
Get the maximum x that this line contains, lazily initialized.
:returns: maximum x this line contains
:rtype: :class:`numbers.Number`
"""
if self._max_x is None:
self._max_x = max(self.start.x, self.end.x)
return self._max_x
@property
def max_y(self):
"""
Get the maximum y that this line contains, lazily initialized.
:returns: maximum x this line contains
:rtype: :class:`numbers.Number`
"""
if self._max_y is None:
self._max_y = max(self.start.y, self.end.y)
return self._max_y
@property
def slope(self):
"""
Get the slope of this line, lazily initialized.
.. caution::
The slope may be 0 (horizontal line) or positive or negative
infinity (vertical lines). It may be necessary to handle
these lines seperately, typically through checking the
:py:attr:`~pygorithm.geometry.line2.Line2.horizontal` and
:py:attr:`~pygorithm.geometry.line2.Line2.vertical` properties.
:returns: the slope of this line (rise over run).
:rtype: :class:`numbers.Number`
"""
if self._slope is None:
if self.delta.x == 0:
if self.delta.y > 0:
self._slope = float('+inf')
else:
self._slope = float('-inf')
else:
self._slope = self.delta.y / self.delta.x
return self._slope
@property
def y_intercept(self):
"""
Get the y-intercept of this line, lazily initialized.
This does not take into account any offset of the
line and may return None if this is a vertical line.
.. caution::
This function will return a y-intercept for non-vertical
line segments that do not reach ``x=0``.
.. caution::
The y-intercept will change based on the offset in a somewhat
complex manner.
:py:meth:`~pygorithm.geometry.line2.Line2.calculate_y_intercept`
accepts an offset parameter.
:returns: the y-intercept of this line when unshifted
:rtype: :class:`numbers.Number` or None
"""
if self.vertical:
return None
if self._y_intercept is None:
self._y_intercept = self.start.y - self.slope * self.start.x
return self._y_intercept
@property
def horizontal(self):
"""
Get if this line is horizontal, lazily initialized.
A line is horizontal if it has a slope of 0. This also
means that ``start.y == end.y``
:returns: if this line is horizontal
:rtype: bool
"""
if self._horizontal is None:
self._horizontal = self.delta.y == 0
return self._horizontal
@property
def vertical(self):
"""
Get if this line is vertical, lazily initialized.
A line is vertical if it has a slope of +inf or -inf. This
also means that ``start.x == end.x``.
:returns: if this line is vertical
:rtype: bool
"""
if self._vertical is None:
self._vertical = self.delta.x == 0
return self._vertical
def __repr__(self):
"""
Get an unambiguous representation of this line
Example:
.. code-block:: python
from pygorithm.geometry import (vector2, line2)
vec1 = vector2.Vector2(1, 1)
vec2 = vector2.Vector2(3, 4)
line = line2.Line2(vec1, vec2)
# prints line2(start=vector2(x=1, y=1), end=vector2(x=3, y=4))
print(repr(line))
:returns: unambiguous representation of this line
:rtype: string
"""
return "line2(start={}, end={})".format(repr(self.start), repr(self.end))
def __str__(self):
"""
Get a human-readable representation of this line
Example:
.. code-block:: python
from pygorithm.geometry import (vector2, line2)
vec1 = vector2.Vector2(1, 1)
vec2 = vector2.Vector2(3, 4)
line = line2.Line2(vec1, vec2)
# prints <1, 1> -> <3, 4>
print(str(line))
# same as above
print(line)
:returns: human-readable representation of this line
:rtype: string
"""
return "{} -> {}".format(self.start, self.end)
def calculate_y_intercept(self, offset):
"""
Calculate the y-intercept of this line when it is at the
specified offset.
If the offset is None this is exactly equivalent to y_intercept
:param offset: the offset of this line for this calculations
:type offset: :class:`pygorithm.geometry.vector2.Vector2` or None
:returns: the y-intercept of this line when at offset
:rtype: :class:`numbers.Number`
"""
if offset is None:
return self.y_intercept
if self.vertical:
return None
# y = mx + b -> b = y - mx
return self.start.y + offset.y - self.slope * (self.start.x + offset.x)
@staticmethod
def are_parallel(line1, line2):
"""
Determine if the two lines are parallel.
Two lines are parallel if they have the same or opposite slopes.
:param line1: the first line
:type line1: :class:`pygorithm.geometry.line2.Line2`
:param line2: the second line
:type line2: :class:`pygorithm.geometry.line2.Line2`
:returns: if the lines are parallel
:rtype: bool
"""
if line1.vertical and line2.vertical:
return True
return math.isclose(line1.slope, line2.slope)
@staticmethod
def contains_point(line, point, offset = None):
"""
Determine if the line contains the specified point.
Optionally, specify an offset for the line. Being
on the line is determined using `math.isclose`.
:param line: the line
:type line: :class:`pygorithm.geometry.line2.Line2`
:param point: the point
:type point: :class:`pygorithm.geometry.vector2.Vector2`
:param offset: the offset of the line or None for the origin
:type offset: :class:`pygorithm.geometry.vector2.Vector2` or None
:returns: if the point is on the line
:rtype: bool
"""
if line.vertical:
x = line.start.x + offset.x if offset is not None else line.start.x
if not math.isclose(point.x, x, abs_tol=1e-07):
return False
ymin = line.min_y + offset.y if offset is not None else line.min_y
ymax = line.max_y + offset.y if offset is not None else line.max_y
if math.isclose(point.y, ymin, abs_tol=1e-07) or math.isclose(point.y, ymax, abs_tol=1e-07):
return True
return point.y > ymin and point.y < ymax
xmin = line.min_x + offset.x if offset is not None else line.min_x
xmax = line.max_x + offset.x if offset is not None else line.max_x
if not (math.isclose(point.x, xmin, abs_tol=1e-07) or point.x > xmin):
return False
if not (math.isclose(point.x, xmax, abs_tol=1e-07) or point.x < xmax):
return False
ystart = line.start.y + offset.y if offset is not None else line.start.y
if line.horizontal:
return math.isclose(ystart, point.y, abs_tol=1e-07)
yint = line.calculate_y_intercept(offset)
yatx = line.slope * point.x + yint
return math.isclose(point.y, yatx, abs_tol=1e-07)
@staticmethod
def find_intersection(line1, line2, offset1 = None, offset2 = None):
"""
Find the intersection between the two lines.
The lines may optionally be offset by a fixed amount. This
will incur a minor performance penalty which is less than
that of recreating new lines.
Two lines are considered touching if they only share exactly
one point and that point is an edge of one of the lines.
If two lines are parallel, their intersection could be a line.
.. tip::
This will never return True, True
:param line1: the first line
:type line1: :class:`pygorithm.geometry.line2.Line2`
:param line2: the second line
:type line2: :class:`pygorithm.geometry.line2.Line2`
:param offset1: the offset of line 1
:type offset1: :class:`pygorithm.geometry.vector2.Vector2` or None
:param offset2: the offset of line 2
:type offset2: :class:`pygorithm.geometry.vector2.Vector2` or None
:returns: (touching, overlapping, intersection_location)
:rtype: (bool, bool, :class:`pygorithm.geometry.line2.Line2` or :class:`pygorithm.geometry.vector2.Vector2` or None)
"""
# We will ensure that:
# - If one line is vertical and one horizontal, line1 is the vertical line
# - If only one line is vertical, line1 is the vertical line
# - If only one line is horizontal, line1 is the horizontal line
if line2.vertical and not line1.vertical:
return Line2.find_intersection(line2, line1, offset2, offset1)
if line2.horizontal and not line1.horizontal and not line1.vertical:
return Line2.find_intersection(line2, line1, offset2, offset1)
l1_st_x = line1.start.x + (offset1.x if offset1 is not None else 0)
l1_st_y = line1.start.y + (offset1.y if offset1 is not None else 0)
l1_en_x = line1.end.x + (offset1.x if offset1 is not None else 0)
l1_en_y = line1.end.y + (offset1.y if offset1 is not None else 0)
l2_st_x = line2.start.x + (offset2.x if offset2 is not None else 0)
l2_st_y = line2.start.y + (offset2.y if offset2 is not None else 0)
l2_en_x = line2.end.x + (offset2.x if offset2 is not None else 0)
l2_en_y = line2.end.y + (offset2.y if offset2 is not None else 0)
if line1.vertical and line2.vertical:
# Two vertical lines
if not math.isclose(l1_st_x, l2_st_x):
return False, False, None
aal1 = axisall.AxisAlignedLine(None, l1_st_y, l1_en_y)
aal2 = axisall.AxisAlignedLine(None, l2_st_y, l2_en_y)
touch, mtv = axisall.AxisAlignedLine.find_intersection(aal1, aal2)
if not touch:
return False, False, None
elif mtv[0] is None:
return True, False, vector2.Vector2(l1_st_x, mtv[1])
else:
return False, True, Line2(vector2.Vector2(l1_st_x, mtv[1]), vector2.Vector2(l1_st_x, mtv[2]))
if line1.horizontal and line2.horizontal:
# Two horizontal lines
if not math.isclose(l1_st_y, l2_st_y):
return False, False, None
aal1 = axisall.AxisAlignedLine(None, l1_st_x, l1_en_x)
aal2 = axisall.AxisAlignedLine(None, l2_st_x, l2_st_y)
touch, mtv = axisall.AxisAlignedLine.find_intersection(aal1, aal2)
if not touch:
return False, False, None
elif mtv[0] is None:
return True, False, vector2.Vector2(mtv[1], l1_st_y)
else:
return False, True, Line2(vector2.Vector2(mtv[1], l1_st_x), vector2.Vector2(mtv[2], l1_st_y))
if Line2.are_parallel(line1, line2):
# Two non-vertical, non-horizontal, parallel lines
yintr1 = line1.calculate_y_intercept(offset1)
yintr2 = line2.calculate_y_intercept(offset2)
if not math.isclose(yintr1, yintr2):
return False, False, None
axis = line1.axis
aal1 = axisall.AxisAlignedLine(axis, l1_st_x * axis.x + l1_st_y * axis.y, l1_en_x * axis.x + l1_en_y * axis.y)
aal2 = axisall.AxisAlignedLine(axis, l2_st_x * axis.x + l2_st_y * axis.y, l2_en_x * axis.x + l2_en_y * axis.y)
touch, mtv = axisall.AxisAlignedLine.find_intersection(aal1, aal2)
def unshift_vec(vec):
numerator = line1.slope * vec.x - yintr1 * axis.x * axis.x
denominator = axis.x * axis.y + line1.slope * axis.y * axis.y
new_x = numerator / denominator
new_y = line1.slope * new_x + yintr1
return vector2.Vector2(new_x, new_y)
if not touch:
return False, False, None
elif mtv[0] is None:
return True, False, unshift_vec(axis * mtv[1])
else:
return False, True, Line2(unshift_vec(axis * mtv[1]), unshift_vec(axis * mtv[2]))
if line1.vertical and line2.horizontal:
# A vertical and horizontal line
l1_min = min(l1_st_y, l1_en_y) if offset1 is not None else line1.min_y
l1_max = max(l1_st_y, l1_en_y) if offset1 is not None else line1.max_y
if l2_st_y < l1_min or l2_st_y > l2_max:
return False, False, None
l2_min = min(l2_st_x, l2_en_x) if offset2 is not None else line2.min_x
l2_max = max(l2_st_x, l2_en_x) if offset2 is not None else line2.max_x
if l1_st_x < l2_min or l1_st_x > l2_max:
return False, False, None
pt = vector2.Vector2(l1_st_x, l2_st_y)
if math.isclose(l2_st_y, l1_min) or math.isclose(l2_st_y, l2_max) or math.isclose(l1_st_x, l2_min) or math.isclose(l2_st_y, l2_max):
return True, False, pt
else:
return False, True, pt
if line1.vertical:
# A vertical and non-horizontal, non-vertical line
line2_y_at_line1_x = line2.slope * l1_st_x + line2.calculate_y_intercept(offset2)
l1_min = min(l1_st_y, l1_en_y) if offset1 is not None else line1.min_y
l1_max = max(l1_st_y, l1_en_y) if offset1 is not None else line1.max_y
if math.isclose(line2_y_at_line1_x, l1_min) or math.isclose(line2_y_at_line1_x, l1_max):
return True, False, vector2.Vector2(l1_st_x, line2_y_at_line1_x)
elif line2_y_at_line1_x < l1_min or line2_y_at_line1_x > l2_max:
return False, False, None
else:
return False, True, vector2.Vector2(l1_st_x, line2_y_at_line1_x)
if line1.horizontal:
# A horizontal and non-vertical, non-horizontal line
# y = mx + b -> x = (y - b) / m
line2_x_at_line1_y = (l1_st_y - line2.calculate_y_intercept(offset2)) / line2.slope
l1_min = min(l1_st_x, l1_en_x) if offset1 is not None else line1.min_x
l1_max = max(l1_st_x, l1_en_x) if offset1 is not None else line1.max_x
if math.isclose(line2_x_at_line1_y, l1_min) or math.isclose(line2_x_at_line1_y, l1_max):
return True, False, vector2.Vector2(line2_x_at_line1_y, l1_st_y)
elif line2_x_at_line1_y < l1_min or line2_x_at_line1_y > l1_max:
return False, False, None
else:
return False, True, vector2.Vector2(line2_x_at_line1_y, l1_st_y)
# Two non-vertical, non-horizontal, non-parallel lines
# y = m1 x + b1
# y = m2 x + b2
# m1 x + b1 = m2 x + b2
# m1 x - m2 x = b2 - b1
# x = (b2 - b1) / (m1 - m2)
yintr1 = line1.calculate_y_intercept(offset1)
yintr2 = line2.calculate_y_intercept(offset2)
intr_x = (yintr2 - yintr1) / (line1.slope - line2.slope)
# Some caution needs to be taken here to ensure we do approximately before range
# checks. It's possible for _approx(a, b) to be True and a < b to be True
on_edge1 = math.isclose(intr_x, l1_st_x) or math.isclose(intr_x, l1_en_x)
on_edge2 = math.isclose(intr_x, l2_st_x) or math.isclose(intr_x, l2_en_x)
if on_edge1 and on_edge2:
intr_y = line1.slope * intr_x + yintr1
return True, False, vector2.Vector2(intr_x, intr_y)
l1_min_x = min(l1_st_x, l1_en_x) if offset1 is not None else line1.min_x
l1_max_x = max(l1_st_x, l1_en_x) if offset1 is not None else line1.max_x
l2_min_x = min(l2_st_x, l2_en_x) if offset2 is not None else line2.min_x
l2_max_x = max(l2_st_x, l2_en_x) if offset2 is not None else line2.max_x
on_line1 = on_edge1 or (intr_x > l1_min_x and intr_x < l1_max_x)
on_line2 = on_edge2 or (intr_x > l2_min_x and intr_x < l2_max_x)
if on_line1 and on_line2:
intr_y = line1.slope * intr_x + yintr1
is_edge = on_edge1 or on_edge2
return is_edge, not is_edge, vector2.Vector2(intr_x, intr_y)
return False, False, None