-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2408 lines (2011 loc) · 79 KB
/
utils.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
General purpose utilities.
"""
from __future__ import print_function
import os
import csv
import glob
import errno
import math
import socket
import inspect
import logging as log
import numpy as np
import matplotlib as mpl
import matplotlib.cm as mpl_cm
import collections
import time
from sys import platform
from netCDF4 import Dataset
from datetime import date, datetime, timedelta
from scipy.ndimage import gaussian_filter
from scipy.spatial import cKDTree
from scipy.stats import describe, binned_statistic_2d
from matplotlib import pyplot as plt
try:
from Tkinter import Tk
from tkFileDialog import askopenfilenames
except ImportError:
from tkinter import Tk
from tkinter.filedialog import askopenfilenames
try:
from mpl_toolkits.basemap import Basemap
except ImportError:
Basemap = None
try:
import cartopy
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
except ImportError:
cartopy = None
log.basicConfig(
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%F %T', level=log.INFO)
# To log debug messages, call
# >>> log.getLogger().setLevel(log.DEBUG)
from packaging import version
__version__ = "1.0"
__author__ = "Yaswant Pradhan"
_tstart_stack = [] # forf tic2() toc2()
class Convert(object):
"""
Simple unit converter
Attributes
----------
value : number
Input value to convert.
"""
def __init__(self, value):
self.value = np.array(value)
def __enter__(self):
return self
def ft2m(self):
return self.value * 0.3048
def ft2km(self):
"""Feet to Kilometre"""
return self.value * 0.3048 / 1e3
def kt2mph(self):
"""Knots to miles-per-hour"""
return self.value * 1.15077945
def mph2kt(self):
"""Miles-per-hour to Knots"""
return self.value / 1.15077945
def kg2lb(self):
"""Kilograms to Pounds"""
return self.value * 2.20462262
def lb2kg(self):
"""Pounds to Kilograms"""
return self.value / 2.20462262
def f2c(self):
"""Fahrenheit to Celsius"""
return (self.value - 32) / 1.8
def c2f(self):
"""Celsius to Fahrenheit"""
return self.value * 1.8 + 32
def solzen2airmass(self):
"""Solar zenith angle (degrees) to Airmass.
Air Mass is the path length which light takes through the atmosphere
normalized to the shortest possible path length (ie, when the sun is
directly overhead). The Air Mass quantifies the reduction in the power
of light as it passes through the atmosphere and is absorbed by air
and dust. For a flat horizontal atmosphere, Airmass is defined as
1/cos(sol_zen)
But because of the curvature of the atmosphere, the air mass is not
quite equal to the atmospheric path length when the sun is close to
the horizon. At sunrise, the angle of the sun from the vertical
position is 90 deg and the air mass is infinite, whereas the path
length clearly is not. An equation which incorporates the curvature of
the earth is given by F. Kasten and Young, A. T. (1989)
"Revised optical air mass tables and approximation formula",
Applied Optics, vol. 28, pp. 4735-4738, 1989.
1/[cos(sol_zen) + 0.50572(96.07995-sol_zen)^-1.6364]
"""
corrected_cosine = np.cos(np.radians(self.value)) + \
0.50572 * (96.07995 - self.value)**-1.6364
return 1 / corrected_cosine
def __exit__(self, exc_type, exc_value, traceback):
self.value = 0
class Integer(object):
"""The usual single-bit operations will work on any Python integer."""
def __init__(self, int_type):
super(Integer, self).__init__()
self.int_type = int_type
def test_bit(self, offset, mask_type=None):
"""test_bit() returns a non-zero result, 2**offset, if the bit at
'offset' is one.
Parameters
----------
offset : int
Bit position to test. It is up to the user to make sure that the
value of offset makes sense in the context of the program
mask_type : str, optional
Returns a boolean (True|False) mask, if set to 'bool' or
a binary (1|0) mask if set to 'bin' or 'int', instead of 2**offset.
Returns
-------
int_type or boolean
Description
Examples
--------
test 3rd bit for 10
>>> print(Integer(10).test_bit(3))
8
>>> print(Integer(10).test_bit(3, mask_type='bool'))
True
>>> print(Integer(10).test_bit(3, mask_type='int'))
1
"""
mask = 1 << offset
if mask_type == 'bool':
return(self.int_type & mask != 0)
elif mask_type in ('int', 'bin'):
return(self.int_type & mask != 0) * 1
else:
return(self.int_type & mask)
def set_bit(self, offset):
"""set_bit() returns an integer with the bit at 'offset' set to 1."""
mask = 1 << offset
return(self.int_type | mask)
def clear_bit(self, offset):
"""clear_bit() returns an integer with the bit at 'offset' cleared."""
mask = ~(1 << offset)
return(self.int_type & mask)
def toggle_bit(self, offset):
"""toggle_bit() returns an integer with the bit at 'offset' inverted,
0 -> 1 and 1 -> 0.
"""
mask = 1 << offset
return(self.int_type ^ mask)
class List(list):
"""Create a custom List object to which user attributes can be added.
Parameters
----------
list : list, optional
input list object
Returns
-------
custom List object with user defined attributes
Example
-------
>>> a_list = List()
>>> a_list.name = 'ListName'
>>> a_list.append(np.array(10))
Or,
>>> a_list = List([np.array(10)], name='ListName')
"""
def __new__(self, *args, **kwargs):
return super(List, self).__new__(self, args, kwargs)
def __init__(self, *args, **kwargs):
if len(args) == 1 and hasattr(args[0], '__iter__'):
list.__init__(self, args[0])
else:
list.__init__(self, args)
self.__dict__.update(kwargs)
def __call__(self, **kwargs):
self.__dict__.update(kwargs)
return self
class Timer(object):
"""A timer class to measure elapsed time as a context manager"""
def __init__(self, name=None):
"""Summary
Parameters
----------
name : str, optional
String to identify the process in output.
Example
-------
>>> with Timer('foo'):
>>> code block
[foo]
Elapsed: 00:00:08
"""
self.name = name
def __enter__(self):
self.tstart = time.monotonic()
def __exit__(self, type, value, traceback):
if self.name:
print('[{}]'.format(self.name), end='', flush=True)
tdiff = time.gmtime(time.monotonic() - self.tstart)
print(' Elapsed time: {}'.format(time.strftime("%H:%M:%S", tdiff)))
class XYZ(object):
"""Discrete triplet data (x, y, z) analyser."""
def __init__(self, x, y, z, wrap_lon=False):
"""XYZ Constructor.
Parameters
----------
x : array_like, shape(N,)
An array containing the x coordinates of the points to be binned
y : array_like, shape(N,)
An array containing the y coordinates of the points to be binned
z : array_like, shape(N,) f(x,y)
actual data to be re-sampled (average at each grid cell)
"""
self.x = np.array(x)
self.y = np.array(y)
self.z = np.array(z)
if wrap_lon:
self.x = ((self.x + 180) % 360) - 180
# bin parameters for griddata
self.delta = (1, 1)
self.limit = np.array([[-180, 180], [-90, 90]])
# plot parameters used in mapdata
self.figsize = (8, 5)
self.figheight = self.figsize[1]
self.gspacing = (30, 30)
self.xlab = [0, 0, 0, 1]
self.ylab = [1, 0, 0, 0]
self.cbpad = '10%'
self.G, self.xc, self.yc = None, None, None
# update xlimit based on actual data
if self.x.max() > 180:
self.limit[0] = [0, 360]
def __enter__(self):
return self
def _get_extent(self):
"""Get extent for x and y values."""
return [[self.x.min(), self.x.max()], [self.y.min(), self.y.max()]]
def _get_latts(self, spacing):
"""Get latitude grid mark locations."""
return np.arange(-90., 99., spacing)
def _get_lonts(self, spacing):
"""Get longitude grid mark locations."""
return np.arange(-180., 181., spacing)
def bindata(self, **kw):
"""Bin irregular 1D data (triplets) on to 2D plane.
Deprecated, use griddata with 'mean' method instead.
Parameters
----------
delta : sequence or [float, float], optional
Output grid resolution in x and y direction (default (1, 1)).
The delta specification:
* If scalar, the grid resolution for the two dimensions are equal
(dx=dx=delta)
* If [float, float], the grid resolution for the two dimensions
(dx, dy = delta)
limit : [[float, float], [float, float]], optional
Output domain limit [[x0,x1], [y0,y1]] (default calculated from
actual x and y range)
globe : bool, optional
If True, sets the grid x and y limit to [-180,180] and [-90,90],
respectively. If False, grid x and y limits are taken from input.
(default False)
order : bool, optional
If True, returns a upside-down flip and rotated array (default
False)
Returns
-------
G : MaskedArray, shape(nxc,nyc)
The 2-dimensional binned (averaged) array of z
xc : ndarray, shape(nx,)
The bin centres along the x dimension
yc : ndarray, shape(ny,)
The bin centres along the y dimension
Example
-------
>>> from numpy.random import normal
>>> from ypylib.utils import XYZ
>>> x = normal(3, 1, 100)
>>> y = normal(1, 1, 100)
>>> z = x * y
>>> G, xc, yc = XYZ(x, y, z).bindata(delta=[0.1, 0.1])
"""
delta = kw.get('delta', self.delta)
globe = kw.get('globe', False)
order = kw.get('order', False)
limit = kw.get('limit', self._get_extent())
if globe is True:
limit = self.limit
if len(delta) == 1:
delta = [delta, delta]
x, y, z = np.asarray(self.x), np.asarray(self.y), np.asarray(self.z)
# construct x and y bins
xs = np.arange(limit[0][0], limit[0][1] + delta[0], delta[0])
ys = np.arange(limit[1][0], limit[1][1] + delta[1], delta[1])
# sum and edges of each bin
Hv, xl, yb = np.histogram2d(x, y, bins=[xs, ys], weights=z)
# shift bin edged by 0.5*delta to get centre of bins
xc, yc = xl[:-1] + delta[0] / 2., yb[:-1] + delta[1] / 2.
# counts for each bin
Hn, _, _ = np.histogram2d(x, y, bins=[xs, ys])
# mask sum array where count = 0 i.e. no data in the bin
Hv = np.ma.masked_where(Hn == 0, Hv)
if order is True:
# rotate grid (column major) for display purpose
return np.flipud(np.rot90(Hv / Hn)), xc, yc
else:
return Hv / Hn, xc, yc
def griddata(self, stat='mean', **kw):
"""Compute a bi-dimensional binned statistic for one or more sets of
data.
This is a generalization of a histogram2d function implemented in
bindata. A histogram divides the space into bins, and returns the
count of the number of points in each bin. This function allows the
computation of the sum, mean, median, or other statistic of the values
(or set of values) within each bin.
Parameters
----------
delta : sequence or [float, float], optional
Output grid resolution in x and y direction (default (1, 1)).
The delta specification:
* If scalar, the grid resolution for the two dimensions are equal
(dx=dx=delta)
* If [float, float], the grid resolution for the two dimensions
(dx, dy = delta)
globe : bool, optional
If True, sets the grid x and y limit to [-180,180] and [-90,90],
respectively. If False, grid x and y limits are taken from input.
(default False)
limit : [[float, float], [float, float]], optional
Output domain limit [[x0,x1], [y0,y1]] (default calculated from
actual x and y range)
stat : str, optional
The statistic to compute (default is 'mean'). Available statistics
are: 'mean', 'std', median', 'count', 'sum', 'min', 'max'
norm : bool, optional
Normalize (rescale values between 0 and 1) gridded output values.
order : bool, optional
If True, returns a upside-down flip and rotated array (default
False)
Returns
-------
G : ndarray, shape(nxc, nyc)
The 2-dimensional binned (averaged) array of z
xc : ndarray, shape(nx,)
The bin centres along the x dimension
yc : ndarray, shape(ny,)
The bin centres along the y dimension
See also
--------
bindata (deprecated)
equivalent to stat='mean'
"""
try:
from collections.abc import Sequence
except ImportError:
from collections import Sequence
delta = kw.get('delta', self.delta)
globe = kw.get('globe', False)
order = kw.get('order', False)
limit = kw.get('limit', self._get_extent())
norm = kw.get('norm', False)
stat = kw.get('method', stat)
# limit = np.asarray(limit)
# parse stat parameter
stat = stat.lower()
stat = 'sum' if stat in ('sum', 'total') else stat
stat = 'mean' if stat in ('avg', 'average', 'mean') else stat
stat = 'count' if stat in ('count', 'frequency') else stat
# if stat in ('sum', 'total'):
# stat = 'sum'
# if stat in ('avg', 'average', 'mean'):
# stat = 'mean'
# if stat in ('count', 'freq', 'frequency'):
# stat = 'count'
if globe is True:
limit = self.limit
if isinstance(delta, Sequence) is False:
delta = [delta, delta]
if len(delta) == 1:
delta = [delta, delta]
# construct x and y bins
xs = np.arange(limit[0][0], limit[0][1] + delta[0], delta[0])
ys = np.arange(limit[1][0], limit[1][1] + delta[1], delta[1])
stat4 = binned_statistic_2d(
self.x, self.y, self.z, statistic=stat, bins=[xs, ys])
# bin edges to bin centres
xc = (stat4[1][1:] + stat4[1][:-1]) / 2
yc = (stat4[2][1:] + stat4[2][:-1]) / 2
# print(xc.min(), xc.max(), yc.min(), yc.max())
# mask sum, std and count arrays when no data available in the bin
if stat in ('count', 'std', 'sum'):
count4 = binned_statistic_2d(
self.x, self.y, self.z, statistic='count', bins=[xs, ys])
G = np.ma.masked_where(count4[0] == 0, stat4[0])
else:
G = np.ma.masked_invalid(stat4[0])
# normalise gridded data if requested
if norm:
gmin, gmax = G.min(), G.max()
G = (G - gmin) / (gmax - gmin)
self.G, self.xc, self.yc = G, xc, yc
# transpose grid if requested
if order:
self.G = G.transpose()
return self.G, self.xc, self.yc
else:
return self.G, self.xc, self.yc
def shift_midpoints(self, **kw):
"""Shift x and y vectors by half-grid for pcolormesh
``pcolormesh`` patches bottom-left is usually aligned with grid centre
(x,y) which makes the plot shift by half-grid in top-right direction.
This method applies the correction so that the patch centres are
aligned with the grid centre.
"""
# - expand/and shift x grid centre
xe = np.zeros(self.xc.size + 2)
xe[1:-1] = self.xc
xe[0] = self.xc[0] - np.diff(self.xc)[0]
xe[-1] = self.xc[-1] + np.diff(self.xc)[-1]
xc = xe[:-1] + 0.5 * (np.diff(xe))
# - expand/and shift y grid centre
ye = np.zeros(self.yc.size + 2)
ye[1:-1] = self.yc
ye[0] = self.yc[0] - np.diff(self.yc)[0]
ye[-1] = self.yc[-1] + np.diff(self.yc)[-1]
yc = ye[:-1] + 0.5 * (np.diff(ye))
return xc, yc
def plot(self, **kw):
"""Line plot (x, y, z) as series."""
_f, ax = plt.subplots(1, figsize=self.figsize)
ax.plot(self.x.ravel(), c='r', label='x', **kw)
ax.plot(self.y.ravel(), c='g', label='y', **kw)
ax.plot(self.z.ravel(), c='b', label='z', **kw)
plt.legend(ncol=3, borderaxespad=0)
plt.tight_layout()
return plt
def scatter(self, **kw):
"""Scatter plot (x, y, z) data triplets."""
_f, ax = plt.subplots(1, figsize=self.figsize)
im = ax.scatter(
self.x, self.y, c=self.z, lw=0, rasterized=True, **kw)
plt.title('xyz.scatter()')
plt.xlabel('x')
plt.ylabel('y')
plt.colorbar(im)
plt.tight_layout()
return plt
def hexbin(self, **kw):
"""Hexagon plot (x, y, z) data triplets.
hexbin is a bivariate histogram in which the xy-plane is tessellated
by a regular grid of hexagons.
"""
_f, ax = plt.subplots(1, figsize=self.figsize)
im = ax.hexbin(
self.x.ravel(), self.y.ravel(), C=self.z.ravel(), bins=None, **kw)
plt.colorbar(im)
plt.tight_layout()
return plt
def pcolormesh(self, delta=(1, 1), **kw):
"""Pcolormesh plot (x, y, z) data triplets."""
_f, ax = plt.subplots(1, figsize=self.figsize)
G, xc, yc = self.griddata(delta=delta)
xx, yy = np.meshgrid(xc, yc)
im = ax.pcolormesh(xx, yy, G, shading='flat', **kw)
plt.colorbar(im)
plt.tight_layout()
return plt
def contour(self, delta=(1, 1), **kw):
"""contour plot (x, y, z) data triplets."""
_f, ax = plt.subplots(1, figsize=self.figsize)
G, xc, yc = self.griddata(delta=delta)
im = ax.contour(xc, yc, G, **kw)
plt.clabel(im, inline=True, fontsize=6, fmt='%g')
return plt
def mapdata(self, use_cartopy=True, **kw):
"""Render xyz data on map.
Parameters
----------
Contour properties:
c_ecolor : mpl.color, optional
Set contour line colours (default '0.5')
c_levels : int or array_like, optional
Determines the number and positions of the contour lines / regions.
An integer value indicates number of levels (mpl decides the
boundaries) where are an array specifies the boundaries
(default 15)
c_lines : bool, optional
Also draw contour lines on top (default: False)
c_smooth : bool, optional
Smooth contour plot if plt_type is set to 'contour' (default False)
c_sm_sigma : The standard deviations of the Gaussian filter applied
for smoothed contour (increase blurriness of the image.
Given for each axis as a sequence, or as a single number, in which
case it is equal for all axes. (default: 0)
Colorbar properties:
cb_extend : str, optional
extend colorbar pointed ends (default: 'neither').
Accepted values are 'neither'|'both'|'min'|'max'.
cb_on : bool, optional
add colorbar on map (default False)
cb_loc : str, optional
location of colorbar position (default 'bottom'). available
options are 'left'|'right'|'top'|'bottom'.
cb_pad : str, optional
padding of colorbar from main plot in % (default '10%').
cb_title : str, optional
title for colorbar title (default None).
cbt_ha : str, optional
colorbar title horizontal alignment (default 'center').
cbt_size : str, optional
colorbar size (default '4%').
cbt_pos : tuple, optional
colorbar title (x, y) position in normal coordinate
(default (0.5, 0.75) for `cbt_ha='centre'`
(1, 0.75) for `cbt_ha='right'`).
clip : bool, optional
clip map extent within valid geographic ranges (default False).
cmap : str, optional
matplotlib colormap name to use (default "Spectral_r").
delta : float or (float, float), optional
resolution specs for binning original data in x and y direction
(default (1, 1).
describe_data : bool, optional
add data statistical description (min, max, mean, ..) for
un-gridded data
drawcountries : bool, optional
draw country boundaries (default False).
drawstates : bool, optional
draw USA state administrative boundaries (default False).
drawstates_ind : bool, optional
draw India state administrative boundaries (default False).
figsize : (number, number), optional
output figure size (default auto adjusted with a base height of 5).
figheight : number, optional
control output figure base height (default 5)
fillcontinents : bool, optional
Underlay continent with solid colour. To mask (overlay) continent
set mask_land=True.
land_color : str, optional
Fill land colour (default: grey)
lake_color : str, optional
Fill lake colour (default: none)
Grid(line) properties:
gcol : str, optional
colours for parallel and meridian lines (default 'grey').
gline : (number, number), optional
grid line style that is dash pattern for meridians and parallels
(default (None, None) for solid line). For example,
``gline = (1, 1)`` will draw 1 pixel on, 1 pixel off.
Available for Basemap version only.
gtextcolor : str, optional
gridline text colour (default '#333333') available for Cartopy only
gtfamily : str, optional
gridline text family (default 'monospace').
gtextsize : number, optional
gridline text size (default 8).
globe : bool, optional
set map extent to global extent (180W:180E, 90S:90N) (default
False). This keyword overrides limit values.
gspacing : (number, number), optional
spacing between grid lines (default (30, 30)).
gzorder : number, optional
zorder of gridlines (default 2). Increase value for visibility
over other masks/data.
limit : [[float,float],[float,float]], optional
output map extent geographic values [[lon0,lon1], [lat0,lat1]]
(default is calculated from min max values).
map_res : str, optional
coastline resolution on map (default 'c' or coarse). available
options are: 'c'oarse|'l'ow|'h'igh.
map_buffer : float, optional
adds extra buffer to map_limit (default None).
pc_midpoints : bool, optional
use grid centres to be the midpoints of pcolormesh patches
(default True).
plt_type : str, optional
plot type option (default 'pcolormesh'). available options are
'hexbin'|'contour'|'tricontour'|pcolormesh'|'scatter'.
projection : str, optional
output map projection (default 'cyl'indrical).
Scatter plot/marker properties:
s_color : str, optional
marker colours for scatter points (default z data).
s_marker : str, optional
marker style for scatter points (default 's'quare).
s_ms : int, optional
marker size for scatter points (default 20).
s_lw : number, optional
linewidth of non-filled markers (e.g., '+', 'x')
show_datapoints : overlay markers at original data points.
show_gridpoints : overlay markers at grid points.
Statistic:
stat : str, optional
statistic to use for data binning before plotting (default 'mean')
Other options are
mean|avg|average, std, median, count, sum|total, min, max.
Not used when ``plt_type='scatter'``.
norm : bool, optional
normalize statistic values between 0 and 1 (default False).
This also applies for plt_type='scatter'
title : str, optional
title string on map (default is no title).
use_cartopy : bool, optional
Force maps to use cartopy in place of default basemap.
verbose : bool, optional
verbose mode (default False).
Data scaling:
vmax : float, optional
maximum value for plot scaling (default max(data)).
vmin : float, optional
minimum value for plot scaling (default min(data))
Returns
-------
matplotlib.pyplt object
Raises
------
ImportError
Basemap required for mapping if ``use_cartopy=False``
NotImplementedError
Raised when projections other than 'cyl', 'laea', 'lcc', 'merc',
'mill', 'moll', 'robin', ot 'sinu' used with Basemap
"""
if cartopy is None and Basemap is None:
raise ImportError('Neither Basemap nor cartopy available.')
if Basemap is None:
use_cartopy = True
stat = kw.get('stat', 'mean')
stat = stat.lower()
describe_data = kw.get('describe_data', False)
plotype = kw.get('plt_type', 'pcolormesh')
plotype = plotype.lower()
# ms = kw.get('markersize', 20)
cbaron = kw.get('cb_on', True)
cbloc = kw.get('cb_loc', 'bottom')
cbpad = kw.get('cb_pad', self.cbpad)
cbextend = kw.get('cb_extend', 'neither')
cbsz = kw.get('cb_size', '4%')
cbtitle = kw.get('cb_title', stat)
auto_cbtha = ['right', 'center'][cbextend in ('max', 'both')]
cbtha = kw.get('cbt_ha', auto_cbtha)
cbtpos = kw.get('cbt_pos', [(0.5, 0.75), (1, 0.75)][cbtha == 'right'])
cmap = kw.get('cmap', 'Spectral_r')
delta = kw.get('delta', self.delta)
drawcountries = kw.get('drawcountries', False)
drawstates = kw.get('drawstates', False)
drawstates_ind = kw.get('drawstates_ind', False)
figsize = kw.get('figsize', self.figsize)
fight = kw.get('figheight', self.figheight)
gcol = kw.get('gcol', 'gray')
gline = kw.get('gline', (None, None))
gzorder = kw.get('gzorder', 2)
gtc = kw.get('gtextcolor', '#333333')
gtf = kw.get('gtfamily', 'monospace')
gts = kw.get('gtextsize', 8)
globe = kw.get('globe', False)
midpoints = kw.get('pc_midpoints', True)
show_datapoints = kw.get('show_datapoints', False)
datapoint_size = kw.get('datapoint_size', 2)
datapoint_color = kw.get('datapoint_size', 'k')
show_gridpoints = kw.get('show_gridpoints', False)
fillcontinents = kw.get('fillcontinents', False)
filloceans = kw.get('filloceans', False)
land_color = kw.get('land_color', '#DEDEDE')
lake_color = kw.get('lake_color', '#97B6E1')
ocean_color = kw.get('ocean_color', '#97B6E1')
mask_land = kw.get('mask_land', False)
mask_ocean = kw.get('mask_ocean', False)
zorder, lm_zorder, om_zorder = 1, 1, 1
if mask_land:
fillcontinents = True
lm_zorder = 2
if mask_ocean:
filloceans = True
om_zorder = 2
limit = np.array(
kw.get('limit', np.array(
[[self.x.min(), self.x.max()], [self.y.min(), self.y.max()]])))
mbuf = kw.get('map_buffer', None)
if mbuf:
limit += np.array([[-mbuf, mbuf], [-mbuf, mbuf]])
for i in (0, 1):
limit[0][i] = min(max(limit[0][i], -180), 180)
limit[1][i] = min(max(limit[1][i], -90), 90)
# - normalise stat
norm = kw.get('norm', False)
if globe is True:
limit = self.limit
gspacing = kw.get('gspacing', self.gspacing)
else:
auto_gs = (np.floor(limit[0].ptp() / 4),
np.floor(limit[1].ptp() / 4))
gspacing = kw.get('gspacing', auto_gs)
clip = kw.get('clip', False)
mres = kw.get('map_res', 'l')
title = kw.get('title', ' ')
vmin = kw.get('vmin', self.z.min())
vmax = kw.get('vmax', self.z.max())
verb = kw.get('verbose', False)
if plotype in ('contour', 'hexbin', 'pcolormesh'):
if self.G is None:
self.G, self.xc, self.yc = self.griddata(
stat=stat, delta=delta, norm=norm, order=True)
# - 2D grid centres
xxc, yyc = np.meshgrid(self.xc, self.yc)
if stat in ('count', 'sum'):
# vmin, vmax = self.G.min(), self.G.max()
vmin = kw.get('vmin', self.G.min())
vmax = kw.get('vmax', self.G.max())
if norm:
vmin, vmax = 0, 1
cbtitle += ' (norm)'
if clip is True:
limit[0] = np.clip(limit[0], -180., 180.)
limit[1] = np.clip(limit[0], -90., 90.)
clon = np.mean(limit[0])
clat = np.mean(limit[1])
dx = np.ptp(np.array(limit[0], 'f'))
dy = np.ptp(np.array(limit[1], 'f'))
aspect = dx / dy
yoff = [1, 0.5][cbloc in ('left', 'right')]
figsize = kw.get('figsize', (fight * aspect + 0.5, fight + yoff))
if verb:
log.info('figsize={}'.format(figsize))
# - draw map
ax = kw.get('ax', None)
if ax is None:
fig = plt.figure(figsize=figsize)
else:
fig = mpl.pyplot.gcf()
if Basemap is None or use_cartopy is True: # ------------ use cartopy
data_proj = cartopy.crs.PlateCarree()
proj = kw.get('projection', data_proj)
try:
proj_name = proj.__class__.__name__
except AttributeError:
raise AttributeError(
'{} is not a valid ccrs proection class'.format(proj))
font_kw = {'family': gtf, 'size': gts, 'color': gtc}
gl_kw = {
'linestyle': '-', 'color': gcol, 'alpha': 0.5,
'xlocs': self._get_lonts(gspacing[0]),
'ylocs': self._get_latts(gspacing[1]),
'zorder': gzorder,
}
if mres in ('h', '10m'):
mres = '10m'
elif mres in ('l', '50m'):
mres = '50m'
else:
mres = '110m'
if 'ax' not in kw:
ax = fig.add_subplot(111, projection=proj, title=title)
# ax = plt.axes(projection=proj, title=title)
# if globe is False:
# ax.set_extent(limit.ravel(), crs=data_proj)
ax.set_extent(limit.ravel(), crs=data_proj)
if drawcountries:
countries = cartopy.feature.NaturalEarthFeature(
category='cultural', name='admin_0_countries',
scale=mres, linewidth=0.5,
facecolor='none', edgecolor='k', alpha=0.6,)
ax.add_feature(countries, zorder=lm_zorder + 3)
# ax.add_feature(
# cartopy.feature.BORDERS, linewidth=0.4, alpha=0.5)
if drawstates:
states_provinces = cartopy.feature.NaturalEarthFeature(
category='cultural', name='admin_1_states_provinces_lines',
scale='10m', linewidth=0.4,
facecolor='none', edgecolor='k', alpha=0.5)
ax.add_feature(states_provinces)
if drawstates_ind:
# add Indian states
import cartopy.io.shapereader as shpreader
adm_1 = os.path.expandvars(
'$HOME/.local/share/cartopy/shapefiles/gadm/cultural/'
'gadm36_IND_1.shp'
)
adm1_shapes = list(shpreader.Reader(adm_1).geometries())
ax.add_geometries(
adm1_shapes, cartopy.crs.PlateCarree(),
edgecolor='k',
linewidth=0.5,
linestyle='dotted',
facecolor='none',
# alpha=0.5,
zorder=3,
)
# add continent, coastline
if fillcontinents:
ax.add_feature(cartopy.feature.LAND, zorder=lm_zorder)
ax.add_feature(cartopy.feature.LAKES, zorder=lm_zorder,
edgecolor='k', linewidth=0.5)
if filloceans:
ax.add_feature(cartopy.feature.OCEAN, zorder=om_zorder)
ax.coastlines(lw=0.5, resolution=mres, zorder=lm_zorder + 3)
if version.parse(cartopy.__version__) > version.parse('0.17.0'):
gl = ax.gridlines(draw_labels=True, **gl_kw)
gl.top_labels, gl.right_labels = False, False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style, gl.ylabel_style = font_kw, font_kw
else:
if proj_name in ('PlateCarree', 'Mercator'):
gl = ax.gridlines(draw_labels=True, **gl_kw)
gl.xlabels_top, gl.ylabels_right = False, False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style, gl.ylabel_style = font_kw, font_kw
else:
ax.gridlines(**gl_kw)
else: # ------------------------------------------------- use Basemap
fig.add_axes([0.05, 0.05, 0.9, 0.9], title=title)
proj = kw.get('projection', 'cyl')
grid_kw = {
'family': gtf,
'fontsize': gts,
'color': gcol,
'linewidth': 0.2,
'dashes': gline,
'zorder': gzorder,
}
valid_proj = (
'cyl', 'laea', 'lcc', 'merc', 'mill', 'moll', 'robin', 'sinu',
)
if proj not in (valid_proj):
raise NotImplementedError(
'\'{}\' not implemented yet.\n'
'Available projections are: {}\n'.format(proj, valid_proj))
try:
# for pseudo-cylindrical projection set the central coordinate
# to 0, 0.
# Note: Geographic subset is not respected for these
# projections with Basemap (use Cartopy instead).
if proj in ('moll', 'robin', 'sinu'):
clat, clon = 0, 0
ax = Basemap(
projection=proj, lat_0=clat, lon_0=clon, resolution=mres,
llcrnrlon=limit[0][0], llcrnrlat=limit[1][0],
urcrnrlon=limit[0][1], urcrnrlat=limit[1][1])
except ValueError as err:
raise ValueError('{}\nTip: Use mapdata(clip=True)'.format(err))
ax.drawmapboundary(fill_color='1')
ax.drawmeridians(
self._get_lonts(gspacing[0]), labels=self.xlab, **grid_kw)
ax.drawparallels(
self._get_latts(gspacing[1]), labels=self.ylab, **grid_kw)
if fillcontinents:
ax.fillcontinents(
color=land_color, lake_color=lake_color, zorder=lm_zorder)
if filloceans:
ax.drawlsmask(