/
read_isochrone.py
369 lines (302 loc) · 15.2 KB
/
read_isochrone.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
"""
Module with reading functionalities for isochrones.
"""
import configparser
import os
import warnings
from typing import Optional, Tuple
import h5py
import numpy as np
from typeguard import typechecked
from scipy.interpolate import griddata
from species.core import box
from species.read import read_model
class ReadIsochrone:
"""
Class for reading isochrone data from the database.
"""
@typechecked
def __init__(self,
tag: str) -> None:
"""
Parameters
----------
tag : str
Database tag of the isochrone data.
Returns
-------
NoneType
None
"""
self.tag = tag
config_file = os.path.join(os.getcwd(), 'species_config.ini')
config = configparser.ConfigParser()
config.read_file(open(config_file))
self.database = config['species']['database']
@typechecked
def get_isochrone(self,
age: float,
masses: np.ndarray,
filters_color: Optional[Tuple[str, str]] = None,
filter_mag: Optional[str] = None) -> box.IsochroneBox:
"""
Function for selecting an isochrone.
Parameters
----------
age : float
Age (Myr) at which the isochrone data is interpolated.
masses : np.ndarray
Masses (Mjup) at which the isochrone data is interpolated.
filters_color : tuple(str, str), None
Filter names for the color as listed in the file with the isochrone data. Not selected
if set to ``None`` or if only evolutionary tracks are available.
filter_mag : str, None
Filter name for the absolute magnitude as listed in the file with the isochrone data.
Not selected if set to ``None`` or if only evolutionary tracks are available.
Returns
-------
species.core.box.IsochroneBox
Box with the isochrone.
"""
age_points = np.full(masses.shape[0], age) # (Myr)
color = None
mag_abs = None
index_teff = 2
index_logg = 4
# Read isochrone data
with h5py.File(self.database, 'r') as h5_file:
model = h5_file[f'isochrones/{self.tag}/evolution'].attrs['model']
evolution = np.asarray(h5_file[f'isochrones/{self.tag}/evolution'])
if model == 'baraffe':
filters = list(h5_file[f'isochrones/{self.tag}/filters'])
magnitudes = np.asarray(h5_file[f'isochrones/{self.tag}/magnitudes'])
# Convert the h5py list of filters from bytes to strings
for i, item in enumerate(filters):
if isinstance(item, bytes):
filters[i] = item.decode('utf-8')
if model == 'baraffe':
if filters_color is not None:
index_color_1 = filters.index(filters_color[0])
index_color_2 = filters.index(filters_color[1])
if filter_mag is not None:
index_mag = filters.index(filter_mag)
if filters_color is not None:
mag_color_1 = griddata(points=evolution[:, 0:2],
values=magnitudes[:, index_color_1],
xi=np.stack((age_points, masses), axis=1),
method='linear',
fill_value='nan',
rescale=False)
mag_color_2 = griddata(points=evolution[:, 0:2],
values=magnitudes[:, index_color_2],
xi=np.stack((age_points, masses), axis=1),
method='linear',
fill_value='nan',
rescale=False)
color = mag_color_1-mag_color_2
if filter_mag is not None:
mag_abs = griddata(points=evolution[:, 0:2],
values=magnitudes[:, index_mag],
xi=np.stack((age_points, masses), axis=1),
method='linear',
fill_value='nan',
rescale=False)
teff = griddata(points=evolution[:, 0:2],
values=evolution[:, index_teff],
xi=np.stack((age_points, masses), axis=1),
method='linear',
fill_value='nan',
rescale=False)
logg = griddata(points=evolution[:, 0:2],
values=evolution[:, index_logg],
xi=np.stack((age_points, masses), axis=1),
method='linear',
fill_value='nan',
rescale=False)
return box.create_box(boxtype='isochrone',
model=self.tag,
filters_color=filters_color,
filter_mag=filter_mag,
color=color,
magnitude=mag_abs,
teff=teff,
logg=logg,
masses=masses)
@typechecked
def get_color_magnitude(self,
age: float,
masses: np.ndarray,
model: str,
filters_color: Tuple[str, str],
filter_mag: str) -> box.ColorMagBox:
"""
Function for calculating color-magnitude combinations from a selected isochrone.
Parameters
----------
age : float
Age (Myr) at which the isochrone data is interpolated.
masses : np.ndarray
Masses (Mjup) at which the isochrone data is interpolated.
model : str
Atmospheric model used to compute the synthetic photometry.
filters_color : tuple(str, str)
Filter names for the color as listed in the file with the isochrone data. The filter
names should be provided in the format of the SVO Filter Profile Service.
filter_mag : str
Filter name for the absolute magnitude as listed in the file with the isochrone data.
The value should be equal to one of the ``filters_color`` values.
Returns
-------
species.core.box.ColorMagBox
Box with the color-magnitude data.
"""
isochrone = self.get_isochrone(age=age,
masses=masses,
filters_color=None,
filter_mag=None)
model1 = read_model.ReadModel(model=model, filter_name=filters_color[0])
model2 = read_model.ReadModel(model=model, filter_name=filters_color[1])
if model1.get_parameters() != ['teff', 'logg']:
raise ValueError('Creating synthetic colors and magnitudes from isochrones is '
'currently only implemented for models with only Teff and log(g) '
'as free parameters. Please create an issue on the Github page if '
'additional functionalities are required.')
mag1 = np.zeros(isochrone.masses.shape[0])
mag2 = np.zeros(isochrone.masses.shape[0])
for i, mass_item in enumerate(isochrone.masses):
model_param = {'teff': isochrone.teff[i],
'logg': isochrone.logg[i],
'mass': mass_item,
'distance': 10.}
if np.isnan(isochrone.teff[i]):
mag1[i] = np.nan
mag2[i] = np.nan
warnings.warn(f'The value of Teff is NaN for the following isochrone sample: '
f'{model_param}. Setting the magnitudes to NaN.')
else:
for item_bounds in model1.get_bounds():
if model_param[item_bounds] <= model1.get_bounds()[item_bounds][0]:
mag1[i] = np.nan
mag2[i] = np.nan
warnings.warn(f'The value of {item_bounds} is {model_param[item_bounds]}, '
f'which is below the lower bound of the model grid '
f'({model1.get_bounds()[item_bounds][0]}). Setting the '
f'magnitudes to NaN for the following isochrone sample: '
f'{model_param}.')
elif model_param[item_bounds] >= model1.get_bounds()[item_bounds][1]:
mag1[i] = np.nan
mag2[i] = np.nan
warnings.warn(f'The value of {item_bounds} is {model_param[item_bounds]}, '
f'which is above the upper bound of the model grid '
f'({model1.get_bounds()[item_bounds][1]}). Setting the '
f'magnitudes to NaN for the following isochrone sample: '
f'{model_param}.')
if not np.isnan(mag1[i]):
mag1[i], _ = model1.get_magnitude(model_param)
mag2[i], _ = model2.get_magnitude(model_param)
if filter_mag == filters_color[0]:
abs_mag = mag1
elif filter_mag == filters_color[1]:
abs_mag = mag2
else:
raise ValueError('The argument of filter_mag should be equal to one of the two filter '
'values of filters_color.')
return box.create_box(boxtype='colormag',
library=model,
object_type='model',
filters_color=filters_color,
filter_mag=filter_mag,
color=mag1-mag2,
magnitude=abs_mag,
sptype=masses,
names=None)
@typechecked
def get_color_color(self,
age: float,
masses: np.ndarray,
model: str,
filters_colors: Tuple[Tuple[str, str],
Tuple[str, str]]) -> box.ColorColorBox:
"""
Function for calculating color-magnitude combinations from a selected isochrone.
Parameters
----------
age : float
Age (Myr) at which the isochrone data is interpolated.
masses : np.ndarray
Masses (Mjup) at which the isochrone data is interpolated.
model : str
Atmospheric model used to compute the synthetic photometry.
filters_colors : tuple(tuple(str, str), tuple(str, str))
Filter names for the colors as listed in the file with the isochrone data. The filter
names should be provided in the format of the SVO Filter Profile Service.
Returns
-------
species.core.box.ColorColorBox
Box with the color-color data.
"""
isochrone = self.get_isochrone(age=age,
masses=masses,
filters_color=None,
filter_mag=None)
model1 = read_model.ReadModel(model=model, filter_name=filters_colors[0][0])
model2 = read_model.ReadModel(model=model, filter_name=filters_colors[0][1])
model3 = read_model.ReadModel(model=model, filter_name=filters_colors[1][0])
model4 = read_model.ReadModel(model=model, filter_name=filters_colors[1][1])
if model1.get_parameters() != ['teff', 'logg']:
raise ValueError('Creating synthetic colors and magnitudes from isochrones is '
'currently only implemented for models with only Teff and log(g) '
'as free parameters. Please contact Tomas Stolker if additional '
'functionalities are required.')
mag1 = np.zeros(isochrone.masses.shape[0])
mag2 = np.zeros(isochrone.masses.shape[0])
mag3 = np.zeros(isochrone.masses.shape[0])
mag4 = np.zeros(isochrone.masses.shape[0])
for i, mass_item in enumerate(isochrone.masses):
model_param = {'teff': isochrone.teff[i],
'logg': isochrone.logg[i],
'mass': mass_item,
'distance': 10.}
if np.isnan(isochrone.teff[i]):
mag1[i] = np.nan
mag2[i] = np.nan
mag3[i] = np.nan
mag4[i] = np.nan
warnings.warn(f'The value of Teff is NaN for the following isochrone sample: '
f'{model_param}. Setting the magnitudes to NaN.')
else:
for item_bounds in model1.get_bounds():
if model_param[item_bounds] <= model1.get_bounds()[item_bounds][0]:
mag1[i] = np.nan
mag2[i] = np.nan
mag3[i] = np.nan
mag4[i] = np.nan
warnings.warn(f'The value of {item_bounds} is {model_param[item_bounds]}, '
f'which is below the lower bound of the model grid '
f'({model1.get_bounds()[item_bounds][0]}). Setting the '
f'magnitudes to NaN for the following isochrone sample: '
f'{model_param}.')
elif model_param[item_bounds] >= model1.get_bounds()[item_bounds][1]:
mag1[i] = np.nan
mag2[i] = np.nan
mag3[i] = np.nan
mag4[i] = np.nan
warnings.warn(f'The value of {item_bounds} is {model_param[item_bounds]}, '
f'which is above the upper bound of the model grid '
f'({model1.get_bounds()[item_bounds][1]}). Setting the '
f'magnitudes to NaN for the following isochrone sample: '
f'{model_param}.')
if not np.isnan(mag1[i]) and not np.isnan(mag2[i]) and\
not np.isnan(mag3[i]) and not np.isnan(mag4[i]):
mag1[i], _ = model1.get_magnitude(model_param)
mag2[i], _ = model2.get_magnitude(model_param)
mag3[i], _ = model3.get_magnitude(model_param)
mag4[i], _ = model4.get_magnitude(model_param)
return box.create_box(boxtype='colorcolor',
library=model,
object_type='model',
filters=filters_colors,
color1=mag1-mag2,
color2=mag3-mag4,
sptype=masses,
names=None)