-
Notifications
You must be signed in to change notification settings - Fork 2
/
step05_calculateNSIFmetrics.py
421 lines (337 loc) · 20.4 KB
/
step05_calculateNSIFmetrics.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
# calculate mean, median, std of all
print 'importing modules'
import numpy as np
from netCDF4 import Dataset
from datetime import datetime
import glob
import nio
from scipy import stats
#import matplotlib.pyplot as plt
#import matplotlib as mpl
#mpl.rcParams['pdf.fonttype'] = 42
#mpl.rcParams['font.sans-serif']=['Arial']
startTime = datetime.now()
path=u'/Volumes/Pitcairn/seaicePPF/northernHemisphere/analysisOutput/'
bgKey=u'B1850C5CN'
runPart1key=u'B20TRC5CNBDRD'
runParts23key=u'BRCP85C5CNBDRD'
runParts23keyRCP45=u'BRCP45C5CNBDRD'
nskey=['nh','sh']
rcpName=['RCP85', 'RCP45']
rcpkey=[runPart1key+'-'+runParts23key,runPart1key+'-'+runParts23keyRCP45]
# two loops. northern/southern + rcp 8.5/4.5
for nsk in nskey:
dirList2=glob.glob(path+'*'+bgKey+'*'+nsk+'*Analysis.nc')
analysisFiles2=[]
for fn in dirList2:
analysisFiles2.append(Dataset(fn, 'r'))
#print fn, (datetime.now()-startTime)
numSIF1850=[]
fir1850=[]
las1850=[]
print 'opening background: ', nsk
for fn in dirList2:
f=Dataset(fn, 'r')
numSIF1850.extend(f.variables['numSIF'][:,:,:])
fir1850.extend(f.variables['firstDOY'][:,:,:])
las1850.extend(f.variables['lastDOY'][:,:,:])
print fn, (datetime.now()-startTime)
f.close()
nSIF1850=np.array(numSIF1850)
first1850=np.array(fir1850)
last1850=np.array(las1850)
del numSIF1850
del fir1850
del las1850
for ittR in range(len(rcpkey)):
fnAnalysis='/Volumes/Pitcairn/seaicePPF/northernHemisphere/analysisOutput/allModels.Summary.'+nsk+ '.'+ rcpName[ittR] +'.nc'
print fnAnalysis
dirList=glob.glob(path+'*'+rcpName[ittR]+'*'+nsk+'*Analysis.nc')
analysisFiles=[]
for fn in dirList:
analysisFiles.append(Dataset(fn, 'r'))
#print fn, (datetime.now()-startTime)
key='numSIF'
f=nio.open_file(dirList[0],'r')
landMask=f.variables[key][0,:,:]>1200
fillVal=f.variables[key].__dict__['_FillValue']
ni=f.dimensions['ni']
nj=f.dimensions['nj']
nm=len(dirList)
numModels=len(dirList)
lastYear=int(np.floor(f.variables['time'][:].max()/365))
numYears=lastYear-1850
if numYears==249:
numYears=250
lastYear=lastYear-1
del f
numSIF=np.nan*np.ones((numModels,numYears,nj,ni))
first=np.nan*np.ones((numModels,numYears,nj,ni))
last=np.nan*np.ones((numModels,numYears,nj,ni))
i=0
for fn in dirList:
f=Dataset(fn, 'r')
ns=f.variables['numSIF'][:,:,:]
numSIF[i,-ns.shape[0]:,:,:]=ns
fs=f.variables['firstDOY'][:,:,:]
first[i,-ns.shape[0]:,:,:]=fs
ls=f.variables['lastDOY'][:,:,:]
last[i,-ns.shape[0]:,:,:]=ls
print fn, (datetime.now()-startTime)
i+=1
f.close()
nSIF=np.array(numSIF)
first=np.array(first)
last=np.array(last)
origData={'nSIF1850':nSIF1850,
'nSIF':nSIF,
'first1850':first1850,
'last1850':last1850,
'first':first,
'last':last}
dataset={}
for k in origData.keys():
d=origData[k]
# do appropriate masking:
d[d>900]=np.nan # set days with all ice to nan for appropriate
# statistics
# if not all models have values, we don't want to make a statistic, therefore don't use nan
# changed mind. do want statistic
tempMean=np.nanmean(d, axis=0)
tempMedian=np.median(d, axis=0)
tempStd=np.nanstd(d, axis=0)
if len(tempMean.shape)==2:
tempMean[landMask]=fillVal
tempMedian[landMask]=fillVal
tempStd[landMask]=fillVal
else:
tempMean[:,landMask]=fillVal
tempMedian[:,landMask]=fillVal
tempStd[:,landMask]=fillVal
dataset[k+'Mean']={'data':tempMean}
dataset[k+'Median']={'data':tempMedian}
dataset[k+'Std']={'data':tempStd}
if k[0]=='n':
dataset[k+'Std']['units']='number of days'
dataset[k+'Mean']['units']='number of days'
dataset[k+'Median']['units']='number of days'
else:
dataset[k+'Std']['units']='day of year'
dataset[k+'Mean']['units']='day of year'
dataset[k+'Median']['units']='day of year'
dataset[k+'Std']['longName']='Standard deviation of the number of '+k
dataset[k+'Mean']['longName']='Mean number of '+k
dataset[k+'Median']['longName']='Median number of '+k
print k, (datetime.now()-startTime)
# calculate comparisons to 1850 (once that modle has been analyzed)
for k in ['nSIF', 'first', 'last']:
for kadd in ['Std', 'Median', 'Mean']:
key=k+kadd
key2=k+'1850'+kadd
data=dataset[key]['data']
data2=dataset[key2]['data']
compdata=np.ones(data.shape)
for i in range(data.shape[0]):
compdata[i,:,:]=(data[i,:,:]-data2)/data2
compdata[:,landMask]=fillVal
isnan=np.isnan(compdata)
compdata[isnan]=fillVal
isinf=np.isinf(compdata)
compdata[isinf]=fillVal
dataset[key+'Comp_prop']={'data':compdata,
'units':'Difference with 1850 normalized by 1850 value',
'longName': 'Comparison of '+dataset[key]['longName']+'with 1850'}
compdata2=np.ones(data.shape)
for i in range(data.shape[0]):
compdata2[i,:,:]=data[i,:,:]-data2
compdata2[:,landMask]=fillVal
dataset[key+'Comp_abs']={'data':compdata2,
'units':'Difference with 1850',
'longName': 'Comparison of '+dataset[key]['longName']+'with 1850'}
######### calculate slopes
slope=np.nan*np.ones((nm, nj, ni))
slope_masked=np.nan*np.ones((nm, nj, ni))
R=np.nan*np.ones((nm, nj, ni))
pval=np.nan*np.ones((nm, nj, ni))
icemask=np.nanmean(nSIF1850, axis=0)<350
final_year=np.nan*np.ones((nm, nj, ni))
time=np.arange(1850,lastYear+2)
startInd=129 # (1979-2014)
stopInd=165
for nii in range(ni):
print 'calculating trendlines', str(nii)+'/'+str(ni), (datetime.now()-startTime)
for njj in range(nj):
if (icemask[njj, nii]==True):
for nmm in range(nm):
s, icpts, r, p, ster = stats.linregress(time[startInd:stopInd],nSIF[nmm,startInd:stopInd, njj, nii])
slope[nmm, njj, nii]=s
R[nmm, njj, nii]=r
pval[nmm, njj, nii]=p
if p<0.05:
slope_masked[nmm, njj, nii]=s
#### choose last year that there is are more than 15 days of ice per year.
fyind=np.where(nSIF[nmm,:, njj, nii]>182)[0]
if len(fyind)==0:
final_year[nmm, njj, nii]=np.nan
else:
final_year[nmm, njj, nii]=time[fyind[0]]
final_year_mean=np.nanmean(final_year, axis=0)
isnan=np.isnan(final_year_mean)
final_year_mean[isnan]=fillVal
isinf=np.isinf(final_year_mean)
final_year_mean[isinf]=fillVal
isnan=np.isnan(final_year)
final_year[isnan]=fillVal
isinf=np.isinf(final_year)
final_year[isinf]=fillVal
# get rid of infs before averaging.
isinf=np.isinf(slope_masked)
slope_masked[isinf]=np.nan
isinf=np.isinf(slope)
slope[isinf]=np.nan
meanSlope=np.nanmean(slope, axis=0)
stdSlope=np.nanstd(slope, axis=0)
meanSlope_masked=np.nanmean(slope_masked, axis=0)
stdSlope_masked=np.nanstd(slope_masked, axis=0)
isnan=np.isnan(slope_masked)
slope_masked[isnan]=fillVal
isinf=np.isinf(slope_masked)
slope_masked[isinf]=fillVal
isnan=np.isnan(slope)
slope[isnan]=fillVal
isinf=np.isinf(slope)
slope[isinf]=fillVal
isnan=np.isnan(meanSlope_masked)
meanSlope_masked[isnan]=fillVal
isinf=np.isinf(meanSlope_masked)
meanSlope_masked[isinf]=fillVal
isnan=np.isnan(stdSlope_masked)
stdSlope_masked[isnan]=fillVal
isinf=np.isinf(stdSlope_masked)
stdSlope_masked[isinf]=fillVal
# 2.5 Save this to a netCDF
f=nio.open_file(dirList[0], 'r')
fAn=Dataset(fnAnalysis, 'w',format='NETCDF4')
# create all the dimentions, set time to unlimited
for k in f.dimensions.keys():
if f.unlimited(k)==True:
fAn.createDimension(k, None)
else:
fAn.createDimension(k, f.dimensions[k])
# use the netCDF4 instead of pyNIO since it seems to work much better with unlimited variables
fAnVars={}
for key in {'TLAT', 'TLON','latt_bounds','lont_bounds','time_bounds', 'time'}:
print 'creating ', key
# the netCDF4 module requires that if a fill value exists, it must be declared when the variable is created.
try:
fAnVars[key]=fAn.createVariable(key, f.variables[key].typecode(), f.variables[key].dimensions, fill_value=f.variables[key].__dict__['_FillValue'])
except:
fAnVars[key]=fAn.createVariable(key, f.variables[key].typecode(), f.variables[key].dimensions)
# sett all the attribute keys.
atts = f.variables[key].__dict__
for attKey in atts.keys():
if attKey != '_FillValue':
setattr(fAn.variables[key],attKey,atts[attKey])
# put data into variables, first the ones we are copying over.
print 'putting data into standard variables'
for key in {'TLAT', 'TLON','latt_bounds','lont_bounds'}:
fAnVars[key][:,:]=f.variables[key][:]
fAnVars['time'][:]=f.variables['time'][-numYears:]
fAnVars['time_bounds'][:,:]=f.variables['time_bounds'][-numYears:,:]
dataKey=dataset.keys()
stdAttributes={'_FillValue': np.array([ 1.00000002e+30], dtype=float),
'cell_measures': 'area: tarea',
'cell_methods': 'time: mean',
'comment': 'none',
'coordinates': 'TLON TLAT time',
'missing_value': np.array([ 1.00000002e+30], dtype=float),
'time_rep': 'averaged'}
for i in range(len(dataKey)):
key=dataKey[i]
d=dataset[key]
data=d['data']
print 'creating ', key
# the netCDF4 module requires that if a fill value exists, it must be declared when the variable is created.
isnan=np.isnan(data)
data[isnan]=fillVal
isinf=np.isinf(data)
data[isinf]=fillVal
if len(data.shape)==3:
fAnVars[key]=fAn.createVariable(key, 'f', ('time', 'nj', 'ni'), fill_value=stdAttributes['_FillValue'])
fAnVars[key][:,:,:]=data
('time', 'nj', 'ni')
elif len(data.shape)==2:
fAnVars[key]=fAn.createVariable(key, 'f', ('nj', 'ni'), fill_value=stdAttributes['_FillValue'])
fAnVars[key][:,:]=data
# set all the attribute keys.
for attKey in stdAttributes.keys():
if attKey != '_FillValue':
setattr(fAn.variables[key],attKey,stdAttributes[attKey])
setattr(fAn.variables[key],'long_name',d['longName'])
setattr(fAn.variables[key],'units',d['units'])
fAn.createDimension('nm', nm)
cKey='meanSlope'
fAn.createVariable(cKey, 'f', ('nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Mean of Slope (1979-2014)')
setattr(fAn.variables[cKey],'units','year')
setattr(fAn.variables[cKey], 'coordinates', 'TLON TLAT')
cKey='stdSlope'
fAn.createVariable(cKey, 'f', ('nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Standard Deviation of Slope (1979-2014)')
setattr(fAn.variables[cKey],'units','year')
setattr(fAn.variables[cKey], 'coordinates', 'TLON TLAT')
cKey='meanSlope_masked'
fAn.createVariable(cKey, 'f', ('nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Mean of Slope (masked by Pval) (1979-2014)')
setattr(fAn.variables[cKey],'units','year')
setattr(fAn.variables[cKey], 'coordinates', 'TLON TLAT')
cKey='stdSlope_masked'
fAn.createVariable(cKey, 'f', ('nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Standard Deviation of Slope (masked by Pval) (1979-2014)')
setattr(fAn.variables[cKey],'units','year')
setattr(fAn.variables[cKey], 'coordinates', 'TLON TLAT')
cKey='pval'
fAn.createVariable(cKey, 'f', ('nm', 'nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Trend pValue')
setattr(fAn.variables[cKey],'units','')
setattr(fAn.variables[cKey], 'coordinates', 'nm TLON TLAT')
cKey='R'
fAn.createVariable(cKey, 'f', ('nm', 'nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','R2')
setattr(fAn.variables[cKey],'units','')
setattr(fAn.variables[cKey], 'coordinates', 'nm TLON TLAT')
cKey='slope'
fAn.createVariable(cKey, 'f', ('nm', 'nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Trend Slope')
setattr(fAn.variables[cKey],'units','Days per Year')
setattr(fAn.variables[cKey], 'coordinates', 'nm TLON TLAT')
cKey='slope_masked'
fAn.createVariable(cKey, 'f', ('nm', 'nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Trend Slope Masked by Pval <0.05 (1979-2014)')
setattr(fAn.variables[cKey],'units','Days per Year')
setattr(fAn.variables[cKey], 'coordinates', 'nm TLON TLAT')
cKey='final_year_mean'
fAn.createVariable(cKey, 'f', ('nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Mean of Final Year with nSIF<182')
setattr(fAn.variables[cKey],'units','year')
setattr(fAn.variables[cKey], 'coordinates', 'TLON TLAT')
cKey='final_year'
fAn.createVariable(cKey, 'f', ('nm', 'nj','ni'),fill_value=fillVal)
setattr(fAn.variables[cKey],'long_name','Final Year with nSIF<182')
setattr(fAn.variables[cKey],'units','year')
setattr(fAn.variables[cKey], 'coordinates', 'nm TLON TLAT')
fAn.variables['final_year'][:,:,:]=final_year
fAn.variables['final_year_mean'][:,:]=final_year_mean
fAn.variables['slope_masked'][:,:,:]=slope_masked
fAn.variables['slope'][:,:,:]=slope
fAn.variables['meanSlope'][:,:]=meanSlope
fAn.variables['stdSlope'][:,:]=stdSlope
fAn.variables['meanSlope_masked'][:,:]=meanSlope_masked
fAn.variables['stdSlope_masked'][:,:]=stdSlope_masked
fAn.variables['pval'][:,:,:]=pval
fAn.variables['R'][:,:,:]=R
fAn.close()
f.close()
del f
del fAn
print'finished analysis of ',fn , (datetime.now()-startTime)