-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDART_state_space.py
More file actions
3101 lines (2567 loc) · 108 KB
/
DART_state_space.py
File metadata and controls
3101 lines (2567 loc) · 108 KB
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
# Python module for DART diagnostic plots in state space.
#
# Lisa Neef, 4 June 2014
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from mpl_toolkits.basemap import Basemap
import datetime
import pandas as pd
import DART as dart
from netCDF4 import Dataset
import WACCM as waccm
import re
import ERA as era
import TEM as tem
import experiment_settings as es
import palettable as pb
## here are some common settings for the different subroutines
# list the 3d, 2d, 1d variables
# TODO: fill this in with other common model variables
var3d = ['U','US','V','VS','T','Z3','DELF','Q','CH4','OH','Nsq']
var2d = ['PS','FLUT','ptrop','ztrop']
var1d = ['hyam','hybm','hyai','hybi']
# constants
H = 7.0 # 7.0km scale height
def retrieve_diagn_and_process(E,Ediff=None,averaging_dimensions=['lat']):
"""
This subroutine retrieves some DART diagnostic defined in experiment
dictionary E, using the routine DART_diagn_to_array.
Then it does the following:
+ retrieve and add all the quantities listed in E['variable']
+ do the same for whatever experiment is given in Ediff and then subtract that array
+ average over the dimensions listed in averaging_dimensions
It returns the resulting array in a dictionary under the entry 'data'.
"""
#----retrieve the main experiment
# check if the desired variable is a sum
if ('+' in E['variable']):
variable_list = E['variable'].split('+')
else:
variable_list=[E['variable']]
# loop over the variables to add and load them all
data_list = []
for variable in variable_list:
Etemp=E.copy()
Etemp['variable']=variable
# load the requested array, and the difference array if needed
D0 = DART_diagn_to_array(Etemp,hostname=hostname,debug=debug)
data_list.append(D0['data'])
# sum over the variables retrieved
if ('+' in E['variable']):
D0['data'] = sum(V for V in data_list)
def plot_diagnostic_globe(E,Ediff=None,projection='miller',clim=None,cbar='vertical',log_levels=None,ncolors=19,hostname='taurus',debug=False,colorbar_label=None,reverse_colors=False,stat_sig=None):
"""
plot a given state-space diagnostic on a given calendar day and for a given variable
field on the globe.
We can also plot the difference between two fields by specifying another list of Experiment
dictionaries called Ediff
To plot climatology fields or anomalies wrt climatology, make the field E['diagn'] 'climatology.XXX' or 'anomaly.XXX',
where 'XXX' some option for loading climatologies accepted by the subroutine ano in MJO.py (see that code for options)
INPUTS:
E: an experimend dictionary given the variable and diagnostic to be plotted, along with level, lat, lon ranges, etc.
Ediff: the difference experiment to subtract out (default is None)
projection: the map projection to use (default is "miller")
clim: the colorbar limits. If the scale is divergent, the limits are set as [-clim,clim]. If it's sequential, we do [0,clim].
cbar: the orientation of the colorbar. Allowed values are 'vertical'|'horizontal'|None
log_levels: a list of the (logarithmic) levels to draw the contours on. If set to none, just draw regular linear levels.
hostname
taurus
debug
colorbar_label: string with which to label the colorbar
reverse_colors: set to false to reverse the colors in the
ncolors: how many colors in the contours - default is 19
stat_sig: a dictionary giving the settings for estimating statistical significance with boostrap.
Entries in this dict are:
P: the probability level at which we estimate the confidence intervals
nsamples: the number of bootstrap samples
If these things are set, we add shading to denote fields that are statistically significantly
different from zero -- so this actually only makes sense for anomaies.
if stat_sig is set to "None" (which is the default), just load the data and plot.
"""
# if plotting a polar stereographic projection, it's better to return all lats and lons, and then
# cut off the unwanted regions with map limits -- otherwise we get artifical circles on a square map
if (projection == 'npstere'):
if E['latrange'][0] < 0:
boundinglat = 0
else:
boundinglat = E['latrange'][0]
E['latrange'] = [-90,90]
E['lonrange'] = [0,361]
if (projection == 'spstere'):
boundinglat = E['latrange'][1]
E['latrange'] = [-90,90]
E['lonrange'] = [0,361]
##-----load data------------------
if stat_sig is None:
# turn the requested diagnostic into an array
Vmatrix,lat,lon,lev,DRnew = DART_diagn_to_array(E,hostname=hostname,debug=debug)
# average over the last dimension, which is time
if len(DRnew) > 1:
VV = np.nanmean(Vmatrix,axis=len(Vmatrix.shape)-1)
else:
VV = np.squeeze(Vmatrix)
# average over vertical levels if the variable is 3D
# -- unless we have already selected a single level in DART_diagn_to_array
if (E['variable'] in var3d) and (type(lev) != np.float64) and (E['levrange'][0] != E['levrange'][1]):
# find the level dimension
nlev = len(lev)
for dimlength,idim in zip(VV.shape,range(len(VV.shape))):
if dimlength == nlev:
levdim = idim
M1 = np.mean(VV,axis=levdim)
else:
M1 = np.squeeze(VV)
# if computing a difference to another field, load that here
if (Ediff != None):
Vmatrix,lat,lon,lev,DRnew = DART_diagn_to_array(Ediff,hostname=hostname,debug=debug)
if len(DRnew) > 1:
VV = np.nanmean(Vmatrix,axis=len(Vmatrix.shape)-1)
else:
VV = np.squeeze(Vmatrix)
# average over vertical levels if the variable is 3D
if (E['variable'] in var3d) and (type(lev) != np.float64) and (E['levrange'][0] != E['levrange'][1]):
M2 = np.mean(VV,axis=levdim)
else:
M2 = np.squeeze(VV)
# subtract the difference field out from the primary field
M = M1-M2
else:
M = M1
else:
# if statistical significance stuff was defined, loop over entire ensemble
# and use bootstrap to compute confidence intervals
# first look up the ensemble size for this experiment from an internal subroutine:
N = es.get_ensemble_size_per_run(E['exp_name'])
# initialize an empty list to hold the ensemble of averaged fields
Mlist = []
# loop over the ensemble
for iens in range(N):
import bootstrap as bs
E['copystring'] = 'ensemble member '+str(iens+1)
# retrieve data for this ensemble member
Vmatrix,lat,lon,lev,DRnew = DART_diagn_to_array(E,hostname=hostname,debug=debug)
# if there is more than one time, average over this dimension (it's always the last one)
if len(DRnew) > 1:
VV = np.nanmean(Vmatrix,axis=len(Vmatrix.shape)-1)
else:
VV = Vmatrix
# average over vertical levels if the variable is 3D and hasn't been averaged yet
if E['variable'] in var3d and type(lev) != np.float64:
# find the level dimension
nlev = len(lev)
for dimlength,idim in zip(VV.shape,len(VV.shape)):
if dimlength == nlev:
levdim = idim
M1 = np.mean(VV,axis=levdim)
else:
M1 = np.squeeze(VV)
# if computing a difference to another field, load that here
if (Ediff != None):
Ediff['copystring'] = 'ensemble member '+str(iens+1)
Vmatrix,lat,lon,lev,DRnew = DART_diagn_to_array(Ediff,hostname=hostname,debug=debug)
if len(DRnew) > 1:
VV = np.nanmean(Vmatrix,axis=len(Vmatrix.shape)-1)
else:
VV = Vmatrix
# average over vertical levels if the variable is 3D
if E['variable'] in var3d and type(lev) != np.float64:
M2 = np.mean(VV,axis=levdim)
else:
M2 = np.squeeze(VV)
# subtract the difference field out from the primary field
M = M1-M2
else:
M = M1
# store the difference (or plain M1 field) in a list
Mlist.append(M)
# turn the list of averaged fields into a matrix, where ensemble index is the first dimension
Mmatrix = np.concatenate([M[np.newaxis,...] for M in Mlist], axis=0)
# now apply bootstrap over the first dimension, which by construction is the ensemble
CI = bs.bootstrap(Mmatrix,stat_sig['nsamples'],np.mean,stat_sig['P'])
# anomalies are significantly different from 0 if the confidence interval does not cross zero
# we can estimate this by checking if there is a sign change
LU = CI.lower*CI.upper
sig = LU > 0 # this mask is True when CI.lower and CI.upper have the same sign
# also compute the ensemble average for plotting
M = np.mean(Mmatrix,axis=0)
##-----done loading data------------------
# set up a map projection
if projection == 'miller':
maxlat = np.min([E['latrange'][1],90.0])
minlat = np.max([E['latrange'][0],-90.0])
map = Basemap(projection='mill',llcrnrlat=minlat,urcrnrlat=maxlat,\
llcrnrlon=E['lonrange'][0],urcrnrlon=E['lonrange'][1],resolution='l')
if 'stere' in projection:
map = Basemap(projection=projection,boundinglat=boundinglat,lon_0=0,resolution='l')
if projection == None:
map = Basemap(projection='ortho',lat_0=54,lon_0=10,resolution='l')
# draw coastlines, country boundaries, fill continents.
coastline_width = 0.25
if projection == 'miller':
coastline_width = 1.0
map.drawcoastlines(linewidth=coastline_width)
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0,360,30),linewidth=0.25)
map.drawparallels(np.arange(-90,90,30),linewidth=0.25)
# compute native map projection coordinates of lat/lon grid.
X,Y = np.meshgrid(lon,lat)
x, y = map(X, Y)
# choose color map based on the variable in question
colors,cmap,cmap_type = state_space_HCL_colormap(E,Ediff,reverse=reverse_colors)
# specify the color limits
if clim is None:
clim = np.nanmax(np.absolute(M))
if debug:
print('++++++clim+++++')
print(clim)
# set the contour levels - it depends on the color limits and the number of colors we have
if cmap_type == 'divergent':
L = np.linspace(start=-clim,stop=clim,num=ncolors)
else:
L = np.linspace(start=0,stop=clim,num=ncolors)
# contour data over the map.
if (projection == 'ortho') or ('stere' in projection):
if log_levels is not None:
cs = map.contourf(x,y,M, norm=mpl.colors.LogNorm(vmin=log_levels[0],vmax=log_levels[len(log_levels)-1]),levels=log_levels,cmap=cmap)
else:
cs = map.contourf(x,y,M,levels=L,cmap=cmap,extend="both")
if projection is 'miller':
cs = map.contourf(x,y,M,L,cmap=cmap,extend="both")
if (cbar is not None):
if (clim > 1000) or (clim < 0.001):
CB = plt.colorbar(cs, shrink=0.6, extend='both',format='%.1e', orientation=cbar)
else:
CB = plt.colorbar(cs, shrink=0.6, extend='both', orientation=cbar)
if colorbar_label is not None:
CB.set_label(colorbar_label)
else:
CB = None
# if desired, add shading for statistical significance - this only works for when we plot anomalies
if stat_sig is not None:
colors = ["#ffffff","#636363"]
cmap = mpl.colors.ListedColormap(colors, name='my_cmap')
map.contourf(x,y,sig,cmap=cmap,alpha=0.3)
else:
sig = None
# return the colorbar handle if available, the map handle, and the data
return CB,map,M,sig
def plot_diagnostic_hovmoeller(E,Ediff=None,clim=None,cbar='vertical',log_levels=None,hostname='taurus',debug=False,scaling_factor=1.0,reverse_colors=False,cmap_type='sequential'):
"""
plot a given state-space diagnostic on a Hovmoeller plot, i.e. with time on the y-axis and
longitudeo on the x-axis.
We can also plot the difference between two fields by specifying another list of Experiment
dictionaries called Ediff.
To plot climatology fields or anomalies wrt climatology, make the field E['diagn'] 'climatology.XXX' or 'anomaly.XXX',
where 'XXX' some option for loading climatologies accepted by the subroutine ano in MJO.py (see that code for options)
INPUTS:
log_levels: a list of the (logarithmic) levels to draw the contours on. If set to none, just draw regular linear levels.
"""
# generate an array from the requested diagnostic
D = DART_diagn_to_array(E,hostname=hostname,debug=debug)
# load the difference array and subtract (if requested)
if Ediff is not None:
D2 = DART_diagn_to_array(Ediff,hostname=hostname,debug=debug)
Vmatrix = D['data']-D2['data']
else:
Vmatrix = D['data']
# find the lat and level dimensions and average
V1 = average_over_named_dimension(Vmatrix,D['lat'])
if 'lev' in D:
if D['lev'] is not None:
V2 = average_over_named_dimension(V1,D['lev'])
else:
V2=V1
else:
V2=V1
# multiply by a scaling factor if needed
M = scaling_factor*np.squeeze(V2)
#---plot setup----------------
time = D['daterange']
lon = D['lon']
# choose color map
cc = nice_colormaps(cmap_type,reverse_colors)
cmap=cc.mpl_colormap
ncolors = cc.number
colors,cmap,cmap_type = state_space_HCL_colormap(E,Ediff)
# specify the color limits
if clim is None:
clim = np.nanmax(np.absolute(M))
# set the contour levels - it depends on the color limits and the number of colors we have
if cmap_type == 'divergent':
L = np.linspace(start=-clim,stop=clim,num=11)
else:
L = np.linspace(start=0,stop=clim,num=11)
# contour plot
MT = np.transpose(M)
cs = plt.contourf(lon,time,MT,L,cmap=cmap,extend="both")
# date axis formatting
if len(time)>30:
fmt = mdates.DateFormatter('%b-%d')
plt.gca().yaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().yaxis.set_major_formatter(fmt)
else:
fmt = mdates.DateFormatter('%b-%d')
plt.gca().yaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().yaxis.set_major_formatter(fmt)
if cbar is not None:
if (clim > 1000) or (clim < 0.001):
CB = plt.colorbar(cs, shrink=0.8, extend='both',orientation=cbar,format='%.3f')
else:
CB = plt.colorbar(cs, shrink=0.8, extend='both',orientation=cbar)
if 'units' in D:
CB.set_label(D['units'])
else:
CB = None
plt.ylabel('Time')
plt.xlabel('Longitude')
# put some outputs into a dictionary
Mout = dict()
Mout['data']=MT
Mout['xname']='Longitude'
Mout['yname']='Date'
Mout['x']=lon
Mout['y']=time
Mout['colorbar']=CB
Mout['contours']=cs
return Mout
def plot_diagnostic_lev_time(E=dart.basic_experiment_dict(),Ediff=None,vertical_coord='log_levels',L=None,clim=None,cbar='vertical',colorbar_label=None,reverse_colors=False,scaling_factor=1.0,cmap_type='sequential',hostname='taurus',debug=False):
"""
Given a DART experiment dictionary E, plot the desired diagnostic as a function of vertical level and time,
averaging over the selected latitude and longitude ranges.
INPUTS:
E: experiment dictionary defining the main diagnostic
Ediff: experiment dictionary for the difference experiment
L: list of values at which to define the contour levels. Default is None - in this case these are computed from clim.
clim: color limits (single number, applied to both ends if the colormap is divergent)
hostname: name of the computer on which the code is running
cbar: how to do the colorbar -- choose 'vertical','horiztonal', or None
reverse_colors: set to True to flip the colormap
scaling_factor: factor by which to multiply the array to be plotted
cmap_type: what kind of colormap do we want? choose 'sequential' or 'divergent'
vertical_coord: option for how to plot the vertical coordinate. These are your choices:
'log_levels' (default) -- plot whatever the variable 'lev' gives (e.g. pressure in hPa) on a logarithmic scale
'levels' -- plot whatever the variable 'lev' gives (e.g. pressure in hPa) on a linear scale
'z' -- convert lev (assumed to be pressure) into log-pressure height coordinates uzing z=H*exp(p/p0) where p0 = 1000 hPa and H=7km
'TPbased': in this case, compute the height of each gridbox relative to the local tropopause and
plot everything on a "tropopause-based" grid, i.e. zt = z-ztrop-ztropmean
"""
# throw an error if the desired variable is 2 dimensional
if E['variable'].upper() not in var3d:
print('Attempting to plot a two dimensional variable ('+E['variable']+') over level and latitude - need to pick a different variable!')
return
# load the requested array, and the difference array if needed
D = DART_diagn_to_array(E,hostname=hostname,debug=debug)
# convert to TP-based coordinates if requested
if vertical_coord=='TPbased':
Vmain,lev=to_TPbased(E,D,hostname=hostname,debug=debug)
D['data']=Vmain
D['lev']=lev
if Ediff is not None:
D2 = DART_diagn_to_array(Ediff,hostname=hostname,debug=debug)
# convert to TP-based coordinates if requested
if vertical_coord=='TPbased':
Vdiff,lev=to_TPbased(E,D2,hostname=hostname,debug=debug)
D2['data']=Vmain
D2['lev']=lev
# subtract the main datarray
Vmatrix=D['data']-D2['data']
else:
Vmatrix=D['data']
# avearage over latitude and longitude
if 'lat' in D:
if D['lat'] is not None:
V0 = average_over_named_dimension(Vmatrix,D['lat'])
else:
V0=Vmatrix
else:
V0=Vmatrix
if 'lon' in D:
if D['lon'] is not None:
V1 = average_over_named_dimension(V0,D['lon'])
else:
V1=V0
else:
V1 = V0
# squeeze out any remaining length-1 dimensions and scale
M = scaling_factor*np.squeeze(V1)
# choose color map
cc = nice_colormaps(cmap_type,reverse_colors)
cmap=cc.mpl_colormap
ncolors = cc.number
# if not already specified,
# set the contour levels - it depends on the color limits and the number of colors we have
if L is None:
if clim is None:
clim0 = np.nanmax(np.absolute(M[np.isfinite(M)]))
clim1 = np.nanmin(M[np.isfinite(M)])
clim2 = np.nanmax(M[np.isfinite(M)])
else:
clim1=clim[0]
clim2=clim[1]
clim0=np.max(np.absolute(clim))
if cmap_type == 'divergent':
L = np.linspace(start=-clim0,stop=clim0,num=ncolors)
else:
L = np.linspace(start=clim1,stop=clim2,num=ncolors)
# compute vertical coordinate depending on choice of pressure or altitude
if 'levels' in vertical_coord:
y=D['lev']
ylabel = 'Level (hPa)'
if vertical_coord=='z':
H=7.0
p0=1000.0
y = H*np.log(p0/D['lev'])
ylabel = 'log-p height (km)'
if vertical_coord=='TPbased':
#from matplotlib import rcParams
#rcParams['text.usetex'] = True
y=lev
ylabel='z (TP-based) (km)'
x = D['daterange']
# contour data
if debug:
print('shape of the array to be plotted:')
print(M.shape)
cs = plt.contourf(x,y,M,L,cmap=cmap,extend="both")
# fix the date exis
if len(x)>30:
fmt = mdates.DateFormatter('%b-%d')
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(fmt)
else:
fmt = mdates.DateFormatter('%b-%d')
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(fmt)
#plt.xticks(rotation=45)
# add a colorbar if desired
if cbar is not None:
if (clim0 > 1000) or (clim0 < 0.001):
CB = plt.colorbar(cs, shrink=0.8, extend='both',orientation=cbar,format='%.0e')
else:
CB = plt.colorbar(cs, shrink=0.8, extend='both',orientation=cbar)
if colorbar_label is not None:
CB.set_label(colorbar_label)
else:
CB = None
plt.xlabel('time')
plt.ylabel(ylabel)
if vertical_coord=='log_levels':
plt.yscale('log')
if 'levels' in vertical_coord:
plt.gca().invert_yaxis()
# put some outputs into a dictionary
Mout = dict()
Mout['data']=M
Mout['xname']='Date'
Mout['yname']=ylabel
Mout['x']=x
Mout['y']=y
Mout['colorbar']=CB
Mout['contour levels']=L
Mout['contours']=cs
return Mout
def plot_diagnostic_lat_time(E=dart.basic_experiment_dict(),Ediff=None,daterange = dart.daterange(date_start=datetime.datetime(2009,1,1), periods=81, DT='1D'),clim=None,hostname='taurus',cbar=True,debug=False):
# loop over the input date range
for date, ii in zip(daterange,np.arange(0,len(daterange))):
# load the data over the desired latitude and longitude range
if (E['diagn'].lower() == 'covariance') or (E['diagn'].lower() == 'correlation') :
if ii == 0:
lev,lat,lon,Cov,Corr = dart.load_covariance_file(E,date,hostname,debug=debug)
nlat = len(lat)
refshape = Cov.shape
else:
dum1,dum2,dum3,Cov,Corr = dart.load_covariance_file(E,date,hostname,debug=debug)
if E['diagn'].lower() == 'covariance':
VV = Cov
if E['diagn'].lower() == 'correlation':
VV = Corr
else:
if ii == 0:
lev,lat,lon,VV,P0,hybm,hyam = dart.load_DART_diagnostic_file(E,date,hostname=hostname,debug=debug)
nlat = len(lat)
refshape = VV.shape
else:
dum1,dum2,dum3,VV,P0,hybm,hyam = dart.load_DART_diagnostic_file(E,date,hostname=hostname,debug=debug)
# if the file was not found, VV will be undefined, so put in empties
if VV is None:
VV = np.empty(shape=refshape)
# average over latitude and (for 3d variables) vertical levels
if (E['variable']=='PS'):
Mlonlev = np.mean(VV,axis=1)
else:
Mlon = np.mean(VV,axis=1)
Mlonlev = np.mean(Mlon,axis=1)
M1 = Mlonlev
# repeat for the difference experiment
if (Ediff != None):
lev2,lat2,lon2,VV,P0,hybm,hyam = dart.load_DART_diagnostic_file(Ediff,date,hostname=hostname,debug=debug)
if (E['variable']=='PS'):
M2lonlev = np.mean(VV,axis=1)
else:
M2lon = np.mean(VV,axis=1)
M2lonlev = np.mean(M2lon,axis=1)
M2 = M2lonlev
M = M1-M2
else:
M = M1
# append the resulting vector to the larger array (or initialize it)
if (ii==0) :
MM = np.zeros(shape=(nlat, len(daterange)), dtype=float)
names=[]
MM[:,ii] = M
# make a grid of levels and days
t = daterange
# choose color map based on the variable in question
colors,cmap,cmap_type = state_space_HCL_colormap(E,Ediff)
# contour data over the map.
cs = plt.contourf(t,lat,MM,len(colors)-1,cmap=cmap,extend="both")
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.axis('tight')
if cmap_type == 'divergent':
if clim is None:
clim = np.nanmax(np.absolute(MM))
plt.clim([-clim,clim])
if debug:
print(cs.get_clim())
if cbar:
if (clim > 1000) or (clim < 0.001):
CB = plt.colorbar(cs, shrink=0.8, extend='both',orientation='vertical',format='%.3f')
else:
CB = plt.colorbar(cs, shrink=0.8, extend='both',orientation='vertical')
else:
CB = None
plt.xlabel('time')
plt.ylabel('Latitude')
# fix the date exis
if len(t)>30:
fmt = mdates.DateFormatter('%b-%d')
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(fmt)
else:
fmt = mdates.DateFormatter('%b-%d')
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(fmt)
return cs,CB
def retrieve_state_space_ensemble(E,averaging=True,ensemble_members='all',scaling_factor=1.0,hostname='taurus',debug=False):
"""
retrieve the prior or posterior ensemble averaged over some region of the state,
for some DART experiment
INPUTS:
E: standard experiment dictionary
averaging: set to True to average over the input latitude, longitude, and level ranges (default=True).
ensemble_members: set to "all" to request entire ensemble, or specify a list with the numbers of the ensemble members you want to plot
scaling_factor: factor by which to multiply the array to be plotted
hostname
debug
"""
# query the daterange of E
daterange = E['daterange']
# decide what ensemble members to loop over here - specific ones, or the whole set?
if type(ensemble_members) is list:
ens_list = ensemble_members
else:
N = es.get_ensemble_size_per_run(E['exp_name'])
ens_list = np.arange(1,N+1)
# loop over the ensemble members and timeseries for each ensemble member, and add to a list
Eens = E.copy()
VElist = []
for iens in ens_list:
if iens < 10:
spacing = ' '
else:
spacing = ' '
copystring = "ensemble member"+spacing+str(iens)
Eens['copystring'] = copystring
D = DART_diagn_to_array(Eens,hostname=hostname,debug=debug)
# if averaging, do that here
if averaging:
# average over latitude
V0 = average_over_named_dimension(D['data'],D['lat'])
# average over longitude
V1 = average_over_named_dimension(V0,D['lon'])
# average over vertical level, if present
# for 3d variables, average over level:
if E['variable'] not in var2d:
V2 = average_over_named_dimension(V1,D['lev'])
else:
V2=V1
# thee might be another length-1 dimension left --average that out here
VV = scaling_factor*np.squeeze(V2)
else:
VV = scaling_factor*D['data']
# append ensemble member to list
VElist.append(VV)
# turn the list of ensemble states into a matrix
VE = np.concatenate([V[np.newaxis,...] for V in VElist], axis=0)
# output - swap out the data array from a single member to all members. Everything else stays the same.
D['data'] = VE
return D
def plot_diagnostic_global_ave(E,Ediff=None,label_for_legend=True,color="#000000",linestyle='-',marker=None,linewidth=1.0,alpha=1.0,x_as_days=False,hostname='taurus',debug=False):
"""
plot a given state-space diagnostic for a given variable field,
as a function of time only (averaging spatially)
We can also plot the difference between two fields by specifying another experiment structure
called Ediff
INPUTS:
E: experiment dictionary denoting what to plot
Ediff: experiment dictionary denoting the experiment or variable to subtract (default is None)
colors: a hex code that gives the color of the curve to be drawn.
When plotting multiple copies, this can be a list of colors.
Defauly is black.
linestyle: string giving the line style to be plotted - default is plain line
marker: string that gives the marker for th e line ploted - default is None
x_as_days: set to True to plot a count of days on the x-axis rather than dates
label_for_legend: if this is set to true, the profile being plotted is assigned whatever is given in E['title']
to appear when you do plt.legend(). The default is True; set this to False to ignore certain profiles
(e.g. individual ensemble members) in the legend.
"""
# set up empty dicts to hold the timeseries and x-axes to plot
MM=dict()
X=dict()
# calculate the number of days from start, if requested
# to do: convert list to array, or change the plotting part of this routine
if x_as_days:
x = [dd -E['daterange'][0] for dd in E['daterange']]
else:
x = E['daterange']
# load the data over the desired latitude and longitude range
DD = DART_diagn_to_array(E,hostname=hostname,debug=debug)
# load the difference array if desired
if Ediff is not None:
DDdiff = DART_diagn_to_array(Ediff,hostname=hostname,debug=debug)
Vmatrix = DD['data']-DDdiff['data']
else:
Vmatrix = DD['data']
# compute global average only if the file was found
if Vmatrix is not None:
if 'lat' not in DD:
DD['lat']=None
if 'lon' not in DD:
DD['lon']=None
if 'lev' not in DD:
DD['lev']=None
# average over latitude, longitude, and vertical level
if DD['lat'] is not None:
Vlat = average_over_named_dimension(Vmatrix,DD['lat'])
else:
Vlat=Vmatrix
if DD['lon'] is not None:
Vlatlon = average_over_named_dimension(Vlat,DD['lon'])
else:
Vlatlon=Vlat
if DD['lev'] is not None:
Vlatlonlev = average_over_named_dimension(Vlatlon,DD['lev'])
else:
Vlatlonlev=Vlatlon
# squeeze out any remaining length-1 dimensions
M = np.squeeze(Vlatlonlev)
else:
# if no file was found, just make the global average a NAN
M = np.NAN
#------plotting----------
y = M
if E['copystring']=='ensemble' or E['copystring']=='ensemble sample':
nC = y.shape[0]
if type(color) is 'list':
color2 = color[iC]
else:
color2=color
for iC in range(nC):
try:
plt.plot(x,y[iC,:],color=color2,linestyle=linestyle,linewidth=linewidth,label=E['title'],alpha=alpha,marker=marker)
except ValueError:
print("There's a problem plotting the time and global average array. Here are their shapes:")
print(len(x))
print(y.shape)
else:
try:
plt.plot(x,y,color=color,linestyle=linestyle,linewidth=linewidth,label=E['title'],alpha=alpha,marker=marker)
except ValueError:
print("There's a problem plotting the time and global average array. Here are their shapes:")
print(len(x))
print(y.shape)
# format the y-axis labels to be exponential if the limits are quite high
ylim= plt.gca().get_ylim()
if (np.max(ylim) > 1000):
ax = plt.gca()
ax.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))
plt.ylabel(DD['long_name']+' ('+DD['units']+')')
if not x_as_days:
# format the x-axis labels to be dates
#if len(x) > 30:
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
#if len(x) < 10:
# plt.gca().xaxis.set_major_locator(mdates.DayLocator(bymonthday=range(len(E['daterange']))))
fmt = mdates.DateFormatter('%b-%d')
plt.gca().xaxis.set_major_formatter(fmt)
# prepare output
DD['data']=M
DD['x']=x
return DD
def state_space_HCL_colormap(E,Ediff=None,reverse=False,ncol=19,debug=False):
"""
loads colormaps (not a matplotlib colormap, but just a list of colors)
based on the HCL theory put forth in Stauffer et al 2014
other sample color maps are available here: http://hclwizard.org/why-hcl/
INPUTS:
E: a DART experiment dictionary. Relevant entries are:
variable: if the variable is a positive definite quantity, use a sequential colormap
extras: if this indicates a postitive definite quantity, use a sequential colormap
Ediff: the differenence experiment dictionary. Used to determine if we are taking a difference, in
which case we would want a divergent colormap.
reverse: flip the colormap -- default is False
ncol: how many colors? Currently only 11 and 19 are supported for divergent maps, and only 11 for
sequential maps. Default is 19.
"""
# appropriate color maps for state space plots
colors_sequential = False
# sequential plot if plotting positive definite variables and not taking a difference
post_def_variables = ['Z3','PS','FLUT','T','Nsq','Q','O3']
if (Ediff == None) and (E['variable'] in post_def_variables):
colors_sequential = True
# for square error plots, we want a sequential color map, but only if not taking a difference
if (E['extras']=='MSE')and (Ediff == None):
colors_sequential = True
# for ensemble spread plots, we want a sequential color map, but only if not taking a diff
if (E['copystring']=='ensemble spread') and (Ediff == None):
colors_sequential = True
# for ensemble variance plots, we want a sequential color map, but only if not taking a diff
if (E['extras']=='ensemble variance scaled') and (Ediff == None):
colors_sequential = True
# if plotting the MJO variance, wnat a sequential colormap
if (E['extras'] == 'MJO variance'):
colors_sequential = True
# if the diagnostic includes a climatological standard deviation, turn on sequential colormap
if 'climatological_std' in E['diagn']:
colors_sequential = True
# if any of the above turned on the sequential colormap but we are looking at anomalies or correlations, turn it back off
if E['extras'] is not None:
if 'Correlation' in E['extras']:
colors_sequential = False
if 'anomaly' in E['diagn']:
colors_sequential = False
# also turn off the sequential colors if the diagnostic is increment
if E['diagn'].lower()=='increment':
colors_sequential = False
# choose sequential or diverging colormap
if colors_sequential:
# yellow to blue
colors = ("#F4EB94","#CEE389","#A4DA87","#74CF8C","#37C293","#00B39B",
"#00A1A0","#008CA1","#00749C","#005792","#202581")
if debug:
print('loading a sequential HCL colormap')
type='sequential'
else:
#---red negative and blue positive with white center instead of gray--
colordict = {11:("#D33F6A","#DB6581","#E28699","#E5A5B1","#E6C4C9","#FFFFFF","#FFFFFF","#C7CBE3","#ABB4E2","#8F9DE1","#7086E1","#4A6FE3"),
19:("#D33F6A","#DA5779","#E26C88","#E88197","#EE94A7","#F3A8B6",
"#F7BBC6","#FBCED6","#FDE2E6","#FFFFFF","#FFFFFF","#E4E7FB",
"#D3D8F7","#C1C9F4","#AFBAF1","#9DABED","#8B9CEA","#788DE6",
"#637EE4","#4A6FE3")}
colors=colordict[ncol]
if debug:
print('loading a diverging HCL colormap')
type='divergent'
if reverse:
colors = colors[::-1]
cmap = mpl.colors.ListedColormap(colors, name='my_cmap')
return colors,cmap,type
def compute_rank_hist(E=dart.basic_experiment_dict(),daterange=dart.daterange(datetime.datetime(2009,1,1),10,'1D'),space_or_time='both',hostname='taurus'):
# given some experiment E, isolate the ensemble at the desired location
# (given by E's entried latrange, lonrange, and levrange), retrieve
# the truth at the same location, and compute a rank histogram over the
# desired date range.
#
# the paramter space_or_time determines whether we count our samples over a blog of time, or in space
# if the choice is 'space', the time where we count is the first date of the daterange
if (space_or_time == 'space'):
dates = daterange[0]
averaging = False
if (space_or_time == 'time'):
averaging = True
dates = daterange
if (space_or_time == 'both'):
averaging = False
dates = daterange
# loop over dates and retrieve the ensemble
VE,VT,lev,lat,lon = retrieve_state_space_ensemble(E,dates,averaging,hostname)
# from this compute the rank historgram
bins,hist = dart.rank_hist(VE,VT[0,:])
return bins,hist,dates
def plot_rank_hist(E=dart.basic_experiment_dict(),daterange=dart.daterange(datetime.datetime(2009,1,1),81,'1D'),space_or_time='space',hostname='taurus'):
# compute the rank historgram over the desired date range
bins,hist,dates = compute_rank_hist(E,daterange,space_or_time,hostname)
# plot the histogram
plt.bar(bins,hist,facecolor='#9999ff', edgecolor='#9999ff')
plt.axis('tight')
plt.xlabel('Rank')
return bins,hist,dates
def compute_state_to_obs_covariance_field(E=dart.basic_experiment_dict(),date=datetime.datetime(2009,1,1),obs_name='ERP_LOD',hostname='taurus'):
# Given a DART experiment, load the desired state-space diagnostic file and corresponding obs_epoch_XXX.nc file,
# and then compute the field of covariances between every point in the field defined by latrange, lonrange, and levrange
# (these are entries in the experiment dictionary, E), and the scalar observation.
# first load the entire ensemble for the desired variable field
#lev,lat,lon,VV = dart.load_DART_diagnostic_file(E,date,hostname)
VV,VT,lev,lat,lon = retrieve_state_space_ensemble(E,date,False,hostname)
# now load the obs epoch file corresponding to this date
obs,copynames = dart.load_DART_obs_epoch_file(E,date,[obs_name],['ensemble member'],hostname)
# compute the ensemble mean value for each point in the variable field
VM = np.mean(VV,0)
# compute the mean and standard deviation of the obs predicted by the ensemble