-
Notifications
You must be signed in to change notification settings - Fork 1
/
UKESMpython.py
2030 lines (1630 loc) · 63.3 KB
/
UKESMpython.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
#
# Copyright 2014, Plymouth Marine Laboratory
#
# This file is part of the bgc-val library.
#
# bgc-val is free software: you can redistribute it and/or modify it
# under the terms of the Revised Berkeley Software Distribution (BSD) 3-clause license.
# bgc-val 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 revised BSD license for more details.
# You should have received a copy of the revised BSD license along with bgc-val.
# If not, see <http://opensource.org/licenses/BSD-3-Clause>.
#
# Address:
# Plymouth Marine Laboratory
# Prospect Place, The Hoe
# Plymouth, PL1 3DH, UK
#
# Email:
# ledm@pml.ac.uk
#
"""
.. module:: UKESMpython
:platform: Unix
:synopsis: A swiss army knife of tools for BGCval.
.. moduleauthor:: Lee de Mora <ledm@pml.ac.uk>
"""
from sys import argv
from string import join
from netCDF4 import Dataset
from os.path import exists,getmtime
from os import mkdir, makedirs
import os
import math
from glob import glob
from itertools import product,izip
import numpy as np
from matplotlib import pyplot
from mpl_toolkits.basemap import Basemap
from matplotlib.ticker import FormatStrFormatter
from matplotlib.colors import LogNorm
try:
import cartopy.crs as ccrs
import cartopy.io.shapereader as shapereader
from cartopy import img_transform, feature as cfeature
except:
print "Unable to load Cartopy"
from scipy.stats.mstats import scoreatpercentile
from scipy.stats import linregress,mode as scimode
from calendar import month_name
from shelve import open as shOpen
import socket
from bgcvaltools.RobustStatistics import MAD
try:import yaml
except: pass
""" UKESMpython is a catch all toolkit for the python methods and shorthands used in this code.
"""
try: defcmap = pyplot.cm.viridis
except:
from bgcvaltools.viridis import viridis
defcmap = viridis
def folder(name):
""" This snippet takes a string, makes the folder and the string.
It also accepts lists of strings.
"""
if type(name) == type(['a','b','c']):
name=join(name,'/')
if name[-1] != '/':
name = name+'/'
if exists(name) is False:
makedirs(name)
print 'makedirs ', name
return name
def rebaseSymlinks(fn,dryrun=True):
"""
:param fn: A full path to a filename. It should be a symbolic link.
:param dryrun: A boolean switch to do a trial run of this function.
This function reduces a chain of symbolic links down to one. It takes a full path,
checks whether it is a sym link, then checks whether the real path is the target of the link.
If not, it replaces the target with the real path.
"""
#####
# fn is a link file
#if not os.path.exists(fn):
# print "rebaseSymlinks:\tfile does not exist.",fn
# return
if not os.path.islink(fn):
print "rebaseSymlinks:\tfile is not a symlink.",fn
return
#####
# Real path and first target:
realpath = os.path.realpath(fn) # The final end of the link chin
linkpath = os.readlink(fn) # The first target in the symlink chain
if realpath == linkpath: return
print "rebaseSymlinks:\tdeleting and re-linking ",fn,'-->', realpath
if dryrun: return
os.remove(fn)
os.symlink(realpath,fn)
def mnStr(month):
"""
:param month: An int between 1 and 100.
Returns a 2 digit number string with a leading zero, if needed.
"""
mn = '%02d' % month
return mn
#def getCommandJobIDandTime():
# jobID = argv[1]
# timestamp = argv[2]
# return jobID,timestamp
def getFileList(fin):
if type(fin)==type('abc') and fin.find('*')<0 and fin.find('?')<0: # fin is a string file:
return [fin,]
if type(fin)==type('abc') and (fin.find('*')>-1 or fin.find('?')>-1 or fin.find('[')>-1): # fin is a string file:
return glob(fin)
if type(fin) == type(['a','b','c',]): # fin is many files:
filesout = []
for f in fin:
filesout.extend(glob(f))
return filesout
def listFiles(a, want=100, listType = 'even' ,first = 30,last = 30):
"""
:param a: A list, usually made of paths to a filename.
:param want: An estimate of the number of filesout
:param listType: Three options available:
'even': evenly distribute data.
'frontloaded': Log scale with most of the data at the front.
'backloaded': Log scale with most of the data at the end.
:param first: All the "first" number of items from the front of the list.
:param last: All the "last" number of items from the end of the list.
"""
l = len(a)
a = sorted(a)
want = int(want)
#####
# Look at them evenly.
if len(a) > want:
if listType=='even':
newlist = list(a[::int(l/float(want))])
if listType=='frontloaded':
newlist = [a[int(f)] for f in np.logspace(0,np.log10(l-1),want,)]
if listType=='backloaded':
newlist = [a[l-int(f)] for f in np.logspace(0,np.log10(l),want,)]
else:
newlist = a
#####
# Add the last 30 files
if last and len(a)>last:
newlist.extend(a[-last:])
else:
newlist.append(a[-1])
#####
# Add the first 30 files
if first and len(a)>first:
newlist.extend(a[:first])
else:
newlist.append(a[0])
#####
# remove duplicates and sort
newlist =sorted({n:True for n in newlist}.keys())
return newlist
def makeThisSafe(arr,debug = True, key='',noSqueeze=False):
"""
:param arr: The numpy array.
:param key: a key, used in debuging.
:param noSqueeze: A boolean flag for squeezing the array.
This tool takes a numpy array and masks it where it is a very high value, nan or inf.
"""
if noSqueeze:pass
else: arr=np.ma.array(arr).squeeze()
ma,mi = arr.max(), arr.min()
if ma > 9.E36:
if debug: print "makeThisSafe: \tMasked values greater than 9.E36",key
arr = np.ma.masked_greater(arr, 9.E36)
if np.isinf(ma ) or np.isnan(ma ):
if debug: print "makeThisSafe: \tMasking infs and Nans",key
arr = np.ma.array(arr)
arr = np.ma.masked_where(np.isnan(arr)+arr.mask +np.isinf(arr) , arr)
return arr
def intersection(a, b):
return list(set(a) & set(b))
def maenumerate(marr):
""" Masked array enumerate command based on numpy.ndenumerate, which iterates a list of (index, value) for n-dimensional arrays.
This version ignores masked values.
"""
mask = ~marr.mask.ravel()
for i, m in izip(np.ndenumerate(marr), mask):
if m: yield i
class AutoVivification(dict):
"""Implementation of perl's autovivification feature.
This class allows you to automate the creating of layered dictionaries.
from https://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python
"""
def __getitem__(self, item):
try: return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def AutoVivToYaml(av,yamlFile):
"""
Saves Nested dictionary or AutoVivification as a yaml readable file.
"""
space = 4*' '
s = ''
def recursivePrint(d,depth,s):
for key in sorted(d.keys()):
if depth==0:s+='\n' # empty line separator.
if isinstance(d[key], dict):
s += depth * space + str(key) + ': \n'
s = recursivePrint(d[key], depth+1, s)
else:
s += depth * space + str(key) + ': ' + str(d[key]) + '\n'
return s
s = recursivePrint(av,0,s)
#print 'AutoVivToYaml:\tFinal string:\n',s
print 'AutoVivToYaml:\tSaving:',yamlFile
fn = open(yamlFile,'w')
fn.write(s)
fn.close()
def YamlToDict(yamlFile):
"""
Opens a yaml file and outputs it as a dictionary.
"""
print 'YamlToDict:\tLoading:',yamlFile
with open(yamlFile, 'r') as f:
d = yaml.load(f)
return d
#def machineName():
# name = str(socket.gethostname())
# if name.find('npm')>-1: return 'PML'
# if name.find('pmpc')>-1: return 'PML'
# if name.find('esmval')>-1: return 'esmval'
# if name.find('ceda')>-1: return 'ceda'
# return False
class NestedDict(dict):
"""
Nested dictionary of arbitrary depth with autovivification.
Allows data access via extended slice notation.
from https://stackoverflow.com/questions/15077973/how-can-i-access-a-deeply-nested-dictionary-using-tuples
"""
def __getitem__(self, keys):
# Let's assume *keys* is a list or tuple.
if not isinstance(keys, basestring):
try:
node = self
for key in keys:
node = dict.__getitem__(node, key)
return node
except TypeError:
# *keys* is not a list or tuple.
pass
try:
return dict.__getitem__(self, keys)
except KeyError:
raise KeyError(keys)
def __setitem__(self, keys, value):
# Let's assume *keys* is a list or tuple.
if not isinstance(keys, basestring):
try:
node = self
for key in keys[:-1]:
try:
node = dict.__getitem__(node, key)
except KeyError:
node[key] = type(self)()
node = node[key]
return dict.__setitem__(node, keys[-1], value)
except TypeError:
# *keys* is not a list or tuple.
pass
dict.__setitem__(self, keys, value)
def getGridFile(grid):
"""
Deprecated.
"""
assert 0
if grid.upper() in ['ORCA1',]:
#grid = 'ORCA1'
gridFile = "data/mesh_mask_ORCA1_75.nc"
if grid in ['Flat1deg',]:
gridFile = 'data/Flat1deg.nc'
if grid.upper() in ['ORCA025',]:
#####
# Please add files to link to
for orcafn in [ "/data/euryale7/scratch/ledm/UKESM/MEDUSA-ORCA025/mesh_mask_ORCA025_75.nc", # PML
"/group_workspaces/jasmin/esmeval/example_data/bgc/mesh_mask_ORCA025_75.nc",]: # JASMIN
if exists(orcafn): gridFile = orcafn
try:
if exists(gridFile):pass
except:
print "UKESMpython:\tgetGridFile:\tERROR:\tIt's not possible to load the ORCA025 grid on this machine."+ \
"\n\t\t\tPlease add the ORCA025 file to the orcafn getGridFile() list to UKESMpython.py"
assert False
return gridFile
def shouldIMakeFile(fin,fout,debug = True):
"""
:param fin: Files in
:param fout: Files out.
Answers the question should I Make this File?
returns: True: make the file, or False: Don't make the file.
It looks at the age of the files in and the file out.
If the output file doesn't exist. The answer is yes.
If the output file exists, but is older than the input files: the answer is yes.
"""
if not exists(fout):
if debug: print 'shouldIMakeFile: out file doesn\'t exit and should be made.'
return True
if type(fin)==type('abc') and fin.find('shelve'):
fin = fin+'*'
# if type(fout)==type('abc') and fout.find('shelve'):
# fout = fout+'*'
if type(fin)==type('abc') and fin.find('*')<0: # fin is a string file:
if not exists(fin):
if debug: print 'Warning: ',fin ,'does not exist'
return False
if getmtime(fin) > getmtime(fout):
if debug: print 'shouldIMakeFile: out-file is younger than in-file, you should make it.'
return True #
if debug: print 'shouldIMakeFile: out-file is older than in-file, you shouldn\'t make it.'
return False
if type(fin)==type('abc') and fin.find('*')>0:
if debug: print 'shouldIMakeFile: in-file contains *, assuming it is a wildcard: ',fin
fin = glob(fin)
if debug: print 'shouldIMakeFile: files : ', fin
if type(fin) == type(['a','b','c',]): # fin is many files:
for f in fin:
if not exists(f):
if debug: print 'Warning: ',f ,'does not exist'
return False
if getmtime(f) > getmtime(fout):
if debug: print 'shouldIMakeFile: ',f,' is younger than an ',fout,', you should make it'
return True
if debug: print 'shouldIMakeFile: no new files in the list. Don\'t make it.'
return False
if debug:
print 'shouldIMakeFile: got to the end somehow:'
print type(fin), fin, fout
return False
def makemapplot(fig,ax,lons,lats,data,title, zrange=[-100,100],lon0=0.,drawCbar=True,cbarlabel='',doLog=False,drawLand=True,cmap='default'):
"""
takes a pyplot figre and axes, lat lon, data, and title and then makes a single map.
"""
lons = np.array(lons)
lats = np.array(lats)
data = np.ma.array(data)
if doLog and zrange[0]*zrange[1] <=0.:
print "makemapplot: \tMasking"
data = np.ma.masked_less_equal(np.ma.array(data), 0.)
print data.min(),lats.min(),lons.min(), data.shape,lats.shape,lons.shape
crojp2, data, newLon,newLat = regrid(data,lats,lons)
if type(cmap) == type('str'):
if cmap=='default':
try: cmap = pyplot.cm.viridis
except: cmap = pyplot.cm.jet
else:
cmap = pyplot.cm.get_cmap(cmap)
if doLog:
im = ax.pcolormesh(newLon, newLat,data, cmap=cmap, transform=ccrs.PlateCarree(),norm=LogNorm(vmin=zrange[0],vmax=zrange[1]),)
else:
im = ax.pcolormesh(newLon, newLat,data, cmap=cmap, transform=ccrs.PlateCarree(),vmin=zrange[0],vmax=zrange[1])
if drawLand: ax.add_feature(cfeature.LAND, facecolor='0.85')
if drawCbar:
c1 = fig.colorbar(im,pad=0.05,shrink=0.75)
if len(cbarlabel)>0: c1.set_label(cbarlabel)
pyplot.title(title)
ax.set_axis_off()
pyplot.axis('off')
ax.axis('off')
return fig, ax,im
def makePolarmapplot(fig,ax,lons,lats,data,title, zrange=[-100,100],lon0=0.,drawCbar=True,cbarlabel='',doLog=False,drawLand=True,cmap='default'):
"""
takes a pyplot figre and axes, lat lon, data, and title and then makes a single polar map.
"""
lons = np.array(lons)
lats = np.array(lats)
data = np.ma.array(data)
if doLog and zrange[0]*zrange[1] <=0.:
print "makemapplot: \tMasking"
data = np.ma.masked_less_equal(np.ma.array(data), 0.)
print data.min(),lats.min(),lons.min(), data.shape,lats.shape,lons.shape
crojp2, data, newLon,newLat = regrid(data,lats,lons)
if type(cmap) == type('str'):
if cmap=='default':
try: cmap = pyplot.cm.viridis
except: cmap = pyplot.cm.jet
else:
cmap = pyplot.cm.get_cmap(cmap)
if doLog:
im = ax.pcolormesh(newLon, newLat,data, cmap=cmap, transform=ccrs.NorthPolarStereo(),norm=LogNorm(vmin=zrange[0],vmax=zrange[1]),)
else:
im = ax.pcolormesh(newLon, newLat,data, cmap=cmap, transform=ccrs.NorthPolarStereo(),vmin=zrange[0],vmax=zrange[1])
if drawLand: ax.add_feature(cfeature.LAND, facecolor='0.85')
if drawCbar:
c1 = fig.colorbar(im,pad=0.05,shrink=0.75)
if len(cbarlabel)>0: c1.set_label(cbarlabel)
pyplot.title(title)
ax.set_axis_off()
pyplot.axis('off')
ax.axis('off')
return fig, ax,im
def robinPlotSingle(lons,lats,data,filename,title, zrange=[-100,100],drawCbar=True,cbarlabel='',doLog=False,dpi=100,):
"""
takes a pyplot lat lon, data, and title, and filename and then makes a single map, then saves it.
"""
fig = pyplot.figure()
fig.set_size_inches(10,6)
lons = np.array(lons)
lats = np.array(lats)
data = np.ma.array(data)
rbmi = min([data.min(),])
rbma = max([data.max(),])
if rbmi * rbma >0. and rbma/rbmi > 100.: doLog=True
print lons.shape,lats.shape,data.shape
lon0 = lons.mean()
ax = pyplot.subplot(111,projection=ccrs.PlateCarree(central_longitude=lon0, ))
fig,ax,im = makemapplot(fig,ax,lons,lats,data,title, zrange=[rbmi,rbma],lon0=lon0,drawCbar=drawCbar,cbarlabel=cbarlabel,doLog=doLog,)
print "robinPlotSingle.py:\tSaving:" , filename
pyplot.savefig(filename ,dpi=dpi)
pyplot.close()
def robinPlotPair(lons, lats, data1,data2,filename,titles=['',''],lon0=0.,marble=False,drawCbar=True,cbarlabel='',doLog=False,scatter=True,dpi=100,):#**kwargs):
"""
takes a pair of lat lon, data, and title, and filename and then makes a pair of maps, then saves the figure.
"""
fig = pyplot.figure()
fig.set_size_inches(10,10)
lons = np.array(lons)
lats = np.array(lats)
data1 = np.ma.array(data1)
data2 = np.ma.array(data2)
ax1 = fig.add_subplot(211)
m1 = Basemap(projection='robin',lon_0=lon0,resolution='c') #lon_0=-106.,
x1, y1 = m1(lons, lats)
m1.drawcoastlines(linewidth=0.5)
rbmi = min([data1.min(),data2.min()])
rbma = max([data1.max(),data2.max()])
if marble: m1.bluemarble()
else:
m1.drawmapboundary(fill_color='1.')
m1.fillcontinents(color=(255/255.,255/255.,255/255.,1))
m1.drawparallels(np.arange(-90.,120.,30.))
m1.drawmeridians(np.arange(0.,420.,60.))
if doLog and rbmi*rbma <=0.:
print "UKESMpython:\trobinPlotPair: \tMasking",
data1 = np.ma.masked_less_equal(ma.array(data1), 0.)
data2 = np.ma.masked_less_equal(ma.array(data2), 0.)
if scatter:
if doLog:
if len(cbarlabel)>0:
cbarlabel='log$_{10}$('+cbarlabel+')'
im1 =m1.scatter(x1,y1,c=np.log10(data1),marker="s",alpha=0.9,linewidth='0', **kwargs)
else: im1 =m1.scatter(x1,y1,c=data1,marker="s",alpha=0.9,linewidth='0',**kwargs)
else:
xi1,yi1,di1=mapIrregularGrid(m1,ax1,lons,lats,data1,lon0,xres=360,yres=180)
if doLog: im1 = m1.pcolormesh(xi1,yi1,di1,cmap=defcmap,norm = LogNorm() )
else: im1 = m1.pcolormesh(xi1,yi1,di1,cmap=pyplot.cm.jet)
if drawCbar:
c1 = fig.colorbar(im1,pad=0.05,shrink=0.75)
if len(cbarlabel)>0: c1.set_label(cbarlabel)
pyplot.title(titles[0])
#lower plot:
ax2 = fig.add_subplot(212)
m2 = Basemap(projection='robin',lon_0=lon0,resolution='c') #lon_0=-106.,
x2, y2 = m2(lons, lats)
m2.drawcoastlines(linewidth=0.5)
if marble: m2.bluemarble()
else:
m2.drawmapboundary(fill_color='1.')
m2.fillcontinents(color=(255/255.,255/255.,255/255.,1))
m2.drawparallels(np.arange(-90.,120.,30.))
m2.drawmeridians(np.arange(0.,420.,60.))
if scatter:
if doLog: im2 =m2.scatter(x2,y2,c=np.log10(data2),marker="s",alpha=0.9,linewidth='0',**kwargs) #vmin=vmin,vmax=vmax)
else: im2 =m2.scatter(x2,y2,c=data2,marker="s",alpha=0.9,linewidth='0',**kwargs) #vmin=vmin,vmax=vmax)
else:
xi2,yi2,di2=mapIrregularGrid(m2,ax2,lons,lats,data2,lon0,xres=360,yres=180)
if doLog: im2 = m2.pcolormesh(xi2,yi2,di2,cmap=defcmap,norm = LogNorm() )
else: im2 = m2.pcolormesh(xi2,yi2,di2,cmap=defcmap) #shading='flat',
if drawCbar:
c2 = fig.colorbar(im2,pad=0.05,shrink=0.75)
if len(cbarlabel)>0: c2.set_label(cbarlabel)
pyplot.title(titles[1])
print "UKESMpython:\trobinPlotPair: \tSaving:" , filename
pyplot.savefig(filename ,dpi=dpi)
pyplot.close()
def robinPlotQuad(lons, lats, data1,data2,filename,titles=['',''],title='',lon0=0.,marble=False,drawCbar=True,cbarlabel='',doLog=False,scatter=True,dpi=100,vmin='',vmax='',maptype='Basemap'):#,**kwargs):
"""
takes a pair of lat lon, data, and title, and filename and then makes a quad of maps (data 1, data 2, difference and quotient), then saves the figure.
"""
fig = pyplot.figure()
fig.set_size_inches(10,6)
lons = np.array(lons)
lats = np.array(lats)
data1 = np.ma.array(data1)
data2 = np.ma.array(data2)
axs,bms,cbs,ims = [],[],[],[]
if not vmin: vmin = data1.min()
if not vmax: vmax = data1.max()
vmin = min([data1.min(),data2.min(),vmin])
vmax = max([data1.max(),data2.max(),vmax])
#doLog, vmin,vmax = determineLimsAndLog(vmin,vmax)
doLog, vmin,vmax = determineLimsFromData(data1,data2)
doLogs = [doLog,doLog,False,True]
print "robinPlotQuad:\t",len(lons),len(lats),len(data1),len(data2)
for i,spl in enumerate([221,222,223,224]):
if spl in [221,222]:
rbmi = vmin
rbma = vmax
if spl in [223,]:
rbmi,rbma = symetricAroundZero(data1,data2)
#rbma =3*np.ma.std(data1 -data2)
#print spl,i, rbma, max(data1),max(data2)
#assert False
#rbmi = -rbma
if spl in [224,]:
rbma = 10. #max(np.ma.abs(data1 -data2))
rbmi = 0.1
if doLogs[i] and rbmi*rbma <=0.:
print "UKESMpython:\trobinPlotQuad: \tMasking",
data1 = np.ma.masked_less_equal(ma.array(data1), 0.)
data2 = np.ma.masked_less_equal(ma.array(data2), 0.)
data = ''
if spl in [221,]:data = np.ma.clip(data1, rbmi,rbma)
if spl in [222,]:data = np.ma.clip(data2, rbmi,rbma)
if spl in [223,]:data = np.ma.clip(data1-data2, rbmi,rbma)
if spl in [224,]:data = np.ma.clip(data1/data2, rbmi,rbma)
if spl in [221,222,]:
if rbmi == -rbma: cmap= pyplot.cm.RdBu_r
else: cmap= defcmap
if spl in [223,224,]: cmap= pyplot.cm.RdBu_r
if maptype=='Basemap':
axs.append(fig.add_subplot(spl))
bms.append( Basemap(projection='robin',lon_0=lon0,resolution='c') )#lon_0=-106.,
x1, y1 = bms[i](lons, lats)
bms[i].drawcoastlines(linewidth=0.5)
if marble: bms[i].bluemarble()
else:
bms[i].drawmapboundary(fill_color='1.')
bms[i].fillcontinents(color=(255/255.,255/255.,255/255.,1))
bms[i].drawparallels(np.arange(-90.,120.,30.))
bms[i].drawmeridians(np.arange(0.,420.,60.))
if doLogs[i]:
rbmi = np.int(np.log10(rbmi))
rbma = np.log10(rbma)
if rbma > np.int(rbma): rbma+=1
rbma = np.int(rbma)
if scatter:
if doLogs[i]:
if len(cbarlabel)>0:
cbarlabel='log$_{10}$('+cbarlabel+')'
ims.append(bms[i].scatter(x1,y1,c = np.log10(data),cmap=cmap, marker="s",alpha=0.9,linewidth='0',vmin=rbmi, vmax=rbma,))# **kwargs))
else: ims.append(bms[i].scatter(x1,y1,c = data, cmap=cmap, marker="s",alpha=0.9,linewidth='0',vmin=rbmi, vmax=rbma,))# **kwargs))
else:
xi1,yi1,di1=mapIrregularGrid(bms[i],axs[i],lons,lats,data,lon0,xres=360,yres=180)
if doLogs[i]: ims.append( bms[i].pcolormesh(xi1,yi1,di1,cmap=cmap,norm = LogNorm() ))
else: ims.append( bms[i].pcolormesh(xi1,yi1,di1,cmap=cmap))
if drawCbar:
if spl in [221,222,223]:
if doLogs[i]: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,ticks = np.linspace(rbmi,rbma,rbma-rbmi+1)))
else: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
if spl in [224,]:
cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
cbs[i].set_ticks ([-1,0,1])
cbs[i].set_ticklabels(['0.1','1.','10.'])
if maptype=='Cartopy':
#axs.append(fig.add_subplot(spl))
bms.append(pyplot.subplot(spl,projection=ccrs.Robinson()))
bms[i].set_global()
if marble: bms[i].stock_img()
else:
# Because Cartopy is hard wired to download the shapes files from a website that doesn't exist anymore:
bms[i].add_geometries(list(shapereader.Reader('data/ne_110m_coastline.shp').geometries()),
ccrs.PlateCarree(), color='k',facecolor = 'none',linewidth=0.5)
if scatter:
if doLogs[i] and spl in [221,222]:
rbmi = np.int(np.log10(rbmi))
rbma = np.log10(rbma)
if rbma > np.int(rbma): rbma+=1
rbma = np.int(rbma)
if doLogs[i]:
ims.append(
bms[i].scatter(lons, lats,c = np.log10(data),
cmap=cmap,marker="s",alpha=0.9,linewidth='0',
vmin=rbmi, vmax=rbma,
transform=ccrs.PlateCarree(),
)
)
else:
ims.append(
bms[i].scatter(lons, lats,c = data,
cmap=cmap,marker="s",alpha=0.9,linewidth='0',
vmin=rbmi, vmax=rbma,
transform=ccrs.PlateCarree(),)
)
if drawCbar:
if spl in [221,222,223]:
if doLogs[i]: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,ticks = np.linspace(rbmi,rbma,rbma-rbmi+1)))
else: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
if spl in [224,]:
cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
cbs[i].set_ticks ([-1,0,1])
cbs[i].set_ticklabels(['0.1','1.','10.'])
else:
crojp2, newData, newLon,newLat = regrid(data.squeeze(),lons, lats)
print "cartopy robin quad:",i,spl,newData.shape,newData.min(),newData.max(), rbmi,rbma
if doLogs[i]:
ims.append(
bms[i].pcolormesh(newLon, newLat,newData,
transform=ccrs.PlateCarree(),
cmap=cmap,
norm=LogNorm(vmin=rbmi,vmax=rbma)
)
)
else:
ims.append(
bms[i].pcolormesh(newLon, newLat,newData,
transform=ccrs.PlateCarree(),
cmap=cmap,
vmin=rbmi,vmax=rbma)
)
bms[i].coastlines() #doesn't work.
#bms[i].fillcontinents(color=(255/255.,255/255.,255/255.,1))
bms[i].add_feature(cfeature.LAND, facecolor='1.')
if drawCbar:
if spl in [221,222,223]:
if doLogs[i]: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))#ticks = np.linspace(rbmi,rbma,rbma-rbmi+1)))
else: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
if spl in [224,]:
cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
cbs[i].set_ticks ([0.1,1.,10.])
cbs[i].set_ticklabels(['0.1','1.','10.'])
#else: ticks = np.linspace( rbmi,rbma,9)
#print i, spl, ticks, [rbmi,rbma]
#pyplot.colorbar(ims[i],cmap=defcmap,values=[rbmi,rbma])#boundaries=[rbmi,rbma])
#cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5))#,ticks=ticks))
cbs[i].set_clim(rbmi,rbma)
if len(cbarlabel)>0 and spl in [221,222,]: cbs[i].set_label(cbarlabel)
if i in [0,1]:
pyplot.title(titles[i])
if i ==2: pyplot.title('Difference ('+titles[0]+' - '+titles[1]+')')
if i ==3: pyplot.title('Quotient (' +titles[0]+' / '+titles[1]+')')
if title:
fig.text(0.5,0.975,title,horizontalalignment='center',verticalalignment='top')
pyplot.tight_layout()
print "UKESMpython:\trobinPlotQuad: \tSaving:" , filename
try: pyplot.savefig(filename, dpi=dpi)
except: print "Unable to save image."
pyplot.close()
def HovPlotQuad(lons,lats, depths,
data1,data2,filename,
titles=['',''],title='',
lon0=0.,marble=False,drawCbar=True,cbarlabel='',doLog=False,scatter=True,dpi=100,vmin='',vmax='',
logy = False,
maskSurface=True,
):#,**kwargs):
"""
:param lons: Longitude array
:param lats: Lattitude array
:param depths: Depth array
:param data1: Data array
:param data2: Second data array
takes a pair of lat lon, depths, data, and title, and filename and then makes a quad of transect plots
(data 1, data 2, difference and quotient), then saves the figure.
"""
fig = pyplot.figure()
fig.set_size_inches(10,6)
depths = np.array(depths)
if depths.max() * depths.min() >0. and depths.max() >0.: depths = -depths
lons = np.array(lons)
lats = np.array(lats)
data1 = np.ma.array(data1)
data2 = np.ma.array(data2)
if maskSurface:
data1 = np.ma.masked_where(depths>-10.,data1)
data2 = np.ma.masked_where(depths>-10.,data2)
if len(data1.compressed())==0:
print "No hovmoeller for surface only plots."
return
doLog, vmin,vmax = determineLimsFromData(data1,data2)
axs,bms,cbs,ims = [],[],[],[]
doLogs = [doLog,doLog,False,True]
print "HovPlotQuad:\t",len(depths),len(lats),len(data1),len(data2)
#####
# Plotting coordinate with lowest standard deviation.
lon_std = lons.std()
lat_std = lats.std()
if lon_std<lat_std:
hovXaxis = lats
else: hovXaxis = lons
for i,spl in enumerate([221,222,223,224]):
if spl in [221,222]:
rbmi = vmin
rbma = vmax
if spl in [223,]:
rbmi,rbma = symetricAroundZero(data1,data2)
#rbma =3*np.ma.std(data1 -data2)
#print spl,i, rbma, max(data1),max(data2)
#rbmi = -rbma
if spl in [224,]:
rbma = 10.001
rbmi = 0.0999
if doLogs[i] and rbmi*rbma <=0.:
print "UKESMpython:\tHovPlotQuad: \tMasking",
data1 = np.ma.masked_less_equal(ma.array(data1), 0.)
data2 = np.ma.masked_less_equal(ma.array(data2), 0.)
data = ''
if spl in [221,]: data = np.ma.clip(data1, rbmi,rbma)
if spl in [222,]: data = np.ma.clip(data2, rbmi,rbma)
if spl in [223,]: data = np.ma.clip(data1-data2, rbmi,rbma)
if spl in [224,]: data = np.ma.clip(data1/data2, rbmi,rbma)
if spl in [221,222,]: cmap= defcmap
if spl in [223,224,]: cmap= pyplot.cm.RdBu_r
axs.append(fig.add_subplot(spl))
if scatter:
if doLogs[i] and spl in [221,222]:
rbmi = np.int(np.log10(rbmi))
rbma = np.log10(rbma)
if rbma > np.int(rbma): rbma+=1
rbma = np.int(rbma)
if doLogs[i]:
ims.append(pyplot.scatter(hovXaxis,depths, c= np.log10(data),cmap=cmap, marker="s",alpha=0.9,linewidth='0',vmin=rbmi, vmax=rbma,))
else: ims.append(pyplot.scatter(hovXaxis,depths, c= data ,cmap=cmap, marker="s",alpha=0.9,linewidth='0',vmin=rbmi, vmax=rbma,))
else:
print "hovXaxis:",hovXaxis.min(),hovXaxis.max(),"\tdepths:",depths.min(),depths.max(),"\tdata:",data.min(),data.max()
newX,newY,newData = arrayify(hovXaxis,depths,data)
print "newX:",newX.min(),newX.max(),"\tnewY:",newY.min(),newY.max(),"\tnewData:",newData.min(),newData.max() , 'range:', rbmi,rbma
if doLogs[i]: ims.append(pyplot.pcolormesh(newX,newY, newData, cmap=cmap, norm=LogNorm(vmin=rbmi,vmax=rbma),))
else: ims.append(pyplot.pcolormesh(newX,newY, newData, cmap=cmap, vmin=rbmi, vmax=rbma,))
#####
# All the tools to make a colour bar
if drawCbar:
if spl in [221,222,223]:
if doLogs[i]: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,ticks = np.linspace(rbmi,rbma,rbma-rbmi+1)))
else: cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
if spl in [224,]:
cbs.append(fig.colorbar(ims[i],pad=0.05,shrink=0.5,))
cbs[i].set_ticks ([0.1,1.,10.])
cbs[i].set_ticklabels(['0.1','1.','10.'])
cbs[i].set_clim(rbmi,rbma)
if doLogs[i] and len(cbarlabel)>0: cbarlabel='log$_{10}$('+cbarlabel+')'
if len(cbarlabel)>0 and spl in [221,222,]: cbs[i].set_label(cbarlabel)
#####
# Add the titles.
if i in [0,1]: pyplot.title(titles[i])
if i ==2: pyplot.title('Difference ('+titles[0]+' - '+titles[1]+')')
if i ==3: pyplot.title('Quotient (' +titles[0]+' / '+titles[1]+')')
#####
# Add the log scaliing and limts.
if logy: axs[i].set_yscale('symlog')
if maskSurface: axs[i].set_ylim([depths.min(),-10.])
axs[i].set_xlim([hovXaxis.min(),hovXaxis.max()])
#####
# Add main title
if title: fig.text(0.5,0.99,title,horizontalalignment='center',verticalalignment='top')
#####
# Print and save
pyplot.tight_layout()
print "UKESMpython:\tHovPlotQuad: \tSaving:" , filename
pyplot.savefig(filename ,dpi=dpi)
pyplot.close()
def ArcticTransectPlotQuad(lons,lats, depths,
data1,data2,filename,
titles=['',''],title='',
lon0=0.,marble=False,drawCbar=True,cbarlabel='',doLog=False,scatter=True,dpi=100,vmin='',vmax='',
logy = False,
maskSurface=True,
transectName = 'ArcTransect',
):#,**kwargs):
"""
:param lons: Longitude array
:param lats: Lattitude array
:param depths: Depth array
:param data1: Data array
:param data2: Second data array
takes a pair of lat lon, depths, data, and title, and filename and then makes a quad of transect plots
(data 1, data 2, difference and quotient), then saves the figure.
This only applies to the Arctic Transect plot
"""
fig = pyplot.figure()
fig.set_size_inches(10,6)
depths = np.array(depths)
if depths.max() * depths.min() >0. and depths.max() >0.: depths = -depths
lons = np.array(lons)
lats = np.array(lats)
data1 = np.ma.array(data1)
data2 = np.ma.array(data2)
if transectName=='AntTransect':
####
# Custom request from Katya for this specific figure.
data1 = np.ma.array(np.ma.masked_where(depths<-500.,data1).compressed())
data2 = np.ma.array(np.ma.masked_where(depths<-500.,data2).compressed())
lats = np.ma.masked_where(depths<-500.,lats).compressed()
lons = np.ma.masked_where(depths<-500.,lons).compressed()
depths = np.ma.masked_where(depths<-500.,depths).compressed()
print lons.shape,lats.shape, depths.shape, data1.shape,data2.shape
logy = False
maskSurface = False
if maskSurface:
data1 = np.ma.masked_where(depths>-10.,data1)
data2 = np.ma.masked_where(depths>-10.,data2)
doLog, vmin,vmax = determineLimsFromData(data1,data2)
axs,bms,cbs,ims = [],[],[],[]
doLogs = [doLog,doLog,False,True]
print "ArcticTransectPlotQuad:\t",len(depths),len(lats),len(data1),len(data2)
#####
# Artificially build an x axis coordinate list for the Arctic.
hovXaxis = []
meanlon = np.mean(lons)
if transectName in ['ArcTransect','CanRusTransect'] :
for i,(la,lo) in enumerate(zip(lats,lons)):
if lo <= meanlon: #lowest lo transect goes first.
hovXaxis.append(la)
else:
nl = 90.+ abs((90.-la))
hovXaxis.append(nl)
else:
hovXaxis = lats