Coverage for spectractor/simulation/atmosphere.py: 13%
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
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
1import os
2import numpy as np
3import matplotlib.pyplot as plt
4from astropy.io import fits
6from scipy.interpolate import interp1d, RegularGridInterpolator
8from spectractor.config import set_logger
9import spectractor.parameters as parameters
11import spectractor.simulation.libradtran as libradtran
12from spectractor.simulation.throughput import plot_transmission_simple
15class Atmosphere:
17 def __init__(self, airmass, pressure, temperature):
18 """Class to evaluate an atmospheric transmission using Libradtran.
20 Parameters
21 ----------
22 airmass: float
23 Airmass of the source object.
24 pressure: float
25 Pressure of the atmosphere in hPa.
26 temperature: float
27 Temperature of the atmosphere in Celsius degrees.
29 Examples
30 --------
31 >>> a = Atmosphere(airmass=1.2, pressure=800, temperature=5)
32 >>> print(a.airmass)
33 1.2
34 >>> print(a.pressure)
35 800
36 >>> print(a.temperature)
37 5
38 >>> print(a.transmission(500))
39 1.0
40 """
41 self.my_logger = set_logger(self.__class__.__name__)
42 self.airmass = airmass
43 self.pressure = pressure
44 self.temperature = temperature
45 self.pwv = None
46 self.ozone = None
47 self.aerosols = None
48 self.transmission = lambda x: np.ones_like(x).astype(float)
49 self.title = ""
50 self.label = ""
52 def set_title(self):
53 """Make a title string for the simulation.
55 """
56 self.title = f'Atmospheric transmission with z={self.airmass:4.2f}, P={self.pressure:4.2f} hPa, ' \
57 rf'T={self.temperature:4.2f}$\degree$C'
59 def set_label(self):
60 """Make a label string for the simulation.
62 """
63 self.label = f'PWV={self.pwv:4.2f}mm, OZ={self.ozone:4.2f}DB, VAOD={self.aerosols:4.2f} '
65 def simulate(self, ozone, pwv, aerosols):
66 """Simulate the atmosphere transparency with Libradtran given atmospheric composition.
68 Values outside the Libradtran simulation range are set to zero.
70 Parameters
71 ----------
72 ozone: float
73 Ozone quantity in Dobson
74 pwv: float
75 Precipitable Water Vapor quantity in mm
76 aerosols: float
77 VAOD Vertical Aerosols Optical Depth
79 Returns
80 -------
81 transmission: callable
82 The transmission function of wavelengths in nm.
84 Examples
85 --------
86 >>> a = Atmosphere(airmass=1.2, pressure=800, temperature=5)
87 >>> transmission = a.simulate(ozone=400, pwv=5, aerosols=0.05)
88 >>> a.ozone
89 400
90 >>> a.pwv
91 5
92 >>> a.aerosols
93 0.05
94 >>> a.plot_transmission()
96 .. doctest::
97 :hide:
99 >>> assert transmission is not None
100 >>> assert a.transmission(500) > 0
102 .. plot::
104 from spectractor.simulation.atmosphere import Atmosphere
105 a = Atmosphere(airmass=1.2, pressure=800, temperature=5)
106 transmission = a.simulate(ozone=400, pwv=5, aerosols=0.05)
107 a.plot_transmission()
108 """
110 self.pwv = pwv
111 self.ozone = ozone
112 self.aerosols = aerosols
113 self.set_title()
114 self.set_label()
115 self.my_logger.debug(f'\n\t{self.title}\n\t\t{self.label}')
117 lib = libradtran.Libradtran()
118 path = lib.simulate(self.airmass, pwv, ozone, aerosols, self.pressure)
119 data = np.loadtxt(path)
120 wl = data[:, 0]
121 atm = data[:, 1]
122 self.transmission = interp1d(wl, atm, kind='linear', bounds_error=False, fill_value=(0, 0))
123 return self.transmission
125 def plot_transmission(self):
126 """Plot the atmospheric transmission computed with Libradtran.
128 Examples
129 --------
130 >>> a = Atmosphere(airmass=1.2, pressure=800, temperature=5)
131 >>> transmission = a.simulate(ozone=400, pwv=5, aerosols=0.05)
132 >>> a.plot_transmission()
134 """
135 plot_transmission_simple(plt.gca(), parameters.LAMBDAS, self.transmission(parameters.LAMBDAS),
136 title=self.title, label=self.label)
137 if parameters.DISPLAY: # pragma: no cover
138 plt.show()
139 else:
140 plt.close('all')
143# ----------------------------------------------------------------------------------
144class AtmosphereGrid(Atmosphere):
146 def __init__(self, image_filename="", filename="", airmass=1., pressure=800., temperature=10.,
147 pwv_grid=[0, 10, 10], ozone_grid=[100, 700, 7], aerosol_grid=[0, 0.1, 10]):
148 """Class to load and interpolate grids of atmospheric transmission computed with Libradtran.
150 Parameters
151 ----------
152 image_filename: str, optional
153 The original image fits file name from which the grid was computed or has to be computed (default: "").
154 filename: str, optional
155 The file name of the atmospheric grid if it exists (default: "").
156 airmass: float, optional
157 Airmass of the source object (default: 1).
158 pressure: float, optional
159 Pressure of the atmosphere in hPa (default: 800).
160 temperature: float, optional
161 Temperature of the atmosphere in Celsius degrees (default: 10).
162 pwv_grid: list
163 List of 3 numbers for the PWV quantity: min, max, number of simulations (default: [0, 10, 10]).
164 ozone_grid: list
165 List of 3 numbers for the ozone quantity: min, max, number of simulations (default: [100, 700, 7]).
166 aerosol_grid: list
167 List of 3 numbers for the aerosol quantity: min, max, number of simulations (default: [0, 0.1, 10]).
169 Examples
170 --------
171 >>> a = AtmosphereGrid(filename='./tests/data/reduc_20170530_134_atmsim.fits')
172 >>> a.image_filename.split('/')[-1]
173 'reduc_20170530_134_spectrum.fits'
174 """
175 Atmosphere.__init__(self, airmass, pressure, temperature)
176 self.my_logger = set_logger(self.__class__.__name__)
177 self.image_filename = image_filename
178 self.filename = filename
179 # ------------------------------------------------------------------------
180 # Definition of data format for the atmospheric grid
181 # -----------------------------------------------------------------------------
183 # row 0 : count number
184 # row 1 : aerosol value
185 # row 2 : pwv value
186 # row 3 : ozone value
187 # row 4 : data start
188 self.index_atm_count = 0
189 self.index_atm_aer = 1
190 self.index_atm_pwv = 2
191 self.index_atm_oz = 3
192 self.index_atm_data = 4
194 # specify parameters for the atmospheric grid
195 self.atmgrid = None
196 self.NB_ATM_HEADER = self.index_atm_data + 1
197 self.NB_ATM_DATA = len(parameters.LAMBDAS) - 1
198 self.NB_ATM_POINTS = 0
199 self.AER_Points = np.array([])
200 self.OZ_Points = np.array([])
201 self.PWV_Points = np.array([])
202 self.set_grid(pwv_grid=pwv_grid, ozone_grid=ozone_grid, aerosol_grid=aerosol_grid)
204 # the interpolated grid
205 self.lambdas = parameters.LAMBDAS
206 self.model = None
208 self.header = fits.Header()
209 if filename != "":
210 self.load_file(filename)
212 def set_grid(self, pwv_grid=[0, 10, 10], ozone_grid=[100, 700, 7], aerosol_grid=[0, 0.1, 10]):
213 """Set the size of the simulation grid self.atmgrid before compute it.
215 The first column of self.atmgrid will contain the wavelengths set by parameters.LAMBDAS,
216 the other columns the future simulations.
218 Parameters
219 ----------
220 pwv_grid: list
221 List of 3 numbers for the PWV quantity: min, max, number of simulations (default: [0, 10, 10]).
222 ozone_grid: list
223 List of 3 numbers for the ozone quantity: min, max, number of simulations (default: [100, 700, 7]).
224 aerosol_grid: list
225 List of 3 numbers for the aerosol quantity: min, max, number of simulations (default: [0, 0.1, 10]).
226 """
227 # aerosols
228 NB_AER_POINTS = int(aerosol_grid[2])
229 AER_MIN = float(aerosol_grid[0])
230 AER_MAX = float(aerosol_grid[1])
232 # ozone
233 NB_OZ_POINTS = int(ozone_grid[2])
234 OZ_MIN = float(ozone_grid[0])
235 OZ_MAX = float(ozone_grid[1])
237 # pwv
238 NB_PWV_POINTS = int(pwv_grid[2])
239 PWV_MIN = float(pwv_grid[0])
240 PWV_MAX = float(pwv_grid[1])
242 # definition of the grid
243 self.AER_Points = np.linspace(AER_MIN, AER_MAX, NB_AER_POINTS)
244 self.OZ_Points = np.linspace(OZ_MIN, OZ_MAX, NB_OZ_POINTS)
245 self.PWV_Points = np.linspace(PWV_MIN, PWV_MAX, NB_PWV_POINTS)
247 # total number of points
248 self.NB_ATM_POINTS = NB_AER_POINTS * NB_OZ_POINTS * NB_PWV_POINTS
250 # create the numpy array that will contains the atmospheric grid
251 self.atmgrid = np.zeros((self.NB_ATM_POINTS + 1, self.NB_ATM_HEADER + self.NB_ATM_DATA))
252 self.atmgrid[0, self.index_atm_data:] = parameters.LAMBDAS
253 self.lambdas = parameters.LAMBDAS
255 def compute(self):
256 """Compute atmospheric transmissions and fill self.atmgrid.
258 The wavelengths used for the computation are the ones set by parameters.LAMBDAS.
260 Returns
261 -------
262 atmospheric_grid: array_like
263 The atmospheric grid self.atmgrid.
265 Examples
266 --------
267 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
268 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
269 >>> atmospheric_grid = a.compute()
270 >>> atmospheric_grid # doctest: +ELLIPSIS
271 array([[0.000000e+00, 0.000000e+00, 0.000000e+00, ..., 1.099400e+03,
272 1.099600e+03, 1.099800e+03],
273 [1.000000e+00, 0.000000e+00, 5.000000e+00, ..., 9.520733e-01,
274 9.520733e-01, 9.520733e-01],
275 ...])
276 >>> a.save_file(a.image_filename.replace('.fits', '_atmsim.fits'))
277 >>> a.plot_transmission()
279 .. plot::
281 from spectractor.simulation.atmosphere import AtmosphereGrid
282 a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits', pwv_grid=[5, 5, 1],
283 ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
284 atmospheric_grid = a.compute()
285 a.plot_transmission()
287 .. doctest::
288 :hide:
290 >>> assert np.all(np.isclose(a.atmgrid[0, a.index_atm_data:], parameters.LAMBDAS))
291 >>> assert not np.any(np.isclose(a.atmgrid[1, a.index_atm_data:],
292 ... np.zeros_like(parameters.LAMBDAS), rtol=1e-6))
293 >>> assert a.atmgrid.shape == (3, a.index_atm_data+len(parameters.LAMBDAS))
294 """
295 # first determine the length
296 self.my_logger.debug(f'\n\tAtmosphere simulations for z={self.airmass:4.2f}, P={self.pressure:4.2f}hPa, '
297 rf'T={self.temperature:4.2f}$\degree$C, for data-file={self.image_filename} ')
298 count = 0
299 for aer in self.AER_Points:
300 for pwv in self.PWV_Points:
301 for oz in self.OZ_Points:
302 count += 1
303 # fills headers info in the numpy array
304 self.atmgrid[count, self.index_atm_count] = count
305 self.atmgrid[count, self.index_atm_aer] = aer
306 self.atmgrid[count, self.index_atm_pwv] = pwv
307 self.atmgrid[count, self.index_atm_oz] = oz
308 transmission = super(AtmosphereGrid, self).simulate(oz, pwv, aer)
309 transm = transmission(parameters.LAMBDAS)
310 self.atmgrid[count, self.index_atm_data:] = transm # each of atmospheric spectrum
311 return self.atmgrid
313 def plot_transmission(self):
314 """Plot the atmospheric transmission contained in the grid.
316 Examples
317 --------
318 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
319 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
320 >>> atmospheric_grid = a.compute()
321 >>> a.plot_transmission()
323 .. plot::
325 from spectractor.simulation.atmosphere import AtmosphereGrid
326 a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits', pwv_grid=[5, 5, 1],
327 ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
328 atmospheric_grid = a.compute()
329 a.plot_transmission()
331 """
332 plt.figure()
333 counts = self.atmgrid[1:, self.index_atm_count]
334 for count in counts:
335 label = f'PWV={self.atmgrid[int(count), self.index_atm_pwv]} ' \
336 f'OZ={self.atmgrid[int(count), self.index_atm_oz]} ' \
337 f'VAOD={self.atmgrid[int(count), self.index_atm_aer]}'
338 plot_transmission_simple(plt.gca(), self.lambdas, self.atmgrid[int(count), self.index_atm_data:],
339 title="Atmospheric grid", label=label)
340 if parameters.DISPLAY: # pragma: no cover
341 plt.show()
342 else:
343 plt.close('all')
345 def plot_transmission_image(self):
346 """Plot the atmospheric transmission contained in the grid using imshow.
348 Examples
349 --------
350 >>> a = AtmosphereGrid(filename='tests/data/reduc_20170530_134_atmsim.fits')
351 >>> a.plot_transmission_image()
353 .. plot::
355 from spectractor.simulation.atmosphere import AtmosphereGrid
356 a = AtmosphereGrid(image_filename='tests/data/reduc_20170530_134_atmsim.fits', pwv_grid=[5, 5, 1],
357 ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
358 atmospheric_grid = a.compute()
359 a.plot_transmission_image()
361 """
362 plt.figure()
363 img = plt.imshow(self.atmgrid[1:, self.index_atm_data:], origin='lower', cmap='jet', aspect="auto")
364 plt.grid(True)
365 plt.xlabel(r"$\lambda$ [nm]")
366 plt.ylabel("Simulation number")
367 plt.title("Atmospheric variations")
368 cbar = plt.colorbar(img)
369 cbar.set_label('Atmospheric transmission')
370 if parameters.DISPLAY:
371 plt.show()
372 else:
373 plt.close('all')
375 def save_file(self, filename=""):
376 """Save the atmospheric grid in a fits file.
378 Parameters
379 ----------
380 filename: str
381 The output file name.
383 Examples
384 --------
385 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
386 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
387 >>> atmospheric_grid = a.compute()
388 >>> a.save_file(a.image_filename.replace('.fits', '_atmsim.fits'))
390 .. doctest::
391 :hide:
393 >>> assert os.path.isfile('tests/data/reduc_20170605_028_atmsim.fits')
394 """
395 hdr = fits.Header()
397 if filename != "":
398 self.filename = filename
400 if self.filename == "":
401 self.my_logger.error('\n\tNo file name is given...')
402 else:
403 hdr['ATMSIM'] = "libradtran"
404 hdr['SIMVERS'] = "2.0.1"
405 hdr['DATAFILE'] = self.image_filename
406 hdr['SIMUFILE'] = os.path.basename(self.filename)
408 hdr['AIRMASS'] = self.airmass
409 hdr['PRESSURE'] = self.pressure
410 hdr['TEMPERAT'] = self.temperature
411 hdr['NBATMPTS'] = self.NB_ATM_POINTS
413 hdr['NBAERPTS'] = self.AER_Points.size
414 hdr['AERMIN'] = self.AER_Points.min()
415 hdr['AERMAX'] = self.AER_Points.max()
417 hdr['NBPWVPTS'] = self.PWV_Points.size
418 hdr['PWVMIN'] = self.PWV_Points.min()
419 hdr['PWVMAX'] = self.PWV_Points.max()
421 hdr['NBOZPTS'] = self.OZ_Points.size
422 hdr['OZMIN'] = self.OZ_Points.min()
423 hdr['OZMAX'] = self.OZ_Points.max()
425 hdr['AER_PTS'] = np.array_str(self.AER_Points)
426 hdr['PWV_PTS'] = np.array_str(self.PWV_Points)
427 hdr['OZ_PTS'] = np.array_str(self.OZ_Points)
428 hdr['NBWLBIN'] = parameters.LAMBDAS.size
429 hdr['WLMIN'] = parameters.LAMBDA_MIN
430 hdr['WLMAX'] = parameters.LAMBDA_MAX
432 hdr['IDX_CNT'] = self.index_atm_count
433 hdr['IDX_AER'] = self.index_atm_aer
434 hdr['IDX_PWV'] = self.index_atm_pwv
435 hdr['IDX_OZ'] = self.index_atm_oz
436 hdr['IDX_DATA'] = self.index_atm_data
438 hdu = fits.PrimaryHDU(self.atmgrid, header=hdr)
439 hdu.writeto(self.filename, overwrite=True)
440 self.my_logger.info(f'\n\tAtmosphere.save atm-file={self.filename}')
442 def load_file(self, filename):
443 """Load the atmospheric grid from a fits file and interpolate across the points
444 using RegularGridInterpolator. Automatically called from __init__.
446 Parameters
447 ----------
448 filename: str
449 The input file name.
451 Examples
452 --------
453 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
454 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
455 >>> atmospheric_grid = a.compute()
456 >>> a.save_file(a.image_filename.replace('.fits', '_atmsim.fits'))
457 >>> assert os.path.isfile('tests/data/reduc_20170605_028_atmsim.fits')
458 >>> a.load_file(a.image_filename.replace('.fits', '_atmsim.fits'))
459 >>> a.AER_Points
460 array([0. , 0.1])
461 >>> a.PWV_Points
462 array([5.])
463 >>> a.OZ_Points
464 array([400.])
465 """
467 if filename != "":
468 self.filename = filename
470 if self.filename == "":
471 self.my_logger.error('\n\tNo file name is given...')
472 else:
474 hdu = fits.open(self.filename)
475 hdr = hdu[0].header
476 self.header = hdr
478 # hdr['ATMSIM'] = "libradtran"
479 # hdr['SIMVERS'] = "2.0.1"
480 self.image_filename = hdr['DATAFILE']
481 # hdr['SIMUFILE']=os.path.basename(self.file_name)
483 self.airmass = hdr['AIRMASS']
484 self.pressure = hdr['PRESSURE']
485 self.temperature = hdr['TEMPERAT']
487 # hope those are the same parameters : TBD !!!!
488 self.NB_ATM_POINTS = hdr['NBATMPTS']
490 NB_AER_POINTS = hdr['NBAERPTS']
491 AER_MIN = hdr['AERMIN']
492 AER_MAX = hdr['AERMAX']
494 NB_PWV_POINTS = hdr['NBPWVPTS']
495 PWV_MIN = hdr['PWVMIN']
496 PWV_MAX = hdr['PWVMAX']
498 NB_OZ_POINTS = hdr['NBOZPTS']
499 OZ_MIN = hdr['OZMIN']
500 OZ_MAX = hdr['OZMAX']
502 self.AER_Points = np.linspace(AER_MIN, AER_MAX, NB_AER_POINTS)
503 self.OZ_Points = np.linspace(OZ_MIN, OZ_MAX, NB_OZ_POINTS)
504 self.PWV_Points = np.linspace(PWV_MIN, PWV_MAX, NB_PWV_POINTS)
506 NBWLBINS = hdr['NBWLBIN']
507 # WLMIN = hdr['WLMIN']
508 # WLMAX = hdr['WLMAX']
510 self.index_atm_count = hdr['IDX_CNT']
511 self.index_atm_aer = hdr['IDX_AER']
512 self.index_atm_pwv = hdr['IDX_PWV']
513 self.index_atm_oz = hdr['IDX_OZ']
514 self.index_atm_data = hdr['IDX_DATA']
516 self.atmgrid = np.zeros((self.NB_ATM_POINTS + 1, self.NB_ATM_HEADER + NBWLBINS - 1))
518 self.atmgrid[:, :] = hdu[0].data[:, :]
520 self.my_logger.debug(f'\n\tAtmosphere.load_image atm-file={self.filename}')
522 # interpolate the grid
523 self.lambdas = self.atmgrid[0, self.index_atm_data:]
524 self.model = RegularGridInterpolator((self.lambdas, self.OZ_Points, self.PWV_Points, self.AER_Points), (
525 self.atmgrid[1:, self.index_atm_data:].reshape(NB_AER_POINTS, NB_PWV_POINTS,
526 NB_OZ_POINTS,
527 len(self.lambdas))).T, bounds_error=False, fill_value=0)
529 def simulate(self, ozone, pwv, aerosols):
530 """Interpolate from the atmospheric grid to get the atmospheric transmission.
532 First ozone, second pwv, last aerosols, to respect order of loops when generating the grid
534 Parameters
535 ----------
536 ozone: float
537 Ozone quantity in Dobson
538 pwv: float
539 Precipitable Water Vapor quantity in mm
540 aerosols: float
541 VAOD Vertical Aerosols Optical Depth
543 Examples
544 --------
546 .. plot::
547 :include-source:
549 >>> from spectractor.simulation.atmosphere import AtmosphereGrid, plot_transmission_simple
550 >>> from spectractor import parameters
551 >>> import numpy as np
552 >>> import matplotlib.pyplot as plt
553 >>> a = AtmosphereGrid(filename='tests/data/reduc_20170530_134_atmsim.fits')
554 >>> lambdas = np.arange(200, 1200)
555 >>> fig = plt.figure()
556 >>> for pwv in np.arange(5):
557 ... transmission = a.simulate(ozone=400, pwv=pwv, aerosols=0.05)
558 ... plot_transmission_simple(plt.gca(), lambdas, transmission(lambdas),
559 ... title=a.title, label=a.label)
560 >>> if parameters.DISPLAY: plt.show()
561 """
562 self.pwv = pwv
563 self.ozone = ozone
564 self.aerosols = aerosols
565 self.set_title()
566 self.set_label()
567 ones = np.ones_like(self.lambdas)
568 points = np.array([self.lambdas, ozone * ones, pwv * ones, aerosols * ones]).T
569 atm = self.model(points)
570 self.transmission = interp1d(self.lambdas, atm, kind='linear', bounds_error=False, fill_value=(0, 0))
571 return self.transmission
574if __name__ == "__main__": 574 ↛ 575line 574 didn't jump to line 575, because the condition on line 574 was never true
575 import doctest
577 doctest.testmod()