/
photometry.py
379 lines (291 loc) · 13 KB
/
photometry.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
"""
Module with functionalities for calculating synthetic photometry.
"""
import os
import math
import warnings
import configparser
import h5py
import numpy as np
from species.data import database
from species.read import read_filter, read_calibration
from species.util import phot_util
class SyntheticPhotometry:
"""
Class for calculating synthetic photometry from a spectrum.
"""
def __init__(self,
filter_name):
"""
Parameters
----------
filter_name : str
Filter ID as listed in the database. Filters from the SVO Filter Profile Service are
downloaded and added to the database.
Returns
-------
NoneType
None
"""
self.filter_name = filter_name
self.filter_interp = None
self.wavel_range = None
self.vega_mag = 0.03 # (mag)
config_file = os.path.join(os.getcwd(), 'species_config.ini')
config = configparser.ConfigParser()
config.read_file(open(config_file))
self.database = config['species']['database']
def zero_point(self):
"""
Internal function for calculating the zero point of the provided ``filter_name``.
Returns
-------
float
Zero-point flux (W m-2 um-1).
"""
if self.wavel_range is None:
transmission = read_filter.ReadFilter(self.filter_name)
self.wavel_range = transmission.wavelength_range()
h5_file = h5py.File(self.database, 'r')
try:
h5_file['spectra/calibration/vega']
except KeyError:
h5_file.close()
species_db = database.Database()
species_db.add_spectrum('vega')
h5_file = h5py.File(self.database, 'r')
readcalib = read_calibration.ReadCalibration('vega', None)
calibbox = readcalib.get_spectrum()
wavelength = calibbox.wavelength
flux = calibbox.flux
wavelength_crop = wavelength[(wavelength > self.wavel_range[0]) &
(wavelength < self.wavel_range[1])]
flux_crop = flux[(wavelength > self.wavel_range[0]) &
(wavelength < self.wavel_range[1])]
h5_file.close()
return self.spectrum_to_flux(wavelength_crop, flux_crop)[0]
def spectrum_to_flux(self,
wavelength,
flux,
error=None,
threshold=0.05):
"""
Function for calculating the average flux from a spectrum and a filter profile. The error
is propagated by sampling 200 random values from the error distributions.
Parameters
----------
wavelength : numpy.ndarray
Wavelength points (um).
flux : numpy.ndarray
Flux (W m-2 um-1).
error : numpy.ndarray
Uncertainty (W m-2 um-1). Not used if set to None.
threshold : float, None
Transmission threshold (value between 0 and 1). If the minimum transmission value is
larger than the threshold, a NaN is returned. This will happen if the input spectrum
does not cover the full wavelength range of the filter profile. Not used if set to
None.
Returns
-------
float
Average flux (W m-2 um-1).
float, None
Uncertainty (W m-2 um-1).
"""
if self.filter_interp is None:
transmission = read_filter.ReadFilter(self.filter_name)
self.filter_interp = transmission.interpolate_filter()
if self.wavel_range is None:
self.wavel_range = transmission.wavelength_range()
if wavelength.size == 0:
raise ValueError('Calculation of the mean flux is not possible because the '
'wavelength array is empty.')
indices = np.where((self.wavel_range[0] <= wavelength) &
(wavelength <= self.wavel_range[1]))[0]
if indices.size < 2:
syn_flux = np.nan
warnings.warn('Calculating a synthetic flux requires more than one wavelength '
'point. Photometry is set to NaN.')
else:
if threshold is None and (wavelength[0] > self.wavel_range[0] or
wavelength[-1] < self.wavel_range[1]):
warnings.warn(f'The filter profile of {self.filter_name} '
f'({self.wavel_range[0]:.4f}-{self.wavel_range[1]:.4f}) extends '
f'beyond the wavelength range of the spectrum ({wavelength[0]:.4f} '
f'-{wavelength[-1]:.4f}). The flux is set to NaN. Setting the '
f'\'threshold\' parameter will loosen the wavelength constraints.')
syn_flux = np.nan
else:
wavelength = wavelength[indices]
flux = flux[indices]
if error is not None:
error = error[indices]
transmission = self.filter_interp(wavelength)
if threshold is not None and \
(transmission[0] > threshold or transmission[-1] > threshold) and \
(wavelength[0] < self.wavel_range[0] or wavelength[-1] >
self.wavel_range[-1]):
warnings.warn(f'The filter profile of {self.filter_name} '
f'({self.wavel_range[0]:.4f}-{self.wavel_range[1]:.4f}) '
f'extends beyond the wavelength range of the spectrum '
f'({wavelength[0]:.4f}-{wavelength[-1]:.4f}). The flux '
f'is set to NaN. Increasing the \'threshold\' parameter '
f'({threshold}) will loosen the wavelength constraint.')
syn_flux = np.nan
else:
indices = np.isnan(transmission)
indices = np.logical_not(indices)
integrand1 = transmission[indices]*flux[indices]
integrand2 = transmission[indices]
integral1 = np.trapz(integrand1, wavelength[indices])
integral2 = np.trapz(integrand2, wavelength[indices])
syn_flux = integral1/integral2
if error is not None and not np.any(np.isnan(error)):
phot_random = np.zeros(200)
for i in range(200):
spec_random = flux + np.random.normal(loc=0.,
scale=1.,
size=wavelength.shape[0])*error
phot_random[i] = self.spectrum_to_flux(wavelength,
spec_random,
error=None,
threshold=threshold)[0]
error_flux = np.std(phot_random)
else:
error_flux = None
return syn_flux, error_flux
def spectrum_to_magnitude(self,
wavelength,
flux,
error=None,
distance=None,
threshold=0.05):
"""
Function for calculating the apparent and absolute magnitude from a spectrum and a
filter profile. The error is propagated by sampling 200 random values from the error
distributions.
Parameters
----------
wavelength : numpy.ndarray
Wavelength points (um).
flux : numpy.ndarray
Flux (W m-2 um-1).
error : numpy.ndarray, list(numpy.ndarray), None
Uncertainty (W m-2 um-1).
distance : tuple(float, float), None
Distance and uncertainty (pc). No absolute magnitude is calculated if set to None.
No error on the absolute magnitude is calculated if the uncertainty is set to None.
threshold : float, None
Transmission threshold (value between 0 and 1). If the minimum transmission value is
larger than the threshold, a NaN is returned. This will happen if the input spectrum
does not cover the full wavelength range of the filter profile. Not used if set to
None.
Returns
-------
tuple(float, float)
Apparent magnitude and uncertainty (mag).
tuple(float, float)
Absolute magnitude and uncertainty (mag).
"""
zp_flux = self.zero_point()
syn_flux = self.spectrum_to_flux(wavelength,
flux,
error=error,
threshold=threshold)
app_mag = self.vega_mag - 2.5*math.log10(syn_flux[0]/zp_flux)
if error is not None and not np.any(np.isnan(error)):
mag_random = np.zeros(200)
for i in range(200):
spec_random = flux + np.random.normal(loc=0.,
scale=1.,
size=wavelength.shape[0])*error
flux_random = self.spectrum_to_flux(wavelength,
spec_random,
error=None,
threshold=threshold)
mag_random[i] = self.vega_mag - 2.5*np.log10(flux_random[0]/zp_flux)
error_app_mag = np.std(mag_random)
else:
error_app_mag = None
if distance is None:
abs_mag = None
error_abs_mag = None
else:
abs_mag = app_mag - 5.*np.log10(distance[0]) + 5.
if error_app_mag is not None and distance[1] is not None:
error_dist = distance[1] * (5./(distance[0]*math.log(10.)))
error_abs_mag = math.sqrt(error_app_mag**2 + error_dist**2)
else:
error_abs_mag = None
return (app_mag, error_app_mag), (abs_mag, error_abs_mag)
def magnitude_to_flux(self,
magnitude,
error=None,
zp_flux=None):
"""
Function for converting a magnitude to a flux.
Parameters
----------
magnitude : float
Magnitude (mag).
error : float, None
Error (mag). Not used if set to None.
zp_flux : float
Zero-point flux (W m-2 um-1). The value is calculated if set to None.
Returns
-------
float
Flux (W m-2 um-1).
float
Error (W m-2 um-1).
"""
if zp_flux is None:
zp_flux = self.zero_point()
flux = 10.**(-0.4*(magnitude-self.vega_mag))*zp_flux
if error is None:
error_flux = None
else:
error_upper = flux * (10.**(0.4*error) - 1.)
error_lower = flux * (1. - 10.**(-0.4*error))
error_flux = (error_lower+error_upper)/2.
return flux, error_flux
def flux_to_magnitude(self,
flux,
error=None,
distance=None):
"""
Function for converting a flux into a magnitude.
Parameters
----------
flux : float, numpy.ndarray
Flux (W m-2 um-1).
error : float, numpy.ndarray, None
Uncertainty (W m-2 um-1). Not used if set to None.
distance : tuple(float, float), tuple(numpy.ndarray, numpy.ndarray)
Distance and uncertainty (pc). The returned absolute magnitude is set to None in case
``distance`` is set to None. The error is not propagated into the error on the absolute
magnitude in case the distance uncertainty is set to None, for example
``distance=(20., None)``
Returns
-------
tuple(float, float), tuple(numpy.ndarray, numpy.ndarray)
Apparent magnitude and uncertainty (mag).
tuple(float, float), tuple(numpy.ndarray, numpy.ndarray)
Absolute magnitude and uncertainty (mag).
"""
zp_flux = self.zero_point()
app_mag = self.vega_mag - 2.5*np.log10(flux/zp_flux)
if error is None:
error_app_mag = None
error_abs_mag = None
else:
error_app_lower = app_mag - (self.vega_mag - 2.5*np.log10((flux+error)/zp_flux))
error_app_upper = (self.vega_mag - 2.5*np.log10((flux-error)/zp_flux)) - app_mag
error_app_mag = (error_app_lower+error_app_upper)/2.
if distance is None:
abs_mag = None
error_abs_mag = None
else:
abs_mag, error_abs_mag = phot_util.apparent_to_absolute(
(app_mag, error_app_mag), distance)
return (app_mag, error_app_mag), (abs_mag, error_abs_mag)