-
Notifications
You must be signed in to change notification settings - Fork 9
/
spectral_calibration.py
383 lines (339 loc) · 12.3 KB
/
spectral_calibration.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
# David R Thompson
from datetime import datetime
from time import strptime
import argparse
import json
import sys, os
import numpy as np
from spectral.io import envi
from isofit.core.common import envi_header
from isofit.utils.surface_model import surface_model
batch_template='''#!/bin/sh
export MKL_NUM_THREADS=1
export OMP_NUM_THREADS=1
ray stop
ps -ef | grep ray | awk '{{print $1}}' | xargs kill
python {isofit_exe} {config_path}
'''
isofit_template='''{{
"ISOFIT_base": "{isofit_base}",
"forward_model": {{
"instrument": {{
"integrations": 1,
"calibration_fixed": false,
"statevector": {{
"GROW_FWHM": {{
"bounds": [
-1,
1
],
"init": 0,
"prior_mean": 0,
"prior_sigma": 100.0,
"scale": 1
}},
"WL_SHIFT": {{
"bounds": [
-1,
1
],
"init": 0,
"prior_mean": 0,
"prior_sigma": 100.0,
"scale": 1
}}
}},
"parametric_noise_file": "{noise_file}",
"unknowns": {{
"uncorrelated_radiometric_uncertainty": 0.01
}},
"wavelength_file": "{wavelength_file}"
}},
"radiative_transfer": {{
"lut_grid": {{
"GNDALT": {alt_grid},
"OBSZEN": [160,170,179.9],
"H2OSTR": {h2o_grid}
}},
"radiative_transfer_engines": {{
"vswir": {{
"wavelength_file": "{wavelength_file_hires}",
"engine_base_dir": "/beegfs/store/shared/MODTRAN6/MODTRAN6.0.0/",
"engine_name": "modtran",
"lut_names": [
"H2OSTR",
"GNDALT",
"OBSZEN"
],
"lut_path": "{lut_directory}",
"statevector_names": [
"H2OSTR",
"GNDALT"
],
"template_file": "{modtran_template_file}"
}}
}},
"statevector": {{
"GNDALT": {{
"bounds": [
{alt_min},
{alt_max}
],
"init": {alt_avg},
"prior_mean": {alt_avg},
"prior_sigma": 100.0,
"scale": 1
}},
"H2OSTR": {{
"bounds": [
{h2o_min},
{h2o_max}
],
"init": {h2o_avg},
"prior_mean": {h2o_avg},
"prior_sigma": 100.0,
"scale": 1
}}
}},
"unknowns": {{
"H2O_ABSCO": 0.0
}}
}},
"surface": {{
"select_on_init": true,
"surface_category": "multicomponent_surface",
"surface_file": "{surface_path}",
}}
}},
"implementation": {{
"inversion": {{
"windows": [
[
380.0,
1340.0
],
[
1450,
1800.0
],
[
1970.0,
2500.0
]
]
}},
"n_cores": 40,
"ray_temp_dir": "/tmp/ray",
"rte_auto_rebuild": true
}},
"input": {{
"measured_radiance_file": "{rdn_path}",
"obs_file": "{obs_path}"
}},
"output": {{
"estimated_reflectance_file": "{rfl_path}",
"estimated_state_file": "{state_path}"
}}
}}'''
modtran_template='''{{
"MODTRAN": [
{{
"MODTRANINPUT": {{
"AEROSOLS": {{
"IHAZE": "AER_NONE"
}},
"ATMOSPHERE": {{
"CO2MX": 410.0,
"H2OSTR": 1.0,
"H2OUNIT": "g",
"M1": "ATM_MIDLAT_SUMMER",
"M2": "ATM_MIDLAT_SUMMER",
"M3": "ATM_MIDLAT_SUMMER",
"M4": "ATM_MIDLAT_SUMMER",
"M5": "ATM_MIDLAT_SUMMER",
"M6": "ATM_MIDLAT_SUMMER",
"MODEL": "ATM_MIDLAT_SUMMER",
"O3STR": 0.3,
"O3UNIT": "a"
}},
"CASE": 0,
"DESCRIPTION": "",
"FILEOPTIONS": {{
"CKPRNT": true,
"NOPRNT": 2
}},
"GEOMETRY": {{
"GMTIME": {gmtime},
"H1ALT": 400,
"IDAY": {dayofyear},
"IPARM": 11,
"ITYPE": 3,
"PARM1": {lat},
"PARM2": {lon}
}},
"NAME": "emit_wavelength_check",
"RTOPTIONS": {{
"DISALB": false,
"IEMSCT": "RT_SOLAR_AND_THERMAL",
"IMULT": "RT_DISORT",
"LYMOLC": false,
"MODTRN": "RT_CORRK_FAST",
"NSTR": 8,
"SOLCON": 0.0,
"T_BEST": false
}},
"SPECTRAL": {{
"BMNAME": "p1_2013",
"DV": 0.1,
"FLAGS": "NT A ",
"FWHM": 0.1,
"V1": 320.0,
"V2": 2600.0,
"XFLAG": "N",
"YFLAG": "R"
}},
"SURFACE": {{
"GNDALT": 0.0,
"NSURF": 1,
"SURFP": {{
"CSALB": "LAMB_CONST_0_PCT"
}},
"SURFTYPE": "REFL_LAMBER_MODEL"
}}
}}
}}
]
}}'''
def main(rawargs=None):
""" This is a helper script to assess EMIT wavelength calibration
using atmospheric features.
Args:
input_radiance (str): radiance data cube [expected ENVI format]
input_loc (str): location data cube, (Lon, Lat, Elevation) [expected ENVI format]
input_obs (str): observation data cube, (path length, to-sensor azimuth, to-sensor zenith, to-sun azimuth,
to-sun zenith, phase, slope, aspect, cosine i, UTC time) [expected ENVI format]
working_directory (str): directory to stage multiple outputs, will contain subdirectories
Returns:
"""
# Parse arguments
parser = argparse.ArgumentParser(description="Apply OE to a block of data.")
parser.add_argument('input_radiance', type=str)
parser.add_argument('input_loc', type=str)
parser.add_argument('input_obs', type=str)
parser.add_argument('working_directory', type=str)
parser.add_argument('--isofit_base', default='/home/drt/src/isofit/')
parser.add_argument('--flip_fpa', default=True)
args = parser.parse_args(rawargs)
isofit_base = args.isofit_base
noise_file = isofit_base+'/data/emit_noise.txt'
isofit_exe = isofit_base+'/bin/isofit'
# Get file ID and GMT time
fid = os.path.split(args.input_radiance)[-1].split('_')[0]
dt = datetime.strptime(fid, 'emit%Y%m%dt%H%M%S')
dayofyear = dt.timetuple().tm_yday
hour = dt.timetuple().tm_hour
minute = dt.timetuple().tm_min
gmtime = float(hour + minute / 60.)
print('FID:', fid, 'GMT Time:',gmtime)
# Find geographic location
loc = envi.open(envi_header(args.input_loc)).load()
lon, lat, elevation = loc[:,:,0], loc[:,:,1], loc[:,:,2]
lat = np.mean(lat)
lon = -np.mean(lon) # swap to MODTRAN convention
# Make atmospheric grids
alt_min, alt_max = np.min(elevation)/1000.0, np.max(elevation)/1000.0
alt_avg = (alt_max-alt_min)/2+alt_min
step = 0.2
alt_max = max(alt_max,alt_min+step)
alt_grid = np.arange(alt_min, alt_max+step, step)
alt_grid = '['+','.join([str(a) for a in alt_grid])+']'
h2o_min, h2o_max = 0.6, 3.0
h2o_max = max(h2o_max,h2o_min+step)
h2o_grid = np.arange(h2o_min, h2o_max+step, step)
h2o_grid = '['+','.join([str(h) for h in h2o_grid])+']'
h2o_avg = 1.5
# Create subdirectories
working_directory = os.path.abspath(args.working_directory)
input_directory = os.path.abspath(os.path.join(working_directory,'input'))
config_directory = os.path.abspath(os.path.join(working_directory,'config'))
output_directory = os.path.abspath(os.path.join(working_directory,'output'))
data_directory = os.path.abspath(os.path.join(working_directory,'data'))
lut_directory = os.path.abspath(os.path.join(working_directory,'lut_'+fid))
for dir in [working_directory, input_directory, output_directory,
config_directory, data_directory, lut_directory]:
if not os.path.exists(dir):
os.mkdir(dir)
# Downtrack average of radiance and OBS data
I = envi.open(envi_header(args.input_obs)).load()
lines,rows,cols = I.shape
I = I.mean(axis=0)
obs_path = input_directory+'/'+fid+'_subs_obs'
envi.save_image(obs_path+'.hdr',np.array(I.reshape(1,rows,cols),
dtype=np.float32), ext='', force=True)
I = envi.open(envi_header(args.input_radiance)).load()
lines,rows,cols = I.shape
I = I.mean(axis=0)
rdn_path = input_directory+'/'+fid+'_subs_obs'
envi.save_image(rdn_path+'.hdr',np.array(I.reshape(1,rows,cols),
dtype=np.float32), ext='', force=True)
# Make highres wavelengths file
wavelength_file_hires = data_directory+'/wavelengths_hires.txt'
x = np.arange(360,2511,0.025) / 1000.0
w = np.ones(len(x))*0.025 / 1000.0
n = np.ones(len(x))
D = np.c_[n,x,w]
np.savetxt(wavelength_file_hires, D, fmt='%8.6f')
# Standard wavelength file
wavelength_file = data_directory+'/wavelengths.txt'
hdr = envi.open(envi_header(args.input_radiance)).metadata.copy()
wl = np.array([float(f) for f in hdr['wavelength']])
fwhm = np.array([float(f) for f in hdr['fwhm']])
c = np.arange(len(wl))
D = np.c_[c,wl,fwhm]
np.savetxt(wavelength_file, D, fmt='%8.6f')
# Surface model
surface_dir = os.path.dirname(os.path.realpath(__file__))+'/surface/'
config = surface_dir + 'surface_constrained.json'
surface_path = data_directory+'/surface.mat'
surface_model(config,output_path=surface_path,wavelength_path=wavelength_file)
# Write MODTRAN file
template = modtran_template.format(**locals())
modtran_template_file = config_directory+'/'+fid+'_modtran.json'
with open(modtran_template_file,'w') as fout:
fout.write(template)
# Write ISOFIT config file
rfl_path = output_directory+'/'+fid+'_rfl'
state_path = output_directory+'/'+fid+'_state'
template = isofit_template.format(**locals())
config_path = config_directory+'/'+fid+'.json'
with open(config_path,'w') as fout:
fout.write(template)
# Write batch script
script_path = config_directory+'/'+fid+'.sh'
with open(script_path,'w') as fout:
fout.write(batch_template.format(**locals()))
# Run
cmd = 'sbatch -N 1 -n 1 -c 40 --mem=180G --partition=emit '+script_path
print(cmd)
os.system(cmd)
# Extract output
state = envi.open(envi_header(state_path)).load()
wl_shift_by_position = np.squeeze(state[0,:,-1])
if args.flip_fpa:
wl_shift_by_position = np.flip(wl_shift_by_position)
use = abs(wl_shift_by_position)>1e-6
wl_shift_by_position = wl_shift_by_position[use]
wl_shift = np.median(wl_shift_by_position)
plt.plot(np.where(use)[0],wl_shift_by_position,color+'.',markersize=2)
poly = np.polyfit(np.where(use)[0],wl_shift_by_position,1)
x = np.arange(len(wl_shift_by_position))
plt.plot(x,np.polyval(poly,x),'k')
print(np.median(np.array(wl_shifts), axis=0))
plt.xlabel('Position')
plt.ylabel('Wavelength shift (nm)')
plt.grid(True)
plt.box(False)
plt.ylim([-1.00,1.00])
plt.savefig('output/'+fid+'_plot.pdf')
if __name__ == '__main__':
main()