-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulation_funcs.py
2371 lines (1930 loc) · 94.6 KB
/
simulation_funcs.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
""" simulation_funcs.py
9/9/2014: Goal is to use this to house functions to
prepare simulation data, and then plot data (at a higher
level than cccmaplots.py)
e.g. simulations and figures more specific to
sea ice paper.
In future, this need not be limited to canam4, so
I have left the filename general, and will update
the innards to be able to handle other model data.
(right now model='CanAM4' etc is hard-coded. 9/9/14)
"""
import numpy as np
import numpy.ma as ma
import scipy as sp
import scipy.stats
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import cccmaplots as cplt
import constants as con
import cccmautils as cutl
import cccmacmaps as ccm
import cccmaNC as cnc
import pandas as pd
cplt = reload(cplt)
con = reload(con)
cutl = reload(cutl)
ccm = reload(ccm)
cnc = reload(cnc)
def calc_plot_seasonal_maps(fielddict,coords,sims,pparams,vert=False,loctimesel=None,
info=None,printtofile=False,seas=None,addflds=None,addpparams=None):
""" calc_plot_seasonal_maps(fielddict,coords,sims,pparams,vert=False,loctimesel=None,info=None,printtofile=False,seas=None, addflds=None,addpparams=None):
info should be a dict of catch-all keywords/info
addflds,addpparams are tuples of fdicts and pparams for field contours to be overlain
returns figure handle
"""
addcont=False # overlay with contours. Start with one extra field.
field=fielddict['field']
ncfield=fielddict['ncfield']
fieldstr=fielddict['fieldstr']
conv=fielddict['conv']
addsie=False
if addflds:
addcont=True
fdictadd = addflds[0]
fieldadd = fdictadd['field']
fieldaddstr = fdictadd['fieldstr']
ncfieldadd = fdictadd['ncfield']
print 'add: ' + fieldadd
if seas != None:
seasons=seas
else: # standard seasons
seasons=('SON','DJF','MAM','JJA')
model=info['model'] #'CanAM4' # @@ move out of function
sigtype=info['sigtype'] # specify sig marking type
sigoff=info['sigoff'] # turn off significance marking?
pct=info['pct'] # percentage change?
nonstandardlev=fielddict['nonstandardlev']
savestr=info['savestr']
screen = info['screen']
figtrans = info['figtrans'] # boolean specifying whether to switch rows/cols
pltype= info['ptype'] # plot projection type for kemmap
bp=con.get_basepath()
basepath=bp['basepath'] + model + '/'; subdir=bp['subdir'] # @@ move out of function?
lat=coords['lat']
nlat=len(lat)
if vert==True:
lev=coords['lev']
nlev=len(lev)
theshape=(len(seasons),nlev,nlat)
else:
lon=coords['lon']
nlon=len(lon)
theshape=(len(seasons),nlat,nlon)
tstat = np.zeros(theshape)
pval = np.zeros(theshape)
fldcallseas = np.zeros(theshape)
fldpallseas = np.zeros(theshape)
fldcallseasadd = np.zeros(theshape)
fldpallseasadd = np.zeros(theshape)
latlim=pparams['latlim']
cmap=pparams['cmap']
cmin=pparams['cmin']; cmax=pparams['cmax']
cmlen=float( plt.cm.get_cmap(cmap).N)
incr = (cmax-cmin) / (cmlen)
conts = np.arange(cmin,cmax+incr,incr)
if addcont:
if fieldadd=='sie':
addsie=True
contsadd=[0.15, 0.15] # @@
else:
cminadd=addpparams[0]['cmin']; cmaxadd=addpparams[0]['cmax']
cmlen=float( plt.cm.get_cmap(cmap).N)
incradd = (cmaxadd-cminadd) / (cmlen)
contsadd = np.arange(cminadd,cmaxadd+incradd,incradd)
contsadd = contsadd[::2]
print 'added contours: ' + str(contsadd)
contclradd=info['contclr'] # contour color
contthkadd=info['contthk'] # linewidths
contstladd=info['contstl'] # linestyles
print contclradd # @@@
if figtrans:
fig6,ax6 = plt.subplots(len(sims),len(seasons)) # 1 row for e/ simulation, 1 col per season
fig6.set_size_inches(7,13)
#lastcol=len(seasons)-1
#lastrow=len(sims)-1
#print 'lastrow ' + str(lastrow) # @@@
print 'figtrans ' + str(figtrans)
if vert:
fig6.subplots_adjust(hspace=.03,wspace=.03)
else:
fig6.subplots_adjust(hspace=.02,wspace=.02)
print '@@@@@@@@@ ax6.shape ' + str(ax6.shape)
print seasons
print sims
print '@@@@@@@@@'
else:
fig6,ax6 = plt.subplots(len(seasons),len(sims)) # 1 col for e/ simulation, 1 row per season
fig6.set_size_inches(12,8)
#lastcol=len(sims)-1
#lastrow=len(seasons)-1
fig6.subplots_adjust(hspace=.15,wspace=.05)
print '@@@@@@@@@ ax6.shape ' + str(ax6.shape)
print seasons
print sims
print '@@@@@@@@@'
lastcol=len(sims)-1
lastrow=len(seasons)-1
for colidx,sim in enumerate(sims): # traverse cols
rowidx=0
simpair = con.get_simpair(sim)
simctl = simpair['ctl']['fullname']
timstr = simpair['ctl']['timestr']
simpt = simpair['pert']['fullname']
timstrp = simpair['pert']['timestr']
frootc = basepath + simctl + subdir + simctl + '_' + field + '_'
frootp = basepath + simpt + subdir + simpt + '_' + field + '_'
rowl=sim
if loctimesel !=None: # e.g. for when want to look at half of a run...
timesel = loctimesel
else:
timesel = simpair['ctl']['timesel']
fnamec = frootc + timstr + '_ts.nc'
fnamep = frootp + timstrp + '_ts.nc'
if addcont:
if addsie:
fieldadd='sicn'; ncfieldadd='SICN'
fnamecadd,fnamepadd = con.build_filepathpair(sim,fieldadd)
print fnamecadd
print fnamepadd
# @@@ I *think* I don't need this anymore since processing the 3D files more
# @@ although getting a nonstandard lev is not supported
if nonstandardlev:
print 'not yet supported for seasonal'
## if threed==0:
## fnamec = frootc + timstr + '_ts.nc'
## fnamep = frootp + timstrp + '_ts.nc'
## else:
## print '@@ fix to use the level NC files'
## fnamec = frootc + '001-061_ts.nc'
## fnamec2 = frootc + '062-121_ts.nc'
## fnamep = frootp + '001-061_ts.nc'
## fnamep2 = frootp + '062-121_ts.nc'
for sea in seasons: # traverse rows (or use map_allseas() ?? @@)
#ax = ax6[ridx][cidx]
if figtrans:
if len(sims)==1:
ax=ax6[colidx]
elif len(seasons)==1:
ax=ax6[colidx]
else:
ax=ax6[colidx][rowidx]
else:
if len(sims)==1:
ax=ax6[rowidx]
elif len(seasons)==1:
#ax=ax6[rowidx] # @@should this be colidx?? YES. prob means above is broken too....
ax=ax6[colidx]
print 'rowidx ' + str(rowidx) + ', colidx ' + str(colidx) + ' ax6.shape ' + str(ax6.shape) # @@@@@
else:
ax = ax6[rowidx][colidx]
ncparams={'timesel':timesel, 'seas': sea}
if field=='turb':
field='hfl'; fieldb='hfs'
fldcsea = cnc.getNCvar(fnamec,field.upper(),**ncparams)*conv + cnc.getNCvar(fnamecb,fieldb.upper(),
**ncparams)*conv
fldpsea = cnc.getNCvar(fnamep,field.upper(),**ncparams)*conv + cnc.getNCvar(fnamepb,fieldb.upper(),
**ncparams)*conv
field='turb'
elif field=='net':
print '@@ not implemented for seasonal maps'
else:
print fnamec # @@@@
#print ncparams
fldcsea = cnc.getNCvar(fnamec,ncfield,**ncparams)*conv
fldpsea = cnc.getNCvar(fnamep,ncfield,**ncparams)*conv
## if threed==0:
## fldcsea = cnc.getNCvar(fnamec,field.upper(),timesel=timesel,
## seas=sea)*conv
## fldpsea = cnc.getNCvar(fnamep,field.upper(),timesel=timesel,
## seas=sea)*conv
## else:
## fldcsea = np.append(cnc.getNCvar(fnamec,ncfield,timesel='0002-01-01,061-12-31',levsel=level,
## seas=sea)*conv,
## cnc.getNCvar(fnamec2,ncfield,levsel=level,seas=sea)*conv,axis=0)
## fldpsea = np.append(cnc.getNCvar(fnamep,ncfield,timesel='0002-01-01,061-12-31',levsel=level,
## seas=sea)*conv,
## cnc.getNCvar(fnamep2,ncfield,levsel=level,seas=sea)*conv,axis=0)
if addcont:
fldcseaadd=cnc.getNCvar(fnamecadd,ncfieldadd,**ncparams)*fdictadd['conv']
fldpseaadd = cnc.getNCvar(fnamepadd,ncfieldadd,**ncparams)*fdictadd['conv']
fldcallseasadd[rowidx,:,:] = np.mean(fldcseaadd,axis=0)
fldpallseasadd[rowidx,:,:] = np.mean(fldpseaadd,axis=0)
if pct:
plotfldadd = (fldpallseasadd[rowidx,:,:]-fldcallseasadd[rowidx,:,:]) / fldcallseasadd[rowidx,:,:] *100
else:
plotfldadd = fldpallseasadd[rowidx,:,:] - fldcallseasadd[rowidx,:,:]
if addsie:
fieldadd='sie';
plotfldadd = fldcallseasadd[rowidx,:,:]
plotfldaddp = fldpallseasadd[rowidx,:,:]
tstat[rowidx,:,:],pval[rowidx,:,:] = sp.stats.ttest_ind(fldpsea,fldcsea,axis=0)
fldcallseas[rowidx,:,:] = np.mean(fldcsea,axis=0)
fldpallseas[rowidx,:,:] = np.mean(fldpsea,axis=0)
if pct:
plotfld = (fldpallseas[rowidx,:,:]-fldcallseas[rowidx,:,:]) / fldcallseas[rowidx,:,:] *100
else:
plotfld = fldpallseas[rowidx,:,:] - fldcallseas[rowidx,:,:]
pparams['axis']=ax
if vert: # zonal mean with height
pparams['suppcb'] = True
#pparams['levlim'] = levlim
pparams['screen'] = screen
pparams['addcontlines'] = True
if colidx!=0: # if not the first column, suppress y labels
if not figtrans:
pparams['suppylab'] = True
if rowidx!=0:
if figtrans: # if not first column, suppress y labels
pparams['suppylab'] = True
else:
if figtrans:
pparams['suppylab'] = False
if rowidx==lastrow:
if figtrans: # if last col
ax.set_ylabel(rowl,fontsize=18)
ax.yaxis.set_label_position("right")
if colidx==lastcol:
if figtrans: # if last row, don't suppress xlabels
pparams['suppxlab'] = False
else:
if figtrans: # otherwise, do suppress xlabels
pparams['suppxlab'] = True
pc = cplt.vert_plot(plotfld,lev,lat,**pparams)
if sigoff==False: # add sig
cplt.addtsig(ax,pval[rowidx,...],lat,lev/100.,sigtype=sigtype) # @@ dims?
if addcont:
lats,levs = np.meshgrid(lat,lev/100.)
ax.contour(lats,levs,plotfldadd,levels=contsadd,colors=contclradd,linewidths=contthkadd,linestyles=contstladd)
if colidx==lastcol:
print 'lastcol ' + str(lastcol) # @@@
if figtrans: # last row?
pass
else:
# put season label on right side.
ax.yaxis.set_label_position("right")
ax.set_ylabel(sea)
if colidx==0:
if figtrans:
# if first row
ax.set_title(sea,fontsize=18)
else: # maps
if pltype !=None:
pparams['ptype']=pltype
pparams['suppcb'] = 1
bm,pc = cplt.kemmap(plotfld,lat,lon,**pparams)#@@
if sigoff==False:
cplt.addtsigm(bm,pval[rowidx,:,:],lat,lon,sigtype=sigtype)
if addcont:
lons, lats = np.meshgrid(lon,lat)
if addsie:
bm.contour(lons,lats,plotfldadd,levels=contsadd,
colors=contclradd,linewidths=contthkadd,latlon=True)
bm.contour(lons,lats,plotfldaddp,levels=contsadd,
colors=contclradd,linewidths=contthkadd,latlon=True,linestyles='--')
else:
bm.contour(lons,lats,plotfldadd,levels=contsadd,
colors=contclradd,linewidths=contthkadd,latlon=True,linestyles=contstladd)
# @@@@ eventually add more contours?
if colidx==0: # when col index is 0, set season
if figtrans: # if first row
ax.set_title(sea,fontsize=18)
else:
ax.set_ylabel(sea,fontsize=18)
if rowidx==0: # when row index is 0, set simulation
if figtrans:# first column
ax.set_ylabel(rowl,fontsize=18)
else:
ax.set_title(rowl,fontsize=18)
rowidx = rowidx+1
if figtrans:
if vert:
cbar_ax = fig6.add_axes([.25,0.04, 0.5, .02])
else:
cbar_ax = fig6.add_axes([.25,0.07, 0.5, .02])
cbor='horizontal'
else:
cbar_ax = fig6.add_axes([.91,.25, .02,.5])
cbor='vertical'
cbar_ax.tick_params(labelsize=15)
fig6.colorbar(pc,cax=cbar_ax, orientation=cbor,format='%.1f')
plt.suptitle(fieldstr)
if printtofile:
if sigoff==False:
sigstr='sig' + sigtype
else:
sigstr=''
#sigstr='sigcont' #@@ hard code
if sigoff==False and sigtype=='hatch':
suff='png'
else:
suff='pdf'
if latlim!= None:
latstr=str(latlim)
else:
latstr=''
if addcont:
savestr=savestr+'_' + fieldaddstr + 'cont3'
if vert:
if screen:
style = 'screen'
else:
style = str(latlim) + 'N' + str(levlim) + 'hPa'
if pct:
fig6.savefig(fieldstr + 'pctdiff' + sigstr + '_enssubplot' + savestr +
'_seas_' + style + '2.' + suff)
else:
fig6.savefig(fieldstr + 'diff' + sigstr + '_enssubplot' + savestr +
'_seas_' + style + '2.' + suff)
else: # maps
if pct: # version 2 has new season order, new filename/key org
fig6.savefig(fieldstr + 'pctdiff' + sigstr + '_enssubplot' + savestr +
'_seas_nh' + latstr + '2.' + suff)
else:
fig6.savefig(fieldstr + 'diff' + sigstr + '_enssubplot' + savestr + '_seas_' + pltype
+ latstr + '2.' + suff)
return fig6
def calc_seasons(fielddict,coords,sims,loctimesel=None,info=None,siglevel=0.05,
calctype=None,seas=None,effdof=False):
""" calc_seasons(fielddict,coords,sims,withlat=False,loctimesel=None,info=None,siglevel=0.05)
info: a dict which specifies lots of things, but in particular, which region to average
calctype: 'zonmean', 'regmean', 'pattcorrwithtime', 'pattcorrwithtimeyr', 'timetosig', 'timetosigsuper',None
seasons default to 'SON','DJF','MAM','JJA'
@@@@ should add a regular anomaly calc here. make it default?
returns a data blob:
blob['ctl'] = fldcdict
blob['pert'] = fldpdict
blob['tstat'] = tstatdict
blob['pval'] = pvaldict
blob['ci'] = cidict
blob['ctlstd'] = fldcstddict
blob['pertstd'] = fldpstddict
blob['diff'] = flddiffdict
blob['mask'] = flddmaskdict
blob['pcorr'] = fldpcorrdict # pattern corr with time only
"""
if seas==None:
seasons='SON','DJF','MAM','JJA'
else:
seasons=seas
sia = False; sie=False
field=fielddict['field']
ncfield=fielddict['ncfield']
fieldstr=fielddict['fieldstr']
conv=fielddict['conv']
threed=fielddict['threed']
isflux=fielddict['isflux']
nonstandardlev=fielddict['nonstandardlev']
model=info['model']
pct=info['pct'] # percentage change?
corrlim=info['corrlim'] # southern limit for pattern correlation
bp=con.get_basepath()
basepath=bp['basepath'] + model + '/'; subdir=bp['subdir'] # @@ move out of function?
lat=coords['lat']
nlat=len(lat)
lon=coords['lon']
nlon=len(lon)
plotzonmean = plotregmean = pattcorrwithtime = pattcorryr = timetosig = timetosigsuper = calcregmeanwithtime = False
if calctype==None:
print 'calctype is None. Just doing regular diff of means for full grid'
#return -1
elif calctype=='zonmean':
plotzonmean=True
elif calctype=='regmean':
plotregmean=True
region=info['region']
elif calctype=='regmeanwithtime':
calcregmeanwithtime=True
region=info['region']
elif calctype=='pattcorrwithtime':
# note that this is pattern correlating a run's
# pattern in time (cumulative avg) w/ its final pattern
pattcorrwithtime=True
elif calctype=='pattcorrwithtimeyr':
# note that this is pattern correlating a run's
# pattern each year in time w/ its final pattern, then sorted
pattcorrwithtime=True
pattcorryr=True
elif calctype=='timetosig':
timetosig=True
elif calctype=='timetosigsuper':
timetosig=True
timetosigsuper=True
else:
print 'calctype not recognized! Just doing regular diff of means'
#return -1
# note that pattern corr with time will be a 1D processed field -->
# for each season, fld.shape = ntime
# zonal mean will be a 1D processed field -->
# for each season, fld.shape = nlat
# regional mean will be a scalar processed field -->
# for each season, fld.shape = 1 (regional mean)
# time to significance is a map for each season
# for each season, fld.shape = nlat x nlon
if field=='sia':
sia=True
field = 'sicn' # while getting the data...
elif field=='sie':
sie=True
field = 'sicn'
tstatdict = dict.fromkeys(sims,{}); pvaldict = dict.fromkeys(sims,{})
fldcdict = dict.fromkeys(sims,{}); fldpdict = dict.fromkeys(sims,{})
fldcstddict = dict.fromkeys(sims,{}); fldpstddict = dict.fromkeys(sims,{})
flddiffdict = dict.fromkeys(sims,{}); flddmaskdict = dict.fromkeys(sims,{})
fldpcorrdict = dict.fromkeys(sims,{}); fldtimetosigdict = dict.fromkeys(sims,{})
cidict = dict.fromkeys(sims,{})
for ridx,sim in enumerate(sims):
seatstatdict=dict.fromkeys(seasons); seapvaldict=dict.fromkeys(seasons)
seafldcdict=dict.fromkeys(seasons); seafldpdict=dict.fromkeys(seasons)
seafldcstddict=dict.fromkeys(seasons); seafldpstddict=dict.fromkeys(seasons)
seadiffdict=dict.fromkeys(seasons); seadmaskdict=dict.fromkeys(seasons)
seapcorrdict=dict.fromkeys(seasons)
seacidict=dict.fromkeys(seasons)
seatimetosigdict=dict.fromkeys(seasons)
simpair = con.get_simpair(sim)
simctl = simpair['ctl']['fullname']
timstr = simpair['ctl']['timestr']
simpt = simpair['pert']['fullname']
timstrp = simpair['pert']['timestr']
frootc = basepath + simctl + subdir + simctl + '_'
frootp = basepath + simpt + subdir + simpt + '_'
if loctimesel !=None: # e.g. for when want to look at half of a run...
timesel = loctimesel
else:
timesel = simpair['ctl']['timesel']
if timesel!=None:
print 'calc_seasons(): selecting time ' + timesel # @@@@@@
if threed and nonstandardlev:
fnamec = frootc + field + '_' + '001-061_ts.nc'
fnamec2 = frootc + field + '_' + '062-121_ts.nc'
fnamep = frootp + field + '_' + '001-061_ts.nc'
fnamep2 = frootp + field + '_' + '062-121_ts.nc'
else:
fnamec = frootc + field + '_' + timstr + '_ts.nc'
fnamep = frootp + field + '_' + timstrp + '_ts.nc'
for sii,sea in enumerate(seasons):
ncparams = {'seas': sea}
# Now get the data
if field in ('turb','net'):
#print 'not implemented @@'
#print 'field is ' + field + '. getting hfl, hfs'
fielda='hfl'; fieldb='hfs'
fnamec = frootc + fielda + '_' + timstr + '_ts.nc'
fnamep = frootp + fielda + '_' + timstrp + '_ts.nc'
fnamecb = frootc + fieldb + '_' + timstr + '_ts.nc'
fnamepb = frootp + fieldb + '_' + timstrp + '_ts.nc'
fldc = cnc.getNCvar(fnamec,fielda.upper(),timesel=timesel,
**ncparams)*conv + cnc.getNCvar(fnamecb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
fldp = cnc.getNCvar(fnamep,fielda.upper(),timesel=timesel,
**ncparams)*conv + cnc.getNCvar(fnamepb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
if field=='net':
#print 'getting flg for net'
fieldb='flg'
conv=-1
fnamecb = frootc + fieldb + '_' + timstr + '_ts.nc'
fnamepb = frootp + fieldb + '_' + timstrp + '_ts.nc'
fldc = fldc + cnc.getNCvar(fnamecb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
fldp = fldp + cnc.getNCvar(fnamepb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
field='net'
conv=1
else:
field='turb'
else:
if threed and nonstandardlev:
ncparams['levsel'] = level
fldc = np.append(cnc.getNCvar(fnamec,ncfield,timesel='0002-01-01,061-12-31',**ncparams)*conv,
cnc.getNCvar(fnamec2,ncfield,**ncparams)*conv,
axis=0)
fldp = np.append(cnc.getNCvar(fnamep,ncfield,timesel='0002-01-01,061-12-31',**ncparams)*conv,
cnc.getNCvar(fnamep2,ncfield,**ncparams)*conv,
axis=0)
else:
print fnamec
print 'ncparams: ' + str(ncparams)
fldc = cnc.getNCvar(fnamec,ncfield,timesel=timesel,
**ncparams)*conv
fldp = cnc.getNCvar(fnamep,ncfield,timesel=timesel,
**ncparams)*conv
if sia:
fldc = cutl.calc_seaicearea(fldc,lat,lon)
fldp = cutl.calc_seaicearea(fldp,lat,lon)
elif sie:
fldc = ma.masked_where(fldc<.15,fldc)#really just mask out <.15?
fldp = ma.masked_where(fldp<.15,fldp)#really just maske out <.15
if isflux: #field in (fluxes,'fsg','turb','net'):
# mask out regions that are not ice in the control (as P&M 2014 JClim)
sicnc = cnc.getNCvar(frootc + 'sicn_' + timstr + '_ts.nc','SICN',timesel=timesel,**ncparams)
fldc = ma.masked_where(sicnc<.10,fldc)
fldp = ma.masked_where(sicnc<.10,fldp)
if plotzonmean:
fldc = np.mean(fldc[...,:-1],axis=2)# take zonal mean, removing extra lon
fldp = np.mean(fldp[...,:-1],axis=2)
elif pattcorrwithtime:
# loop through each year
# calc pattern corr either yearly or integrated
years=np.arange(0,fldc.shape[0])
fldctm = np.mean(fldc[:,lat>corrlim,...],axis=0)
pcorr = np.zeros(len(years))
for yr in years:
areas = cutl.calc_cellareas(lat,lon)
areas = areas[lat>corrlim,:]
weights = areas / np.sum(np.sum(areas,axis=1),axis=0)
if pattcorryr:
# yearly anomaly pattern corr w/ the time mean pattern
tmp = fldp[yr,lat>corrlim,...]-fldctm
else:
tmp = np.mean(fldp[:yr,lat>corrlim,...],axis=0)-fldctm # integrated anomaly pattern
tmpmean = np.mean(fldp[:,lat>corrlim,...],axis=0) - fldctm # end pattern to compare against
pcorr[yr] = cutl.pattcorr(tmp.flatten()*weights.flatten(),tmpmean.flatten()*weights.flatten())
seapcorrdict[sea] = pcorr
elif timetosig: # @@@@@ time to become significant
# use the control climo as the baseline (rather than 1 year), and give
# the full control timeseries to the ttest every time
nyr,nlat,nlon = fldc.shape
years = np.arange(0,nyr)
plotd = np.zeros(fldc.shape)
tstat = np.zeros(fldc.shape)
pval = np.zeros(fldc.shape)
fldctm = np.mean(fldc,axis=0) # time mean of control
for yr in years:
plotd[yr,...] = np.mean(fldp[0:yr,...]-fldctm,axis=0)
if yr>5:
tstat[yr,...],pval[yr,...] = sp.stats.ttest_ind(fldp[0:yr,...],fldc,axis=0)
else:
pval[yr,...] = np.ones((1,nlat,nlon))
# this should be a map of first year of significance.
firstsigyr = np.argmax(pval<=siglevel,axis=0) # returns index of first occurrence (True)
#firstsigyr = ma.masked_where(firstsigyr==0,firstsigyr) # somehow the mask doesn't get carried on?
firstsigyr = firstsigyr.astype(float) # in order to set nans below, need to convert to floats.
# if first sig year is 0 that mean there was never a True. set to a year past sim length
firstsigyr[firstsigyr==0] = np.nan #nyr+1 @@@
#print firstsigyr.shape # @@
seatimetosigdict[sea] = firstsigyr
elif plotregmean or calcregmeanwithtime:
#limsdict = con.get_regionlims(region)
if sia:
# calc total SIA in the requested region
#print 'should isarea=True here? @@@ 10/28/2014'
fldc = cutl.calc_regtotseaicearea(fldc,lat,lon,region,isarea=True)
fldp = cutl.calc_regtotseaicearea(fldp,lat,lon,region,isarea=True)
else:
if sie:
print 'sie does not make sense for regmean'
return -1
fldc = cutl.calc_regmean(fldc,lat,lon,region)#limsdict)
fldp = cutl.calc_regmean(fldp,lat,lon,region)#limsdict)
else: # just calculate a polar mean
print '@@@ no calctype flags are True. '
print '@@@ Previous behavior calculated '
print '@@@ polar mean (seacyclatlim) or SIA'
print '@@@ New behavior is to do nothing and '
print '@@@ simply return the full grid '
print '@@@ difference, std, pvals, etc'
#if sia:
# print 'should isarea=True here? @@@ 10/28/2014' # I think so...
# fldc,sh = cutl.calc_totseaicearea(fldc,lat,lon,isarea=True)
# fldp,sh = cutl.calc_totseaicearea(fldp,lat,lon,isarea=True)
#else:
# fldc = cutl.polar_mean_areawgted3d(fldc,lat,lon,latlim=seacyclatlim)
# fldp = cutl.polar_mean_areawgted3d(fldp,lat,lon,latlim=seacyclatlim)
seafldcstddict[sea] = np.std(fldc,axis=0)
seafldpstddict[sea] = np.std(fldp,axis=0)
#@@ttmp,pvtmp = sp.stats.ttest_ind(fldp,fldc,axis=0)
#print 'calculating ttest with effective DOF @@'
ttmp,pvtmp = cutl.ttest_ind(fldp,fldc,axis=0,effdof=effdof) # @@
# calculate confidence interval
# double-check the scale setting
# interval(alpha, df, loc=0, scale=1): Endpoints of the range that contains
# alpha percent of the distribution
meananom = np.mean(fldp,axis=0)-np.mean(fldc,axis=0)
df = len(fldp)-1 # degrees of freedom @@@
if effdof:
print 'calculating conf int with effective DOF @@'
df = cutl.calc_effectiveDOF(fldp-fldc)
#stder = np.std(fldp,axis=0)/np.sqrt(df+1) # standard error: sigma/sqrt(n)
stder = np.std(fldp-fldc,axis=0)/np.sqrt(df+1) #@@@
#stder = np.std(fldp-np.mean(fldc,axis=0),axis=0)/np.sqrt(df+1)
ci = sp.stats.t.interval(1-siglevel, df, loc= meananom, scale=stder)
seacidict[sea] = ci
seatstatdict[sea] = ttmp
seapvaldict[sea] = pvtmp
if calcregmeanwithtime:
seafldcdict[sea] = fldc # keep time dim
seafldpdict[sea] = fldp
seadiffdict[sea] = fldp-np.mean(fldc,axis=0)
else:
seafldcdict[sea] = np.mean(fldc,axis=0) # time mean
seafldpdict[sea] = np.mean(fldp,axis=0)
seadiffdict[sea] = np.mean(fldp,axis=0)- np.mean(fldc,axis=0)
seadmaskdict[sea] = ma.masked_where(pvtmp>siglevel,seadiffdict[sea])
# end loop through seasons
fldcstddict[sim] = seafldcstddict
fldpstddict[sim] = seafldpstddict
cidict[sim] = seacidict
tstatdict[sim] = seatstatdict
pvaldict[sim] = seapvaldict
fldcdict[sim] = seafldcdict
fldpdict[sim] = seafldpdict
flddiffdict[sim] = seadiffdict
flddmaskdict[sim] = seadmaskdict
if pattcorrwithtime==1:
fldpcorrdict[sim] = seapcorrdict
if timetosig:
fldtimetosigdict[sim] = seatimetosigdict
# end loop through simulations
if sia:
field = 'sia' # put back after getting the data. prob not important in the function context
elif sie:
field = 'sie'
blob = {}
blob['ctl'] = fldcdict
blob['pert'] = fldpdict
blob['tstat'] = tstatdict
blob['pval'] = pvaldict
blob['ci'] = cidict
blob['ctlstd'] = fldcstddict
blob['pertstd'] = fldpstddict
blob['diff'] = flddiffdict
blob['mask'] = flddmaskdict
if pattcorrwithtime:
blob['pcorr'] = fldpcorrdict
if timetosig:
blob['timetosig'] = fldtimetosigdict
return blob # datablob
def calc_seasonal_cycle(fielddict,coords,sims,withlat=False,loctimesel=None,info=None,siglevel=0.05):
""" calc_seasonal_cycle(fielddict,coords,sims,withlat=False,loctimesel=None,info=None,siglevel=0.05)
info: a dict which specifies lots of things, but in particular, which region to average
returns a data blob:
blob['ctl'] = fldcdict
blob['pert'] = fldpdict
blob['tstat'] = tstatdict
blob['pval'] = pvaldict
blob['ci'] = cidict
blob['ctlstd'] = fldcstddict
blob['pertstd'] = fldpstddict
blob['diff'] = flddiffdict
blob['mask'] = flddmaskdict
blob['sigarea'] # @@@
"""
print 'calc_seasonal_cycle()'
sia = False
# make standard function that will be called by "seasonal_cycle", "regional mean", etc...
# this can be adapted for lots of processing rather than have multiple copies of code. @@
field=fielddict['field']
ncfield=fielddict['ncfield']
fieldstr=fielddict['fieldstr']
conv=fielddict['conv']
threed=fielddict['threed']
isflux=fielddict['isflux']
model=info['model']
pct=info['pct'] # percentage change?
nonstandardlev=fielddict['nonstandardlev']
bp=con.get_basepath()
basepath=bp['basepath'] + model + '/'; subdir=bp['subdir'] # @@ move out of function?
lat=coords['lat']
nlat=len(lat)
lon=coords['lon']
nlon=len(lon)
# ====== from canam4sims_analens......
""" # get data for either zonal mean or sea cycle figures
if plotzonmean==1 or pattcorrwithtime==1 or plotregmean==1:
# seasons is defined above
corrlim = 45
elif plotseacyc==1:
if field in (fluxes,'fsg','turb','net'):
seacyclatlim=40
# else leave seacyclatlim as set at top of script"""
seacyc = con.get_mon()
seacyclatlim=info['seacyclatlim'] # should be 40N for (fluxes,'fsg','turb','net')
region = info['region'] # if region is set, it supercedes seacyclatlim! @@
if field=='sia':
sia=True
field = 'sicn' # while getting the data...
tstatdict = dict.fromkeys(sims,{}); pvaldict = dict.fromkeys(sims,{})
fldcdict = dict.fromkeys(sims,{}); fldpdict = dict.fromkeys(sims,{})
fldcstddict = dict.fromkeys(sims,{}); fldpstddict = dict.fromkeys(sims,{})
flddiffdict = dict.fromkeys(sims,{}); flddmaskdict = dict.fromkeys(sims,{})
fldpcorrdict = dict.fromkeys(sims,{});
cidict = dict.fromkeys(sims,{}); sigardict = dict.fromkeys(sims,{})
for ridx,sim in enumerate(sims):
seatstat = np.zeros((12)); seapval = np.zeros((12))
seafldc = np.zeros((12)); seafldp = np.zeros((12))
seafldcstd = np.zeros((12)); seafldpstd = np.zeros((12))
seadiff= np.zeros((12)); seadmask=np.zeros((12))
seaci = np.zeros((12,2));
seasigar = np.zeros((12));
## seatstatdict=dict.fromkeys(seacyc); seapvaldict=dict.fromkeys(seacyc)
## seafldcdict=dict.fromkeys(seacyc); seafldpdict=dict.fromkeys(seacyc)
## seafldcstddict=dict.fromkeys(seacyc); seafldpstddict=dict.fromkeys(seacyc)
## seadiffdict=dict.fromkeys(seacyc); seadmaskdict=dict.fromkeys(seacyc)
## seapcorrdict=dict.fromkeys(seacyc)
## seacidict=dict.fromkeys(seacyc)
# switch these to just an array? 0:12. @@
simpair = con.get_simpair(sim)
simctl = simpair['ctl']['fullname']
timstr = simpair['ctl']['timestr']
simpt = simpair['pert']['fullname']
timstrp = simpair['pert']['timestr']
frootc = basepath + simctl + subdir + simctl + '_'
frootp = basepath + simpt + subdir + simpt + '_'
if loctimesel !=None: # e.g. for when want to look at half of a run...
timesel = loctimesel
else:
timesel = simpair['ctl']['timesel']
"""if sim=='kemhad' or sim=='kemnsidc':
frootc = basepath + sim + 'ctl' + subdir + sim + 'ctl' + '_'
frootp = basepath + sim + 'pert' + subdir + sim + 'pert' + '_'
elif sim in ('kem1pert1b','kem1pert3','kem1rcp85a'):
frootc = basepath + 'kemctl1' + subdir + 'kemctl1' + '_'
frootp = basepath + sim + subdir + sim + '_'
else:
frootc = basepath + bcasename + sim + subdir + bcasename + sim + '_'
frootp = basepath + bcasenamep + sim + subdir + bcasenamep + sim + '_' """
if threed and nonstandardlev:
fnamec = frootc + field + '_' + '001-061_ts.nc'
fnamec2 = frootc + field + '_' + '062-121_ts.nc'
fnamep = frootp + field + '_' + '001-061_ts.nc'
fnamep2 = frootp + field + '_' + '062-121_ts.nc'
else:
fnamec = frootc + field + '_' + timstr + '_ts.nc'
fnamep = frootp + field + '_' + timstrp + '_ts.nc'
#for sii,sea in enumerate(seacyc):
if 1: # @@ try getting rid of loop through months.
print '@@ will have to remove ncparams'
#@@ncparams = {'monsel': sii+1}
# Now get the data
if field in ('turb','net'):
#print 'not implemented @@'
#print 'field is ' + field + '. getting hfl, hfs'
fielda='hfl'; fieldb='hfs'
fnamec = frootc + fielda + '_' + timstr + '_ts.nc'
fnamep = frootp + fielda + '_' + timstrp + '_ts.nc'
fnamecb = frootc + fieldb + '_' + timstr + '_ts.nc'
fnamepb = frootp + fieldb + '_' + timstrp + '_ts.nc'
fldc = cnc.getNCvar(fnamec,fielda.upper(),timesel=timesel,
**ncparams)*conv + cnc.getNCvar(fnamecb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
fldp = cnc.getNCvar(fnamep,fielda.upper(),timesel=timesel,
**ncparams)*conv + cnc.getNCvar(fnamepb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
if field=='net':
#print 'getting flg for net'
fieldb='flg'
conv=-1
fnamecb = frootc + fieldb + '_' + timstr + '_ts.nc'
fnamepb = frootp + fieldb + '_' + timstrp + '_ts.nc'
fldc = fldc + cnc.getNCvar(fnamecb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
fldp = fldp + cnc.getNCvar(fnamepb,fieldb.upper(),
timesel=timesel,**ncparams)*conv
field='net' # return field name to what it should be
conv=1
else:
field='turb' # return field name to what it should be
# end if turb or net
else:
"""if threed==0:
fldczm = cnc.getNCvar(fnamec,field.upper(),timesel=timesel,
**ncparams)*conv
fldpzm = cnc.getNCvar(fnamep,field.upper(),timesel=timesel,
**ncparams)*conv
else:
#print '@@ fix to use level NC files'"""
if threed and nonstandardlev:
ncparams['levsel'] = level
fldc = np.append(cnc.getNCvar(fnamec,ncfield,timesel='0002-01-01,061-12-31',**ncparams)*conv,
cnc.getNCvar(fnamec2,ncfield,**ncparams)*conv,
axis=0)
fldp = np.append(cnc.getNCvar(fnamep,ncfield,timesel='0002-01-01,061-12-31',**ncparams)*conv,
cnc.getNCvar(fnamep2,ncfield,**ncparams)*conv,
axis=0)
else:
# @@ really have only tested this one...
fldc = cnc.getNCvar(fnamec,ncfield,timesel=timesel)*conv#,
#**ncparams)*conv
fldp = cnc.getNCvar(fnamep,ncfield,timesel=timesel)*conv#,
#**ncparams)*conv
if sia==True:
fldc = cutl.calc_seaicearea(fldc,lat,lon)
fldp = cutl.calc_seaicearea(fldp,lat,lon)
# end getting data initially
# now do processing (regional means, tot SIA, etc)
if isflux: #field in (fluxes,'fsg','turb','net'):
# mask out regions that are not ice in the control (as P&M 2014 JClim)
sicnc = cnc.getNCvar(frootc + 'sicn_' + timstr + '_ts.nc','SICN',timesel=timesel,**ncparams)
fldc = ma.masked_where(sicnc<.10,fldc)
fldp = ma.masked_where(sicnc<.10,fldp)
#elif plotseacyc==1:
if withlat:
# leave the latitude dimension intact
# dims are time x lat x lon to start
# take zonal mean
fldc = np.mean(fldc,axis=2) # take zonal mean
fldp = np.mean(fldp,axis=2)
else:
if sia:
#calc total area instead of average
fldc,sh = cutl.calc_totseaicearea(fldc,lat,lon,isarea=True) #np.sum(np.sum(fldczm[:,lat>0,:],axis=2),axis=1)
fldp,sh = cutl.calc_totseaicearea(fldp,lat,lon,isarea=True) #np.sum(np.sum(fldpzm[:,lat>0,:],axis=2),axis=1)
else:
# consider masking out land for sfc fluxes...?
# @@@ switch to regional mean? which includes polar means....
if region!=None:
fldc = cutl.calc_regmean(fldc,lat,lon,region)
fldp = cutl.calc_regmean(fldp,lat,lon,region)
else:
fldc = cutl.polar_mean_areawgted3d(fldc,lat,lon,latlim=seacyclatlim)
fldp = cutl.polar_mean_areawgted3d(fldp,lat,lon,latlim=seacyclatlim)
# now save the processed fields
# @@ got rid of loop through months so have to deal with that here:
seafldcstd = cutl.calc_monthlystd(fldc)
seafldpstd = cutl.calc_monthlystd(fldp)
seatstat,seapval = cutl.calc_monthlytstat(fldp,fldc)
#seafldcstddict[sea] = np.std(fldc,axis=0)
#seafldpstddict[sea] = np.std(fldp,axis=0)
#ttmp,pvtmp = sp.stats.ttest_ind(fldp,fldc,axis=0)