Coverage for spectractor/simulation/atmosphere.py: 12%
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.PdfPages:
138 parameters.PdfPages.savefig()
139 if parameters.DISPLAY: # pragma: no cover
140 plt.show()
141 else:
142 plt.close('all')
145# ----------------------------------------------------------------------------------
146class AtmosphereGrid(Atmosphere):
148 def __init__(self, image_filename="", filename="", airmass=1., pressure=800., temperature=10.,
149 pwv_grid=[0, 10, 10], ozone_grid=[100, 700, 7], aerosol_grid=[0, 0.1, 10]):
150 """Class to load and interpolate grids of atmospheric transmission computed with Libradtran.
152 Parameters
153 ----------
154 image_filename: str, optional
155 The original image fits file name from which the grid was computed or has to be computed (default: "").
156 filename: str, optional
157 The file name of the atmospheric grid if it exists (default: "").
158 airmass: float, optional
159 Airmass of the source object (default: 1).
160 pressure: float, optional
161 Pressure of the atmosphere in hPa (default: 800).
162 temperature: float, optional
163 Temperature of the atmosphere in Celsius degrees (default: 10).
164 pwv_grid: list
165 List of 3 numbers for the PWV quantity: min, max, number of simulations (default: [0, 10, 10]).
166 ozone_grid: list
167 List of 3 numbers for the ozone quantity: min, max, number of simulations (default: [100, 700, 7]).
168 aerosol_grid: list
169 List of 3 numbers for the aerosol quantity: min, max, number of simulations (default: [0, 0.1, 10]).
171 Examples
172 --------
173 >>> a = AtmosphereGrid(filename='./tests/data/reduc_20170530_134_atmsim.fits')
174 >>> a.image_filename.split('/')[-1]
175 'reduc_20170530_134_spectrum.fits'
176 """
177 Atmosphere.__init__(self, airmass, pressure, temperature)
178 self.my_logger = set_logger(self.__class__.__name__)
179 self.image_filename = image_filename
180 self.filename = filename
181 # ------------------------------------------------------------------------
182 # Definition of data format for the atmospheric grid
183 # -----------------------------------------------------------------------------
185 # row 0 : count number
186 # row 1 : aerosol value
187 # row 2 : pwv value
188 # row 3 : ozone value
189 # row 4 : data start
190 self.index_atm_count = 0
191 self.index_atm_aer = 1
192 self.index_atm_pwv = 2
193 self.index_atm_oz = 3
194 self.index_atm_data = 4
196 # specify parameters for the atmospheric grid
197 self.atmgrid = None
198 self.NB_ATM_HEADER = self.index_atm_data + 1
199 self.NB_ATM_DATA = len(parameters.LAMBDAS) - 1
200 self.NB_ATM_POINTS = 0
201 self.AER_Points = np.array([])
202 self.OZ_Points = np.array([])
203 self.PWV_Points = np.array([])
204 self.set_grid(pwv_grid=pwv_grid, ozone_grid=ozone_grid, aerosol_grid=aerosol_grid)
206 # the interpolated grid
207 self.lambdas = parameters.LAMBDAS
208 self.model = None
210 self.header = fits.Header()
211 if filename != "":
212 self.load_file(filename)
214 def set_grid(self, pwv_grid=[0, 10, 10], ozone_grid=[100, 700, 7], aerosol_grid=[0, 0.1, 10]):
215 """Set the size of the simulation grid self.atmgrid before compute it.
217 The first column of self.atmgrid will contain the wavelengths set by parameters.LAMBDAS,
218 the other columns the future simulations.
220 Parameters
221 ----------
222 pwv_grid: list
223 List of 3 numbers for the PWV quantity: min, max, number of simulations (default: [0, 10, 10]).
224 ozone_grid: list
225 List of 3 numbers for the ozone quantity: min, max, number of simulations (default: [100, 700, 7]).
226 aerosol_grid: list
227 List of 3 numbers for the aerosol quantity: min, max, number of simulations (default: [0, 0.1, 10]).
228 """
229 # aerosols
230 NB_AER_POINTS = int(aerosol_grid[2])
231 AER_MIN = float(aerosol_grid[0])
232 AER_MAX = float(aerosol_grid[1])
234 # ozone
235 NB_OZ_POINTS = int(ozone_grid[2])
236 OZ_MIN = float(ozone_grid[0])
237 OZ_MAX = float(ozone_grid[1])
239 # pwv
240 NB_PWV_POINTS = int(pwv_grid[2])
241 PWV_MIN = float(pwv_grid[0])
242 PWV_MAX = float(pwv_grid[1])
244 # definition of the grid
245 self.AER_Points = np.linspace(AER_MIN, AER_MAX, NB_AER_POINTS)
246 self.OZ_Points = np.linspace(OZ_MIN, OZ_MAX, NB_OZ_POINTS)
247 self.PWV_Points = np.linspace(PWV_MIN, PWV_MAX, NB_PWV_POINTS)
249 # total number of points
250 self.NB_ATM_POINTS = NB_AER_POINTS * NB_OZ_POINTS * NB_PWV_POINTS
252 # create the numpy array that will contains the atmospheric grid
253 self.atmgrid = np.zeros((self.NB_ATM_POINTS + 1, self.NB_ATM_HEADER + self.NB_ATM_DATA))
254 self.atmgrid[0, self.index_atm_data:] = parameters.LAMBDAS
255 self.lambdas = parameters.LAMBDAS
257 def compute(self):
258 """Compute atmospheric transmissions and fill self.atmgrid.
260 The wavelengths used for the computation are the ones set by parameters.LAMBDAS.
262 Returns
263 -------
264 atmospheric_grid: array_like
265 The atmospheric grid self.atmgrid.
267 Examples
268 --------
269 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
270 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
271 >>> atmospheric_grid = a.compute()
272 >>> atmospheric_grid # doctest: +ELLIPSIS
273 array([[0.000000e+00, 0.000000e+00, 0.000000e+00, ..., 1.099400e+03,
274 1.099600e+03, 1.099800e+03],
275 [1.000000e+00, 0.000000e+00, 5.000000e+00, ..., 9.520733e-01,
276 9.520733e-01, 9.520733e-01],
277 ...])
278 >>> a.save_file(a.image_filename.replace('.fits', '_atmsim.fits'))
279 >>> a.plot_transmission()
281 .. plot::
283 from spectractor.simulation.atmosphere import AtmosphereGrid
284 a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits', pwv_grid=[5, 5, 1],
285 ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
286 atmospheric_grid = a.compute()
287 a.plot_transmission()
289 .. doctest::
290 :hide:
292 >>> assert np.all(np.isclose(a.atmgrid[0, a.index_atm_data:], parameters.LAMBDAS))
293 >>> assert not np.any(np.isclose(a.atmgrid[1, a.index_atm_data:],
294 ... np.zeros_like(parameters.LAMBDAS), rtol=1e-6))
295 >>> assert a.atmgrid.shape == (3, a.index_atm_data+len(parameters.LAMBDAS))
296 """
297 # first determine the length
298 self.my_logger.debug(f'\n\tAtmosphere simulations for z={self.airmass:4.2f}, P={self.pressure:4.2f}hPa, '
299 rf'T={self.temperature:4.2f}$\degree$C, for data-file={self.image_filename} ')
300 count = 0
301 for aer in self.AER_Points:
302 for pwv in self.PWV_Points:
303 for oz in self.OZ_Points:
304 count += 1
305 # fills headers info in the numpy array
306 self.atmgrid[count, self.index_atm_count] = count
307 self.atmgrid[count, self.index_atm_aer] = aer
308 self.atmgrid[count, self.index_atm_pwv] = pwv
309 self.atmgrid[count, self.index_atm_oz] = oz
310 transmission = super(AtmosphereGrid, self).simulate(oz, pwv, aer)
311 transm = transmission(parameters.LAMBDAS)
312 self.atmgrid[count, self.index_atm_data:] = transm # each of atmospheric spectrum
313 return self.atmgrid
315 def plot_transmission(self):
316 """Plot the atmospheric transmission contained in the grid.
318 Examples
319 --------
320 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
321 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
322 >>> atmospheric_grid = a.compute()
323 >>> a.plot_transmission()
325 .. plot::
327 from spectractor.simulation.atmosphere import AtmosphereGrid
328 a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits', pwv_grid=[5, 5, 1],
329 ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
330 atmospheric_grid = a.compute()
331 a.plot_transmission()
333 """
334 plt.figure()
335 counts = self.atmgrid[1:, self.index_atm_count]
336 for count in counts:
337 label = f'PWV={self.atmgrid[int(count), self.index_atm_pwv]} ' \
338 f'OZ={self.atmgrid[int(count), self.index_atm_oz]} ' \
339 f'VAOD={self.atmgrid[int(count), self.index_atm_aer]}'
340 plot_transmission_simple(plt.gca(), self.lambdas, self.atmgrid[int(count), self.index_atm_data:],
341 title="Atmospheric grid", label=label)
342 if parameters.PdfPages:
343 parameters.PdfPages.savefig()
344 if parameters.DISPLAY: # pragma: no cover
345 plt.show()
346 else:
347 plt.close('all')
349 def plot_transmission_image(self):
350 """Plot the atmospheric transmission contained in the grid using imshow.
352 Examples
353 --------
354 >>> a = AtmosphereGrid(filename='tests/data/reduc_20170530_134_atmsim.fits')
355 >>> a.plot_transmission_image()
357 .. plot::
359 from spectractor.simulation.atmosphere import AtmosphereGrid
360 a = AtmosphereGrid(image_filename='tests/data/reduc_20170530_134_atmsim.fits', pwv_grid=[5, 5, 1],
361 ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
362 atmospheric_grid = a.compute()
363 a.plot_transmission_image()
365 """
366 plt.figure()
367 img = plt.imshow(self.atmgrid[1:, self.index_atm_data:], origin='lower', cmap='jet', aspect="auto")
368 plt.grid(True)
369 plt.xlabel(r"$\lambda$ [nm]")
370 plt.ylabel("Simulation number")
371 plt.title("Atmospheric variations")
372 cbar = plt.colorbar(img)
373 cbar.set_label('Atmospheric transmission')
374 if parameters.PdfPages:
375 parameters.PdfPages.savefig()
376 if parameters.DISPLAY:
377 plt.show()
378 else:
379 plt.close('all')
382 def save_file(self, filename=""):
383 """Save the atmospheric grid in a fits file.
385 Parameters
386 ----------
387 filename: str
388 The output file name.
390 Examples
391 --------
392 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
393 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
394 >>> atmospheric_grid = a.compute()
395 >>> a.save_file(a.image_filename.replace('.fits', '_atmsim.fits'))
397 .. doctest::
398 :hide:
400 >>> assert os.path.isfile('tests/data/reduc_20170605_028_atmsim.fits')
401 """
402 hdr = fits.Header()
404 if filename != "":
405 self.filename = filename
407 if self.filename == "":
408 self.my_logger.error('\n\tNo file name is given...')
409 else:
410 hdr['ATMSIM'] = "libradtran"
411 hdr['SIMVERS'] = "2.0.1"
412 hdr['DATAFILE'] = self.image_filename
413 hdr['SIMUFILE'] = os.path.basename(self.filename)
415 hdr['AIRMASS'] = self.airmass
416 hdr['PRESSURE'] = self.pressure
417 hdr['TEMPERAT'] = self.temperature
418 hdr['NBATMPTS'] = self.NB_ATM_POINTS
420 hdr['NBAERPTS'] = self.AER_Points.size
421 hdr['AERMIN'] = self.AER_Points.min()
422 hdr['AERMAX'] = self.AER_Points.max()
424 hdr['NBPWVPTS'] = self.PWV_Points.size
425 hdr['PWVMIN'] = self.PWV_Points.min()
426 hdr['PWVMAX'] = self.PWV_Points.max()
428 hdr['NBOZPTS'] = self.OZ_Points.size
429 hdr['OZMIN'] = self.OZ_Points.min()
430 hdr['OZMAX'] = self.OZ_Points.max()
432 hdr['AER_PTS'] = np.array_str(self.AER_Points)
433 hdr['PWV_PTS'] = np.array_str(self.PWV_Points)
434 hdr['OZ_PTS'] = np.array_str(self.OZ_Points)
435 hdr['NBWLBIN'] = parameters.LAMBDAS.size
436 hdr['WLMIN'] = parameters.LAMBDA_MIN
437 hdr['WLMAX'] = parameters.LAMBDA_MAX
439 hdr['IDX_CNT'] = self.index_atm_count
440 hdr['IDX_AER'] = self.index_atm_aer
441 hdr['IDX_PWV'] = self.index_atm_pwv
442 hdr['IDX_OZ'] = self.index_atm_oz
443 hdr['IDX_DATA'] = self.index_atm_data
445 hdu = fits.PrimaryHDU(self.atmgrid, header=hdr)
446 hdu.writeto(self.filename, overwrite=True)
447 self.my_logger.info(f'\n\tAtmosphere.save atm-file={self.filename}')
449 def load_file(self, filename):
450 """Load the atmospheric grid from a fits file and interpolate across the points
451 using RegularGridInterpolator. Automatically called from __init__.
453 Parameters
454 ----------
455 filename: str
456 The input file name.
458 Examples
459 --------
460 >>> a = AtmosphereGrid(image_filename='tests/data/reduc_20170605_028.fits',
461 ... pwv_grid=[5, 5, 1], ozone_grid=[400, 400, 1], aerosol_grid=[0.0, 0.1, 2])
462 >>> atmospheric_grid = a.compute()
463 >>> a.save_file(a.image_filename.replace('.fits', '_atmsim.fits'))
464 >>> assert os.path.isfile('tests/data/reduc_20170605_028_atmsim.fits')
465 >>> a.load_file(a.image_filename.replace('.fits', '_atmsim.fits'))
466 >>> a.AER_Points
467 array([0. , 0.1])
468 >>> a.PWV_Points
469 array([5.])
470 >>> a.OZ_Points
471 array([400.])
472 """
474 if filename != "":
475 self.filename = filename
477 if self.filename == "":
478 self.my_logger.error('\n\tNo file name is given...')
479 else:
481 hdu = fits.open(self.filename)
482 hdr = hdu[0].header
483 self.header = hdr
485 # hdr['ATMSIM'] = "libradtran"
486 # hdr['SIMVERS'] = "2.0.1"
487 self.image_filename = hdr['DATAFILE']
488 # hdr['SIMUFILE']=os.path.basename(self.file_name)
490 self.airmass = hdr['AIRMASS']
491 self.pressure = hdr['PRESSURE']
492 self.temperature = hdr['TEMPERAT']
494 # hope those are the same parameters : TBD !!!!
495 self.NB_ATM_POINTS = hdr['NBATMPTS']
497 NB_AER_POINTS = hdr['NBAERPTS']
498 AER_MIN = hdr['AERMIN']
499 AER_MAX = hdr['AERMAX']
501 NB_PWV_POINTS = hdr['NBPWVPTS']
502 PWV_MIN = hdr['PWVMIN']
503 PWV_MAX = hdr['PWVMAX']
505 NB_OZ_POINTS = hdr['NBOZPTS']
506 OZ_MIN = hdr['OZMIN']
507 OZ_MAX = hdr['OZMAX']
509 self.AER_Points = np.linspace(AER_MIN, AER_MAX, NB_AER_POINTS)
510 self.OZ_Points = np.linspace(OZ_MIN, OZ_MAX, NB_OZ_POINTS)
511 self.PWV_Points = np.linspace(PWV_MIN, PWV_MAX, NB_PWV_POINTS)
513 NBWLBINS = hdr['NBWLBIN']
514 # WLMIN = hdr['WLMIN']
515 # WLMAX = hdr['WLMAX']
517 self.index_atm_count = hdr['IDX_CNT']
518 self.index_atm_aer = hdr['IDX_AER']
519 self.index_atm_pwv = hdr['IDX_PWV']
520 self.index_atm_oz = hdr['IDX_OZ']
521 self.index_atm_data = hdr['IDX_DATA']
523 self.atmgrid = np.zeros((self.NB_ATM_POINTS + 1, self.NB_ATM_HEADER + NBWLBINS - 1))
525 self.atmgrid[:, :] = hdu[0].data[:, :]
527 self.my_logger.debug(f'\n\tAtmosphere.load_image atm-file={self.filename}')
529 # interpolate the grid
530 self.lambdas = self.atmgrid[0, self.index_atm_data:]
531 self.model = RegularGridInterpolator((self.lambdas, self.OZ_Points, self.PWV_Points, self.AER_Points), (
532 self.atmgrid[1:, self.index_atm_data:].reshape(NB_AER_POINTS, NB_PWV_POINTS,
533 NB_OZ_POINTS,
534 len(self.lambdas))).T, bounds_error=False, fill_value=0)
536 def simulate(self, ozone, pwv, aerosols):
537 """Interpolate from the atmospheric grid to get the atmospheric transmission.
539 First ozone, second pwv, last aerosols, to respect order of loops when generating the grid
541 Parameters
542 ----------
543 ozone: float
544 Ozone quantity in Dobson
545 pwv: float
546 Precipitable Water Vapor quantity in mm
547 aerosols: float
548 VAOD Vertical Aerosols Optical Depth
550 Examples
551 --------
553 .. plot::
554 :include-source:
556 >>> from spectractor.simulation.atmosphere import AtmosphereGrid, plot_transmission_simple
557 >>> from spectractor import parameters
558 >>> import numpy as np
559 >>> import matplotlib.pyplot as plt
560 >>> a = AtmosphereGrid(filename='tests/data/reduc_20170530_134_atmsim.fits')
561 >>> lambdas = np.arange(200, 1200)
562 >>> fig = plt.figure()
563 >>> for pwv in np.arange(5):
564 ... transmission = a.simulate(ozone=400, pwv=pwv, aerosols=0.05)
565 ... plot_transmission_simple(plt.gca(), lambdas, transmission(lambdas),
566 ... title=a.title, label=a.label)
567 >>> if parameters.DISPLAY: plt.show()
568 """
569 self.pwv = pwv
570 self.ozone = ozone
571 self.aerosols = aerosols
572 self.set_title()
573 self.set_label()
574 ones = np.ones_like(self.lambdas)
575 points = np.array([self.lambdas, ozone * ones, pwv * ones, aerosols * ones]).T
576 atm = self.model(points)
577 self.transmission = interp1d(self.lambdas, atm, kind='linear', bounds_error=False, fill_value=(0, 0))
578 return self.transmission
581if __name__ == "__main__": 581 ↛ 582line 581 didn't jump to line 582, because the condition on line 581 was never true
582 import doctest
584 doctest.testmod()