forked from rai-opensource/spatialmath-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeom2d.py
More file actions
executable file
·634 lines (477 loc) · 16.7 KB
/
geom2d.py
File metadata and controls
executable file
·634 lines (477 loc) · 16.7 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 09:42:30 2020
@author: corkep
"""
from functools import reduce
from spatialmath.base.graphics import axes_logic
from spatialmath import base, SE2
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.transforms import Affine2D
from matplotlib.collections import PatchCollection
import numpy as np
class Polygon2:
"""
Class to represent 2D (planar) polygons
.. note:: Uses Matplotlib primitives to perform transformations and
intersections.
"""
def __init__(self, vertices=None):
"""
Create planar polygon from vertices
:param vertices: vertices of polygon, defaults to None
:type vertices: ndarray(2, N), optional
Create a polygon from a set of points provided as columns of the 2D
array ``vertices``.
A closed polygon is created so the last vertex should not equal the
first.
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
.. warning:: The points must be sequential around the perimeter and
counter clockwise.
.. note:: The polygon is represented by a Matplotlib ``Path``
"""
if isinstance(vertices, (list, tuple)):
vertices = np.array(vertices).T
elif isinstance(vertices, np.ndarray):
if vertices.shape[0] != 2:
raise ValueError('ndarray must be 2xN')
elif vertices is None:
return
else:
raise TypeError('expecting list of 2-tuples or ndarray(2,N)')
# replicate the first vertex to make it closed.
# setting closed=False and codes=None leads to a different
# path which gives incorrect intersection results
vertices = np.hstack((vertices, vertices[:, 0:1]))
self.path = Path(vertices.T, closed=True)
self.path0 = self.path
def __str__(self):
"""
Polygon to string
:return: brief summary of polygon
:rtype: str
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> print(p)
"""
return f"Polygon2 with {len(self.path)} vertices"
def __len__(self):
"""
Number of vertices in polygon
:return: number of vertices
:rtype: int
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> len(p)
"""
return len(self.path)
def plot(self, ax=None, **kwargs):
"""
Plot polygon
:param ax: axes in which to draw the polygon, defaults to None
:type ax: Axes, optional
:param kwargs: options passed to Matplotlib ``Patch``
A Matplotlib Patch is created with the passed options ``**kwargs`` and
added to the axes.
:seealso: :meth:`animate` :func:`matplotlib.PathPatch`
"""
self.patch = PathPatch(self.path, **kwargs)
ax = base.axes_logic(ax, 2)
ax.add_patch(self.patch)
plt.draw()
self.kwargs = kwargs
self.ax = ax
def animate(self, T, **kwargs):
"""
Animate a polygon
:param T: new pose of Polygon
:type T: SE2
:param kwargs: options passed to Matplotlib ``Patch``
The plotted polygon is moved to the pose given by ``T``. The pose is
always with respect to the initial vertices when the polygon was
constructed. The vertices of the polygon will be updated to reflect
what is plotted.
If the polygon has already plotted, it will keep the same graphical
attributes. If new attributes are given they will replace those
given at construction time.
:seealso: :meth:`plot`
"""
# get the path
if self.patch is not None:
self.patch.remove()
self.path = self.path0.transformed(Affine2D(T.A))
if len(kwargs) > 0:
self.args = kwargs
self.patch = PathPatch(self.path, **self.kwargs)
self.ax.add_patch(self.patch)
def contains(self, p, radius=0.0):
"""
Test if point is inside polygon
:param p: point
:type p: array_like(2)
:param radius: Add an additional margin to the polygon boundary, defaults to 0.0
:type radius: float, optional
:return: True if point is contained by polygon
:rtype: bool
``radius`` can be used to inflate the polygon, or if negative, to
deflated it.
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.contains([0, 0])
>>> p.contains([2, 3])
.. warning:: Returns True if the point is on the edge of the polygon
but False if the point is one of the vertices.
.. warning:: For a polygon with clockwise ordering of vertices the
sign of ``radius`` is flipped.
:seealso: :func:`matplotlib.contains_point`
"""
# note the sign of radius is negated if the polygon is drawn clockwise
# https://stackoverflow.com/questions/45957229/matplotlib-path-contains-points-radius-parameter-defined-inconsistently
# edges are included but the corners are not
if isinstance(p, (list, tuple)) or (isinstance(p, np.ndarray) and p.ndim == 1):
return self.path.contains_point(tuple(p), radius=radius)
else:
return self.path.contains_points(p.T, radius=radius)
def bbox(self):
"""
Bounding box of polygon
:return: bounding box as [xmin, xmax, ymin, ymax]
:rtype: ndarray(4)
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.bbox()
"""
return np.array(self.path.get_extents()).ravel(order='F')
def radius(self):
"""
Radius of smallest enclosing circle
:return: radius
:rtype: float
This is the radius of the smalleset circle, centred at the centroid,
that encloses all vertices.
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.radius()
"""
c = self.centroid()
dmax = -np.inf
for vertex in self.path.vertices:
d = np.linalg.norm(vertex - c)
if d > dmax:
dmax = d
return d
def intersects(self, other):
"""
Test for intersection
:param other: object to test for intersection
:type other: Polygon2 or Line2
:return: True if the polygon intersects ``other``
:rtype: bool
"""
if isinstance(other, Polygon2):
# polygon-polygon intersection is done by matplotlib
return self.path.intersects_path(other.path, filled=True)
elif isinstance(other, Line2):
# polygon-line intersection
for p1, p2 in self.segments():
# test each edge segment against the line
if other.intersect_segment(p1, p2):
return True
return False
elif isinstance(other, (list, tuple)):
for polygon in other:
if self.path.intersects_path(polygon.path, filled=True):
return True
return False
def transformed(self, T):
"""
A transformed copy of polygon
:param T: planar transformation
:type T: SE2
:return: transformed polygon
:rtype: Polygon2
Returns a new polgyon whose vertices have been transformed by ``T``.
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2, SE2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.vertices()
>>> p.transformed(SE2(10, 0, 0)).vertices() # shift by x+10
"""
new = Polygon2()
new.path = self.path.transformed(Affine2D(T.A))
return new
def area(self):
"""
Area of polygon
:return: area
:rtype: float
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.area()
.. warning:: For a polygon with clockwise ordering of vertices the
area will be negative.
:seealso: :meth:`moment`
"""
return self.moment(0, 0)
def centroid(self):
"""
Centroid of polygon
:return: centroid
:rtype: ndarray(2)
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.centroid()
:seealso: :meth:`moment`
"""
return np.r_[self.moment(1, 0), self.moment(0, 1)] / self.moment(0, 0)
def vertices(self, closed=False):
"""
Vertices of polygon
:param closed: include first vertex twice, defaults to False
:type closed: bool, optional
:return: vertices
:rtype: ndarray(2,n)
Returns the set of vertices. If ``closed`` is True then the last
column is the same as the first, that is, the polygon is explicitly
closed.
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.vertices()
>>> p.vertices(closed=True)
"""
if closed:
vertices = self.path.vertices
vertices = np.vstack([vertices, vertices[0, :]])
return vertices.T
else:
return self.path.vertices.T
def edges(self):
"""
Iterate over polygon edge segments
Creates an iterator that returns pairs of points representing the
end points of each segment.
"""
vertices = self.vertices(closed=True)
for i in range(len(self)):
yield(vertices[:, i], vertices[:, i+1])
def moment(self, p, q):
r"""
Moments of polygon
:param p: moment order x
:type p: int
:param q: moment order y
:type q: int
Returns the pq'th moment of the polygon
.. math::
M(p, q) = \sum_{i=0}^{n-1} x_i^p y_i^q
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.moment(0, 0) # area
>>> p.moment(3, 0)
"""
def combin(n, r):
# compute number of combinations of size r from set n
def prod(values):
try:
return reduce(lambda x, y: x * y, values)
except TypeError:
return 1
return prod(range(n - r + 1, n + 1)) / prod(range(1, r + 1))
vertices = self.vertices(closed=True)
x = vertices[0, :]
y = vertices[1, :]
m = 0.0
n = len(x)
for l in range(n):
l1 = (l - 1) % n
dxl = x[l] - x[l1]
dyl = y[l] - y[l1]
Al = x[l] * dyl - y[l] * dxl
s = 0.0
for i in range(p + 1):
for j in range(q + 1):
s += (-1)**(i + j) \
* combin(p, i) \
* combin(q, j) / ( i+ j + 1) \
* x[l]**(p - i) * y[l]**(q - j) \
* dxl**i * dyl**j
m += Al * s
return m / (p + q + 2)
class Line2:
"""
Class to represent 2D lines
The internal representation is in homogeneous format
.. math::
ax + by + c = 0
"""
def __init__(self, line):
self.line = base.getvector(line, 3)
@classmethod
def TwoPoints(self, p1, p2):
"""
Create 2D line from two points
:param p1: point on the line
:type p1: array_like(2) or array_like(3)
:param p2: another point on the line
:type p2: array_like(2) or array_like(3)
The points can be given in Euclidean or homogeneous form.
"""
p1 = base.getvector(p1)
if len(p1) == 2:
p1 = np.r_[p1, 1]
p2 = base.getvector(p2)
if len(p2) == 2:
p2 = np.r_[p2, 1]
return Line2(np.cross(p1, p2))
@classmethod
def General(self, m, c):
"""
Create line from general line
:param m: line gradient
:type m: float
:param c: line intercept
:type c: float
:return: a 2D line
:rtype: a Line2 instance
Creates a line from the parameters of the general line :math:`y = mx + c`.
.. note:: A vertical line cannot be represented.
"""
return Line2([m, -1, c])
def general(self):
r"""
Parameters of general line
:return: parameters of general line (m, c)
:rtype: ndarray(2)
Return the parameters of a general line :math:`y = mx + c`.
"""
return -self.line[[0, 2]] / self.line[1]
def __str__(self):
return f"Line2: {self.line}"
def plot(self, **kwargs):
"""
Plot the line using matplotlib
:param kwargs: arguments passed to Matplotlib ``pyplot.plot``
"""
base.plot_homline(self.line, **kwargs)
def intersect(self, other):
"""
Intersection with line
:param other: another 2D line
:type other: Line2
:return: intersection point in homogeneous form
:rtype: ndarray(3)
If the lines are parallel then the third element of the returned
homogeneous point will be zero (an ideal point).
"""
# return intersection of 2 lines
# return mindist and points if no intersect
return np.cross(self.line, other.line)
def contains(self, p):
"""
Test if point is in line
:param p1: point to test
:type p1: array_like(2) or array_like(3)
:return: True if point lies in the line
:rtype: bool
"""
p = base.getvector(p)
if len(p) == 2:
p = np.r_[p, 1]
return base.iszero(self.line * p)
# variant that gives lambda
def intersect_segment(self, p1, p2):
"""
Test for line intersecting line segment
:param p1: start of line segment
:type p1: array_like(2) or array_like(3)
:param p2: end of line segment
:type p2: array_like(2) or array_like(3)
:return: True if they intersect
:rtype: bool
Tests whether the line intersects the line segment defined by endpoints
``p1`` and ``p2`` which are given in Euclidean or homogeneous form.
"""
p1 = base.getvector(p1)
if len(p1) == 2:
p1 = np.r_[p1, 1]
p2 = base.getvector(p2)
if len(p2) == 2:
p2 = np.r_[p2, 1]
z1 = self.line * p1
z2 = self.line * p2
if np.sign(z1) != np.sign(z2):
return True
if self.contains(p1) or self.contains(p2):
return True
return False
# these should have same names as for 3d case
def distance_line_line():
pass
def distance_line_point():
pass
def points_join():
pass
def intersect_polygon___line():
pass
def contains_polygon_point():
pass
class LineSegment2(Line2):
# line segment class that subclass
# has hom line + 2 values of lambda
pass
if __name__ == "__main__":
p = Polygon2([[1, 3, 2], [2, 2, 4]])
p.transformed(SE2(0, 0, np.pi/2)).vertices()
a = Line2.TwoPoints((1,2), (7,5))
print(a)
p = Polygon2(np.array([[4, 4, 6, 6], [2, 1, 1, 2]]))
base.plotvol2([8])
p.plot(color='b', alpha=0.3)
for theta in np.linspace(0, 2*np.pi, 100):
p.animate(SE2(0, 0, theta))
plt.show()
plt.pause(0.05)
# print(p)
# p.plot(alpha=0.5, color='b')
# print(p.contains([5.,5.]))
# print(p.contains([5,1.5]))
# print(p.contains([4, 2.1]))
# print(p.vertices())
# print(p.area())
# print(p.centroid())
# print(p.bbox())
# print(p.radius())
# print(p.vertices(closed=True))
# for e in p.edges():
# print(e)
# p2 = p.transformed(SE2(-5, -1.5, 0))
# print(p2.vertices())
# print(p2.area())
# p2.plot(alpha=0.5, facecolor='r')
# p.move(SE2(0, 0, 0.7))
# plt.show(block=True)