-
Notifications
You must be signed in to change notification settings - Fork 16
/
pyCRTM.py
executable file
·367 lines (343 loc) · 19.9 KB
/
pyCRTM.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
#!/usr/bin/env python3
import configparser
import os, h5py, sys
import numpy as np
from matplotlib import pyplot as plt
thisDir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0,thisDir)
from pycrtm import pycrtm
from crtm_io import readSpcCoeff
from collections import namedtuple
# Absorber IDs taken from CRTM.
gases = {}
gases['Q'] = 1 # H2O for anyone not NWP focused ;)
gases['CO2'] = 2
gases['O3'] = 3
gases['N2O'] = 4
gases['CO'] = 5
gases['CH4'] = 6
gases['O2'] = 7
gases['NO'] = 8
gases['SO2'] = 9
gases['NO2'] = 10
gases['NH3'] = 11
gases['HNO3'] = 12
gases['OH'] = 13
gases['HF'] = 14
gases['HCl'] = 15
gases['HBr'] = 16
gases['HI'] = 17
gases['ClO'] = 18
gases['OCS'] = 19
gases['H2CO'] = 20
gases['HOCl'] = 21
gases['N2'] = 22
gases['HCN'] = 23
gases['CH3l'] = 24
gases['H2O2'] = 25
gases['C2H2'] = 26
gases['C2H6'] = 27
gases['PH3'] = 28
gases['COF2'] = 29
gases['SF6'] = 30
gases['H2S'] = 31
gases['HCOOH'] = 32
def profilesCreate( nProfiles, nLevels, nAerosols=1, nClouds=1, additionalGases=[] ):
keys = [ 'P', 'T', 'Q', 'O3']
for g in additionalGases:
if g in list(gases.keys()) and g not in keys:
keys.append(g)
elif g == 'H2O' or g.lower() == 'water' or g=='ozone':
print("You worry too much, of course we have {}! Water and Ozone are always turned on.".format(g))
else:
print("Warning! I don't know this gas: {}! I can't add it to the simulation!".format(g))
print("You could pick one of these instead:")
for gg in list(gases.keys()): print(gg)
p = {}
for k in list(keys):
p[k] = np.nan*np.ones([nProfiles,nLevels])
p['Pi'] = np.nan*np.ones([nProfiles, nLevels+1])
# satzen, sataz, sunzen, sunaz, scanangle
p['Angles'] = np.nan*np.ones([nProfiles, 5])
# P (2meter), T (2meter), Q (2meter), U(10meter), V(10meter), fetch
p['S2m'] = np.nan*np.ones([nProfiles,6])
# skin T, salinity, snow_fraction, foam_fraction, fastem coef 1:5
p['Skin'] = np.nan*np.zeros([nProfiles,10])
# surftype, water type
p['SurfType'] = np.nan*np.zeros([nProfiles,2])
# latitude, longitude, elevation
p['SurfGeom'] = np.nan*np.zeros([nProfiles,3])
# yy, mm, dd, hh, mm, ss
p['DateTimes'] = np.zeros([nProfiles,6], dtype=int)
p['DateTimes'][:,0] = 2001
p['DateTimes'][:,1] = 1
p['DateTimes'][:,2] = 1
# concentration, effective radius
if(nAerosols>0):
p['aerosols'] = np.nan*np.ones([nProfiles, nLevels, nAerosols, 2])
p['aerosolType'] =-1 *np.ones([nProfiles,nAerosols], dtype =int)
# concentration, effective radius
if(nClouds>0):
p['clouds'] = np.nan*np.ones([nProfiles, nLevels, nClouds, 2])
p['cloudType'] = -1 *np.ones([nProfiles,nClouds], dtype =int)
p['cloudFraction'] = np.zeros([nProfiles,nLevels])
p['LAI'] = np.zeros([nProfiles])
# surface
p['surfaceTemperatures'] = np.zeros([nProfiles,4])
p['surfaceFractions'] = np.zeros([nProfiles,4])
# land, soil, veg, water, snow, ice
p['surfaceTypes'] = np.zeros([nProfiles,6], dtype=int)
p['climatology'] = 6*np.ones([nProfiles], dtype=int) # use usstd as default climatology for unspecified layers to 0.005 mbar (crtm will fill in the gaps if the user doesn't)
p['windSpeed10m'] = np.zeros([nProfiles])
p['windDirection10m'] = np.zeros([nProfiles])
profiles = namedtuple("Profiles", p.keys())(*p.values())
return profiles
class pyCRTM:
def __init__(self):
self.coefficientPath = ''
self.sensor_id = ''
self.profiles = []
self.traceConc = []
self.traceIds = []
self.usedGases = []
self.Bt = []
self.TauLevels = []
self.surfEmisRefl = []
self.TK = []
self.QK = []
self.O3K = []
self.CO2K = []
self.N2OK = []
self.CH4K = []
self.COK = []
self.SkinK = []
self.SurfEmisK = []
self.SurfReflK = []
self.windSpeedK = []
self.windDirectionK = []
self.Wavenumbers = []
self.wavenumbers = []
self.wavenumber = []
self.Wavenumber = []
self.frequencyGHz = []
self.wavelengthMicrons = []
self.wavelengthCm = []
self.nChan = 0
self.output_tb_flag = True
self.StoreTrans = True
self.StoreEmis = True
self.nThreads = 1
self.MWwaterCoeff_File = 'FASTEM6.MWwater.EmisCoeff.bin'
self.IRwaterCoeff_File = 'Nalli.IRwater.EmisCoeff.bin'
def loadInst(self):
if ( os.path.exists( os.path.join(self.coefficientPath, self.sensor_id+'.SpcCoeff.bin') ) ):
o = readSpcCoeff(os.path.join(self.coefficientPath, self.sensor_id+'.SpcCoeff.bin'))
self.nChan = o['n_Channels']
# For those who care to associate channel number with something physical:
# just to save sanity put the permutations of (W/w)avenumber(/s) in here so things just go.
self.wavenumbers = np.asarray(o['Wavenumber'])
self.wavenumber = self.wavenumbers
self.Wavenumber = self.wavenumbers
self.Wavenumbers = self.wavenumbers
#For those more microwave oriented:
self.frequencyGHz = 29.9792458 * self.wavenumbers
self.wavelengthCm = 1.0/self.wavenumbers
# And those who aren't interferometer oriented (people who like um):
self.wavelengthMicrons = 10000.0/self.wavenumbers
self.wmo_sensor_id = o['wmo_sensor_id']
self.wmo_satellite_id = o['wmo_satellite_id']
else:
print("Warning! {} doesn't exist!".format( os.path.join(self.coefficientPath, self.sensor_id+'.SpcCoeff.bin') ) )
def setupGases(self):
#If this has been run by previous call to runK or runDirect, don't run it again!
if(len(self.traceIds)>0): return
# Figure out what gases the user has defined in profile
availableGases = list(gases.keys())
profileItems = list(self.profiles._asdict().keys())
for p in profileItems:
if (p in availableGases):self.usedGases.append(p)
#Set the size of the trace gas array.
max_abs = len(self.usedGases)
nprof, nlay = self.profiles.T.shape
self.traceConc = np.zeros([nprof,nlay,max_abs])
self.traceIds = np.zeros(max_abs, dtype=np.int)
#Fill array with what the user specified in profile.
for i,g in enumerate(self.usedGases):
self.traceConc[:,:,i] = self.profiles._asdict()[g][:,:]
self.traceIds[i] = gases[g]
def runDirect(self):
if(not len(self.surfEmisRefl)==0):
pycrtm.emissivityreflectivity = np.asfortranarray(self.surfEmisRefl)
use_passed = True
else: use_passed = False
#print(pycrtm.wrap_forward.__doc__)
self.setupGases()
if('aerosolType' in list(self.profiles._asdict().keys())):
pycrtm.aerosoltype = self.profiles.aerosolType
pycrtm.aerosoleffectiveradius = self.profiles.aerosols[:,:,:,1]
pycrtm.aerosolconcentration = self.profiles.aerosols[:,:,:,0]
if('cloudType' in list(self.profiles._asdict().keys())):
pycrtm.cloudtype = self.profiles.cloudType
pycrtm.cloudeffectiveradius = self.profiles.clouds[:,:,:,1]
pycrtm.cloudconcentration = self.profiles.clouds[:,:,:,0]
pycrtm.cloudfraction = self.profiles.cloudFraction
self.Bt = pycrtm.wrap_forward( self.coefficientPath,
self.sensor_id,
self.IRwaterCoeff_File,
self.MWwaterCoeff_File,
self.output_tb_flag,
self.StoreTrans,
self.profiles.Angles[:,0],
self.profiles.Angles[:,4],
self.profiles.Angles[:,1],
self.profiles.Angles[:,2:4],
self.StoreEmis,
use_passed,
self.profiles.DateTimes[:,0],
self.profiles.DateTimes[:,1],
self.profiles.DateTimes[:,2],
self.nChan,
self.profiles.Pi,
self.profiles.P,
self.profiles.T,
self.traceConc,
self.traceIds,
self.profiles.climatology,
self.profiles.surfaceTemperatures,
self.profiles.surfaceFractions,
self.profiles.LAI,
self.profiles.S2m[:,1],
self.profiles.windSpeed10m,
self.profiles.windDirection10m,
self.profiles.surfaceTypes[:,0],
self.profiles.surfaceTypes[:,1],
self.profiles.surfaceTypes[:,2],
self.profiles.surfaceTypes[:,3],
self.profiles.surfaceTypes[:,4],
self.profiles.surfaceTypes[:,5],
self.nThreads )
if(self.StoreTrans):
self.TauLevels = pycrtm.outtransmission
if(self.StoreEmis):
self.surfEmisRefl = pycrtm.emissivityreflectivity
def runK(self):
if(not len(self.surfEmisRefl)==0):
pycrtm.emissivityreflectivity = np.asfortranarray(self.surfEmisRefl)
use_passed=True
else: use_passed=False
self.setupGases()
#print(pycrtm.wrap_k_matrix.__doc__)
if('aerosolType' in list(self.profiles._asdict().keys())):
pycrtm.aerosoltype = self.profiles.aerosolType
pycrtm.aerosoleffectiveradius = self.profiles.aerosols[:,:,:,1]
pycrtm.aerosolconcentration = self.profiles.aerosols[:,:,:,0]
if('cloudType' in list(self.profiles._asdict().keys())):
pycrtm.cloudtype = self.profiles.cloudType
pycrtm.cloudeffectiveradius = self.profiles.clouds[:,:,:,1]
pycrtm.cloudconcentration = self.profiles.clouds[:,:,:,0]
pycrtm.cloudfraction = self.profiles.cloudFraction
self.Bt, self.TK, traceK, self.SkinK, self.SurfEmisK, self.ReflK,self.WindSpeedK, self.windDirectionK = pycrtm.wrap_k_matrix( self.coefficientPath,
self.sensor_id,
self.IRwaterCoeff_File,
self.MWwaterCoeff_File,
self.output_tb_flag,
self.StoreTrans,
self.profiles.Angles[:,0],
self.profiles.Angles[:,4],
self.profiles.Angles[:,1],
self.profiles.Angles[:,2:4],
self.StoreEmis,
use_passed,
self.profiles.DateTimes[:,0],
self.profiles.DateTimes[:,1],
self.profiles.DateTimes[:,2],
self.nChan,
self.profiles.Pi,
self.profiles.P,
self.profiles.T,
self.traceConc,
self.traceIds,
self.profiles.climatology,
self.profiles.surfaceTemperatures,
self.profiles.surfaceFractions,
self.profiles.LAI,
self.profiles.S2m[:,1],
self.profiles.windSpeed10m,
self.profiles.windDirection10m,
self.profiles.surfaceTypes[:,0],
self.profiles.surfaceTypes[:,1],
self.profiles.surfaceTypes[:,2],
self.profiles.surfaceTypes[:,3],
self.profiles.surfaceTypes[:,4],
self.profiles.surfaceTypes[:,5],
self.nThreads )
for i,ids in enumerate(list(self.traceIds)):
# I think I can do something smarter here in python to contruct self.QK etc through an execute, or something along those lines?
if(ids == gases['Q']): self.QK = traceK[:,:,:,i]
if(ids == gases['O3']): self.O3K = traceK[:,:,:,i]
if(ids == gases['CH4']): self.CH4K = traceK[:,:,:,i]
if(ids == gases['CO2']): self.CO2K = traceK[:,:,:,i]
if(ids == gases['CO']): self.COK = traceK[:,:,:,i]
if(ids == gases['N2O']): self.N2OK = traceK[:,:,:,i]
# if we don't have any "weird" gases, empty out traceK,traceConc to save on RAM.
if not any(g in self.usedGases for g in ['Q', 'O3', 'CH4', 'CO','CO2', 'N2O']):
print("saving on RAM")
self.traceK = []
self.traceConc = []
if(self.StoreTrans):
self.TauLevels = pycrtm.outtransmission
if(self.StoreEmis):
self.surfEmisRefl = pycrtm.emissivityreflectivity
if __name__ == "__main__":
thisDir = os.path.dirname(os.path.abspath(__file__))
cases = os.listdir( os.path.join(thisDir,'testCases','data') )
cases.sort()
pathInfo = configparser.ConfigParser()
pathInfo.read( os.path.join(thisDir,'crtm.cfg') )
profiles = profilesCreate( 4, 92 )
for i,c in enumerate(cases):
h5 = h5py.File(os.path.join(thisDir, 'testCases','data',c) , 'r')
profiles.Angles[i,0] = h5['zenithAngle'][()]
profiles.Angles[i,1] = 999.9
profiles.Angles[i,2] = 100.0 # 100 degrees zenith below horizon.
profiles.Angles[i,3] = 0.0 # zero solar azimuth
profiles.Angles[i,4] = h5['scanAngle'][()]
profiles.DateTimes[i,0] = 2001
profiles.DateTimes[i,1] = 1
profiles.DateTimes[i,2] = 1
profiles.Pi[i,:] = np.asarray(h5['pressureLevels'] )
profiles.P[i,:] = np.asarray(h5['pressureLayers'][()])
profiles.T[i,:] = np.asarray(h5['temperatureLayers'])
profiles.Q[i,:] = np.asarray(h5['humidityLayers'])
profiles.O3[i,:] = np.asarray(h5['ozoneConcLayers'])
profiles.CO2[i,:] = np.asarray(h5['co2ConcLayers'])
profiles.clouds[i,:,0,0] = np.asarray(h5['cloudConcentration'])
profiles.clouds[i,:,0,1] = np.asarray(h5['cloudEffectiveRadius'])
profiles.aerosols[i,:,0,0] = np.asarray(h5['aerosolConcentration'])
profiles.aerosols[i,:,0,1] = np.asarray(h5['aerosolEffectiveRadius'])
profiles.aerosolType[i] = h5['aerosolType'][()]
profiles.cloudType[i] = h5['cloudType'][()]
profiles.cloudFraction[i,:] = h5['cloudFraction'][()]
profiles.climatology[i] = h5['climatology'][()]
profiles.surfaceFractions[i,:] = h5['surfaceFractions']
profiles.surfaceTemperatures[i,:] = h5['surfaceTemperatures']
profiles.S2m[i,1] = 33.0 # just use salinity out of S2m for the moment.
profiles.windSpeed10m[i] = 5.0
profiles.windDirection10m[i] = h5['windDirection10m'][()]
# land, soil, veg, water, snow, ice
profiles.surfaceTypes[i,0] = h5['landType'][()]
profiles.surfaceTypes[i,1] = h5['soilType'][()]
profiles.surfaceTypes[i,2] = h5['vegType'][()]
profiles.surfaceTypes[i,3] = h5['waterType'][()]
profiles.surfaceTypes[i,4] = h5['snowType'][()]
profiles.surfaceTypes[i,5] = h5['iceType'][()]
profiles.LAI[i] = h5['LAI'][()]
h5.close()
crtmOb = pyCRTM()
crtmOb.profiles = profiles
crtmOb.coefficientPath = pathInfo['CRTM']['coeffs_dir']
crtmOb.sensor_id = 'atms_npp'
crtmOb.nThreads = 4
crtmOb.loadInst()
crtmOb.runDirect()
crtmOb.runK()