-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanesm_LE_composite.py
2724 lines (2254 loc) · 105 KB
/
canesm_LE_composite.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
""" taken from canesm_LE_regress.py: July 2, 2015
"""
import loadLE as le
import cccmaplots as cplt
import cccmautils as cutl
import canesm_LE_general as leg
import loadmodeldata as lmd
import pandas as pd
import constants as con
import loadCanESM2data as lcd
import matplotlib.lines as mlines
from matplotlib import gridspec
import matplotlib.font_manager as fm
import scipy.io as sio
import datetime as datetime
import string as string
printtofile=False
#dataloaded=True
loadmat=True;
when='14:51:28.762886'; styearsR = [ 8., 7., 2., 8., 8.] # variable SIC styears
styearsE=[ 4., 1., 7., 3., 1.]; styearsN=[1.] #when for these: 17:01:16.908687
styearsPI = 2
# PI anomyrs when: '14:51:28.762886sic'. mean eursat=-0.0026
anomyearsPI =[[74, 8],
[57, 5],
[50, 53],
[51, 42],
[ 7, 81],
[15, 9],
[61, 57],
[48, 21],
[49, 24],
[65, 24],
[33, 66],
[71, 36],
[29, 43],
[48, 68],
[18, 67],
[ 5, 21],
[17, 1],
[40, 16],
[79, 18],
[10, 82],
[ 0, 19],
[70, 36],
[82, 67],
[14, 7],
[57, 13],
[18, 34],
[59, 29],
[20, 6],
[12, 6],
[58, 68],
[82, 49],
[66, 2],
[ 0, 10],
[28, 59],
[63, 73],
[28, 83],
[51, 54],
[19, 2],
[26, 47],
[52, 66],
[27, 10],
[37, 48],
[38, 64],
[33, 36],
[42, 85],
[28, 24],
[79, 51],
[80, 10],
[44, 57],
[32, 41]]
"""styearPI = 0 # PI styear
#<coldeur for PI> when='14:43:36.586252'
anomyearsPI = [[79, 26],
[58, 17],
[79, 41],
[28, 24],
[37, 80],
[25, 48],
[30, 49],
[33, 85],
[51, 43],
[82, 6],
[62, 34],
[ 3, 17],
[56, 63],
[67, 4],
[29, 73],
[74, 0],
[28, 8],
[46, 56],
[14, 76],
[72, 37],
[88, 4],
[31, 56],
[31, 4],
[40, 0],
[20, 49],
[21, 81],
[68, 56],
[77, 37],
[18, 1],
[82, 26],
[78, 55],
[22, 47],
[78, 16],
[54, 76],
[ 5, 47],
[58, 25],
[49, 20],
[64, 36],
[34, 2],
[62, 18],
[89, 3],
[25, 10],
[10, 30],
[84, 55],
[88, 18],
[87, 50],
[68, 26],
[ 5, 67],
[77, 13],
[74, 61]] """
saveascii=False
savemat=False
dofigures=False
local=True
addsig=False
compagcm=False # compare R sims and E sims
cisiglevel=0.05
siglevel=0.05
timeselc='1979-01-01,1989-12-31'
timeselp='2002-01-01,2012-12-31'
ftype='fullts' # 'fullclimo' or 'climo' or 'fullts'
# this is not implemented here. but would do regressions in time on LE ensemble avg
ensmean=False
seasp='DJF' # season of spatial field
sear='DJF' # season of regional avgs
#sear='SON'; print 'COMPOSITE ON SON!!! @@@@'
if sear=='SON' and seasp=='DJF':
# make sure to be consistent with DJF following SON
# Choose the SON timeperiod to end one year early
timeselc='1979-01-01,1988-12-31'
timeselp='2002-01-01,2011-12-31'
diffttl1=diffttl2=diffttl3='Low-High' # for comp on BKS SIC and Eur SAT (otherwise High-Low)
diffmult1=diffmult2=diffmult3=1 # if High-Low then need to mult by -1
# spatial field1 in color
leconvsp=1
fieldsp='tas'; ncfieldsp='tas'; compsp='Amon'; spkey='sat'
cminsp=-3; cmaxsp=3 # for colors
cminspbig=-3; cmaxspbig=3 # for colors
cminspa=-1; cmaxspa=1 # for colors for AGCM
cminice=-10; cmaxice=10 # colors for ice
# spatial field2 in contours
leconvsp2=1
fieldsp2='zg50000.00'; ncfieldsp2='zg'; compsp2='Amon'; sp2key='z500'
cminsp2=-30; cmaxsp2=30 # to calc contour interval
cminsp2big=-30; cmaxsp2big=30 # to calc contour interval
cminsp2a=-10; cmaxsp2a=10 # to calc contour interval for AGCM
# COMPOSITE ON THESE VALUES
leconvr=leconvr2=leconvr3=1
# regional avg field 1
fieldr='sic'; ncfieldr='sic'; compr='OImon'; regionr='bksmori';
r1str='BKS SIC'; r1strlong='Barents/Kara SIC'; r1units='%'; r1key='bkssic'
#fieldr='turb'; ncfieldr='turb'; compr='Amon'; regionr='bksmori'; #@@@
#r1str='BKS Turb'; r1strlong='Barents/Kara turbulent heat flux'; r1units='W/m2'; r1key='bksturb'
# regional avg field 2
# cooling=high heights
fieldr2='tas'; ncfieldr2='tas'; compr2='Amon'; regionr2='eurasiamori';
r2str='Eur SAT'; r2strlong='Eurasian SAT'; r2units='$^\circ$C'; r2key='eursat' #leconvr2=-1
# regional avg field 3
fieldr3='zg50000.00'; ncfieldr3='zg'; compr3='Amon';
regionr3='bksmori'; r3str='BKS Z500'; r3strlong='Barents/Kara Z500'; r3key='bksz500'
diffttl3='High-Low'; diffmult3=-1; r3units='m'
#leconvr=-1; #leconvr2=-1; #both conv -1 to get figs to show low-high equal to high heights and cold continent.
#fieldr3='turb'; ncfieldr3='turb'; compr3='Amon'; regionr3='bksmori'; #@@@
#r3str='BKS Turb'; r3strlong='Barents/Kara turbulent heat flux'; r3units='W/m2'; r3key='bksturb'
sttl1='Comp on ' + r1str
sttl2='Comp on ' + r2str
sttl3='Comp on ' + r3str
fdictsp = {'field': fieldsp, 'ncfield': ncfieldsp, 'comp': compsp}
fdictsp2 = {'field': fieldsp2, 'ncfield': ncfieldsp2, 'comp': compsp2}
if fieldr=='turb':
fdictice = {'field': 'turb', 'ncfield': 'turb', 'comp': 'Amon'} #@@@ testing. misleading names.
else:
fdictice = {'field': 'sic', 'ncfield': 'sic', 'comp':'OImon'}
fdictr = {'field': fieldr+regionr, 'ncfield': ncfieldr, 'comp': compr}
fdictr2 = {'field': fieldr2+regionr2, 'ncfield': ncfieldr2, 'comp': compr2}
fdictr3 = {'field': fieldr3+regionr3,'ncfield': ncfieldr3, 'comp': compr3}
# used for file loading & figures
#regions=('bkssic','eursat','bksz500')
regions=('eursat',r1key,r3key) # SWAP order
#fields=('ice','sat','z500')
fields=('sat','ice','z500') # SWAP order
lat=le.get_lat(local=local)
lon=le.get_lon(local=local)
nlat=len(lat); nlon=len(lon)
alat=con.get_t63lat(); alon=con.get_t63lon()
alons, alats = np.meshgrid(alon,alat)
if addsig:
prstr='sig'
else:
prstr=''
def load_field(fdict,casename,timesel,seas,ftype='fullts',conv=1,local=False,verb=False):
"""
returns [numens x space.flat] or [numens]
"""
ledat = le.load_LEdata(fdict,casename,timesel=timesel,
rettype='ndarray',conv=conv,ftype=ftype,local=local,verb=verb)
print '@@@ ledat.shape ' + str(ledat.shape) # why does the 3d data have space flattened already...
# time needs to be first dimension
try:
if ledat.ndim==2:
ledat = ledat.T
elif ledat.ndim==3:
ledat = np.transpose(ledat,(1,0,2))
else:
print 'Loaded data is not 2 or 3 dimensions. Do not understand.'
raise Exception
except:
raise
lesea = cutl.seasonalize_monthlyts(ledat,season=seas).mean(axis=0) # numens x space.flat
return lesea
def load_canesmfield(fdict,casename,seas,conv=1,subsampyrs=11,numsamp=50,
styear=None,anomyears=None,local=False,verb=False,addcyc=True):
""" loads subsampled CGCM data from specified simulation
(assumes a long control, e.g. piControl)
number of total chunks will be determined by length of sim data
and numyrs (ntime / numyrs). First the simulation is chunked into
numyrs segments. Then 2 segments at a time are randomly chosen
(at least a decade apart) to generate anomalies. This is done
numsamp times (e.g. 50)
returns subsamp (subsampled anomalies)
styears (start index of chunking of long run)
anomyears (indices of anomaly differences)
"""
pidat = lcd.load_data(fdict,casename,local=local,conv=conv,verb=verb)
piseadat = cutl.seasonalize_monthlyts(pidat,season=seas)
# the data must be seasonalized before using this func.
pisea,styear,anomyears = leg.subsamp_anom_pi(piseadat, numyrs=subsampyrs,numsamp=numsamp,
styear=styear,anomyears=anomyears)
if addcyc:
st=pisea[...,-1]
pisea=np.dstack((pisea,st[...,None]))
return pisea,styear,anomyears
def load_agcmfield(field,sims,seas,conv=1,region=None,subsampyrs=11,styears=None):
""" loads subsampled agcm data from specified simulations
number of total samples will be determined by length of all sim data
and numyrs (e.g. (ntime / numyrs)*numsims)
returns subsamp
styears
"""
threed=False
simconv=conv
if field=='tas': simfield='st'; simncfield='ST'
elif field=='zg50000.00': simfield='gz50000'; simncfield='PHI'; simconv=1/con.get_g()
elif field=='sia': simfield='sicn'; simncfield='SICN'; print '@@ danger, sia actually sicn average'
elif field=='sic': simfield='sicn'; simncfield='SICN'
elif field=='turb': simfield='turb'; simncfield='turb'; # the sim var names are placeholders
else: print 'cannot addsims for ' + field
if region!=None:
simflddf = pd.DataFrame(lmd.loaddata((simfield,),sims,ncfields=(simncfield,), timefreq=seas,
region=region))*simconv
else:
# assume threed b/c no region given.
threed=True
simflddf = lmd.loaddata((simfield,),sims,ncfields=(simncfield,), timefreq=seas,
region=region,rettype='ndarray')*simconv
subsamp,styearsss = leg.subsamp_sims(simflddf,numyrs=subsampyrs,styears=styears,threed=threed)
return subsamp,styearsss
def composite_lefield(casenames, fdictsp, fdictr, loaddictsp, loaddictr,verb=False,local=False):
""" composite fdictsp on fdictr
returns (hi spatial comp, lo spatial comp, mean spatial, hipval, lopval, lo v hi pval, hi idx, lo idx)
"""
for cii,casename in enumerate(casenames):
# loaddict should have: timeselp, timeselc, sea, ftype, leconv
# for each field being loaded
# SPATIAL FIELD
lecseasp = load_field(fdictsp, casename, loaddictsp['timeselc'], loaddictsp['sea'],
ftype=loaddictsp['ftype'], conv=loaddictsp['conv'],verb=verb,local=local)
lepseasp = load_field(fdictsp, casename, loaddictsp['timeselp'], loaddictsp['sea'],
ftype=loaddictsp['ftype'], conv=loaddictsp['conv'],verb=verb,local=local)
leseasp = lepseasp-lecseasp
# REGIONAL AVG FIELD: 1D
lecsear = load_field(fdictr, casename, loaddictr['timeselc'], loaddictr['sea'],
ftype=loaddictr['ftype'], conv=loaddictr['conv'],verb=verb,local=local)
lepsear = load_field(fdictr, casename, loaddictr['timeselp'], loaddictr['sea'],
ftype=loaddictr['ftype'], conv=loaddictr['conv'],verb=verb,local=local)
lesear = lepsear-lecsear
if cii != 0:
tmp = np.vstack((tmp,leseasp))
tmpr = np.hstack((tmpr,lesear))
else:
tmp = leseasp
tmpr = lesear
leseasp=tmp
lesear=tmpr
return do_composite(lesear,leseasp,rshape=(nlat,nlon),verb=verb,addcyc=True)
# end composite_lefield()
def do_composite(rfld,spfld,nn=10,rshape=None,verb=False,addcyc=False):
"""
returns (hi spatial comp, lo spatial comp, mean spatial, hipval, lopval, lo v hi pval, hi idx, lo idx)
"""
numens = rfld.shape[0] # numens or numsamp
highidx = (-rfld).argsort()[:nn]
lowidx = rfld.argsort()[:nn]
if rshape==None:
# this should have the effect of keeping shape the same
# when calling reshape (since it's not necessary)
rshape=spfld.shape[1:] # lat x lon dim
rshapenn=(nn,)+rshape
rshapeens=(numens,)+rshape
meanlesp = spfld.mean(axis=0).reshape(rshape)
highlesp = spfld[highidx,...].mean(axis=0).reshape(rshape)
lowlesp = spfld[lowidx,...].mean(axis=0).reshape(rshape)
if verb:
print 'highidx vals: ' + str(rfld[highidx])
print 'lowidx vals: ' + str(rfld[lowidx])
# low vs high
splowt=spfld[lowidx,...].reshape(rshapenn) # keep sample dim
sphight=spfld[highidx,...].reshape(rshapenn) # keep sample dim
(lesptstat, lesppval) = cutl.ttest_ind(splowt, sphight)
# low vs mean
(lelosptstat, lelosppval) = cutl.ttest_ind(splowt,
spfld.reshape(rshapeens))
# high vs mean
(lehisptstat, lehisppval) = cutl.ttest_ind(sphight,
spfld.reshape(rshapeens))
if addcyc:
st=meanlesp[...,-1]
meanlesp=np.hstack((meanlesp,st[...,None]))
st=highlesp[...,-1]
highlesp=np.hstack((highlesp,st[...,None]))
st=lowlesp[...,-1]
lowlesp=np.hstack((lowlesp,st[...,None]))
st=lesppval[...,-1]
lesppval=np.hstack((lesppval,st[...,None]))
st=lehisppval[...,-1]
lehisppval=np.hstack((lehisppval,st[...,None]))
st=lelosppval[...,-1]
lelosppval=np.hstack((lelosppval,st[...,None]))
st=sphight[...,-1]
sphight=np.dstack((sphight,st[...,None]))
st=splowt[...,-1]
splowt=np.dstack((splowt,st[...,None]))
compdt = {'highsp': highlesp, 'lowsp': lowlesp, 'meansp': meanlesp,
'hisppval': lehisppval, 'losppval': lelosppval, 'sppval': lesppval,
'highidx': highidx, 'lowidx': lowidx, 'highspt': sphight, 'lowspt': splowt}
return compdt
# end do_composite()
if loadmat:
leallrdt={r1key:dict.fromkeys(fields),
'eursat':dict.fromkeys(fields),
r3key:dict.fromkeys(fields)}
matbase='pymatfiles/LE_composites_'
for rkey in regions:
for fkey in fields:
matname = matbase + rkey + '_' + fkey + '_' + when + '.mat'
leallrdt[rkey][fkey]=sio.loadmat(matname,squeeze_me=True)
piallrdt={r1key:dict.fromkeys(fields),
'eursat':dict.fromkeys(fields),
r3key:dict.fromkeys(fields)}
matbase='pymatfiles/PI_composites_'
for rkey in regions:
for fkey in fields:
matname = matbase + rkey + '_' + fkey + '_' + when + '.mat'
piallrdt[rkey][fkey]=sio.loadmat(matname,squeeze_me=True)
aallrdt={r1key:dict.fromkeys(fields),
'eursat':dict.fromkeys(fields),
r3key:dict.fromkeys(fields)}
matbase='pymatfiles/AGCMRsims_composites_'
for rkey in regions:
for fkey in fields:
matname = matbase + rkey + '_' + fkey + '_' + when + '.mat'
aallrdt[rkey][fkey]=sio.loadmat(matname,squeeze_me=True)
aeallrdt={r1key:dict.fromkeys(fields),
'eursat':dict.fromkeys(fields),
r3key:dict.fromkeys(fields)}
matbase='pymatfiles/AGCMEsims_composites_'
for rkey in regions:
for fkey in fields:
matname = matbase + rkey + '_' + fkey + '_' + when + '.mat'
aeallrdt[rkey][fkey]=sio.loadmat(matname,squeeze_me=True)
#if not dataloaded:
else:
nn=10 #@@
#casenames=('historical','historicalNat','historicalMisc')
casenames=('historical',)
loaddictsp={'timeselc':timeselc, 'timeselp': timeselp,
'sea': seasp, 'ftype': ftype, 'conv':leconvsp}
loaddictsp2={'timeselc':timeselc, 'timeselp': timeselp,
'sea': seasp, 'ftype': ftype, 'conv':leconvsp2}
loaddictice={'timeselc':timeselc, 'timeselp': timeselp,
'sea': seasp, 'ftype': ftype, 'conv':leconvsp}
loaddictr={'timeselc':timeselc, 'timeselp': timeselp,
'sea': sear, 'ftype': ftype, 'conv':leconvr}
loaddictr2={'timeselc':timeselc, 'timeselp': timeselp,
'sea': sear, 'ftype': ftype, 'conv':leconvr2}
loaddictr3={'timeselc':timeselc, 'timeselp': timeselp,
'sea': sear, 'ftype': ftype, 'conv':leconvr3}
print fdictsp
print fdictr
# "high" for regional BKS SIC is 'high ice loss' (conv=-1)
# "high" for regional Eur SAT is 'warm temp anomaly' (conv=1)
# if conv=1, "high" for regional BKS Z500 is 'high height anomaly'
# comp on region 1
print 'CGCM comp on BKS SIC'
# highlesp, lowlesp, meanlesp, lehisppval, lelosppval, lesppval, highidx, lowidx
lespr1dt = composite_lefield(casenames,
fdictsp, fdictr,
loaddictsp, loaddictr,
verb=True,local=local)
# highlesp2, lowlesp2, meanlesp2, lehisp2pval, lelosp2pval, lesp2pval, highidx, lowidx
lesp2r1dt = composite_lefield(casenames,
fdictsp2, fdictr,
loaddictsp2, loaddictr,
verb=True,local=local)
# highleice, lowleice, meanleice, lehiicepval, leloicepval, leicepval, highidx, lowidx
leicer1dt = composite_lefield(casenames,
fdictice, fdictr,
loaddictice, loaddictr,
verb=True,local=local)
# comp on region 2
print 'CGCM comp on Eur SAT'
# highlespr2, lowlespr2, meanlespr2, lehispr2pval, lelospr2pval, lespr2pval, highidx2, lowidx2
lespr2dt = composite_lefield(casenames,
fdictsp, fdictr2,
loaddictsp, loaddictr2,
verb=True,local=local)
# highlesp2r2, lowlesp2r2, meanlesp2r2, lehisp2r2pval, lelosp2r2pval, lesp2r2pval, highidx2, lowidx2
lesp2r2dt = composite_lefield(casenames,
fdictsp2, fdictr2,
loaddictsp2, loaddictr2,
verb=True,local=local)
# highleicer2, lowleicer2, meanleicer2, lehiicer2pval, leloicer2pval, leicer2pval, highidx2, lowidx2
leicer2dt = composite_lefield(casenames,
fdictice, fdictr2,
loaddictice, loaddictr2,
verb=True,local=local)
# comp on region 3
print 'CGCM comp on BKS Z500'
lespr3dt = composite_lefield(casenames,
fdictsp, fdictr3,
loaddictsp, loaddictr3,
verb=True,local=local)
lesp2r3dt = composite_lefield(casenames,
fdictsp2, fdictr3,
loaddictsp2, loaddictr3,
verb=True,local=local)
leicer3dt = composite_lefield(casenames,
fdictice, fdictr3,
loaddictice, loaddictr3,
verb=True,local=local)
now = str(datetime.datetime.now().time())
now=when
ler1flds={'sat':lespr1dt,'z500':lesp2r1dt,'ice':leicer1dt}
ler2flds={'sat':lespr2dt,'z500':lesp2r2dt,'ice':leicer2dt}
ler3flds={'sat':lespr3dt,'z500':lesp2r3dt,'ice':leicer3dt}
leallrdt={r1key:ler1flds,'eursat':ler2flds,r3key:ler3flds}
if savemat:
matbase='pymatfiles/LE_composites_'
for rkey in regions:
for fkey in fields:
savedt=leallrdt[rkey][fkey]
matname = matbase + rkey + '_' + fkey + '_' + now + '.mat'
sio.savemat(matname,savedt)
# ========== PRE-IND ==============
piseasp,styear,anomyears = load_canesmfield(fdictsp,'piControl',seasp,conv=leconvsp,
local=local,styear=styearPI,anomyears=anomyearsPI)
piseasp2,styear,anomyears = load_canesmfield(fdictsp2,'piControl',seasp,conv=leconvsp2,
local=local,styear=styear,anomyears=anomyears)
piseaspice,styear,anomyears = load_canesmfield(fdictice,'piControl',sear,conv=1,
local=local,styear=styear,anomyears=anomyears)
pisear,styear,anomyears = load_canesmfield(fdictr,'piControl',sear,conv=leconvr,
local=local,styear=styear,anomyears=anomyears,addcyc=False)
pisear2,styear,anomyears = load_canesmfield(fdictr2,'piControl',sear,conv=leconvr2,
local=local,styear=styear,anomyears=anomyears,addcyc=False)
pisear3,styear,anomyears = load_canesmfield(fdictr3,'piControl',sear,conv=leconvr3,
local=local,styear=styear,anomyears=anomyears,addcyc=False)
print 'PI comp on BKS SIC'
# pihighsp,pilowsp,pimeansp,pihisppval,pilosppval,pisppval,pihighidx,pilowidx
pispr1dt = do_composite(pisear,piseasp,verb=True)
# pihighsp2,pilowsp2,pimeansp2,pihisp2pval,pilosp2pval,pisp2pval,pihighidx,pilowidx
pisp2r1dt = do_composite(pisear,piseasp2,verb=True)
# pihighice,pilowice,pimeanice,pihiicepval,piloicepval,piicepval,pihighidx,pilowidx
piicer1dt = do_composite(pisear,piseaspice,verb=True)
print 'PI comp on Eur SAT'
# pihighspr2,pilowspr2,pimeanspr2,pihispr2pval,pilospr2pval,pispr2pval,pihighidxr2,pilowidxr2
pispr2dt = do_composite(pisear2,piseasp,verb=True)
# pihighsp2r2,pilowsp2r2,pimeansp2r2,pihisp2r2pval,pilosp2r2pval,pisp2r2pval,pihighidxr2,pilowidxr2
pisp2r2dt = do_composite(pisear2,piseasp2,verb=True)
# pihighicer2,pilowicer2,pimeanicer2,pihiicer2pval,piloicer2pval,piicer2pval,pihighidxr2,pilowidxr2
piicer2dt = do_composite(pisear2,piseaspice,verb=True)
print 'PI comp on BKS Z500'
pispr3dt = do_composite(pisear3,piseasp,verb=True)
pisp2r3dt = do_composite(pisear3,piseasp2,verb=True)
piicer3dt = do_composite(pisear3,piseaspice,verb=True)
pir1flds={'sat':pispr1dt,'z500':pisp2r1dt,'ice':piicer1dt}
pir2flds={'sat':pispr2dt,'z500':pisp2r2dt,'ice':piicer2dt}
pir3flds={'sat':pispr3dt,'z500':pisp2r3dt,'ice':piicer3dt}
piallrdt={r1key:pir1flds,'eursat':pir2flds,r3key:pir3flds}
if savemat:
matbase='pymatfiles/PI_composites_'
for rkey in regions:
for fkey in fields:
savedt=piallrdt[rkey][fkey]
matname = matbase + rkey + '_' + fkey + '_' + now + '.mat'
sio.savemat(matname,savedt)
sio.savemat(matbase+'anomyears_'+now+'.mat',{'anomyears':anomyears})
sio.savemat(matbase+'styear_'+now+'.mat',{'styear':styear})
# === AGCM ==========
simsE=('E1','E2','E3','E4','E5');
sims=('R1','R2','R3','R4','R5');
simsO=('NSIDC',)
asseasp,styearsr = load_agcmfield(fieldsp,sims,seasp,styears=styearsR) # already anomalies
asseasp2,styearsr = load_agcmfield(fieldsp2,sims,seasp,styears=styearsr) # already anomalies
asseaice,styearsr = load_agcmfield('sic',sims,seasp,styears=styearsr,conv=100) # want the SICN pattern
assear,styearsr = load_agcmfield(fieldr,sims,sear,styears=styearsr,region=regionr,conv=leconvr) # already anomalies
assear2,styearsr = load_agcmfield(fieldr2,sims,sear,styears=styearsr,region=regionr2,conv=leconvr2) # already anomalies
assear3,styearsr = load_agcmfield(fieldr3,sims,sear,styears=styearsr,region=regionr3,conv=leconvr3) # already anomalies
assear=assear # / assear.std()
assear2=assear2 #/ assear2.std()
assear3=assear3
(anens,anlat,anlon)=asseasp.shape
rshape=(anens,anlat*anlon)
print 'AGCMR comp on BKS SIC'
aspr1dt= do_composite(assear,asseasp,verb=True)
asp2r1dt = do_composite(assear,asseasp2,verb=True)
aicer1dt = do_composite(assear,asseaice,verb=True)
print 'AGCMR comp on Eur SAT'
aspr2dt = do_composite(assear2,asseasp,verb=True)
asp2r2dt = do_composite(assear2,asseasp2,verb=True)
aicer2dt = do_composite(assear2,asseaice,verb=True)
print 'AGCMR comp on BKS Z500'
aspr3dt = do_composite(assear3,asseasp,verb=True)
asp2r3dt = do_composite(assear3,asseasp2,verb=True)
aicer3dt = do_composite(assear3,asseaice,verb=True)
ar1flds={'sat':aspr1dt,'z500':asp2r1dt,'ice':aicer1dt}
ar2flds={'sat':aspr2dt,'z500':asp2r2dt,'ice':aicer2dt}
ar3flds={'sat':aspr3dt,'z500':asp2r3dt,'ice':aicer3dt}
aallrdt={r1key:ar1flds,'eursat':ar2flds,r3key:ar3flds}
if savemat:
matbase='pymatfiles/AGCMRsims_composites_'
for rkey in regions:
for fkey in fields:
savedt=aallrdt[rkey][fkey]
matname = matbase + rkey + '_' + fkey + '_' + now + '.mat'
sio.savemat(matname,savedt)
sio.savemat(matbase+'styears_'+now+'.mat',{'styears':styearsr})
if compagcm: # if compare AGCM ensembles
# === E sims:
aesseasp,styearse = load_agcmfield(fieldsp,simsE,seasp,styears=styearsE) # already anomalies
aesseasp2,styearse = load_agcmfield(fieldsp2,simsE,seasp,styears=styearse) # already anomalies
aesseaice,styearse = load_agcmfield('sic',simsE,seasp,styears=styearse,conv=100) # want the SICN pattern
aessear,styearse = load_agcmfield(fieldr,simsE,sear,styears=styearse,region=regionr,conv=leconvr) # already anomalies
aessear2,styearse = load_agcmfield(fieldr2,simsE,sear,styears=styearse,region=regionr2,conv=leconvr2) # already anomalies
aessear3,styearse = load_agcmfield(fieldr3,simsE,sear,styears=styearse,region=regionr3,conv=leconvr3) # already anomalies
aessear=aessear # / assear.std()
aessear2=aessear2 #/ assear2.std()
aessear3=aessear3
print 'AGCME comp on BKS SIC'
aespr1dt= do_composite(aessear,aesseasp,verb=True)
aesp2r1dt = do_composite(aessear,aesseasp2,verb=True)
aeicer1dt = do_composite(aessear,aesseaice,verb=True)
print 'AGCME comp on Eur SAT'
aespr2dt = do_composite(aessear2,aesseasp,verb=True)
aesp2r2dt = do_composite(aessear2,aesseasp2,verb=True)
aeicer2dt = do_composite(aessear2,aesseaice,verb=True)
print 'AGCME comp on BKS Z500'
aespr3dt = do_composite(aessear3,aesseasp,verb=True)
aesp2r3dt = do_composite(aessear3,aesseasp2,verb=True)
aeicer3dt = do_composite(aessear3,aesseaice,verb=True)
aer1flds={'sat':aespr1dt,'z500':aesp2r1dt,'ice':aeicer1dt}
aer2flds={'sat':aespr2dt,'z500':aesp2r2dt,'ice':aeicer2dt}
aer3flds={'sat':aespr3dt,'z500':aesp2r3dt,'ice':aeicer3dt}
aeallrdt={r1key:aer1flds,'eursat':aer2flds,r3key:aer3flds}
if savemat:
matbase='pymatfiles/AGCMEsims_composites_'
for rkey in regions:
for fkey in fields:
savedt=aeallrdt[rkey][fkey]
matname = matbase + rkey + '_' + fkey + '_' + now + '.mat'
sio.savemat(matname,savedt)
sio.savemat(matbase+'styears_'+now+'.mat',{'styears':styearse})
# AGCM RESIDUAL pvals (var vs const)
#(aressptstat,aressppval) = cutl.ttest_ind(asseasp[alow2idx,...]- asseasp[ahigh2idx,...],
# aesseasp[aelow2idx,...]- aesseasp[aehigh2idx,...])
#(aressp2tstat,aressp2pval) = cutl.ttest_ind(asseasp2[alow2idx,...]- asseasp2[ahigh2idx,...],
# aesseasp2[aelow2idx,...]- aesseasp2[aehigh2idx,...])
# === Obs sims (NSIDC):
aosseasp,styearso = load_agcmfield(fieldsp,simsO,seasp,styears=styearsN) # already anomalies
aosseasp2,styearso = load_agcmfield(fieldsp2,simsO,seasp,styears=styearso) # already anomalies
aosseaice,styearso = load_agcmfield('sic',simsO,seasp,styears=styearso,conv=100) # want the SICN pattern
aossear,styearso = load_agcmfield(fieldr,simsO,sear,styears=styearso,region=regionr,conv=leconvr) # already anomalies
aossear2,styearso = load_agcmfield(fieldr2,simsO,sear,styears=styearso,region=regionr2,conv=leconvr2) # already anomalies
aossear3,styearso = load_agcmfield(fieldr3,simsO,sear,styears=styearso,region=regionr3,conv=leconvr3) # already anomalies
aossear=aossear # / assear.std()
aossear2=aossear2 #/ assear2.std()
aossear3=aossear3
if savemat:
matbase='pymatfiles/AGCMOsims_composites_' # @@ not really a composite. just save startyr
sio.savemat(matbase+'styears_'+now+'.mat',{'styears':styearso})
if saveascii:
# write ascii file for john:
agcmout1=np.hstack((assear, aossear, aessear))*100 # column 1 (BKS SIC: variable SIC, NSIDC SIC, mean SIC)
agcmout2=np.hstack((assear2, aossear2, aessear2)) # column 2 (Eur SAT)
agcmout3=np.hstack((assear3, aossear3, aessear3)) # column 3 (BKS Z500)
agcmout = np.vstack((agcmout1,agcmout2,agcmout3)).T
np.savetxt('agcmout3.ascii',agcmout,delimiter='\t')
#
#cgcmout1=np.hstack((lefldcnd,lefldncnd,lefldmcnd)) # (ALL forcing, NAT, AERO/MISC)
#cgcmout2=np.hstack((lefld2,lefld2n,lefld2m))
#cgcmout3=np.hstack((lefld1,lefld1n,lefld1m))
#cgcmout = np.vstack((cgcmout1,cgcmout2,cgcmout3)).T
#np.savetxt('cgcmout.ascii',cgcmout,delimiter='\t')
# For each composite (r1, r2, r3), compute the BKS SIC average:
allcasedt = {'Preindustrial':piallrdt, 'CGCM': leallrdt, 'AGCM':aallrdt}
allcasedt = {'CGCM': leallrdt, 'AGCM_variable': aallrdt, 'AGCM_fixed': aeallrdt}
# Here calculate the BKS SIC associated with each composite
allregimdt={};allregimlodt={};allregimhidt={}; allregitdt={}; allregimcidt={}; allregitcidt={}
allregimlocidt={};allregimhicidt={};
fkey='ice'
print '@@@@@@@@@@@@@ calculating CI for ICE, all composites'
for ckey in allcasedt.keys():
print '=ENS ' + ckey
regmdt={}; regmlodt={}; regmhidt={}; regtotdt={}; regmcidt={}; regtcidt={}
regmlocidt={}; regmhicidt={}
allrdt=allcasedt[ckey]
for rkey in regions:
print ' REGION ' + rkey
dt=allrdt[rkey][fkey]
diff = dt['lowspt']-dt['highspt'] # with sample dim
regt = cutl.calc_regtotseaicearea(diff[...,:-1],lat,lon,'bksmori')
regm = cutl.calc_regmean(diff[...,:-1],lat,lon,'bksmori')
# Confidence interval: 2.5-97.5% interval on the mean
regmci = sp.stats.t.interval(1-cisiglevel,len(regm)-1,
loc=regm.mean(axis=0),
scale=regm.std(axis=0)/np.sqrt(len(regm)))
regtci = sp.stats.t.interval(1-cisiglevel,len(regt)-1,
loc=regt.mean(axis=0),
scale=regt.std(axis=0)/np.sqrt(len(regt)))
print ' DIFF: ' + str(regm.mean(axis=0)) + ', CI: ' + str(regmci) # @@
# @@ CONFIDENCE interval on the low! (for John to compare)
regmlo = cutl.calc_regmean(dt['lowspt'][...,:-1],lat,lon,'bksmori')
regmhi = cutl.calc_regmean(dt['highspt'][...,:-1],lat,lon,'bksmori')
regmloci = sp.stats.t.interval(1-cisiglevel,len(regmlo)-1,
loc=regmlo.mean(axis=0),
scale=regmlo.std(axis=0)/np.sqrt(len(regmlo)))
regmhici = sp.stats.t.interval(1-cisiglevel,len(regmhi)-1,
loc=regmhi.mean(axis=0),
scale=regmhi.std(axis=0)/np.sqrt(len(regmhi)))
print ' LO: ' + str(regmlo.mean(axis=0)) + ', CI: ' + str(regmloci) # @@
#print ' LO vals: ' + str(regmlo)
print ' HI: ' + str(regmhi.mean(axis=0)) + ', CI: ' + str(regmhici) # @@
junk,regmdiffpval = cutl.ttest_ind(regmlo,regmhi)
print ' LO v HI pval: ' + str(regmdiffpval)
regmdt[rkey]=regm.mean(axis=0)
regmlodt[rkey]=regmlo.mean(axis=0)
regmhidt[rkey]=regmhi.mean(axis=0)
regtotdt[rkey]=regt.mean(axis=0) # not sure which one i want
regmcidt[rkey]=regmci
regmlocidt[rkey]=regmloci
regmhicidt[rkey]=regmhici
regtcidt[rkey]=regtci
allregimdt[ckey]=regmdt # i for ice
allregimlodt[ckey]=regmlodt # i for ice
allregimhidt[ckey]=regmhidt # i for ice
allregitdt[ckey]=regtotdt
allregimcidt[ckey]=regmcidt
allregimlocidt[ckey]=regmlocidt
allregimhicidt[ckey]=regmhicidt
allregitcidt[ckey]=regtcidt
allregimdf=pd.DataFrame(allregimdt)
allregitdf=pd.DataFrame(allregitdt)
allregimcidf=pd.DataFrame(allregimcidt)
allregitcidf=pd.DataFrame(allregitcidt)
# Here calculate the Eur SAT associated with each composite
allregspmdt={}; allregspmcidt={};
fkey='sat'
print '@@@@@@@@@@@@@ calculating CI for SAT, all composites'
for ckey in allcasedt.keys():
print '=ENS ' + ckey
regmdt={}; regtotdt={}; regmcidt={}; regtcidt={}
allrdt=allcasedt[ckey]
for rkey in regions:
print ' REGION ' + rkey
dt=allrdt[rkey][fkey]
diff = dt['lowspt']-dt['highspt']
regm = cutl.calc_regmean(diff[...,:-1],lat,lon,'eurasiamori')
# Confidence interval: 2.5-97.5% interval on the mean
regmci = sp.stats.t.interval(1-cisiglevel,len(regm)-1,
loc=regm.mean(axis=0),
scale=regm.std(axis=0)/np.sqrt(len(regm)))
print ' DIFF: ' + str(regm.mean(axis=0)) + ', CI: ' + str(regmci) # @@
# @@ CONFIDENCE interval on the low! (for John to compare)
regmlo = cutl.calc_regmean(dt['lowspt'][...,:-1],lat,lon,'eurasiamori')
regmhi = cutl.calc_regmean(dt['highspt'][...,:-1],lat,lon,'eurasiamori')
regmloci = sp.stats.t.interval(1-cisiglevel,len(regmlo)-1,
loc=regmlo.mean(axis=0),
scale=regmlo.std(axis=0)/np.sqrt(len(regmlo)))
regmhici = sp.stats.t.interval(1-cisiglevel,len(regmhi)-1,
loc=regmhi.mean(axis=0),
scale=regmhi.std(axis=0)/np.sqrt(len(regmhi)))
print ' LO: ' + str(regmlo.mean(axis=0)) + ', CI: ' + str(regmloci) # @@
#print ' LO vals: ' + str(regmlo)
print ' HI: ' + str(regmhi.mean(axis=0)) + ', CI: ' + str(regmhici) # @@
junk,regmdiffpval = cutl.ttest_ind(regmlo,regmhi)
print ' LO v HI pval: ' + str(regmdiffpval)
regmdt[rkey]=regm.mean(axis=0)
regmcidt[rkey]=regmci
allregspmdt[ckey]=regmdt # sp for spatial 1 (SAT)
allregspmcidt[ckey]=regmcidt
allregspmdf=pd.DataFrame(allregspmdt)
allregspmcidf=pd.DataFrame(allregspmcidt)
# Here calculate the BKS Z500 associated with each composite
allregsp2mdt={}; allregsp2mcidt={};allregsp2mlodt={}; allregsp2mlocidt={};
allregsp2mhidt={}; allregsp2mhicidt={};
fkey='z500'
print '@@@@@@@@@@@@@ calculating CI for Z500, all composites'
for ckey in allcasedt.keys():
print '=ENS ' + ckey # @@
regmdt={};regmlodt={};regmhidt={}; regtotdt={}; regmcidt={}; regmlocidt={};regmhicidt={}
allrdt=allcasedt[ckey]
for rkey in regions:
print ' REGION ' + rkey # @@
dt=allrdt[rkey][fkey]
diff = dt['lowspt']-dt['highspt']
regm = cutl.calc_regmean(diff[...,:-1],lat,lon,'bksmori')
# Confidence interval: 2.5-97.5% interval on the mean
regmci = sp.stats.t.interval(1-cisiglevel,len(regm)-1,
loc=regm.mean(axis=0),
scale=regm.std(axis=0)/np.sqrt(len(regm)))
print ' DIFF: ' + str(regm.mean(axis=0)) + ', CI: ' + str(regmci) # @@
# @@ CONFIDENCE interval on the low! (for John to compare)
regmlo = cutl.calc_regmean(dt['lowspt'][...,:-1],lat,lon,'bksmori')
regmhi = cutl.calc_regmean(dt['highspt'][...,:-1],lat,lon,'bksmori')
regmloci = sp.stats.t.interval(1-cisiglevel,len(regmlo)-1,
loc=regmlo.mean(axis=0),
scale=regmlo.std(axis=0)/np.sqrt(len(regmlo)))
regmhici = sp.stats.t.interval(1-cisiglevel,len(regmhi)-1,
loc=regmhi.mean(axis=0),
scale=regmhi.std(axis=0)/np.sqrt(len(regmhi)))
print ' LO: ' + str(regmlo.mean(axis=0)) + ', CI: ' + str(regmloci) # @@
#print ' LO vals: ' + str(regmlo)
print ' HI: ' + str(regmhi.mean(axis=0)) + ', CI: ' + str(regmhici) # @@
junk,regmdiffpval = cutl.ttest_ind(regmlo,regmhi)
print ' LO v HI pval: ' + str(regmdiffpval)
regmdt[rkey]=regm.mean(axis=0)
regmcidt[rkey]=regmci
regmlodt[rkey]=regmlo.mean(axis=0)
regmlocidt[rkey]=regmloci
regmhidt[rkey]=regmhi.mean(axis=0)
regmhicidt[rkey]=regmhici
allregsp2mdt[ckey]=regmdt # sp for spatial 1 (SAT)
allregsp2mcidt[ckey]=regmcidt
allregsp2mlodt[ckey]=regmlodt # sp for spatial 1 (SAT)
allregsp2mlocidt[ckey]=regmlocidt
allregsp2mhidt[ckey]=regmhidt # sp for spatial 1 (SAT)
allregsp2mhicidt[ckey]=regmhicidt
allregsp2mdf=pd.DataFrame(allregsp2mdt)
allregsp2mcidf=pd.DataFrame(allregsp2mcidt)
fontP = fm.FontProperties()
fontP.set_size('small')
lons, lats = np.meshgrid(lon,lat)
cmlen=15.
incr = (cmaxsp2-cminsp2) / (cmlen)
conts = np.arange(cminsp2,cmaxsp2+incr,incr)
incrbig = (cmaxsp2big-cminsp2big) / (cmlen)
contsbig = np.arange(cminsp2big,cmaxsp2big+incrbig,incrbig)
stxx=1
xx=np.arange(stxx,(stxx+len(allregimdf.keys())-1)*1.2,1.2)
#regs=('bkssic','eursat','bksz500')
#regs=('eursat','bkssic','bksz500') # SWAP order. @@ Actually, use regions instead
multfacs=(1,1,-1) # multiply the comp on z500 by -1 to get high over bks
enss=('CGCM','Preindustrial','AGCM')
enss=('CGCM','AGCM_variable','AGCM_fixed')
mkrs=('s','o','^')
clrs=('r','b','0.4')
#clrs=('.4','.4','.4')
# prepare legend entries
lgs=(mlines.Line2D([],[],color=clrs[0],linewidth=2),
mlines.Line2D([],[],color=clrs[1],linewidth=2),
mlines.Line2D([],[],color=clrs[2],linewidth=2)) #,linestyle='none',marker=mkrs[0]),
#mlines.Line2D([],[],color=clrs[1],linestyle='none',marker=mkrs[1]),
#mlines.Line2D([],[],color=clrs[2],linestyle='none',marker=mkrs[2]))
#lgstrs=('BKS SIC','Eur SAT','BKS Z500')
lgstrs=(r2str,r1str,r3str) # SWAP order
lespr1dt=leallrdt[r1key][spkey]
lesp2r1dt=leallrdt[r1key][sp2key]
lespr2dt=leallrdt[r2key][spkey]
lesp2r2dt=leallrdt[r2key][sp2key]
lespr3dt=leallrdt[r3key][spkey]
lesp2r3dt=leallrdt[r3key][sp2key]
fig=plt.figure(figsize=(12,9))
gs1 = gridspec.GridSpec(1, 6)
gs1.update(top=0.97,bottom=0.55,left=0.08,right=0.92,wspace=0.04)
ax=plt.subplot(gs1[0,0:2])