-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathgraphics.py
1801 lines (1490 loc) · 61.5 KB
/
graphics.py
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
from itertools import product
import warnings
import numpy as np
from matplotlib import colors
from spatialmath import base as smb
from spatialmath.base.types import *
# To assist code portability to headless platforms, these graphics primitives
# are defined as null functions.
"""
Set of functions to draw 2D and 3D graphical primitives using matplotlib.
The 2D functions all allow color and line style to be specified by a fmt string
like, 'r' or 'b--'.
The 3D functions require explicity arguments to set properties, like color='b'
All return a list of the graphic objects they create.
"""
try:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from mpl_toolkits.mplot3d.art3d import (
Poly3DCollection,
Line3DCollection,
pathpatch_2d_to_3d,
)
from mpl_toolkits.mplot3d import Axes3D
# TODO
# return a redrawer object, that can be used for animation
# =========================== 2D shapes =================================== #
def plot_text(
pos: ArrayLike2,
text: str,
ax: Optional[plt.Axes] = None,
color: Optional[Color] = None,
**kwargs,
) -> List[plt.Artist]:
"""
Plot text using matplotlib
:param pos: position of text
:type pos: array_like(2)
:param text: text
:type text: str
:param ax: axes to draw in, defaults to ``gca()``
:type ax: Axis, optional
:param color: text color, defaults to None
:type color: str or array_like(3), optional
:param kwargs: additional arguments passed to ``pyplot.text()``
:return: the matplotlib object
:rtype: list of Text instance
Example::
>>> from spatialmath.base import plotvol2, plot_text
>>> plotvol2(5)
>>> plot_text((1,3), 'foo')
>>> plot_text((2,2), 'bar', color='b')
>>> plot_text((2,2), 'baz', fontsize=14, horizontalalignment='centre')
.. plot::
from spatialmath.base import plotvol2, plot_text
ax = plotvol2(5)
plot_text((0,0), 'foo')
plot_text((1,1), 'bar', color='b')
plot_text((2,2), 'baz', fontsize=14, horizontalalignment='center')
ax.grid()
:seealso: :func:`plot_point`
"""
defaults = {"horizontalalignment": "left", "verticalalignment": "center"}
for k, v in defaults.items():
if k not in kwargs:
kwargs[k] = v
if ax is None:
ax = plt.gca()
handle = ax.text(pos[0], pos[1], text, color=color, **kwargs)
return [handle]
def plot_point(
pos: ArrayLike2,
marker: Optional[str] = "bs",
text: Optional[str] = None,
ax: Optional[plt.Axes] = None,
textargs: Optional[dict] = None,
textcolor: Optional[Color] = None,
**kwargs,
) -> List[plt.Artist]:
"""
Plot a point using matplotlib
:param pos: position of marker
:type pos: array_like(2), ndarray(2,n), list of 2-tuples
:param marker: matplotlub marker style, defaults to 'bs'
:type marker: str or list of str, optional
:param text: text label, defaults to None
:type text: str, optional
:param ax: axes to plot in, defaults to ``gca()``
:type ax: Axis, optional
:return: the matplotlib object
:rtype: list of Text and Line2D instances
Plot one or more points, with optional text label.
- The color of the marker can be different to the color of the text, the
marker color is specified by a single letter in the marker string.
- A point can have multiple markers, given as a list, which will be
overlaid, for instance ``["rx", "ro"]`` will give a ⨂ symbol.
- The optional text label is placed to the right of the marker, and
vertically aligned.
- Multiple points can be marked if ``pos`` is a 2xn array or a list of
coordinate pairs. In this case:
- all points have the same ``text`` label
- ``text`` can include the format string {} which is susbstituted for the
point index, starting at zero
- ``text`` can be a tuple containing a format string followed by vectors
of shape(n). For example::
``("#{0} a={1:.1f}, b={2:.1f}", a, b)``
will label each point with its index (argument 0) and consecutive
elements of ``a`` and ``b`` which are arguments 1 and 2 respectively.
Example::
>>> from spatialmath.base import plotvol2, plot_text
>>> plotvol2(5)
>>> plot_point((0, 0)) # plot default marker at coordinate (1,2)
>>> plot_point((1,1), 'r*') # plot red star at coordinate (1,2)
>>> plot_point((2,2), 'r*', 'foo') # plot red star at coordinate (1,2) and
label it as 'foo'
.. plot::
from spatialmath.base import plotvol2, plot_text
ax = plotvol2(5)
plot_point((0, 0))
plot_point((1,1), 'r*')
plot_point((2,2), 'r*', 'foo')
ax.grid()
Plot red star at points defined by columns of ``p`` and label them sequentially
from 0::
>>> p = np.random.uniform(size=(2,10), low=-5, high=5)
>>> plotvol2(5)
>>> plot_point(p, 'r*', '{0}')
.. plot::
from spatialmath.base import plotvol2, plot_point
import numpy as np
p = np.random.uniform(size=(2,10), low=-5, high=5)
ax = plotvol2(5)
plot_point(p, 'r*', '{0}')
ax.grid()
Plot red star at points defined by columns of ``p`` and label them all with
successive elements of ``z``
>>> p = np.random.uniform(size=(2,10), low=-5, high=5)
>>> value = np.random.uniform(size=(1,10))
>>> plotvol2(5)
>>> plot_point(p, 'r*', ('{1:.2f}', value))
.. plot::
from spatialmath.base import plotvol2, plot_point
import numpy as np
p = np.random.uniform(size=(2,10), low=-5, high=5)
value = np.random.uniform(size=(10,))
ax = plotvol2(5)
plot_point(p, 'r*', ('{1:.2f}', value))
ax.grid()
:seealso: :func:`plot_text`
"""
defaults = {"horizontalalignment": "left", "verticalalignment": "center"}
if isinstance(pos, np.ndarray):
if pos.ndim == 1:
x = pos[0]
y = pos[1]
elif pos.ndim == 2 and pos.shape[0] == 2:
x = pos[0, :]
y = pos[1, :]
elif isinstance(pos, (tuple, list)):
# [x, y]
# [(x,y), (x,y), ...]
# [xlist, ylist]
# [xarray, yarray]
if smb.islistof(pos, (tuple, list)):
x = [z[0] for z in pos]
y = [z[1] for z in pos]
elif smb.islistof(pos, np.ndarray):
x = pos[0]
y = pos[1]
else:
x = pos[0]
y = pos[1]
textopts = {
"fontsize": 12,
"horizontalalignment": "left",
"verticalalignment": "center",
}
if textargs is not None:
textopts = {**textopts, **textargs}
if textcolor is not None and "color" not in textopts:
textopts["color"] = textcolor
if ax is None:
ax = plt.gca()
handles = []
if isinstance(marker, (list, tuple)):
for m in marker:
handles.append(ax.plot(x, y, m, **kwargs))
else:
handles.append(ax.plot(x, y, marker, **kwargs))
if text is not None:
try:
xy = zip(x, y)
except TypeError:
xy = [(x, y)]
if isinstance(text, str):
# simple string, but might have format chars
for i, (x, y) in enumerate(xy):
handles.append(ax.text(x, y, " " + text.format(i), **textopts))
elif isinstance(text, (tuple, list)):
(
fmt,
*values,
) = text # unpack (fmt, values...) values is iterable, one per point
for i, (x, y) in enumerate(xy):
handles.append(
ax.text(
x,
y,
" " + fmt.format(i, *[d[i] for d in values]),
**textopts,
)
)
return handles
def plot_homline(
lines: Union[ArrayLike3, NDArray],
*args,
ax: Optional[plt.Axes] = None,
xlim: Optional[ArrayLike2] = None,
ylim: Optional[ArrayLike2] = None,
**kwargs,
) -> List[plt.Artist]:
r"""
Plot homogeneous lines using matplotlib
:param lines: homgeneous line or lines
:type lines: array_like(3), ndarray(3,N)
:param ax: axes to plot in, defaults to ``gca()``
:type ax: Axis, optional
:param kwargs: arguments passed to ``plot``
:return: matplotlib object
:rtype: list of Line2D instances
Draws the 2D line given in homogeneous form :math:`\ell[0] x + \ell[1] y + \ell[2] = 0` in the current
2D axes.
.. warning: A set of 2D axes must exist in order that the axis limits can
be obtained. The line is drawn from edge to edge.
If ``lines`` is a 3xN array then ``N`` lines are drawn, one per column.
Example::
>>> from spatialmath.base import plotvol2, plot_homline
>>> plotvol2(5)
>>> plot_homline((1, -2, 3))
>>> plot_homline((1, -2, 3), 'k--') # dashed black line
.. plot::
from spatialmath.base import plotvol2, plot_homline
ax = plotvol2(5)
plot_homline((1, -2, 3))
plot_homline((1, -2, 3), 'k--') # dashed black line
ax.grid()
:seealso: :func:`plot_arrow`
"""
ax = axes_logic(ax, 2)
# get plot limits from current graph
if xlim is None:
xlim = np.r_[ax.get_xlim()]
if ylim is None:
ylim = np.r_[ax.get_ylim()]
# if lines.ndim == 1:
# lines = lines.
lines = smb.getmatrix(lines, (3, None))
handles = []
for line in lines.T: # for each column
if abs(line[1]) > abs(line[0]):
y = (-line[2] - line[0] * xlim) / line[1]
ax.plot(xlim, y, *args, **kwargs)
else:
x = (-line[2] - line[1] * ylim) / line[0]
handles.append(ax.plot(x, ylim, *args, **kwargs))
return handles
def plot_box(
*fmt: Optional[str],
lbrt: Optional[ArrayLike4] = None,
lrbt: Optional[ArrayLike4] = None,
lbwh: Optional[ArrayLike4] = None,
bbox: Optional[ArrayLike4] = None,
ltrb: Optional[ArrayLike4] = None,
lb: Optional[ArrayLike2] = None,
lt: Optional[ArrayLike2] = None,
rb: Optional[ArrayLike2] = None,
rt: Optional[ArrayLike2] = None,
wh: Optional[ArrayLike2] = None,
centre: Optional[ArrayLike2] = None,
w: Optional[float] = None,
h: Optional[float] = None,
ax: Optional[plt.Axes] = None,
filled: bool = False,
**kwargs,
) -> List[plt.Artist]:
"""
Plot a 2D box using matplotlib
:param lb: left-bottom corner, defaults to None
:type lb: array_like(2), optional
:param lt: left-top corner, defaults to None
:type lt: array_like(2), optional
:param rb: right-bottom corner, defaults to None
:type rb: array_like(2), optional
:param rt: right-top corner, defaults to None
:type rt: array_like(2), optional
:param wh: width and height, if both are the same provide scalar, defaults to None
:type wh: scalar, array_like(2), optional
:param centre: centre of box, defaults to None
:type centre: array_like(2), optional
:param w: width of box, defaults to None
:type w: float, optional
:param h: height of box, defaults to None
:type h: float, optional
:param ax: the axes to draw on, defaults to ``gca()``
:type ax: Axis, optional
:param bbox: bounding box matrix, defaults to None
:type bbox: array_like(4), optional
:param color: box outline color
:type color: array_like(3) or str
:param fillcolor: box fill color
:type fillcolor: array_like(3) or str
:param alpha: transparency, defaults to 1
:type alpha: float, optional
:param thickness: line thickness, defaults to None
:type thickness: float, optional
:return: the matplotlib object
:rtype: Patch.Rectangle instance
The box can be specified in many ways:
- bounding box [xmin, xmax, ymin, ymax]
- alternative box [xmin, ymin, xmax, ymax]
- centre and width+height
- left-bottom and right-top corners
- left-bottom corner and width+height
- right-top corner and width+height
- left-top corner and width+height
For plots where the y-axis is inverted (eg. for images) then top is the
smaller vertical coordinate.
Example::
>>> plotvol2(5)
>>> plot_box("b--", centre=(2, 3), wh=1) # w=h=1
>>> plot_box(lt=(0, 0), rb=(3, -2), filled=True, color="r")
.. plot::
from spatialmath.base import plotvol2, plot_box
ax = plotvol2(5)
plot_box("b--", centre=(2, 3), wh=1) # w=h=1
plot_box(lt=(0, 0), rb=(3, -2), filled=True, hatch="/", edgecolor="k", color="r")
ax.grid()
"""
if wh is not None:
if smb.isscalar(wh):
w, h = wh, wh
else:
w, h = wh
# test for various 4-coordinate versions
if bbox is not None:
lb = bbox[:2]
w, h = bbox[2:]
elif lbwh is not None:
lb = lbwh[:2]
w, h = lbwh[2:]
elif lbrt is not None:
lb = lbrt[:2]
rt = lbrt[2:]
w, h = rt[0] - lb[0], rt[1] - lb[1]
elif lrbt is not None:
lb = (lrbt[0], lrbt[2])
rt = (lrbt[1], lrbt[3])
w, h = rt[0] - lb[0], rt[1] - lb[1]
elif ltrb is not None:
lb = (ltrb[0], ltrb[3])
rt = (ltrb[2], ltrb[1])
w, h = rt[0] - lb[0], rt[1] - lb[1]
elif w is not None and h is not None:
# we have width & height, one corner is enough
if centre is not None:
lb = (centre[0] - w / 2, centre[1] - h / 2)
elif lt is not None:
lb = (lt[0], lt[1] - h)
elif rt is not None:
lb = (rt[0] - w, rt[1] - h)
elif rb is not None:
lb = (rb[0] - w, rb[1])
else:
# we need two opposite corners
if lb is not None and rt is not None:
w = rt[0] - lb[0]
h = rt[1] - lb[1]
elif lt is not None and rb is not None:
lb = (lt[0], rb[1])
w = rb[0] - lt[0]
h = lt[1] - rb[1]
else:
raise ValueError("cant compute box")
if w < 0:
raise ValueError("width must be positive")
if h < 0:
raise ValueError("height must be positive")
# we only need lb, wh
ax = axes_logic(ax, 2)
if filled:
r = plt.Rectangle(lb, w, h, fill=True, clip_on=True, **kwargs)
else:
ec = None
ls = ""
if len(fmt) > 0:
colors = "rgbcmywk"
for f in fmt[0]:
if f in colors:
ec = f
else:
ls += f
if ls == "":
ls = None
if "color" in kwargs:
ec = kwargs["color"]
del kwargs["color"]
r = plt.Rectangle(
lb, w, h, clip_on=True, linestyle=ls, edgecolor=ec, fill=False, **kwargs
)
ax.add_patch(r)
return r
def plot_arrow(
start: ArrayLike2,
end: ArrayLike2,
label: Optional[str] = None,
label_pos: str = "above:0.5",
ax: Optional[plt.Axes] = None,
**kwargs,
) -> List[plt.Artist]:
r"""
Plot 2D arrow
:param start: start point, arrow tail
:type start: array_like(2)
:param end: end point, arrow head
:type end: array_like(2)
:param label: arrow label text, optional
:type label: str
:param label_pos: position of arrow label "above|below:fraction", optional
:type label_pos: str
:param ax: axes to draw into, defaults to None
:type ax: Axes, optional
:param kwargs: argumetns to pass to :class:`matplotlib.patches.Arrow`
Draws an arrow from ``start`` to ``end``.
A ``label``, if given, is drawn above or below the arrow. The position of the
label is controlled by ``label_pos`` which is of the form
``"position:fraction"`` where ``position`` is either ``"above"`` or ``"below"``
the arrow, and ``fraction`` is a float between 0 (tail) and 1 (head) indicating
the distance along the arrow where the label will be placed. The text is
suitably justified to not overlap the arrow.
Example::
>>> from spatialmath.base import plotvol2, plot_arrow
>>> plotvol2(5)
>>> plot_arrow((-2, 2), (2, 4), color='r', width=0.1) # red arrow
>>> plot_arrow((4, 1), (2, 4), color='b', width=0.1) # blue arrow
.. plot::
from spatialmath.base import plotvol2, plot_arrow
ax = plotvol2(5)
plot_arrow((-2, 2), (3, 4), color='r', width=0.1) # red arrow
plot_arrow((4, 1), (3, 4), color='b', width=0.1) # blue arrow
ax.grid()
Example::
>>> from spatialmath.base import plotvol2, plot_arrow
>>> plotvol2(5)
>>> plot_arrow((-2, -2), (2, 4), label=r"$\mathit{p}_3$", color='r', width=0.1)
.. plot::
from spatialmath.base import plotvol2, plot_arrow
ax = plotvol2(5)
ax.grid()
plot_arrow(
(-2, -2), (2, 4), label="$\mathit{p}_3$", color="r", width=0.1
)
plt.show(block=True)
:seealso: :func:`plot_homline`
"""
ax = axes_logic(ax, 2)
dx = end[0] - start[0]
dy = end[1] - start[1]
ax.arrow(
start[0],
start[1],
dx,
dy,
length_includes_head=True,
**kwargs,
)
if label is not None:
# add a label
label_pos = label_pos.split(":")
if label_pos[0] == "below":
above = False
try:
fraction = float(label_pos[1])
except:
fraction = 0.5
theta = np.arctan2(dy, dx)
quadrant = theta // (np.pi / 2)
pos = [start[0] + fraction * dx, start[1] + fraction * dy]
if quadrant in (0, 2):
# quadrants 1 and 3, line is sloping up to right or down to left
opt = {"verticalalignment": "bottom", "horizontalalignment": "right"}
label = label + " "
else:
# quadrants 2 and 4, line is sloping up to left or down to right
opt = {"verticalalignment": "top", "horizontalalignment": "left"}
label = " " + label
ax.text(*pos, label, **opt)
def plot_polygon(
vertices: NDArray, *fmt, close: Optional[bool] = False, **kwargs
) -> List[plt.Artist]:
"""
Plot polygon
:param vertices: vertices
:type vertices: ndarray(2,N)
:param close: close the polygon, defaults to False
:type close: bool, optional
:param kwargs: arguments passed to Patch
:return: Matplotlib artist
:rtype: line or patch
Example::
>>> from spatialmath.base import plotvol2, plot_polygon
>>> plotvol2(5)
>>> vertices = np.array([[-1, 2, -1], [1, 0, -1]])
>>> plot_polygon(vertices, filled=True, facecolor='g') # green filled triangle
.. plot::
from spatialmath.base import plotvol2, plot_polygon
ax = plotvol2(5)
vertices = np.array([[-1, 2, -1], [1, 0, -1]])
plot_polygon(vertices, filled=True, facecolor='g') # green filled triangle
ax.grid()
"""
if close:
vertices = np.hstack((vertices, vertices[:, [0]]))
return _render2D(vertices, fmt=fmt, **kwargs)
def _render2D(
vertices: NDArray,
pose=None,
filled: Optional[bool] = False,
color: Optional[Color] = None,
ax: Optional[plt.Axes] = None,
fmt: Optional[Callable] = None,
**kwargs,
) -> List[plt.Artist]:
ax = axes_logic(ax, 2)
if pose is not None:
vertices = pose * vertices
if filled:
if color is not None:
kwargs["facecolor"] = color
kwargs["edgecolor"] = color
r = plt.Polygon(vertices.T, closed=True, **kwargs)
ax.add_patch(r)
else:
if color is not None:
kwargs["color"] = color
r = plt.plot(vertices[0, :], vertices[1, :], *fmt, **kwargs)
return r
def circle(
centre: ArrayLike2 = (0, 0),
radius: float = 1,
resolution: int = 50,
closed: bool = False,
) -> Points2:
"""
Points on a circle
:param centre: centre of circle, defaults to (0, 0)
:type centre: array_like(2), optional
:param radius: radius of circle, defaults to 1
:type radius: float, optional
:param resolution: number of points on circumferece, defaults to 50
:type resolution: int, optional
:param closed: perimeter is closed, last point == first point, defaults to False
:type closed: bool
:return: points on circumference
:rtype: ndarray(2,N) or ndarray(3,N)
Returns a set of ``resolution`` that lie on the circumference of a circle
of given ``center`` and ``radius``.
If ``len(centre)==3`` then the 3D coordinates are returned, where the
circle lies in the xy-plane and the z-coordinate comes from ``centre[2]``.
.. note:: By default returns a unit circle centred at the origin.
"""
if closed:
resolution += 1
u = np.linspace(0.0, 2.0 * np.pi, resolution, endpoint=closed)
x = radius * np.cos(u) + centre[0]
y = radius * np.sin(u) + centre[1]
if len(centre) == 3:
z = np.full(x.shape, centre[2])
return np.array((x, y, z))
else:
return np.array((x, y))
def plot_circle(
radius: float,
centre: ArrayLike2,
*fmt: Optional[str],
resolution: Optional[int] = 50,
ax: Optional[plt.Axes] = None,
filled: Optional[bool] = False,
**kwargs,
) -> List[plt.Artist]:
"""
Plot a circle using matplotlib
:param centre: centre of circle, defaults to (0,0)
:type centre: array_like(2), optional
:param args:
:param radius: radius of circle
:type radius: float
:param resolution: number of points on circumference, defaults to 50
:type resolution: int, optional
:return: the matplotlib object
:rtype: list of Line2D or Patch.Polygon
Plot or more circles. If ``centre`` is a 3xN array, then each column is
taken as the centre of a circle. All circles have the same radius, color
etc.
Example::
>>> from spatialmath.base import plotvol2, plot_circle
>>> plotvol2(5)
>>> plot_circle(1, (0,0), 'r') # red circle
>>> plot_circle(2, (1, 2), 'b--') # blue dashed circle
>>> plot_circle(0.5, (3,4), filled=True, facecolor='y') # yellow filled circle
.. plot::
from spatialmath.base import plotvol2, plot_circle
ax = plotvol2(5)
plot_circle(1, (0,0), 'r') # red circle
plot_circle(2, (1, 2), 'b--') # blue dashed circle
plot_circle(0.5, (3,4), filled=True, facecolor='y') # yellow filled circle
ax.grid()
"""
centres = smb.getmatrix(centre, (2, None))
ax = axes_logic(ax, 2)
handles = []
for centre in centres.T:
xy = circle(centre, radius, resolution, closed=not filled)
if filled:
patch = plt.Polygon(xy.T, **kwargs)
handles.append(ax.add_patch(patch))
else:
handles.append(ax.plot(xy[0, :], xy[1, :], *fmt, **kwargs))
return handles
def ellipse(
E: R2x2,
centre: Optional[ArrayLike2] = (0, 0),
scale: Optional[float] = 1,
confidence: Optional[float] = None,
resolution: Optional[int] = 40,
inverted: Optional[bool] = False,
closed: Optional[bool] = False,
) -> Points2:
r"""
Points on ellipse
:param E: ellipse
:type E: ndarray(2,2)
:param centre: ellipse centre, defaults to (0,0,0)
:type centre: tuple, optional
:param scale: scale factor for the ellipse radii
:type scale: float
:param confidence: if E is an inverse covariance matrix plot an ellipse
for this confidence interval in the range [0,1], defaults to None
:type confidence: float, optional
:param resolution: number of points on circumferance, defaults to 40
:type resolution: int, optional
:param inverted: if :math:`\mat{E}^{-1}` is provided, defaults to False
:type inverted: bool, optional
:param closed: perimeter is closed, last point == first point, defaults to False
:type closed: bool
:raises ValueError: [description]
:return: points on circumference
:rtype: ndarray(2,N)
The ellipse is defined by :math:`x^T \mat{E} x = s^2` where :math:`x \in
\mathbb{R}^2` and :math:`s` is the scale factor.
.. note:: For some common cases we require :math:`\mat{E}^{-1}`, for example
- for robot manipulability
:math:`\nu (\mat{J} \mat{J}^T)^{-1} \nu` i
- a covariance matrix
:math:`(x - \mu)^T \mat{P}^{-1} (x - \mu)`
so to avoid inverting ``E`` twice to compute the ellipse, we flag that
the inverse is provided using ``inverted``.
"""
from scipy.linalg import sqrtm
if E.shape != (2, 2):
raise ValueError("ellipse is defined by a 2x2 matrix")
if confidence:
from scipy.stats.distributions import chi2
# process the probability
s = math.sqrt(chi2.ppf(confidence, df=2)) * scale
else:
s = scale
xy = circle(resolution=resolution, closed=closed) # unit circle
if not inverted:
E = np.linalg.inv(E)
e = s * sqrtm(E) @ xy + np.array(centre, ndmin=2).T
return e
def plot_ellipse(
E: R2x2,
centre: ArrayLike2,
*fmt: Optional[str],
scale: Optional[float] = 1,
confidence: Optional[float] = None,
resolution: Optional[int] = 40,
inverted: Optional[bool] = False,
ax: Optional[plt.Axes] = None,
filled: Optional[bool] = False,
**kwargs,
) -> List[plt.Artist]:
r"""
Plot an ellipse using matplotlib
:param E: matrix describing ellipse
:type E: ndarray(2,2)
:param centre: centre of ellipse, defaults to (0, 0)
:type centre: array_like(2), optional
:param scale: scale factor for the ellipse radii
:type scale: float
:param resolution: number of points on circumferece, defaults to 40
:type resolution: int, optional
:return: the matplotlib object
:rtype: Line2D or Patch.Polygon
The ellipse is defined by :math:`x^T \mat{E} x = s^2` where :math:`x \in
\mathbb{R}^2` and :math:`s` is the scale factor.
.. note:: For some common cases we require :math:`\mat{E}^{-1}`, for example
- for robot manipulability
:math:`\nu (\mat{J} \mat{J}^T)^{-1} \nu` i
- a covariance matrix
:math:`(x - \mu)^T \mat{P}^{-1} (x - \mu)`
so to avoid inverting ``E`` twice to compute the ellipse, we flag that
the inverse is provided using ``inverted``.
Returns a set of ``resolution`` that lie on the circumference of a circle
of given ``center`` and ``radius``.
Example:
>>> from spatialmath.base import plotvol2, plot_ellipse
>>> plotvol2(5)
>>> plot_ellipse(np.array([[1, 1], [1, 2]]), [0,0], 'r') # red ellipse
>>> plot_ellipse(np.array([[1, 1], [1, 2]]), [1, 2], 'b--') # blue dashed ellipse
>>> plot_ellipse(np.array([[1, 1], [1, 2]]), [-2, -1], filled=True, facecolor='y') # yellow filled ellipse
.. plot::
from spatialmath.base import plotvol2, plot_ellipse
ax = plotvol2(5)
plot_ellipse(np.array([[1, 1], [1, 2]]), [0,0], 'r') # red ellipse
plot_ellipse(np.array([[1, 1], [1, 2]]), [1, 2], 'b--') # blue dashed ellipse
plot_ellipse(np.array([[1, 1], [1, 2]]), [-2, -1], filled=True, facecolor='y') # yellow filled ellipse
ax.grid()
"""
# allow for centre[2] to plot ellipse in a plane in a 3D plot
xy = ellipse(E, centre, scale, confidence, resolution, inverted, closed=True)
ax = axes_logic(ax, 2)
if filled:
patch = plt.Polygon(xy.T, **kwargs)
ax.add_patch(patch)
else:
plt.plot(xy[0, :], xy[1, :], *fmt, **kwargs)
# =========================== 3D shapes =================================== #
def sphere(
radius: Optional[float] = 1,
centre: Optional[ArrayLike2] = (0, 0, 0),
resolution: Optional[int] = 50,
) -> Tuple[NDArray, NDArray, NDArray]:
"""
Points on a sphere
:param centre: centre of sphere, defaults to (0, 0, 0)
:type centre: array_like(3), optional
:param radius: radius of sphere, defaults to 1
:type radius: float, optional
:param resolution: number of points ``N`` on circumferece, defaults to 50
:type resolution: int, optional
:return: X, Y and Z braid matrices
:rtype: 3 x ndarray(N, N)
.. note:: By default returns a unit sphere centred at the origin.
:seealso: :func:`plot_sphere`, :func:`~matplotlib.pyplot.plot_surface`, :func:`~matplotlib.pyplot.plot_wireframe`
"""
theta_range = np.linspace(0, np.pi, resolution)
phi_range = np.linspace(-np.pi, np.pi, resolution)
Phi, Theta = np.meshgrid(phi_range, theta_range)
x = radius * np.sin(Theta) * np.cos(Phi) + centre[0]
y = radius * np.sin(Theta) * np.sin(Phi) + centre[1]
z = radius * np.cos(Theta) + centre[2]
return (x, y, z)
def plot_sphere(
radius: float,
centre: Optional[ArrayLike3] = (0, 0, 0),
pose: Optional[SE3Array] = None,
resolution: Optional[int] = 50,
ax: Optional[plt.Axes] = None,
**kwargs,
) -> List[plt.Artist]:
"""
Plot a sphere using matplotlib
:param centre: centre of sphere, defaults to (0, 0, 0)
:type centre: array_like(3), ndarray(3,N), optional
:param radius: radius of sphere, defaults to 1
:type radius: float, optional
:param resolution: number of points on circumferece, defaults to 50
:type resolution: int, optional
:param pose: pose of sphere, defaults to None
:type pose: SE3, optional
:param ax: axes to draw into, defaults to None
:type ax: Axes3D, optional
:param filled: draw filled polygon, else wireframe, defaults to False
:type filled: bool, optional
:param kwargs: arguments passed to ``plot_wireframe`` or ``plot_surface``
:return: matplotlib collection
:rtype: list of Line3DCollection or Poly3DCollection
Plot one or more spheres. If ``centre`` is a 3xN array, then each column is
taken as the centre of a sphere. All spheres have the same radius, color
etc.
Example::
>>> from spatialmath.base import plot_sphere
>>> plot_sphere(radius=1, color="r", resolution=10) # red sphere wireframe
>>> plot_sphere(radius=1, centre=(1,1,1), filled=True, facecolor='b')
.. plot::
from spatialmath.base import plot_sphere, plotvol3
plotvol3(2)
plot_sphere(radius=1, color='r', resolution=5) # red sphere wireframe
.. plot::
from spatialmath.base import plot_sphere, plotvol3
plotvol3(5)
plot_sphere(radius=1, centre=(1,1,1), filled=True, facecolor='b')
:seealso: :func:`~matplotlib.pyplot.plot_surface`, :func:`~matplotlib.pyplot.plot_wireframe`
"""
ax = axes_logic(ax, 3)
centre = smb.getmatrix(centre, (3, None))
handles = []
for c in centre.T:
X, Y, Z = sphere(centre=c, radius=radius, resolution=resolution)
handles.append(_render3D(ax, X, Y, Z, **kwargs))
return handles
def ellipsoid(
E: R2x2,
centre: Optional[ArrayLike3] = (0, 0, 0),
scale: Optional[float] = 1,
confidence: Optional[float] = None,
resolution: Optional[int] = 40,
inverted: Optional[bool] = False,
) -> Tuple[NDArray, NDArray, NDArray]:
r"""
Points on an ellipsoid
:param centre: centre of ellipsoid, defaults to (0, 0, 0)