-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlblTools.py
1522 lines (1235 loc) · 51.3 KB
/
lblTools.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
#!/usr/bin/python
# for Python 3 compatibility
from __future__ import print_function
# -*- coding: utf-8 -*-
import os
import sys
import shutil
import re
import time
import math
import types
import glob
import struct
import numpy as np
import stat
import FortranFile
import traceback
import logging
logger = logging.getLogger(__name__)
#from configTools import xmlConfig
OPTICAL_DEPTH = 'opticalDepth'
RADIANCE = 'radiance'
TRANSMISSION = 'transmission'
NUMBER_DENSITY = 'numberDensity'
LAYER_OPTICAL_DEPTHS = 'layerOpticalDepths'
SOLAR = 'solar'
WAVE_NUMBER = 'waveNumber'
SOLAR_OPTICAL_DEPTH = 'solarOD'
SOLAR_RADIANCE = 'solarRadiance'
def interP(p, pin, vin, debug=False, rh=None):
"""
Interpolate pressure grid
Input
p -- float array
pin -- float array
vin -- float arr
Output
z -- float array
"""
z = []
for p1 in p:
mmin = [-999999, p1]
mmax = [999999, p1]
cont = 0
for k in range(len(pin)):
if p1 != pin[k]:
gg = pin[k] - p1
if gg > 0 and gg < mmax[0]:
mmax = [gg, pin[k], k]
elif gg < 0 and gg > mmin[0]:
mmin = [gg, pin[k], k]
# endif p1 !=
if p1 == pin[k]:
z.append(vin[k])
cont = 1
break
# endif p1 ==
if cont: continue
if mmax[1] == p1:
mmax = [-999999, p1]
for k in range(len(pin)):
if p1 != pin[k] and k != mmin[2]:
gg = pin[k] - p1
if gg < 0 and gg > mmax[0]: mmax = [gg, pin[k], k]
# endif p1 and k
# endif mmax[1]
if mmin[1] == p1: mmin = [999999, p1]
for k in range(len(pin)):
if p1 != pin[k] and k != mmax[2]:
gg = pin[k] - p1
if gg > 0 and gg < mmin[0]: mmin = [gg, pin[k], k]
# end if p1 and k
# endif mmin[1]
z1 = math.log(p1) - math.log(mmin[1])
z2 = math.log(mmax[1]) - math.log(mmin[1])
z3 = vin[mmax[2]] - vin[mmin[2]]
z4 = vin[mmin[2]]
hh = z4 + z1 / z2 * z3
if (rh is not None) and (p1 < 100) and (hh > 0.003): hh = 0.001
z.append(hh)
# end p loop
return z
# end interP()
def readOD(path, double=False):
"""
Read in binary LBLRTM ODint files (IMRG=1 and IOD=1, 3, or 4 in
LBLRTM specifications (Record 1.2 in lblrtm_instructions.html)
Call
(ff, od, parms) = readOD(path)
Input
path -- string, full path to directory with ODint files
Output
ff -- float array, wavenumbers of spectrum
od -- float array, optical depths of spectrum
parms -- float array, nLayers x nMolecules, molecular amounts
(cm-2) as a funtion of molecule and layer
Keywords
double -- boolean, read in double precision OD values
"""
ff, od = readTape12(path, double=double)
# this assumes a directory of OD files is provided
# we will make the function handle one level (i.e., one OD file)
# as specified by the user in "path"
"""
# grab list of OD files in path
ll = glob.glob(os.path.join(path, 'ODint_*'))
od = None
ll.sort()
for i in range(len(ll)):
# read in binary data like a TAPE12, store into OD array
(ff, s) = readTape12(ll[i], double=double)
if od is None:
od=np.vstack((np.asarray(s),))
else:
od=np.vstack((od,np.asarray(s),))
# end loop over ODint files
"""
# not all LBLRTM runs have IATM=1 such that LBLATM is called for
# density computation
"""
f = open(os.path.join(path, 'TAPE7'))
lines = f.readlines()
f.close()
z = re.split('\s+', lines[1].strip())
n = int(z[1])
# initialize list that will eventually be nMol x nLayers
# (molecules per cm-2)
# list of lists, where each sublist contains nMol elements
parms = []
# read in ASCII TAPE7 parameters (calculations of molecular amounts)
# loop over layers (this may be assuming a certain number of
# molecules, or at least the number should not exceed a threshold
# of 7)
for i in range(2,len(lines),2):
p = []
z = re.split('\s+', lines[i].strip())
p.append(float(z[0]))
if len(z)>5:
a0 = float(z[3])
p0 = float(z[4])
else:
zz = re.split('\.', z[3])
a0 = float(zz[0] + '.' + zz[1])
p0 = float('.' + zz[2])
# endif len z
if len(z)>7:
a1 = float(z[6])
dz = a1 - a0
a2 = a1
p1 = float(z[7])
dp = p0 - p1
p2 = p1
elif len(z)>3:
dz = a0 - a2
a2 = a0
dp = p2 - p0
p2 = p0
else:
dz = 0
dp = 0
# endif len z
p.append(dz)
p.append(dp)
z = re.split('\s+', lines[i + 1].strip())
# for i in z:p.append(float(i))
# concatenatate (NOT append) floating point list of z onto
# existing p (mol amounts for all all molecules in a given layer)
p += map(float, z)
parms.append(p)
# end loop over TAPE7
"""
#return (np.array(ff), np.array(od), np.array(parms))
return (np.array(ff), np.array(od))
# end readOD()
def readTape7(fName, sList=False):
"""
Read LBLRTM TAPE7 ASCII file (molecular amounts computed by LBLATM)
Call
ll = readTape7(fName)
Input
fName -- string, full path to TAPE7 to be read
Output
ll --
Keywords
sList --
"""
def cnvline(l, fmt=','):
ll = re.split(fmt, l.strip())
ll = map(float, ll)
return ll
# end cnvline()
f = open(fName)
l = f.readlines()
f.close()
ll = []
l = l[2:]
# loop over layers (this may be assuming a certain number of
# molecules, or at least the number should not exceed a threshold
# of 7)
for i in range(0, len(l), 2):
q = re.split('\s+', l[i].strip())
if not i:
try:
if sList:
q = [float(q[0]), float(q[1]), float(q[6]),
float(q[6]) - float(q[3])]
else:
q = [[float(q[0]), float(q[4]), float(q[7])],
[float(q[1]), float(q[5]), float(q[8])],
float(q[6]), float(q[6]) - float(q[3])]
# endif sList
except (KeyboardInterrupt, SystemExit):
raise
except (IndexError,ValueError):
q = [float(q[0]), float(q[1]), 0, 0]
else:
ind = len(ll) - 1
if sList:
q2 = ll[ind][2]
try:
q = [float(q[0]), float(q[1]), float(q[3]),
float(q[3]) - q2]
except (IndexError,ValueError):
zz = re.split('\.', q[3])
q3 = float(zz[0] + zz[1])
q = [float(q[0]), float(q[1]), q3, q3 - q2]
else:
q0 = ll[ind][0][2]
q1 = ll[ind][1][2]
q2 = ll[ind][2]
q = [[float(q[0]), q0, float(q[4])], [float(q[1]), q1,
float(q[5])], float(q[3]), float(q[3]) - q2]
# endif sList
q += cnvline(l[i + 1].strip(), fmt='\s+')
ll.append(q)
# end loop over lines
return ll
# end readTape7
def readTape12(fileName, double=False, fType=0):
"""
Read in a TAPE12 (or similar TAPE10-13) LBLRTM output binary file
and return spectrum
Original: Scott Zaccheo (AER), modified by Rick Pernak (AER, 2017)
Call
waveNumbers, output = readTape12(fileName)
Input
fileName -- string, full path to binary file
Output
waveNumbers -- float array, wavenumbers of spectrum
output -- float array, corresponding parameter (radiance,
transmittance, optical depth -- see lblrtm_instructions.html
file assignments)
Keywords
double -- boolean, read in double-precision bits
fType -- int, file type; from
/project/rc/rc2/mshep/idl/patbrown/read_lbl_file.pro:
0: scanned transmittance or radiance, optical depth
1: radiance from monochromatic radiance calculation
2: transmittance from monochromatic radiance calculation
3: Aerosol absorbtance from spectral aerosol transmittance file
4: Aerosol scattering from spectral aerosol transmittance file
5: Aerosol asymmetry from spectral aerosol transmittance file
6: transmittance from monochromatic radiance calculation
File types 3, 4, and 5 are from TAPE20 files and have not been
tested with this function
"""
def readLBLPanel(ffObj, pHeaderForm):
"""
Read in a single panel
Input
ffObj -- FortranFile object
pHeaderForm -- string, format of panel header (e.g., 'dddl' for
3 doubles and a long integer, which would mean wn_start and
wn_end are doubles, the spectral resolution is double
precision, and the number of points in the panel is a long
integer; wn_start and wn_end are always doubles)
Output
outWN -- float array, wavenumbers of spectrum for a given panel
outParam -- float array, corresponding parameter (radiance,
transmittance, optical depth -- see lblrtm_instructions.html
file assignments) of panel
Keywords
"""
# initialization of variables that change with panel
OK = True;
outWN = []; outParam = []
ctr = 1
while OK:
buff = fortranFile.getRecord()
# grab binary data if valid buffer and not a panel header
#if len(buff) == struct.calcsize(lfmt): continue
while buff is not None and len(buff) != struct.calcsize(lfmt):
buff = fortranFile.getRecord()
# end while buff
if buff:
try:
# read panel header and underlying data
(v1, v2, dv, nPanel) = struct.unpack(lfmt, buff)
data = fortranFile.readDoubleVector() if double else \
fortranFile.readFloatVector()
#print len(data), ctr
ctr += 1
# concatenate (NOT append) onto output
# for now, this is just radiance -- looks like other
# parameters like transmittances are in other panels
outParam += data
# concatenate wavenumber array (without numpy) based
# on spectral resolution and starting wavenumber
outWN += \
map(lambda x:v1 + x * dv, range(len(data)))
except (KeyboardInterrupt, SystemExit):
raise
except:
#print 'Data could not be read, file may be corrupted'
OK = False
else:
# end of panel
#continue
OK = False
# endif buff
# end while OK
return outWN, outParam
# end readLBLPanel()
# main readTape12()
iFormat = 'l'
if struct.calcsize('l') == 8:iFormat = 'i'
# instantiate FortranFile object
fortranFile = FortranFile.FortranFile(fileName)
# read file header
data = fortranFile.getRecord()
# format for each panel header
if double: lfmt = 'dddl'
else: lfmt = 'ddf%s' % iFormat
waveNumbers, output = readLBLPanel(fortranFile, lfmt)
# read file header
#waveNumbers, output = readLBLPanel(fortranFile, lfmt, header=False)
#print len(waveNumbers)
#waveNumbers, output = readLBLPanel(fortranFile, lfmt)
return np.array(waveNumbers), np.array(output)
# end readTape12()
def rpReadTape12(fileName, double=False, fType=0):
"""
Read in a TAPE12 (or similar TAPE10-13) LBLRTM output binary file
and return spectrum
Original: Scott Zaccheo (AER), modified by Rick Pernak (AER, 2017)
Call
waveNumbers, output = rpReadTape12(fileName)
Input
fileName -- string, full path to binary file
Output
waveNumbers -- float array, wavenumbers of spectrum
output -- float array, corresponding parameter (radiance,
transmittance, optical depth -- see lblrtm_instructions.html
file assignments)
Keywords
double -- boolean, read in double-precision bits
fType -- int, file type; from
/project/rc/rc2/mshep/idl/patbrown/read_lbl_file.pro:
0: scanned transmittance or radiance, optical depth
1: radiance from monochromatic radiance calculation
2: transmittance from monochromatic radiance calculation
3: Aerosol absorbtance from spectral aerosol transmittance file
4: Aerosol scattering from spectral aerosol transmittance file
5: Aerosol asymmetry from spectral aerosol transmittance file
6: transmittance from monochromatic radiance calculation
File types 3, 4, and 5 are from TAPE20 files and have not been
tested with this function
"""
import utils
# main readTape12()
iFormat = 'l'
if struct.calcsize('l') == 8:iFormat = 'i'
# instantiate FortranFile object
fortranFile = FortranFile.FortranFile(fileName)
# read file header
data = fortranFile.getRecord()
# format for each panel header
lfmt = 'dddl' if double else 'ddf%s' % iFormat
headLen = struct.calcsize(lfmt)
# the number of output parameters differs by file type,
# how many are expected?
if fType in [0, 1]:
paramExp = 1
elif fType in range(2, 6):
paramExp = 2
else:
paramExp = 3
# endif fType
paramStr = ['Scanned', 'Radiance', 'Transmittance']
while True:
# skip to first panel header
buff = fortranFile.getRecord()
#while buff is None: buff = fortranFile.getRecord()
#while buff is not None and len(buff) != headLen:
# buff = fortranFile.getRecord()
if buff:
if buff and len(buff) == headLen:
(v1, v2, dv, nPtPanel) = struct.unpack(lfmt, buff)
print(v1, v2, dv)
else:
data = fortranFile.readDoubleVector() if double else \
fortranFile.readFloatVector()
# endif buf and len
else:
data = fortranFile.readDoubleVector() if double else \
fortranFile.readFloatVector()
print(len(data))
# endif buff len
break
if data is None: break
# concatenate (NOT append) onto output
# for now, this is just radiance -- looks like other
# parameters like transmittances are in other panels
outParam += data
# concatenate wavenumber array (without numpy) based
# on spectral resolution and starting wavenumber
outWN += \
map(lambda x:v1 + x * dv, range(len(data)))
#print ctr, v1, v2, len(outParam)
# endwhile
sys.exit('GOT HERE')
if buff:
try:
# read panel header and underlying data
data = fortranFile.readDoubleVector() if double else \
fortranFile.readFloatVector()
# concatenate (NOT append) onto output
# for now, this is just radiance -- looks like other
# parameters like transmittances are in other panels
outParam += data
# concatenate wavenumber array (without numpy) based
# on spectral resolution and starting wavenumber
outWN += \
map(lambda x:v1 + x * dv, range(len(data)))
except (KeyboardInterrupt, SystemExit):
raise
except:
#print 'Data could not be read, file may be corrupted'
OK = False
else:
# end of panel
#continue
OK = False
# endif buff
# end while OK
waveNumbers, output = np.array(outWN), np.array(outParam)
return waveNumbers, output
# end rpReadTape12()
def getOD(tape5, ostream=sys.stdout):
"""
Read in OD from...TAPE5!?!
Input
tape5 -- string, full path to TAPE5 file
Output
None
"""
path = os.path.dirname(tape5)
return readOD(path, fout=ostream)
# end getOD
def removeFileName(fileName):
"""
Remove given file
Input
fileName -- string, full path to file to be removed
Output
None
"""
try: os.remove(fileName)
except OSError: pass
# end removeFileName
def generatePressureGrid(pressure, observer, target, nLayers):
try:
try:
mn = int(min(pressure))
mx = int(max(pressure))
except (ValueError,IndexError,TypeError):
mn = int(min([observer, target]))
mx = int(max([observer, target]))
# end try
dx = (mx - mn) / (nLayers - 1)
layers = map(lambda x: mx - x * dx, range(nLayers))
return -len(layers), layers
except (KeyboardInterrupt, SystemExit):
raise
except:
return 0, 0
# end try
# end generatePressureGrid
def generateHeightGrid(heights, observer, target, nLayers):
# input heights assumed to be in meters
try:
dx = int(max(heights) - min(heights)) / (nLayers - 1)
layers = map(lambda x: x * dx / 1000. + min(heights) / 1000., range(nLayers))
return len(layers), layers
except (KeyboardInterrupt, SystemExit):
raise
except:
try:
hRange = max([observer, target]) - min([observer, target])
dx = hRange / (nLayers - 1)
layers = map(lambda x: x * dx + min([observer, target]), range(nLayers))
return len(layers), layers
except (KeyboardInterrupt, SystemExit):
raise
except:
return 0, 0
def writeTape5(path, parameterDictionary, isFile=False, monoRTM=False,useMeters=False):
DEFAULT_NMOL=7
DEFAULT_CO2=330.
DEFAULT_CH4=1.7
if isFile:
outputFileName = path
else:
if monoRTM: baseName = 'MONORTM.IN'
else: baseName = 'TAPE5'
outputFileName = os.path.join(path, baseName)
try:
os.makedirs(path)
except OSError:
pass
tape5file = open(outputFileName, 'w')
waveNumber1 = parameterDictionary['v1']
waveNumber2 = parameterDictionary['v2']
deltaWaveNumber = parameterDictionary['dv']
# Define Tangent
if parameterDictionary.has_key('tangentFlag') and parameterDictionary['tangentFlag']:
tangent=1
else:
tangent=0
# Define IAERSL
if parameterDictionary.has_key('aerosols'):
aerosols = parameterDictionary['aerosols']
else:
aerosols = 0
# Define IEMIT
if parameterDictionary.has_key('output'):
outputType = int(parameterDictionary['output'])
else: outputType = 0
if parameterDictionary.has_key('model'):
model = int(parameterDictionary['model'])
else: model = None
if parameterDictionary.has_key('units'):
units = int(parameterDictionary['units'])
else: units = None
if not parameterDictionary.has_key('usePressure'):
observer = parameterDictionary['h1'] / 1000.
target = parameterDictionary['h2'] / 1000.
units = 1
elif not parameterDictionary['usePressure']:
observer = parameterDictionary['h1'] / 1000.
target = parameterDictionary['h2'] / 1000.
units = 1
else:
observer = parameterDictionary['h1']
target = parameterDictionary['h2']
units = -1
if parameterDictionary.has_key('pathL'): pl = parameterDictionary['pathL'] / 1000.
elif parameterDictionary.has_key('pathLength'): pl = parameterDictionary['pathLength'] / 1000.
else: pl = 0
if parameterDictionary.has_key('horz'):
if parameterDictionary['horz']:
horz=1
else:
horz=0
else: horz = 0
angle = parameterDictionary['angle']
# define user defined layers/levels
userAltitudes = []
userPressures = []
if parameterDictionary.has_key('userDefinedLevels'):
parameterDictionary['udl'] = parameterDictionary['userDefinedLevels']
if parameterDictionary.has_key('udl'):
if parameterDictionary['udl']:
if type(parameterDictionary['udl']) == types.ListType:
if parameterDictionary.has_key('usePressure') and parameterDictionary['usePressure']:
userPressures = sorted(parameterDictionary['udl'],
None, None, 1)
userDefinedLayers = -len(parameterDictionary['udl'])
else:
userAltitudes = sorted(parameterDictionary['udl'])
userDefinedLayers = len(parameterDictionary['udl'])
else:
if parameterDictionary['udl'] is True: userDefinedLayers = 100
elif parameterDictionary['udl'] > 10: userDefinedLayers = parameterDictionary['udl']
else: userDefinedLayers = 100
if parameterDictionary.has_key('Height'): height = parameterDictionary['Height']
else: height = None
if parameterDictionary.has_key('usePressure'):
if parameterDictionary['usePressure']:
userDefinedLayers, userPressures = generatePressureGrid(parameterDictionary['Pres'],
observer, target,
userDefinedLayers)
else:
userDefinedLayers, userAltitudes = generateHeightGrid(height,
observer, target, userDefinedLayers)
else:
userDefinedLayers, userAltitudes = generateHeightGrid(height,
observer, target, userDefinedLayers)
else: userDefinedLayers = 0
else: userDefinedLayers = 0
if parameterDictionary.has_key('surfaceTerrain'):
surfaceTerrain = parameterDictionary['surfaceTerrain']
else: surfaceTerrain = [300, 0.1, 0, 0, 0.9, 0, 0]
# write record 1.1
print >> tape5file, '$ TAPE5 by Python, range %f %f %s' % (waveNumber1, waveNumber2, time.asctime())
if not parameterDictionary.has_key('inFlag'): parameterDictionary['inFlag'] = 0
if not parameterDictionary.has_key('iotFlag'): parameterDictionary['iotFlag'] = 0
# solar upwelling
if outputType == 2 and not monoRTM:
if parameterDictionary['inFlag'] == 2 and parameterDictionary['iotFlag'] == 2:
print >> tape5file, ' HI=0 F4=0 CN=0 AE=0 EM=2 SC=0 FI=0 PL=0 TS=0 AM=0 MG=0 LA=0 OD=0 XS=0 0 0'
print >> tape5file, "%5d%5d %3d" % (parameterDictionary['inFlag'], parameterDictionary['iotFlag'],
parameterDictionary['solarDay'])
print >> tape5file, "0.0 0.0"
print >> tape5file, "-1."
print >> tape5file, "%"
tape5file.close()
return os.path.join(path, 'TAPE5')
if parameterDictionary.has_key('iodFlag'):
iodFlag = parameterDictionary['iodFlag']
else:
if outputType: iodFlag = 1
else: iodFlag = 1
if parameterDictionary.has_key('noContinuum'):
if parameterDictionary['noContinuum']:
continuumFlag = 0
else:
continuumFlag = 1
else:
continuumFlag = 1
# write record 1.2
if monoRTM:
iPlot = 1
iod = 0
print >> tape5file, "%4s%1i%9s%1i%9s%1i%14s%1i%9s%1i%14s%1i%4s%1i%16s%4i" % ("", 1, "", 1, "", 1, "", iPlot, "", 1, "", iod, "", 0, "", 0)
else:
if outputType < 2:
print >> tape5file, \
' HI=1 F4=1 CN=%0d AE=%0d EM=%0d SC=0 FI=0 PL=0 TS=0 AM=1 MG=0 LA=0 OD=%0d XS=0 0 0' \
% (continuumFlag,aerosols, outputType, iodFlag)
else:
print >> tape5file, \
' HI=0 F4=0 CN=0 AE=%0d EM=%0d SC=0 FI=0 PL=0 TS=0 AM=1 MG=0 LA=0 OD=%0d XS=0 0 0' \
% (aerosols, outputType, iodFlag)
# write record 1.2a
if outputType == 2:
# INFLAG, IOTFLG, JULDAT
# 1-5, 6-10, 13-15
# I5, I5, 2X, I3
print >> tape5file, "%5d%5d %3d" % (parameterDictionary['inFlag'], parameterDictionary['iotFlag'],
parameterDictionary['solarDay'])
# determine molecule scaling
nms = 0
if parameterDictionary.has_key('co2scale'):
if parameterDictionary['co2scale']: nms = 6
if parameterDictionary.has_key('wvScale'):
if parameterDictionary['wvScale']: nms = 6
if parameterDictionary.has_key('ch4scale'):
if parameterDictionary['ch4scale']: nms = 6
if nms>0:
co2scale = DEFAULT_CO2
if parameterDictionary.has_key('co2scale'): co2scale = parameterDictionary['co2scale']
if not co2scale: co2scale = DEFAULT_CO2
wvScale = 1.0
if parameterDictionary.has_key('wvScale'): wvScale = parameterDictionary['wvScale']
if not wvScale: wvScale = 1.0
ch4scale = DEFAULT_CH4
if parameterDictionary.has_key('ch4scale'): ch4scale = parameterDictionary['ch4scale']
if not ch4scale: ch4scale = DEFAULT_CH4
co2only=False
o2only=False
if parameterDictionary.has_key('co2only'):
if parameterDictionary['co2only']:
nms=DEFAULT_NMOL
co2only=True
elif parameterDictionary.has_key('o2only'):
if parameterDictionary['o2only']:
nms=DEFAULT_NMOL
o2only=True
# write record 1.3
if monoRTM:
print >> tape5file, '%10.3f%10.3f%10s%10.3e%63s%2i' % (waveNumber1,
waveNumber2, '', deltaWaveNumber, '', nms)
else:
if iodFlag:
print >> tape5file, '%10.3f%10.3f%70s%10.3e %2i' % (waveNumber1,
waveNumber2, '', deltaWaveNumber, nms)
else:
print >> tape5file, '%10.3f%10.3f%70s%10.3e %2i' % (waveNumber1,
waveNumber2, '', 0, nms)
if nms>0:
print >> tape5file, '11 1'
if o2only:
stringFormat='%15d%15d%15d%15d%15d%15d%15d'
scaleFactors=(0,0,0,0,0,0,1)
elif co2only:
stringFormat='%15d%15d%15d%15d%15d%15d%15d'
scaleFactors=(0,1,0,0,0,0,0)
else:
stringFormat='%15.7e%15.7e%15.7e%15.7e%15.7e%15.7e'
scaleFactors=(wvScale,co2scale/float(DEFAULT_CO2),1,1,1,ch4scale/float(DEFAULT_CH4))
# write record 1.3a
print >> tape5file,stringFormat % scaleFactors
# write record 1.4
if monoRTM:
print >> tape5file, '%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%5s' % tuple(surfaceTerrain + [''])
else:
if outputType == 1:
if parameterDictionary['angle'] > 90 and parameterDictionary['angle'] <= 180: surfRefl = ['l']
else: surfRefl = ['s']
print >> tape5file, '%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%5s' % tuple(surfaceTerrain + surfRefl)
if observer == target:
heightType = 1
userDefinedLayers = 0
else:
if tangent:
heightType = 3
else:
heightType = 2
# write record 3.1
iFXTYPE = 0
iMunits = 0
Re = ''
hSpace = ''
vBar = ''
if parameterDictionary.has_key('refLatitude'):
refLat = "%10.3f" % float(parameterDictionary['refLatitude'])
else:
refLat = ''
if horz:
print >> tape5file, ' %1d 1 0 1 0 7 1%2i %2i%10s%10s%10s%10s%10s' % \
(model, iFXTYPE, iMunits, Re, hSpace, vBar, '', refLat)
print >> tape5file, ' 0.000 %10.3f' % pl
userDefinedLayers = 0
else:
print >> tape5file, ' %1d %1d%5d 1 0 7 1%2i %2i%10s%10s%10s%10s%10s' % (model, heightType,
userDefinedLayers,
iFXTYPE,
iMunits, Re,
hSpace, vBar, '',
refLat)
print >> tape5file, '%10.3f%10.3f%10.3f%10s%5i' % (observer, target, angle,'',tangent)
if not model:
# aptg is altitude, pressure, temperature and gases vector
aptg = parameterDictionary['aptg']
# build table for the first 6 gases and set default to US standard
for i in range(len(aptg), 9): aptg.append(6)
if len(aptg) > 9: aptg = aptg[:9]
if parameterDictionary.has_key('Height'):
a = parameterDictionary['Height']
else:
a = None
if parameterDictionary.has_key('Pres'):
p = parameterDictionary['Pres']
else:
p = None
if parameterDictionary.has_key('Temp'):
t = parameterDictionary['Temp']
else:
t = None
if parameterDictionary.has_key('WV'):
w = parameterDictionary['WV']
else:
w = None
if aptg[3] > '9': co2 = parameterDictionary['CO2']
else: co2 = None
if aptg[4] > '9': o3 = parameterDictionary['O3']
else: o3 = None
if aptg[5] > '9': n2o = parameterDictionary['N2O']
else: n2o = None
if aptg[6] > '9': co = parameterDictionary['C0']
else: co = None
if aptg[7] > '9': ch4 = parameterDictionary['CH4']
else: ch4 = None
if aptg[8] > '9': o2 = parameterDictionary['O2']
else: o2 = None
if units > 0:
b = sorted(a)
z = map(a.index, b)
else:
b = sorted(p, reverse=1)
z = map(p.index, b)
if a: a = map(lambda x: a[x] / 1000, z)
if p: p = map(lambda x: p[x], z)
if t is not None: t = map(lambda x: t[x], z)
if w is not None: w = map(lambda x: w[x], z)
if co2 is not None: co2 = map(lambda x: co2[x], z)
if o3 is not None: o3 = map(lambda x: o3[x], z)
if n2o is not None: n2o = map(lambda x: n2o[x], z)
if co is not None: co = map(lambda x: co[x], z)
if ch4 is not None: ch4 = map(lambda x: ch4[x], z)
if o2 is not None: o2 = map(lambda x: o2[x], z)
if userDefinedLayers:
if userDefinedLayers > 0:
for i in range(0, len(userAltitudes), 8):
print >> tape5file, '',
for j in range(8):
try: print >> tape5file, '%9.3f' % userAltitudes[i + j],
except IndexError: break
print >> tape5file
else:
for i in range(0, len(userPressures), 8):
print >> tape5file, '',
for j in range(8):
try:
print >> tape5file, '%9.3f' % userPressures[i + j],
except IndexError:
break
print >> tape5file
else:
if not horz:
print >> tape5file
if horz:
print >> tape5file, \
' 1 Input from python application max h=%dm' \
% observer
else:
print >> tape5file, \
'%5d Input from python application max h=%dm' \
% (units * len(p), observer)
fmt = '%10.3f%10.3f%10.3f %s%s %s%s%s%s%s%s%s'
fmt2 = ''