-
Notifications
You must be signed in to change notification settings - Fork 5
/
plotters.py
executable file
·2167 lines (1846 loc) · 75.9 KB
/
plotters.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
"""Plotters and formatoption of the psy-maps psyplot plugin."""
# Disclaimer
# ----------
#
# Copyright (C) 2021 Helmholtz-Zentrum Hereon
# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht
# Copyright (C) 2016-2021 University of Lausanne
#
# This file is part of psy-maps and is released under the GNU LGPL-3.O license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3.0 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LGPL-3.0 license for more details.
#
# You should have received a copy of the GNU LGPL-3.0 license
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import six
import re
import warnings
from abc import abstractproperty
from difflib import get_close_matches
import copy
from itertools import starmap, chain, repeat
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cf
from cartopy.mpl.gridliner import Gridliner
import matplotlib as mpl
import matplotlib.ticker as ticker
from matplotlib.colors import BoundaryNorm
import numpy as np
from psyplot import rcParams
from psyplot.compat.pycompat import map
from psyplot.docstring import docstrings
from psyplot.data import InteractiveList, _infer_interval_breaks
from psyplot.plotter import (
Formatoption, START, DictFormatoption, END, BEFOREPLOTTING)
import psy_simple.plotters as psyps
import psy_simple.base
from psy_maps.boxes import lonlatboxes
from psy_simple.colors import FixedBoundaryNorm
wrap_proj_types = (ccrs._RectangularProjection,
ccrs._WarpedRectangularProjection,
ccrs.InterruptedGoodeHomolosine,
ccrs.Mercator)
cartopy_version = list(map(int, cartopy.__version__.split(".")[:2]))
@docstrings.get_sections(base='shiftdata')
def shiftdata(lonsin, datain, lon_0):
"""
Shift longitudes (and optionally data) so that they match map projection
region.
Only valid for cylindrical/pseudo-cylindrical global projections and data
on regular lat/lon grids. longitudes and data can be 1-d or 2-d, if 2-d
it is assumed longitudes are 2nd (rightmost) dimension.
Parameters
----------
lonsin
original 1-d or 2-d longitudes.
datain
original 1-d or 2-d data
lon_0
center of map projection region
References
----------
This function is copied and taken from the
:class:`mpl_toolkits.basemap.Basemap` class. The only difference is that
we do not mask values outside the map projection region
"""
lonsin = np.asarray(lonsin)
if lonsin.ndim not in [1, 2]:
raise ValueError('1-d or 2-d longitudes required')
if datain is not None:
# if it's a masked array, leave it alone.
if not np.ma.isMA(datain):
datain = np.asarray(datain)
if datain.ndim not in [1, 2]:
raise ValueError('1-d or 2-d data required')
# 2-d data.
if lonsin.ndim == 2:
raise NotImplementedError(
"Shifting of 2D-data is currently not supported")
# 1-d data.
elif lonsin.ndim == 1:
lonsin = np.where(lonsin > lon_0+180, lonsin-360, lonsin)
lonsin = np.where(lonsin < lon_0-180, lonsin+360, lonsin)
londiff = np.abs(lonsin[0:-1]-lonsin[1:])
londiff_sort = np.sort(londiff)
thresh = 360.-londiff_sort[-2]
itemindex = len(lonsin) - np.where(londiff >= thresh)[0]
if itemindex:
# check to see if cyclic (wraparound) point included
# if so, remove it.
if np.abs(lonsin[0]-lonsin[-1]) < 1.e-4:
hascyclic = True
lonsin_save = lonsin.copy()
lonsin = lonsin[1:]
if datain is not None:
datain_save = datain.copy()
datain = datain[1:]
else:
hascyclic = False
lonsin = np.roll(lonsin, itemindex-1)
if datain is not None:
datain = np.roll(datain, itemindex-1)
# add cyclic point back at beginning.
if hascyclic:
lonsin_save[1:] = lonsin
lonsin_save[0] = lonsin[-1]-360.
lonsin = lonsin_save
if datain is not None:
datain_save[1:] = datain
datain_save[0] = datain[-1]
datain = datain_save
if datain is not None:
return lonsin, datain
else:
return lonsin
def degree_format():
if mpl.rcParams['text.usetex']:
return r'${%g\/^{\circ}\/%s}$'
else:
return u'%g\N{DEGREE SIGN}%s'
def format_lons(x, pos):
fmt_string = degree_format()
x = x - 360 if x > 180 else x
if x == 0:
return fmt_string % (x, '')
return fmt_string % (abs(x), 'W' if x < 0 else 'E')
def format_lats(x, pos):
fmt_string = degree_format()
if x == 0:
return fmt_string % (abs(x), '')
return fmt_string % (abs(x), 'S' if x < 0 else 'N')
class Transpose(Formatoption):
"""Transpose the data before plotting
This formatoption can be used in case the data order of the variable
dimensions is (x, y) instead of (y, x)"""
priority = START
group = 'axes'
name = 'Transpose (switch) x- and y-dimensions'
def update(self, value):
for i, (raw, data) in enumerate(zip(
self.iter_raw_data, self.iter_data)):
base_var = next(raw.psy.iter_base_variables)
is_unstructured = raw.psy.decoder.is_unstructured(base_var)
if is_unstructured and value:
decoder = copy.copy(data.psy.decoder)
xcoord = data.psy.get_coord('x').name
ycoord = data.psy.get_coord('y').name
decoder.x.add(ycoord)
decoder.y.add(xcoord)
self.set_decoder(decoder, i)
elif is_unstructured:
self.set_decoder(raw.psy.decoder, i)
elif value:
if data.ndim > 2:
new_dims = data.dims[:-2] + data.dims[-2:][::-1]
else:
new_dims = data.dims[::-1]
self.set_data(data.transpose(*new_dims), i)
lon_formatter = ticker.FuncFormatter(format_lons)
lat_formatter = ticker.FuncFormatter(format_lats)
@docstrings.get_sections(base=
'ProjectionBase', sections=['Possible types', 'See Also'])
class ProjectionBase(Formatoption):
"""
Base class for formatoptions that uses cartopy.crs.CRS instances
Possible types
--------------
cartopy.crs.CRS
A cartopy projection instance (e.g. :class:`cartopy.crs.PlateCarree`)
str
A string specifies the projection instance to use. The centered
longitude and latitude are determined by the :attr:`clon` and
:attr:`clat` formatoptions.
Possible strings are (each standing for the specified projection)
=========== =======================================
cf try to decode the CF-conventions
cyl :class:`cartopy.crs.PlateCarree`
robin :class:`cartopy.crs.Robinson`
moll :class:`cartopy.crs.Mollweide`
geo :class:`cartopy.crs.Geostationary`
northpole :class:`cartopy.crs.NorthPolarStereo`
southpole :class:`cartopy.crs.SouthPolarStereo`
ortho :class:`cartopy.crs.Orthographic`
stereo :class:`cartopy.crs.Stereographic`
near :class:`cartopy.crs.NearsidePerspective`
rotated :class:`cartopy.crs.RotatedPole`
=========== =======================================
The special case ``'cf'`` tries to decode the CF-conventions in the
data. If this is not possible, we assume a standard lat-lon projection
(``'cyl'``)
See Also
--------
`Grid-mappings of cf-conventions <http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#appendix-grid-mappings>`__
"""
projections = {
'cyl': ccrs.PlateCarree,
'robin': ccrs.Robinson,
'moll': ccrs.Mollweide,
'geo': ccrs.Geostationary,
'northpole': ccrs.NorthPolarStereo,
'southpole': ccrs.SouthPolarStereo,
'ortho': ccrs.Orthographic,
'stereo': ccrs.Stereographic,
'near': ccrs.NearsidePerspective,
'rotated': ccrs.RotatedPole,
}
projection_kwargs = dict(
chain(zip(projections.keys(), repeat(['central_longitude']))))
projection_kwargs['ortho'] = ['central_longitude', 'central_latitude']
projection_kwargs['stereo'] = ['central_longitude', 'central_latitude']
projection_kwargs['near'] = ['central_longitude', 'central_latitude']
projection_kwargs['rotated'] = ['pole_longitude', 'pole_latitude']
# CRS that are supported to be interpreted by CF-conventions
supported_crs = [
'albers_conical_equal_area',
'azimuthal_equidistant',
'geostationary',
'lambert_azimuthal_equal_area',
'lambert_conformal_conic',
'lambert_cylindrical_equal_area',
'latitude_longitude',
'mercator',
#'oblique_mercator', # not available for cartopy
'orthographic',
'polar_stereographic',
'rotated_latitude_longitude',
'sinusoidal',
'stereographic',
'transverse_mercator',
#'vertical_perspective', # not available for cartopy
]
@property
def cf_projection(self):
data = next(self.iter_data)
if 'grid_mapping' in data.attrs:
try:
crs = data[data.attrs['grid_mapping']]
except KeyError:
try:
crs = data.psy.base[data.attrs['grid_mapping']]
except KeyError:
warnings.warn(
"Grid mapping variable %(grid_mapping)s specified but "
"impossible to find!" % data.attrs)
return
if 'grid_mapping_name' not in crs.attrs:
warnings.warn(
"Grid mapping variable %(grid_mapping)s specified but "
"without 'grid_mapping_name' attribute!" % data.attrs)
return
elif crs.attrs['grid_mapping_name'] not in self.supported_crs:
warnings.warn(
"Grid mapping %(grid_mapping_name)s not supported!" %
crs.attrs)
return
else:
func = getattr(
self, crs.attrs['grid_mapping_name'] + '_from_cf')
try:
return func(crs)
except Exception:
self.logger.debug(
"Failed to get CRS from crs variable %s",
crs.name, exc_info=True)
warnings.warn(
f"Failed to get CRS from crs variable {crs.name}")
def albers_conical_equal_area_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_central_meridian,
central_latitude=crs.latitude_of_projection_origin,
standard_parallels=crs.standard_parallel
)
try:
iter(kwargs['standard_parallels'])
except TypeError:
kwargs['standard_parallels'] = [kwargs['standard_parallels']]
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.AlbersEqualArea(**kwargs)
def azimuthal_equidistant_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_projection_origin,
central_latitude=crs.latitude_of_projection_origin,
)
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.AzimuthalEquidistant(**kwargs)
def geostationary_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_projection_origin,
satellite_height=crs.perspective_point_height,
sweep_axis=crs.sweep_angle_axis,
)
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.Geostationary(**kwargs)
def lambert_azimuthal_equal_area_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_projection_origin,
central_latitude=crs.latitude_of_projection_origin,
)
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.LambertAzimuthalEqualArea(**kwargs)
def lambert_conformal_conic_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_central_meridian,
central_latitude=crs.latitude_of_projection_origin,
standard_parallels=crs.standard_parallel,
)
try:
iter(kwargs['standard_parallels'])
except TypeError:
kwargs['standard_parallels'] = [kwargs['standard_parallels']]
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.LambertConformal(**kwargs)
def lambert_cylindrical_equal_area_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_central_meridian
)
return ccrs.LambertCylindrical(**kwargs)
def latitude_longitude_from_cf(self, crs):
return ccrs.PlateCarree()
def mercator_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_projection_origin,
)
if hasattr(crs, 'scale_factor_at_projection_origin'):
kwargs['scale_factor'] = crs.scale_factor_at_projection_origin
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.Mercator(**kwargs)
def orthographic_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_projection_origin,
central_latitude=crs.latitude_of_projection_origin,
)
return ccrs.Orthographic(**kwargs)
def polar_stereographic_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.straight_vertical_longitude_from_pole)
if crs.latitude_of_projection_origin == -90:
return ccrs.SouthPolarStereo(**kwargs)
else:
return ccrs.NorthPolarStereo(**kwargs)
def rotated_latitude_longitude_from_cf(self, crs):
args = [crs.grid_north_pole_longitude,
crs.grid_north_pole_latitude]
if hasattr(crs, 'north_pole_grid_longitude'):
args.append(crs.north_pole_grid_longitude)
return ccrs.RotatedPole(*args)
def sinusoidal_from_cf(self, crs):
try:
kwargs = dict(
central_longitude=crs.longitude_of_projection_origin,
)
except AttributeError:
kwargs = dict(
central_longitude=crs.longitude_of_central_meridian,
)
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.Sinusoidal(**kwargs)
def stereographic_from_cf(self, crs):
kwargs = dict(
central_latitude=crs.latitude_of_projection_origin,
central_longitude=crs.longitude_of_projection_origin,
scale_factor=crs.scale_factor_at_projection_origin
)
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.Stereographic(**kwargs)
def transverse_mercator_from_cf(self, crs):
kwargs = dict(
central_longitude=crs.longitude_of_central_meridian,
central_latitude=crs.latitude_of_projection_origin,
scale_factor=crs.scale_factor_at_central_meridian,
)
if getattr(crs, 'false_easting', None):
kwargs['false_easting'] = crs.false_easting
if getattr(crs, 'false_northing', None):
kwargs['false_northing'] = crs.false_northing
return ccrs.TransverseMercator(**kwargs)
def set_projection(self, value, *args, **kwargs):
if value == 'cf':
ret = self.cf_projection
if ret is not None:
return ret
if isinstance(value, ccrs.CRS):
return value
else:
value = 'cyl' if value == 'cf' else value
return self.projections[value](**self.get_kwargs(
value, *args, **kwargs))
def get_kwargs(self, value, clon=None, clat=None):
ret = {}
keys = self.projection_kwargs[value]
if 'central_longitude' in keys:
ret['central_longitude'] = self.clon.clon if clon is None else clon
if 'central_latitude' in keys:
ret['central_latitude'] = self.clat.clat if clat is None else clat
if 'pole_longitude' in keys: # rotated pole
ret['pole_longitude'] = self.clon.clon if clon is None else clon
ret['pole_longitude'] -= 180
if 'pole_latitude' in keys: # rotated pole
ret['pole_latitude'] = self.clat.clat if clat is None else clat
self.logger.debug("Setting projection with %s", ret)
return ret
class Projection(ProjectionBase):
"""
Specify the projection for the plot
This formatoption defines the projection of the plot
Possible types
--------------
%(ProjectionBase.possible_types)s
See Also
--------
%(ProjectionBase.see_also)s
Warnings
--------
An update of the projection clears the axes!
"""
# the axes has to be cleared completly if the projection is updated
priority = START
#: an update of this formatoption requires that the axes is cleared
requires_clearing = True
name = 'Projection of the plot'
dependencies = ['clon', 'clat']
connections = ['transform']
def __init__(self, *args, **kwargs):
super(Projection, self).__init__(*args, **kwargs)
self.projection = None
def initialize_plot(self, value, clear=True):
"""Initialize the plot and set the projection for the axes
"""
self.projection = self.set_projection(value)
if self.plotter.cleared:
self.ax.projection = self.projection
self.ax.clear()
def update(self, value):
"""Update the formatoption
Since this formatoption requires clearing, this method does nothing.
Everything is done in the :meth:`initialize_plot` method.
"""
pass
@docstrings.get_sections(base='BoxBase')
class BoxBase(Formatoption):
"""
Abstract base class for specifying a longitude-latitude box
Possible types
--------------
str
A pattern that matches any of the keys in the :attr:`psyplot.rcParams`
``'extents.boxes'`` item (contains user-defined longitude-latitude
boxes) or the :attr:`psyplot.plotter.boxes.lonlatboxes` dictionary
(contains longitude-latitude boxes of different countries and
continents)
[lonmin, lonmax, latmin, latmax]
The surrounding longitude-latitude that shall be used. Values can be
either a float or a string as above
See Also
--------
LonLatBox, MapExtent
"""
def lola_from_pattern(self, s):
"""
Calculate the longitude-latitude box based upon a pattern
This method uses the psyplot.rcParams ``'extents.boxes'`` item to find
longitude that match `s` and takes the surrounding box.
Parameters
----------
s: str
The pattern to use for the keys in the
:attr:`psyplot.plotter.maps.lonlatboxes` dictionary and the
``'extents.boxes'`` item in the :attr:`psyplot.rcParams`
Returns
-------
float: lonmin, lonmax, latmin, latmax or None
The surrounding longitude-latitude box of all items in
``psyplot.rcParams['extents.boxes']`` whose key match `s` if there
was any match. Otherwise None is returned
"""
patt = re.compile(s)
boxes = np.array([
box for key, box in chain(*map(
six.iteritems, [lonlatboxes, rcParams['lonlatbox.boxes']]))
if patt.search(key)])
if len(boxes) == 0:
similar_keys = get_close_matches(s, rcParams['lonlatbox.boxes'])
message = "Did not find any matches for %s!" % s
if similar_keys:
message += " Maybe you mean on of " + ', '.join(
similar_keys)
warnings.warn(message, RuntimeWarning)
return
return [boxes[:, 0].min(), boxes[:, 1].max(),
boxes[:, 2].min(), boxes[:, 3].max()]
docstrings.keep_types('BoxBase.possible_types', 'str', 'str')
class CenterLon(BoxBase):
"""
Set the center longitude of the plot
Parameters
----------
None
Let the :attr:`lonlatbox` formatoption determine the center
float
Specifiy the center manually
%(BoxBase.possible_types.str)s
"""
priority = START
name = 'Longitude of the center of the plot'
requires_clearing = True
dependencies = ['lonlatbox']
def update(self, value):
self.lon_mean = float(np.mean(self.lonlatbox.lonlatbox[:2]))
if value is not None:
if isinstance(value, six.string_types):
box = self.lola_from_pattern(value)
if box is not None:
self.clon = float(np.mean(box[:2]))
else:
value = None
else:
self.clon = value
if value is None:
lonmin, lonmax = self.lonlatbox.lonlatbox[:2]
if lonmax - lonmin > 350:
self.clon = 0.0
else:
self.clon = self.lon_mean
class CenterLat(BoxBase):
"""
Set the center latitude of the plot
Parameters
----------
None
Let the :attr:`lonlatbox` formatoption determine the center
float
Specifiy the center manually
%(BoxBase.possible_types.str)s
"""
priority = START
name = 'Latitude of the center of the plot'
requires_clearing = True
dependencies = ['lonlatbox']
def update(self, value):
self.lat_mean = float(np.mean(self.lonlatbox.lonlatbox[2:]))
if value is not None:
if isinstance(value, six.string_types):
box = self.lola_from_pattern(value)
if box is not None:
self.clat = float(np.mean(box[2:]))
else:
value = None
else:
self.clat = value
if value is None:
latmin, latmax = self.lonlatbox.lonlatbox[2:]
if latmax - latmin > 170:
self.clat = 0
else:
self.clat = self.lat_mean
@docstrings.get_sections(base='LonLatBox')
class LonLatBox(BoxBase):
"""
Set the longitude-latitude box of the data shown
This formatoption extracts the data that matches the specified box.
Possible types
--------------
None
Use the full data
%(BoxBase.possible_types)s
Notes
-----
- For only specifying the region of the plot, see the :attr:`map_extent`
formatoption
- If the coordinates are two-dimensional (e.g. for a circumpolar grid),
than the data is not extracted but values outside the specified
longitude-latitude box are set to NaN
See Also
--------
map_extent"""
priority = START
name = 'Longitude-Latitude box of the data'
requires_clearing = True
dependencies = ['transform', 'transpose']
@property
def lonlatbox_transformed(self):
value = np.asarray(self.lonlatbox)
transformed = self.transform.projection.transform_points(
ccrs.PlateCarree(), value[:2], value[2:])[..., :2]
value[:2] = transformed[..., 0]
value[2:] = transformed[..., 1]
if value[0] == value[1] and isinstance(self.transform.projection,
ccrs.PlateCarree):
value[1] += 360
return value
def data_dependent(self, data, set_data=True):
if isinstance(data, InteractiveList):
data = data[0]
decoder = data.psy.decoder
lon, lat = self._get_lola(data, decoder)
new_lonlatbox = self.calc_lonlatbox(
lon, lat, decoder.is_unstructured(data))
update = self.data_lonlatbox != new_lonlatbox
if not update and set_data and self.value is not None:
self.update(self.value)
elif update:
self.logger.debug(
"Reinitializing because lonlatbox of new data %s does not "
"match the old one %s", new_lonlatbox, self.data_lonlatbox)
return update
def update(self, value):
if isinstance(self.data, InteractiveList):
for i, arr in enumerate(self.data):
decoder = self.get_decoder(i)
self.data[i] = self.update_array(
value, arr, decoder, next(six.itervalues(
self.raw_data[i].psy.base_variables)))
else:
arr = self.data
arr = self.update_array(
value, arr, self.decoder, next(six.itervalues(
self.raw_data.psy.base_variables)))
self.data = arr
def _get_lola(self, data, decoder):
"""Get longitude and latitde informations from the given data array"""
lon_da = decoder.get_x(data, data.coords)
lat_da = decoder.get_y(data, data.coords)
lon, lat = self.to_degree(lon_da.attrs.get('units'), lon_da.values,
lat_da.values)
data_shape = data.shape[-2:] if not decoder.is_unstructured(data) \
else (data.shape[-1], )
is_combined = data_shape != data.shape
if lon.shape == data_shape and lat.shape == data_shape:
vals = data.values[0 if is_combined else slice(None)]
lon = np.where(np.isnan(vals), np.nan, lon)
lat = np.where(np.isnan(vals), np.nan, lat)
return lon, lat
def update_array(self, value, data, decoder, base_var=None):
"""Update the given `data` array"""
lon, lat = self._get_lola(data, decoder)
self.data_lonlatbox = self.calc_lonlatbox(
lon, lat, decoder.is_unstructured(data))
if value is None:
self.lonlatbox = self.data_lonlatbox
return data
else:
if isinstance(value, six.string_types):
value = self.lola_from_pattern(value)
if value is None:
self.lonlatbox = self.data_lonlatbox
return data
value = list(value)
for i, v in enumerate(value):
if isinstance(v, six.string_types):
value[i] = self.lola_from_pattern(v)[i]
is_unstructured = decoder.is_unstructured(
base_var if base_var is not None else data)
is_rectilinear = lon.ndim == 1 and not is_unstructured
shift = isinstance(self.transform.projection, ccrs.PlateCarree)
if is_rectilinear and shift:
data = data.copy(True)
lon, data.values = self.shiftdata(
lon, data.values, np.mean(value[:2]))
lon_name = decoder.get_x(data, data.coords).name
data[lon_name] = (data[lon_name].dims, lon,
data[lon_name].attrs)
elif is_unstructured and shift:
# make sure that we are inside the map extent
ret = self.transform.projection.transform_points(
self.transform.projection, lon, lat)
lon = ret[..., 0]
lat = ret[..., 1]
self.lonlatbox = value
value = self.lonlatbox_transformed
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'invalid value encountered',
RuntimeWarning)
if is_rectilinear and (lat[1:] < lat[:-1]).all():
lat_values = value[3:1:-1]
else:
lat_values = value[2:]
if is_rectilinear:
kwargs = dict(zip(
data.dims[-2:], starmap(
slice, [lat_values, value[:2]])))
ret = data.sel(**kwargs)
else:
ret = self.mask_outside(data.copy(True), lon, lat, *value,
is_unstructured=is_unstructured)
lon, lat = self._get_lola(ret, decoder)
self.data_lonlatbox = self.calc_lonlatbox(
lon, lat, is_unstructured)
return ret
def to_degree(self, units=None, *args):
"""Converts arrays with radian units to degree
Parameters
----------
units: str
if ``'radian'``, the arrays in ``*args`` will be converted
``*args``
numpy arrays
Returns
-------
list of np.ndarray
returns the arrays provided with ``*args``
Notes
-----
if `units` is ``'radian'``, a copy of the array will be returned"""
args = list(args)
if units == 'radian' and isinstance(self.transform.projection,
ccrs.PlateCarree):
for i, array in enumerate(args):
args[i] = array * 180. / np.pi
return args
def mask_outside(self, data, lon, lat, lonmin, lonmax, latmin, latmax,
is_unstructured=False):
data.values = data.values.copy()
ndim = 2 if not is_unstructured else 1
if lonmax < lonmin:
lonmax += 360
lon[lon < 0] += 360
mask = np.any([lon < lonmin, lon > lonmax, lat < latmin,
lat > latmax], axis=0)
if data.ndim > ndim:
if is_unstructured:
data = data.psy[:, np.where(~mask)[0]]
else:
for i, arr in enumerate(data.values):
arr[mask] = np.nan
data.values[i, :] = arr
else:
if is_unstructured:
data = data.psy[np.where(~mask)[0]]
else:
data.values[mask] = np.nan
return data
def calc_lonlatbox(self, lon, lat, is_unstructured=False):
if isinstance(self.transform.projection, ccrs.PlateCarree):
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'invalid value encountered',
RuntimeWarning)
lon = lon[np.all([lon >= -180, lon <= 360], axis=0)]
lat = lat[np.all([lat >= -90, lat <= 90], axis=0)]
return [lon.min(), lon.max(), lat.min(), lat.max()]
else:
if lon.ndim == 1 and not is_unstructured:
lon, lat = np.meshgrid(lon, lat)
points = ccrs.PlateCarree().transform_points(
self.transform.projection, lon, lat)
lon = points[..., 0]
lat = points[..., 1]
lon_0 = self.transform.projection.proj4_params.get('lon_0')
if lon_0 is not None:
lon = np.where(lon > lon_0 + 180, lon - 360, lon)
lon = np.where(lon < lon_0 - 180, lon + 360, lon)
return [lon.min(), lon.max(), lat.min(), lat.max()]
def shiftdata(self, lonsin, datain, lon_0):
"""
Shift the data such that it matches the region we want to show
Parameters
----------
%(shiftdata.parameters)s
Notes
-----
`datain` can also be multiple fields stored in a three-dimensional
array. Then we shift all fields along the first dimension
"""
# shiftdata does not work properly if we do not give the bounds of
# the array
lonsin = lonsin.copy()
if lonsin.ndim == 1:
get_centers = True
lonsin = _infer_interval_breaks(lonsin)
else:
get_centers = False
if datain.ndim == 2:
lonsin, datain = shiftdata(lonsin, datain, lon_0)
elif datain.ndim == 3:
lon_save = lonsin.copy()
for i, a in enumerate(datain):
lonsin, datain[i] = shiftdata(lon_save, a, lon_0)
if get_centers:
lonsin = np.mean([lonsin[1:], lonsin[:-1]], axis=0)
return lonsin, datain
class MapExtent(BoxBase):
"""
Set the extent of the map
Possible types
--------------
None
The map extent is specified by the data (i.e. by the :attr:`lonlatbox`
formatoption)
'global'
The whole globe is shown
'data'
The extent is set to the longitude-latitute box defined by the
:attr:`lonlatbox` formatoption
%(BoxBase.possible_types)s
Notes
-----
This formatoption sets the extent of the plot. For choosing the region for
the data, see the :attr:`lonlatbox` formatoption
See Also
--------
lonlatbox"""
dependencies = ['lonlatbox', 'plot', 'vplot']
name = 'Longitude-Latitude box of the plot'
priority = END
update_after_plot = True
@property
def coords(self):
arr = next(self.iter_data)
return [arr.psy.get_coord('x'),
arr.psy.get_coord('y')]
def update(self, value):
set_global = False
if isinstance(value, six.string_types):
if value == 'global':
set_global = True
elif value == 'data':
value = self.lonlatbox.lonlatbox
else:
value = self.lola_from_pattern(value)
elif value is None:
# use autoscale
self.ax.autoscale()
return
else:
value = list(value)
for i, v in enumerate(value):
if isinstance(v, six.string_types):
value[i] = self.lola_from_pattern(v)[i]
# Since the set_extent method does not always work and the data limits
# are not always correctly set, we test here whether the wished
# extent (the value) is almost global. If so, we set it to a global
# value
if not set_global:
with self.ax.hold_limits():
self.ax.set_global()
try:
x1, x2, y1, y2 = self.ax.get_extent(ccrs.PlateCarree())
except ValueError:
# extent could not be guessed, we let cartopy do everything
x_rng = 360
y_rng = 180