-
Notifications
You must be signed in to change notification settings - Fork 25
/
shapes.py
2128 lines (1693 loc) · 74.4 KB
/
shapes.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
"""Plot shape classes (for data visualization)."""
import logging
from functools import partial, wraps
from contextlib import contextmanager, ExitStack
from matplotlib.collections import PolyCollection, QuadMesh, TriMesh
from matplotlib.tri import Triangulation
from matplotlib.collections import Collection
from pyproj import CRS
import numpy as np
from .helpers import register_modules
_log = logging.getLogger(__name__)
class _CollectionAccessor:
"""
Accessor class to handle contours drawn by plt.contour.
The main purpose of this class is to serve as a single Artist-like container
that executes relevant functions on ALL collections returned by plt.contour.
The `ContourSet` returned by plt.contour is accessible via `.contour_set`
To add labels to the contours on the map, use:
>>> m = Maps()
>>> m.set_data(...)
>>> m.set_shape.contour()
>>> m.plot_map()
>>>
>>> labels = m3_1.ax.clabel(m.coll.contour_set)
>>> for i in labels:
>>> m.BM.add_bg_artist(i, layer=m.layer)
"""
def __init__(self, cont, filled):
self.contour_set = cont
self._filled = filled
self._label = ""
self.collections = self.contour_set.collections
# TODO check why cmap and norm are not properly set on the collections
# of the contourplot ("over", "under" colors etc. get lost)
for c in self.collections:
c.set_cmap(self.cmap)
c.set_norm(self.norm)
methods = [
f
for f in dir(Collection)
if (callable(getattr(Collection, f)) and not f.startswith("__"))
]
custom_funcs = [i for i in dir(self) if not i.startswith("__")]
for name in methods:
if name not in custom_funcs:
setattr(self, name, self._get_func_for_all_colls(name))
def __getattr__(self, name):
return getattr(self.collections[0], name)
def _get_func_for_all_colls(self, name):
@wraps(getattr(self.collections[0], name))
def cb(*args, **kwargs):
returns = []
for c in self.collections:
returns.append(getattr(c, name)(*args, **kwargs))
return returns
return cb
def get_zorder(self):
return self.collections[0].get_zorder()
@property
def levels(self):
return self.contour_set.levels
@property
def norm(self):
return self.contour_set.norm
@property
def cmap(self):
return self.contour_set.cmap
def get_label(self):
return self._label
def set_label(self, s):
self._label = s
for i, c in enumerate(self.collections):
c.set_label(f"__EOmaps_exclude {s} (level {i})")
@contextmanager
def _cm_set(self, **kwargs):
with ExitStack() as stack:
try:
for c in self.collections:
stack.enter_context(c._cm_set(**kwargs))
yield
finally:
pass
class Shapes(object):
"""
Set the plot-shape to represent the data-points.
By default, "ellipses" is used for datasets smaller than 500k pixels and shading
with "shade_raster" is used for larger datasets (if datashader is installed).
Possible shapes are:
(check the individual docs for details!)
- Projected ellipses
>>> m.set_shape.ellipses(radius, radius_crs)
- Projected rectangles
>>> m.set_shape.rectangles(radius, radius_crs, mesh)
- Projected geodetic circles
>>> m.set_shape.geod_circles(radius)
- Voronoi diagram
>>> m.set_shape.voronoi_diagram(masked, mask_radius)
- Delaunay triangulation
>>> m.set_shape.delaunay_triangulation(masked, mask_radius, mask_radius_crs, flat)
- Point-based shading
>>> m.set_shape.shade_points(aggregator, shade_hook, agg_hook)
- Raster-based shading
>>> m.set_shape.delaunay_triangulation(aggregator, shade_hook, agg_hook)
Attributes
----------
_radius_estimation_range : int
The number of datapoints to use for estimating the radius of a shape.
(only relevant if the radius is not specified explicitly.)
The default is 100000
"""
_shp_list = [
"geod_circles",
"ellipses",
"rectangles",
"raster",
"voronoi_diagram",
"delaunay_triangulation",
"shade_points",
"shade_raster",
]
def __init__(self, m):
self._m = m
self._radius_estimation_range = 100000
def _get(self, shape, **kwargs):
# get the name of the class for a given shape
# (CamelCase without underscores)
shapeclass_name = "_" + "".join(i.capitalize() for i in shape.split("_"))
shp = getattr(self, shapeclass_name)(self._m)
shp._select_radius = False # disable radius selection based on dataset
for key, val in kwargs.items():
setattr(shp, key, val)
return shp
@staticmethod
def _get_radius(m, radius, radius_crs):
if (isinstance(radius, str) and radius == "estimate") or radius is None:
if m._estimated_radius is None:
# make sure props are defined otherwise we can't estimate the radius!
if m._data_manager.x0 is None:
m._data_manager.set_props(None)
_log.info("EOmaps: Estimating shape radius...")
radiusx, radiusy = Shapes._estimate_radius(m, radius_crs)
if radiusx == radiusy:
_log.info(
"EOmaps: radius = "
f"{np.format_float_scientific(radiusx, precision=4)}"
)
else:
_log.info(
"EOmaps: radius = "
f"({np.format_float_scientific(radiusx, precision=4)}, "
f"{np.format_float_scientific(radiusy, precision=4)})"
)
radius = (radiusx, radiusy)
# remember estimated radius to avoid re-calculating it all the time
m._estimated_radius = (radiusx, radiusy)
else:
radius = m._estimated_radius
else:
# get manually specified radius (e.g. if radius != "estimate")
if isinstance(radius, (list, np.ndarray)):
radiusx = radiusy = np.asanyarray(radius).ravel()
elif isinstance(radius, tuple):
radiusx, radiusy = radius
elif isinstance(radius, (int, float, np.number)):
radiusx = radiusy = radius
else:
radiusx = radiusy = radius
radius = (radiusx, radiusy)
return radius
@staticmethod
def _estimate_radius(m, radius_crs, method=np.nanmedian):
assert radius_crs in [
"in",
"out",
], "radius can only be estimated if radius_crs is 'in' or 'out'!"
if m._data_manager.x0_1D is not None:
x, y = m._data_manager.x0_1D, m._data_manager.y0_1D
else:
if radius_crs == "in":
x, y = m._data_manager.xorig, m._data_manager.yorig
elif radius_crs == "out":
x, y = m._data_manager.x0, m._data_manager.y0
radius = None
# try to estimate radius for 2D datasets
if len(x.shape) == 2 and len(y.shape) == 2:
userange = int(np.sqrt(m.set_shape._radius_estimation_range))
radiusx = method(np.diff(x[:userange, :userange], axis=1)) / 2
radiusy = method(np.diff(y[:userange, :userange], axis=0)) / 2
radius = (radiusx, radiusy)
if not np.isfinite(radius).all() or not all(i > 0 for i in radius):
radius = None
# for 1D datasets (or if 2D radius-estimation fails), use the median distance
# of 3 neighbours of the first N datapoints (N=shape._radius_estimation_range)
if radius is None:
from scipy.spatial import cKDTree
# take care of 2D data with 1D coordinates
if m._data_manager.x0_1D is not None:
userange = int(np.sqrt(m.set_shape._radius_estimation_range))
x, y = np.meshgrid(x[:userange], y[:userange])
x, y = x.flat, y.flat
else:
x = x.flat[: m.set_shape._radius_estimation_range]
x = x[np.isfinite(x)]
y = y.flat[: m.set_shape._radius_estimation_range]
y = y[np.isfinite(y)]
in_tree = cKDTree(
np.stack(
[
x,
y,
],
axis=1,
),
compact_nodes=False,
balanced_tree=False,
)
dists, pts = in_tree.query(in_tree.data, min(len(in_tree.data), 3))
# consider only neighbors
# (the first entry is the search-point again!)
pts = pts[:, 1:]
# get the average distance between points having a distance > 0
d = np.abs(in_tree.data[:, np.newaxis] - in_tree.data[pts]).reshape(-1, 2)
use_dx = d[:, 0] > 0
use_dy = d[:, 1] > 0
if any(use_dx):
radiusx = method(d[:, 0][use_dx]) / 2
else:
radiusx = np.nan
if any(use_dy):
radiusy = method(d[:, 1][use_dy]) / 2
else:
radiusy = np.nan
rxOK = np.isfinite(radiusx) and (radiusx > 0)
ryOK = np.isfinite(radiusy) and (radiusy > 0)
if rxOK and ryOK:
radius = (radiusx, radiusy)
elif rxOK:
radius = (radiusx, radiusx)
elif ryOK:
radius = (radiusy, radiusy)
else:
radius = None
assert radius is not None, (
"EOmaps: Radius estimation failed... maybe there's something wrong with "
"the provided coordinates? "
"You can manually specify a radius with 'm.set_shape.<SHAPE>(radius=...)' "
"or you can increase the number of datapoints used to estimate the radius "
"by increasing `m.set_shape._radius_estimation_range`."
)
return radius
@staticmethod
def _get_colors_and_array(kwargs, mask):
# identify colors and the array
# special treatment of array input to properly mask values
array = kwargs.pop("array", None)
if array is not None:
if mask is not None:
array = array[mask]
else:
array = None
color_vals = dict()
for c_key in ["fc", "facecolor", "color"]:
color = kwargs.pop(c_key, None)
if color is not None:
# explicit treatment for recarrays (to avoid performance issues)
# with matplotlib.colors.to_rgba_array()
# (recarrays are used to convert 3/4 arrays into an rgb(a) array
# in m._handle_explicit_colors() )
if isinstance(color, np.recarray):
color_vals[c_key] = color[mask.reshape(color.shape)].view(
(float, len(color.dtype.names))
) # .ravel()
elif isinstance(color, np.ndarray):
color_vals[c_key] = color[mask.reshape(color.shape)]
else:
color_vals[c_key] = color
if len(color_vals) == 0:
return {"array": array}
else:
color_vals["array"] = None
return color_vals
# a base class for shapes that support setting the number of intermediate points
class _ShapeBase:
name = "none"
def __init__(self, m):
self._m = m
self._n = None
self._select_radius = True
def _get_auto_n(self):
s = self._m._data_manager._get_current_datasize()
if self.name == "rectangles":
# mesh currently only supports n=1
if self.mesh is True:
return 1
# if plot crs is same as input-crs there is no need for
# intermediate points since the rectangles are not curved!
if self._m._crs_plot == self._m.data_specs.crs:
return 1
if s < 10:
n = 100
elif s < 100:
n = 75
elif s < 1000:
n = 50
elif s < 10000:
n = 20
else:
n = 12
return n
@property
def n(self):
if self._n is None:
return self._get_auto_n()
else:
return self._n
@n.setter
def n(self, val):
if self.name == "rectangles" and self.mesh is True:
if val is not None and val != 1:
_log.info("EOmaps: rectangles with 'mesh=True' only support n=1")
self._n = 1
else:
self._n = val
@property
def _selected_radius(self):
# option to override radius-selection in case the shape is used
# to create markers (e.g. call is independent of plot-extent)
if self._select_radius is False:
return self.radius
# if radius was provided as a array (for individual shape radius)
# select values according to the dat-manager query to get values
# of visible points
# if no data is assigned, just return the radius
if not self._m._data_manager._current_data:
return self.radius
# check if mutiple individual x-y radius was provided
q1 = isinstance(self.radius, tuple) and isinstance(
self.radius[0], np.ndarray
)
# chedk if multiple radius values were provided
q2 = isinstance(self.radius, np.ndarray)
if q1 or q2:
mask = self._m._data_manager._get_q()[0]
# quick exit if full data is in extent
if mask is True:
return self.radius
if q1:
radius = (self.radius[0][mask], self.radius[1][mask])
elif q2:
radius = self.radius[mask]
else:
radius = self.radius
return radius
class _GeodCircles(_ShapeBase):
name = "geod_circles"
def __init__(self, m):
super().__init__(m=m)
def __call__(self, radius=None, n=None):
"""
Draw geodesic circles with a radius defined in meters.
Parameters
----------
radius : float or array-like
The radius of the circles in meters.
If you provide an array of sizes, each datapoint will be drawn with
the respective size!
n : int or None
The number of intermediate points to calculate on the geodesic circle.
If None, 100 is used for < 10k pixels and 20 otherwise.
The default is None.
Returns
-------
self
The class representing the plot-shape.
"""
if radius is None:
raise TypeError(
"EOmaps: If 'm.set_shape.geod_circles(...)' is used, "
"you must provide a radius!"
)
from . import MapsGrid # do this here to avoid circular imports!
for m in self._m if isinstance(self._m, MapsGrid) else [self._m]:
shape = self.__class__(m)
shape.radius = radius
shape.n = n
m._shape = shape
@property
def _initargs(self):
return dict(radius=self._radius, n=self._n)
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, val):
if isinstance(val, (int, float, np.number)):
self._radius = val
else:
self._radius = np.asanyarray(np.atleast_1d(val))
@property
def radius_crs(self):
return "geod"
def __repr__(self):
try:
s = f"geod_circles(radius={self.radius}, n={self.n})"
except AttributeError:
s = "geod_circles(radius, n)"
return s
def _calc_geod_circle_points(self, lon, lat, radius, n=20, start_angle=0):
"""
Calculate points on a geodetic circle with a given radius.
Parameters
----------
lon : array-like
the longitudes
lat : array-like
the latitudes
radius : float
the radius in meters
n : int, optional
the number of points to calculate.
The default is 10.
start_angle : int, optional
the starting angle for the points in radians
Returns
-------
lons : array-like
the longitudes of the geodetic circle points.
lats : array-like
the latitudes of the geodetic circle points.
"""
size = lon.size
if isinstance(radius, (int, float)):
radius = np.full((size, n), radius)
else:
if radius.size != lon.size:
radius = np.broadcast_to(radius[:, None], (size, n))
else:
radius = np.broadcast_to(radius.ravel()[:, None], (size, n))
geod = self._m.crs_plot.get_geod()
lons, lats, back_azim = geod.fwd(
lons=np.broadcast_to(lon[:, None], (size, n)),
lats=np.broadcast_to(lat[:, None], (size, n)),
az=np.linspace(
[start_angle] * size, [360 - start_angle] * size, n, axis=1
),
dist=radius,
radians=False,
)
return lons.T, lats.T
def _get_geod_circle_points(self, x, y, crs, radius, n=20):
x, y = np.asarray(x), np.asarray(y)
# transform from in-crs to lon/lat
radius_t = self._m._get_transformer(
self._m.get_crs(crs),
self._m.CRS.PlateCarree(globe=self._m.crs_plot.globe),
)
# transform from lon/lat to the plot_crs
plot_t = self._m._get_transformer(
self._m.CRS.PlateCarree(globe=self._m.crs_plot.globe),
CRS.from_user_input(self._m.crs_plot),
)
lon, lat = radius_t.transform(x, y)
# calculate some points on the geodesic circle
lons, lats = self._calc_geod_circle_points(lon, lat, radius, n=n)
xs, ys = np.ma.masked_invalid(plot_t.transform(lons, lats), copy=False)
if self._m._crs_plot in (
self._m.CRS.Orthographic(),
self._m.CRS.Geostationary(),
self._m.CRS.NearsidePerspective(),
):
mask = np.full(lons.shape, True)
else:
# get the mask for invalid, very distorted or very large shapes
dx = xs.max(axis=0) - xs.min(axis=0)
dy = ys.max(axis=0) - ys.min(axis=0)
mask = (
~xs.mask.any(axis=0)
& ~ys.mask.any(axis=0)
& ((dx / dy) < 10)
& (dx < np.max(radius) * 50)
& (dy < np.max(radius) * 50)
)
mask = np.broadcast_to(mask[:, None].T, lons.shape)
return xs, ys, mask
def get_coll(self, x, y, crs, **kwargs):
xs, ys, mask = self._get_geod_circle_points(
x, y, crs, self._selected_radius, self.n
)
# only plot polygons if they contain 2 or more vertices
vertmask = np.count_nonzero(mask, axis=0) > 2
# remember masked points
self._m._data_mask = vertmask
verts = np.stack((xs, ys)).T
verts = np.ma.masked_array(
verts,
np.broadcast_to(~mask[:, None].T.swapaxes(1, 2), verts.shape),
)
verts = list(
i.compressed().reshape(-1, 2) for i, m in zip(verts, vertmask) if m
)
color_and_array = Shapes._get_colors_and_array(kwargs, vertmask)
coll = PolyCollection(
verts,
# transOffset=self._m.ax.transData,
**color_and_array,
**kwargs,
)
return coll
class _Ellipses(_ShapeBase):
name = "ellipses"
def __init__(self, m):
super().__init__(m=m)
def __call__(self, radius="estimate", radius_crs="in", n=None):
"""
Draw projected ellipses with dimensions defined in units of a given crs.
Parameters
----------
radius : int, float, array-like or str, optional
The radius in x- and y- direction.
The default is "estimate" in which case the radius is attempted
to be estimated from the input-coordinates.
If you provide an array of sizes, each datapoint will be drawn with
the respective size!
radius_crs : crs-specification, optional
The crs in which the dimensions are defined.
The default is "in".
n : int or None
The number of intermediate points to calculate on the circle.
If None, 100 is used for < 10k pixels and 20 otherwise.
The default is None.
"""
from . import MapsGrid # do this here to avoid circular imports!
for m in self._m if isinstance(self._m, MapsGrid) else [self._m]:
shape = self.__class__(m)
shape._radius = radius
shape.radius_crs = radius_crs
shape.n = n
m._shape = shape
@property
def _initargs(self):
return dict(radius=self._radius, radius_crs=self.radius_crs, n=self._n)
@property
def radius(self):
radius = Shapes._get_radius(self._m, self._radius, self.radius_crs)
return radius
@radius.setter
def radius(self, val):
if isinstance(val, (list, np.ndarray)):
self._radius = np.asanyarray(val).ravel()
else:
self._radius = val
def __repr__(self):
try:
try:
s = f"ellipses(radius={self.radius}, radius_crs={self.radius_crs}, n={self.n})"
except AttributeError:
s = "ellipses(radius, radius_crs, n)"
return s
except:
return object.__repr__(self)
def _calc_ellipse_points(self, x0, y0, a, b, theta, n, start_angle=0):
"""
Calculate points on a rotated ellipse.
Parameters
----------
x0, y0 : array-like
the center-position of the ellipse.
a, b : array-like
the ellipse half-axes.
theta : array-like
the rotation-angle of the ellipse.
n : int
the number of points to calculate on the ellipse.
start_angle : float, optional
the angle at which the ellipse-point calculation starts.
The default is 0.
Returns
-------
xs, ys : array-like
the coordinates of the ellipse points.
"""
a = np.broadcast_to(a[:, None], (x0.size, n))
b = np.broadcast_to(b[:, None], (x0.size, n))
theta = np.broadcast_to(theta[:, None], a.shape)
angs = np.linspace(start_angle, 2 * np.pi + start_angle, n)
angs = np.broadcast_to(angs, (x0.size, n))
x0 = np.broadcast_to(x0[:, None], a.shape)
y0 = np.broadcast_to(y0[:, None], a.shape)
xs = (
x0 + a * np.cos(angs) * np.cos(theta) - b * np.sin(angs) * np.sin(theta)
)
ys = (
y0 + a * np.cos(angs) * np.sin(theta) + b * np.sin(angs) * np.cos(theta)
)
return (xs, ys)
def _get_ellipse_points(self, x, y, crs, radius, radius_crs="in", n=20):
crs = self._m.get_crs(crs)
radius_crs = self._m.get_crs(radius_crs)
# transform from crs to the plot_crs
t_in_plot = self._m._get_transformer(crs, self._m.crs_plot)
# transform from crs to the radius_crs
t_in_radius = self._m._get_transformer(crs, radius_crs)
# transform from crs to the radius_crs
t_radius_plot = self._m._get_transformer(radius_crs, self._m.crs_plot)
if isinstance(radius, (int, float, np.number)):
rx, ry = radius, radius
else:
rx, ry = radius
# transform corner-points
if radius_crs == crs:
p = (x, y)
theta = np.full_like(x, 0)
xs, ys = self._calc_ellipse_points(
p[0],
p[1],
np.broadcast_to(rx, x.shape).astype(float),
np.broadcast_to(ry, y.shape).astype(float),
np.full_like(x, 0),
n=n,
)
xs, ys = np.ma.masked_invalid((xs, ys), copy=False)
xs, ys = np.ma.masked_invalid(t_in_plot.transform(xs, ys), copy=False)
else:
p = t_in_radius.transform(x, y)
theta = np.full_like(x, 0)
xs, ys = self._calc_ellipse_points(
p[0],
p[1],
np.broadcast_to(rx, x.shape).astype(float),
np.broadcast_to(ry, y.shape).astype(float),
np.full_like(x, 0),
n=n,
)
xs, ys = np.ma.masked_invalid((xs, ys), copy=False)
xs, ys = np.ma.masked_invalid(
t_radius_plot.transform(xs, ys), copy=False
)
# ------------------------- implement some kind of "wraparound"
if self._m._crs_plot in (
self._m.CRS.Orthographic(),
self._m.CRS.Geostationary(),
self._m.CRS.NearsidePerspective(),
):
# avoid masking in those crs
mask = np.full(xs.shape[0], True)
else:
# check if any points are in different halfspaces with respect to x
# and if so, mask the ones in the wrong halfspace
# (required for proper longitude wrapping)
# TODO this might be a lot easier (and faster) to implement!
xc = 0 # the center-point (e.g. (-180 + 180)/2 = 0 )
def getQ(x, xc):
quadrants = np.full_like(x, -1)
quadrant = x < xc
quadrants[quadrant] = 0
quadrant = x > xc
quadrants[quadrant] = 1
return quadrants
t_in_lonlat = self._m._get_transformer(crs, 4326)
t_plot_lonlat = self._m._get_transformer(self._m.crs_plot, 4326)
# transform the coordinates to lon/lat
xp, _ = t_in_lonlat.transform(x, y)
xsp, _ = t_plot_lonlat.transform(xs, ys)
quadrants, pts_quadrants = getQ(xp, xc), getQ(xsp, xc)
# mask any point that is in a different quadrant than the center point
maskx = pts_quadrants != quadrants[:, np.newaxis]
# take care of points that are on the center line (e.g. don't mask them)
# (use a +- 25 degree around 0 as threshold)
cpoints = np.broadcast_to(
np.isclose(xp, xc, atol=25)[:, np.newaxis], xs.shape
)
maskx[cpoints] = False
xs.mask[maskx] = True
ys.mask = xs.mask
# mask any datapoint that has less than 4 of the ellipse-points unmasked
mask = ~(
n - np.count_nonzero(xs.mask, axis=1) <= min(n / 2, 4)
) & np.isfinite(theta)
return xs, ys, mask
def get_coll(self, x, y, crs, **kwargs):
xs, ys, mask = self._get_ellipse_points(
x, y, crs, self._selected_radius, self.radius_crs, n=self.n
)
# compress the coordinates (masked arrays produce artefacts on the boundary
# in case intermediate points are masked)
verts = (
np.column_stack((x.compressed(), y.compressed()))
for i, (x, y) in enumerate(zip(xs, ys))
if mask[i]
)
# remember masked points
self._m._data_mask = mask
color_and_array = Shapes._get_colors_and_array(kwargs, mask)
coll = PolyCollection(
verts,
# transOffset=self._m.ax.transData,
**color_and_array,
**kwargs,
)
return coll
class _Rectangles(_ShapeBase):
name = "rectangles"
def __init__(self, m):
super().__init__(m=m)
def __call__(self, radius="estimate", radius_crs="in", mesh=False, n=None):
"""
Draw projected rectangles with fixed dimensions (and possibly curved edges).
Parameters
----------
radius : int, float, tuple or str, optional
The radius in x- and y- direction.
The default is "estimate" in which case the radius is attempted
to be estimated from the input-coordinates.
If you provide an array of sizes, each datapoint will be drawn with
the respective size!
radius_crs : crs-specification, optional
The crs in which the dimensions are defined.
The default is "in".
mesh : bool
Indicator if polygons (False) or a triangular mesh (True)
should be plotted.
Using polygons allows setting edgecolors, using a triangular mesh
does NOT allow setting edgecolors but it has the advantage that
boundaries between neighbouring rectangles are not visible.
Only n=1 is currently supported!
n : int or None
The number of intermediate points to calculate on the rectangle edges
(e.g. to properly plot "curved" rectangles in projected crs)
Use n=1 to force rectangles!
If None, 40 is used for <10k datapoints and 10 is used otherwise.
The default is None
"""
from . import MapsGrid # do this here to avoid circular imports!
for m in self._m if isinstance(self._m, MapsGrid) else [self._m]:
shape = self.__class__(m)
shape._radius = radius
shape.radius_crs = radius_crs
shape.mesh = mesh
shape.n = n
m._shape = shape
@property
def _initargs(self):
return dict(
radius=self._radius,
radius_crs=self.radius_crs,
n=self._n,
mesh=self.mesh,
)
@property
def radius(self):
radius = Shapes._get_radius(self._m, self._radius, self.radius_crs)
return radius
@radius.setter
def radius(self, val):
if isinstance(val, (list, np.ndarray)):
self._radius = np.asanyarray(val).ravel()
else:
self._radius = val
def __repr__(self):
try:
s = f"rectangles(radius={self.radius}, radius_crs={self.radius_crs})"
except AttributeError:
s = "rectangles(radius, radius_crs)"
return s
def _get_rectangle_verts(self, x, y, crs, radius, radius_crs="in", n=4):
in_crs = self._m.get_crs(crs)
if isinstance(radius, (int, float, np.number)):
rx, ry = radius, radius
else:
rx, ry = radius
# transform corner-points
if radius_crs == crs:
in_crs = self._m.get_crs(crs)
# transform from crs to the plot_crs
t = self._m._get_transformer(
CRS.from_user_input(in_crs), self._m.crs_plot
)
# make sure we do not transform out of bounds (if possible)
if in_crs.area_of_use is not None:
transformer = self._m._get_transformer(in_crs.geodetic_crs, in_crs)
xmin, ymin, xmax, ymax = transformer.transform_bounds(
*in_crs.area_of_use.bounds
)
clipx = partial(np.clip, a_min=xmin, a_max=xmax)
clipy = partial(np.clip, a_min=ymin, a_max=ymax)
else:
clipx, clipy = lambda x: x, lambda y: y
p = x, y
else:
r_crs = self._m.get_crs(radius_crs)
# transform from crs to the radius_crs
t_in_radius = self._m._get_transformer(in_crs, r_crs)
# transform from radius_crs to the plot_crs
t = self._m._get_transformer(r_crs, self._m.crs_plot)
# make sure we do not transform out of bounds (if possible)
if r_crs.area_of_use is not None:
transformer = self._m._get_transformer(r_crs.geodetic_crs, r_crs)
xmin, ymin, xmax, ymax = transformer.transform_bounds(
*r_crs.area_of_use.bounds
)
clipx = partial(np.clip, a_min=xmin, a_max=xmax)
clipy = partial(np.clip, a_min=ymin, a_max=ymax)
else:
clipx, clipy = lambda x: x, lambda y: y