Coverage for spectractor/simulation/libradtran.py: 9%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

138 statements  

1################################################################ 

2# 

3# Script to evaluate air transparency with LibRadTran 

4# With a pure absorbing atmosphere 

5# author: sylvielsstfr, jeremy.neveu 

6# creation date : November 2nd 2016 

7# update : July 2018 

8# 

9################################################################# 

10import os 

11import re 

12import sys 

13import numpy as np 

14 

15import subprocess 

16 

17from spectractor.tools import ensure_dir 

18import spectractor.parameters as parameters 

19from spectractor.config import set_logger 

20 

21 

22class Libradtran: 

23 

24 def __init__(self, home=''): 

25 """Initialize the Libradtran settings for Spectractor. 

26 

27 Parameters 

28 ---------- 

29 home: str, optional 

30 The path to the directory where libradtran directory is. If not specified $HOME is taken (default: ''). 

31 """ 

32 self.my_logger = set_logger(self.__class__.__name__) 

33 if home == '': 

34 self.home = os.environ['HOME'] 

35 else: 

36 self.home = home 

37 self.settings = {} 

38 

39 # Definitions and configuration 

40 # ------------------------------------- 

41 

42 # LibRadTran installation directory 

43 self.simulation_directory = 'libradtran' 

44 ensure_dir(self.simulation_directory) 

45 self.libradtran_path = parameters.LIBRADTRAN_DIR 

46 

47 # Filename : RT_LS_pp_us_sa_rt_z15_wv030_oz30.txt 

48 # : Prog_Obs_Rte_Atm_proc_Mod_zXX_wv_XX_oz_XX 

49 self.Prog = 'RT' # definition the simulation program is libRadTran 

50 self.proc = 'as' # Absoprtion + Rayleigh + aerosols special 

51 self.equation_solver = 'pp' # pp for parallel plane or ps for pseudo-spherical 

52 self.Atm = ['us'] # short name of atmospheric sky here US standard and Subarctic winter 

53 self.Proc = 'sa' # light interaction processes : sc for pure scattering,ab for pure absorption 

54 # sa for scattering and absorption, ae with aerosols default, as with aerosol special 

55 self.Mod = 'rt' # Models for absorption bands : rt for REPTRAN, lt for LOWTRAN, k2 for Kato2 

56 

57 def write_input(self, filename): 

58 f = open(filename, 'w') 

59 for key in sorted(self.settings): 

60 if key == "mol_modify2": 

61 f.write("mol_modify" + ' ' + str(self.settings[key]) + '\n') 

62 else: 

63 f.write(key + ' ' + str(self.settings[key]) + '\n') 

64 f.close() 

65 

66 def run(self, inp, out, path=''): 

67 """Run the libratran command uvpsec. 

68 

69 Parameters 

70 ---------- 

71 inp: str 

72 Input file. 

73 out: str 

74 Output file. 

75 path: str, optional 

76 Path to bin/uvpsec if necessary, otherwise use self.home (default: "") 

77 """ 

78 if path != '': 

79 cmd = os.path.join(path, 'bin/uvspec') + ' < ' + inp + ' > ' + out 

80 else: 

81 cmd = os.path.join(self.home, '/libRadtran/bin/uvspec') + ' < ' + inp + ' > ' + out 

82 subprocess.run(cmd, shell=True, check=True) 

83 

84 def simulate(self, airmass, pwv, ozone, aerosol, pressure): 

85 """Simulate the atmosphere transmission with Libratran. 

86 

87 Parameters 

88 ---------- 

89 airmass: float 

90 The airmass of the atmosphere. 

91 pwv: float 

92 Precipitable Water Vapor amount in mm. 

93 ozone: float 

94 Ozone quantity in Dobson units. 

95 aerosol: float 

96 VAOD of the aerosols. 

97 pressure: float 

98 Pressure of the atmosphere in hPa. 

99 

100 Returns 

101 ------- 

102 output_file_name: str 

103 The output file name relative to the current directory. 

104 

105 Examples 

106 -------- 

107 >>> parameters.DEBUG = True 

108 >>> lib = Libradtran() 

109 >>> output = lib.simulate(1.2, 2, 400, 0.07, 800) 

110 >>> print(output) 

111 libradtran/pp/us/as/rt/in/RT_CTIO_pp_us_as_rt_z12_pwv20_oz40_aer7.OUT 

112 """ 

113 

114 self.my_logger.debug( 

115 f'\n\t--------------------------------------------' 

116 f'\n\tevaluate' 

117 f'\n\t 1) airmass = {airmass}' 

118 f'\n\t 2) pwv = {pwv}' 

119 f'\n\t 3) ozone = {ozone}' 

120 f'\n\t 4) aer = {aerosol}' 

121 f'\n\t 5) pressure = {pressure}' 

122 f'\n\t--------------------------------------------') 

123 

124 # build the part 1 of file_name 

125 base_filename_part1 = self.Prog + '_' + parameters.OBS_NAME + '_' + self.equation_solver + '_' 

126 

127 aerosol_string = f'500 {aerosol:.20f}' 

128 # aerosol_str=str(wl0_num)+ ' '+str(tau0_num) 

129 aerosol_index = int(aerosol * 100.) 

130 

131 # Set up type of run 

132 if self.proc == 'sc': 

133 runtype = 'no_absorption' 

134 elif self.proc == 'ab': 

135 runtype = 'no_scattering' 

136 elif self.proc == 'ae': 

137 runtype = 'aerosol_default' 

138 elif self.proc == 'as': 

139 runtype = 'aerosol_special' 

140 else: 

141 runtype = 'clearsky' 

142 

143 # Selection of RTE equation solver 

144 if self.equation_solver == 'pp': # parallel plan 

145 equation_solver_equations = 'disort' 

146 elif self.equation_solver == 'ps': # pseudo spherical 

147 equation_solver_equations = 'sdisort' 

148 else: 

149 self.my_logger.error(f'Unknown RTE equation solver {self.equation_solver}.') 

150 sys.exit() 

151 

152 # Selection of absorption model 

153 absorption_model = 'reptran' 

154 if self.Mod == 'rt': 

155 absorption_model = 'reptran' 

156 if self.Mod == 'lt': 

157 absorption_model = 'lowtran' 

158 if self.Mod == 'kt': 

159 absorption_model = 'kato' 

160 if self.Mod == 'k2': 

161 absorption_model = 'kato2' 

162 if self.Mod == 'fu': 

163 absorption_model = 'fu' 

164 if self.Mod == 'cr': 

165 absorption_model = 'crs' 

166 

167 # for simulation select only two atmosphere 

168 # atmospheres = np.array(['afglus','afglms','afglmw','afglt','afglss','afglsw']) 

169 atmosphere_map = dict() # map atmospheric names to short names 

170 atmosphere_map['afglus'] = 'us' 

171 atmosphere_map['afglms'] = 'ms' 

172 atmosphere_map['afglmw'] = 'mw' 

173 atmosphere_map['afglt'] = 'tp' 

174 atmosphere_map['afglss'] = 'ss' 

175 atmosphere_map['afglsw'] = 'sw' 

176 

177 atmospheres = [] 

178 for skyindex in self.Atm: 

179 if re.search('us', skyindex): 

180 atmospheres.append('afglus') 

181 if re.search('sw', skyindex): 

182 atmospheres.append('afglsw') 

183 

184 output_directory, output_filename = None, None 

185 # 1) LOOP ON ATMOSPHERE 

186 for atmosphere in atmospheres: 

187 # if atmosphere != 'afglus': # just take us standard sky 

188 # break 

189 atmkey = atmosphere_map[atmosphere] 

190 

191 # manage settings and output directories 

192 topdir = f'{self.simulation_directory}/{self.equation_solver}/{atmkey}/{self.proc}/{self.Mod}' 

193 ensure_dir(topdir) 

194 input_directory = topdir + '/' + 'in' 

195 ensure_dir(input_directory) 

196 output_directory = topdir + '/' + 'out' 

197 ensure_dir(output_directory) 

198 

199 # loop on molecular model resolution 

200 # molecular_resolution = np.array(['coarse','medium','fine']) 

201 # select only COARSE Model 

202 molecular_resolution = 'coarse' 

203 

204 # water vapor 

205 pwv_str = f'H2O {pwv:.20f} MM' 

206 pwv_index = int(10 * pwv) 

207 

208 # airmass 

209 airmass_index = int(airmass * 10) 

210 

211 # Ozone 

212 oz_str = f'O3 {ozone:.20f} DU' 

213 ozone_index = int(ozone / 10.) 

214 

215 base_filename = f'{base_filename_part1}{atmkey}_{self.proc}_{self.Mod}_z{airmass_index}' \ 

216 f'_pwv{pwv_index}_oz{ozone_index}_aer{aerosol_index}' 

217 

218 self.settings["data_files_path"] = self.libradtran_path + 'data' 

219 

220 self.settings["atmosphere_file"] = self.libradtran_path + 'data/atmmod/' + atmosphere + '.dat' 

221 self.settings["albedo"] = '0.2' 

222 

223 self.settings["rte_solver"] = equation_solver_equations 

224 

225 if self.Mod == 'rt': 

226 self.settings["mol_abs_param"] = absorption_model + ' ' + molecular_resolution 

227 else: 

228 self.settings["mol_abs_param"] = absorption_model 

229 

230 # Convert airmass into zenith angle 

231 sza = np.arccos(1. / airmass) * 180. / np.pi 

232 

233 # Should be no_absorption 

234 if runtype == 'aerosol_default': 

235 self.settings["aerosol_default"] = '' 

236 elif runtype == 'aerosol_special': 

237 self.settings["aerosol_default"] = '' 

238 self.settings["aerosol_set_tau_at_wvl"] = aerosol_string 

239 

240 if runtype == 'no_scattering': 

241 self.settings["no_scattering"] = '' 

242 if runtype == 'no_absorption': 

243 self.settings["no_absorption"] = '' 

244 

245 # set up the ozone value 

246 self.settings["mol_modify"] = pwv_str 

247 self.settings["mol_modify2"] = oz_str 

248 

249 # rescale pressure if reasonable pressure values are provided 

250 if 600. < pressure < 1015.: 

251 self.settings["pressure"] = pressure 

252 else: 

253 self.my_logger.error(f'\n\tcrazy pressure p={pressure} hPa') 

254 

255 self.settings["output_user"] = 'lambda edir' 

256 self.settings["altitude"] = str(parameters.OBS_ALTITUDE) # Altitude LSST observatory 

257 self.settings["source"] = 'solar ' + self.libradtran_path + 'data/solar_flux/kurudz_1.0nm.dat' 

258 self.settings["sza"] = str(sza) 

259 self.settings["phi0"] = '0' 

260 self.settings["wavelength"] = '250.0 1200.0' 

261 self.settings["output_quantity"] = 'reflectivity' # 'transmittance' # 

262 self.settings["quiet"] = '' 

263 

264 input_filename = os.path.join(input_directory, base_filename + '.INP') 

265 output_filename = os.path.join(input_directory, base_filename + '.OUT') 

266 

267 self.write_input(input_filename) 

268 self.run(input_filename, output_filename, path=self.libradtran_path) 

269 

270 return output_filename 

271 

272 

273def clean_simulation_directory(): 

274 """Remove the libradtran directory. 

275 

276 Examples 

277 -------- 

278 >>> ensure_dir('libradtran') 

279 >>> clean_simulation_directory() 

280 >>> assert not os.path.isfile('libradtran') 

281 """ 

282 os.system("rm -rf libradtran") 

283 

284 

285if __name__ == "__main__": 285 ↛ 286line 285 didn't jump to line 286, because the condition on line 285 was never true

286 import doctest 

287 

288 doctest.testmod()