Coverage for spectractor/simulation/throughput.py: 18%
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
5from scipy.interpolate import interp1d
7from spectractor.config import set_logger
8import spectractor.parameters as parameters
11def load_transmission(file_name):
12 """Load the transmission files and crop in wavelength using LAMBDA_MIN and LAMBDA_MAX.
14 The input file must have two or three columns:
15 1. wavelengths in nm
16 2. transmissions between 0 and 1.
17 3. uncertainties on the transmissions (optional)
19 Returns
20 -------
21 lambdas: array_like
22 The wavelengths array in nm.
23 transmissions: array_like
24 The transmission array, values are between 0 and 1.
25 uncertainties: array_like
26 The uncertainty on the transmission array (0 if file does not contain the info).
28 Examples
29 --------
30 >>> parameters.LAMBDA_MIN = 500
31 >>> lambdas, transmissions, errors = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, "qecurve.txt"))
32 >>> print(lambdas[:3])
33 [500.81855389 508.18553888 519.23601637]
34 >>> print(transmissions[:3])
35 [0.74355972 0.75526932 0.76932084]
36 >>> print(errors[:3])
37 [0. 0. 0.]
39 """
40 data = np.loadtxt(file_name).T
41 lambdas = data[0]
42 sorted_indices = lambdas.argsort()
43 lambdas = lambdas[sorted_indices]
44 y = data[1][sorted_indices]
45 err = np.zeros_like(y)
46 if data.shape[0] == 3:
47 err = data[2][sorted_indices]
48 indexes = np.logical_and(lambdas > parameters.LAMBDA_MIN, lambdas < parameters.LAMBDA_MAX)
49 return lambdas[indexes], y[indexes], err[indexes]
52def plot_transmission_simple(ax, lambdas, transmissions, uncertainties=None, label="", title="", lw=2):
53 """Plot the transmission with respect to the wavelength.
55 Parameters
56 ----------
57 ax: Axes
58 An Axes instance.
59 lambdas: array_like
60 The wavelengths array in nm.
61 transmissions: array_like
62 The transmission array, values are between 0 and 1.
63 uncertainties: array_like, optional
64 The uncertainty on the transmission array (default: None).
65 label: str, optional
66 The label of the curve for the legend (default: "")
67 title: str, optional
68 The title of the plot (default: "")
69 lw: int
70 Line width (default: 2).
72 Examples
73 --------
75 .. plot::
76 :include-source:
78 >>> from spectractor.simulation.atmosphere import plot_transmission_simple
79 >>> from spectractor import parameters
80 >>> fig = plt.figure()
81 >>> ax = plt.gca()
82 >>> parameters.LAMBDA_MIN = 500
83 >>> lambdas, transmissions, errors = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, "qecurve.txt"))
84 >>> plot_transmission_simple(ax, lambdas, transmissions, errors, title="CTIO", label="Quantum efficiency")
85 >>> lambdas, transmissions, errors = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, "lsst_mirrorthroughput.txt"))
86 >>> plot_transmission_simple(ax, lambdas, transmissions, errors, title="CTIO", label="Mirror 1")
87 >>> lambdas, transmissions, errors = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, "FGB37.txt"))
88 >>> plot_transmission_simple(ax, lambdas, transmissions, errors, title="CTIO", label="FGB37")
89 >>> lambdas, transmissions, errors = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, "RG715.txt"))
90 >>> plot_transmission_simple(ax, lambdas, transmissions, errors, title="CTIO", label="RG715")
91 >>> lambdas, transmissions, errors = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, parameters.OBS_TELESCOPE_TRANSMISSION))
92 >>> plot_transmission_simple(ax, lambdas, transmissions, errors, title="CTIO", label="Telescope")
93 >>> if parameters.DISPLAY: plt.show()
95 """
96 if uncertainties is None or np.all(np.isclose(uncertainties, np.zeros_like(transmissions))):
97 ax.plot(lambdas, transmissions, "-", label=label, lw=lw)
98 else:
99 ax.errorbar(lambdas, transmissions, yerr=uncertainties, label=label, lw=lw)
100 if title != "":
101 ax.set_title(title)
102 ax.set_xlabel(r"$\lambda$ [nm]")
103 ax.set_ylabel("Transmission")
104 ax.set_xlim(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX)
105 ax.grid()
106 if label != "":
107 ax.legend(loc="best")
110class TelescopeTransmission:
112 def __init__(self, filter_label=""):
113 """Transmission of the telescope as product of the following transmissions:
115 - mirrors
116 - throughput
117 - quantum efficiency
118 - Filter
120 Parameters
121 ----------
122 filter_label: str, optional
123 The filter string name.
125 Examples
126 --------
127 >>> t = TelescopeTransmission()
128 >>> t.plot_transmission()
129 """
131 self.my_logger = set_logger(self.__class__.__name__)
132 self.filter_label = filter_label
133 self.transmission = None
134 self.transmission_err = None
135 self.load_transmission()
137 def load_transmission(self):
138 """Load the transmission files and make a function.
140 Returns
141 -------
142 transmission: callable
143 The transmission function using wavelengths in nm.
145 Examples
146 --------
147 >>> t = TelescopeTransmission()
148 >>> t.plot_transmission()
150 >>> t2 = TelescopeTransmission(filter_label="RG715")
151 >>> t2.plot_transmission()
153 .. doctest:
154 :hide:
156 >>> assert t.transmission is not None
157 >>> assert t.transmission_err is not None
158 >>> assert t2.transmission is not None
159 >>> assert t2.transmission_err is not None
160 >>> assert np.sum(t.transmission(parameters.LAMBDAS)) > np.sum(t2.transmission(parameters.LAMBDAS))
162 """
163 wl, trm, err = load_transmission(os.path.join(parameters.THROUGHPUT_DIR,
164 parameters.OBS_FULL_INSTRUMENT_TRANSMISSON))
165 to = interp1d(wl, trm, kind='linear', bounds_error=False, fill_value=0.)
166 err = np.sqrt(err ** 2 + parameters.OBS_TRANSMISSION_SYSTEMATICS ** 2)
167 to_err = interp1d(wl, err, kind='linear', bounds_error=False, fill_value=0.)
169 TF = lambda x: 1
170 TF_err = lambda x: 0
171 if self.filter_label != "" and "empty" not in self.filter_label.lower():
172 if ".txt" in self.filter_label:
173 filter_filename = self.filter_label
174 else:
175 filter_filename = self.filter_label + ".txt"
176 wl, trb, err = load_transmission(os.path.join(parameters.THROUGHPUT_DIR, filter_filename))
177 TF = interp1d(wl, trb, kind='linear', bounds_error=False, fill_value=0.)
178 TF_err = interp1d(wl, err, kind='linear', bounds_error=False, fill_value=0.)
180 # self.transmission=lambda x: self.qe(x)*self.to(x)*(self.tm(x)**2)*self.tf(x)
181 self.transmission = lambda x: to(x) * TF(x)
182 self.transmission_err = lambda x: np.sqrt(to_err(x)**2 + TF_err(x)**2)
183 return self.transmission
185 def plot_transmission(self):
186 """Plot the transmission function and the associated uncertainties.
188 Examples
189 --------
190 >>> t = TelescopeTransmission()
191 >>> t.plot_transmission()
193 """
194 plt.figure()
195 plot_transmission_simple(plt.gca(), parameters.LAMBDAS, self.transmission(parameters.LAMBDAS),
196 uncertainties=self.transmission_err(parameters.LAMBDAS))
197 if parameters.DISPLAY:
198 plt.show()
199 else:
200 plt.close('all')
202 def reset_lambda_range(self, transmission_threshold=1e-4):
203 integral = np.cumsum(self.transmission(parameters.LAMBDAS))
204 parameters.LAMBDA_MIN = max(parameters.LAMBDAS[np.argmin(np.abs(integral - transmission_threshold))],
205 parameters.LAMBDA_MIN)
206 parameters.LAMBDA_MAX = min(parameters.LAMBDAS[np.argmin(np.abs(integral -
207 (integral[-1] - transmission_threshold)))],
208 parameters.LAMBDA_MAX)
209 parameters.LAMBDAS = np.arange(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX, parameters.LAMBDA_STEP)
210 self.my_logger.info(f"\n\tWith filter {self.filter_label}, set parameters.LAMBDA_MIN={parameters.LAMBDA_MIN} "
211 f"and parameters.LAMBDA_MAX={parameters.LAMBDA_MAX}.")
214if __name__ == "__main__": 214 ↛ 215line 214 didn't jump to line 215, because the condition on line 214 was never true
215 import doctest
217 doctest.testmod()