-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathphot_modules.py
385 lines (275 loc) · 13.6 KB
/
phot_modules.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
380
381
382
383
384
385
"""
All the functions listed here requires the generation of the particle
information file.
"""
import numpy as np
import pandas as pd
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname("__file__"), '..')))
from functools import partial
import schwimmbad
import SynthObs
from SynthObs.SED import models
import FLARE
import FLARE.filters
from FLARE.photom import lum_to_M, M_to_lum
import h5py
def DTM_fit(Z, Age):
"""
Fit function from L-GALAXIES dust modeling
Formula uses Age in Gyr while the supplied Age is in Myr
"""
D0, D1, alpha, beta, gamma = 0.008, 0.329, 0.017, -1.337, 2.122
tau = 5e-5/(D0*Z)
DTM = D0 + (D1-D0)*(1.-np.exp(-alpha*(Z**beta)*((Age/(1e3*tau))**gamma)))
if np.isnan(DTM) or np.isinf(DTM): DTM = 0.
return DTM
def get_data(ii, tag, inp = 'FLARES'):
num = str(ii)
if inp == 'FLARES':
if len(num) == 1:
num = '0'+num
sim = rF"./data/FLARES_{num}_sp_info.hdf5"
else:
sim = rF"./data/EAGLE_{inp}_sp_info.hdf5"
with h5py.File(sim, 'r') as hf:
S_len = np.array(hf[tag+'/Galaxy'].get('S_Length'), dtype = np.int64)
G_len = np.array(hf[tag+'/Galaxy'].get('G_Length'), dtype = np.int64)
S_mass = np.array(hf[tag+'/Particle'].get('S_MassInitial'), dtype = np.float64)
S_Z = np.array(hf[tag+'/Particle'].get('S_Z_smooth'), dtype = np.float64)
S_age = np.array(hf[tag+'/Particle'].get('S_Age'), dtype = np.float64)*1e3
S_los = np.array(hf[tag+'/Particle'].get('S_los'), dtype = np.float64)
G_Z = np.array(hf[tag+'/Particle'].get('G_Z_smooth'), dtype = np.float64)
begin = np.zeros(len(S_len), dtype = np.int64)
end = np.zeros(len(S_len), dtype = np.int64)
begin[1:] = np.cumsum(S_len)[:-1]
end = np.cumsum(S_len)
gbegin = np.zeros(len(G_len), dtype = np.int64)
gend = np.zeros(len(G_len), dtype = np.int64)
gbegin[1:] = np.cumsum(G_len)[:-1]
gend = np.cumsum(G_len)
return S_mass, S_Z, S_age, S_los, G_Z, S_len, G_len, begin, end, gbegin, gend
def lum(sim, kappa, tag, BC_fac, inp = 'FLARES', IMF = 'Chabrier_300', LF = True, filters = ['FAKE.TH.FUV'], Type = 'Total', log10t_BC = 7., extinction = 'default'):
S_mass, S_Z, S_age, S_los, G_Z, S_len, G_len, begin, end, gbegin, gend = get_data(sim, tag, inp)
if np.isscalar(filters):
Lums = np.zeros(len(begin), dtype = np.float64)
else:
Lums = np.zeros((len(begin), len(filters)), dtype = np.float64)
model = models.define_model(F'BPASSv2.2.1.binary/{IMF}') # DEFINE SED GRID -
if extinction == 'default':
model.dust_ISM = ('simple', {'slope': -1.}) #Define dust curve for ISM
model.dust_BC = ('simple', {'slope': -1.}) #Define dust curve for birth cloud component
elif extinction == 'Calzetti':
model.dust_ISM = ('Starburst_Calzetti2000', {''})
model.dust_BC = ('Starburst_Calzetti2000', {''})
elif extinction == 'SMC':
model.dust_ISM = ('SMC_Pei92', {''})
model.dust_BC = ('SMC_Pei92', {''})
elif extinction == 'MW':
model.dust_ISM = ('MW_Pei92', {''})
model.dust_BC = ('MW_Pei92', {''})
elif extinction == 'N18':
model.dust_ISM = ('MW_N18', {''})
model.dust_BC = ('MW_N18', {''})
else: ValueError("Extinction type not recognised")
z = float(tag[5:].replace('p','.'))
# --- create rest-frame luminosities
F = FLARE.filters.add_filters(filters, new_lam = model.lam)
model.create_Lnu_grid(F) # --- create new L grid for each filter. In units of erg/s/Hz
for jj in range(len(begin)):
Masses = S_mass[begin[jj]:end[jj]]
Ages = S_age[begin[jj]:end[jj]]
Metallicities = S_Z[begin[jj]:end[jj]]
MetSurfaceDensities = S_los[begin[jj]:end[jj]]
# GMetallicities = G_Z[gbegin[jj]:gend[jj]]
# Mage = np.nansum(Masses*Ages)/np.nansum(Masses)
# Z = np.nanmean(GMetallicities)
#
# MetSurfaceDensities = DTM_fit(Z, Mage) * MetSurfaceDensities
if Type == 'Total':
tauVs_ISM = kappa * MetSurfaceDensities # --- calculate V-band (550nm) optical depth for each star particle
tauVs_BC = BC_fac * (Metallicities/0.01)
fesc = 0.0
elif Type == 'Pure-stellar':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = np.zeros(len(Masses))
fesc = 1.0
elif Type == 'Intrinsic':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = np.zeros(len(Masses))
fesc = 0.0
elif Type == 'Only-BC':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = BC_fac * (Metallicities/0.01)
fesc = 0.0
else:
ValueError(F"Undefined Type {Type}")
Lnu = models.generate_Lnu(model, Masses, Ages, Metallicities, tauVs_ISM, tauVs_BC, F, fesc = fesc, log10t_BC = log10t_BC) # --- calculate rest-frame Luminosity. In units of erg/s/Hz
Lums[jj] = list(Lnu.values())
return Lums#, S_len + G_len
def flux(sim, kappa, tag, BC_fac, inp = 'FLARES', IMF = 'Chabrier_300', filters = FLARE.filters.NIRCam_W, Type = 'Total', log10t_BC = 7., extinction = 'default'):
S_mass, S_Z, S_age, S_los, G_Z, S_len, G_len, begin, end, gbegin, gend = get_data(sim, tag, inp)
if np.isscalar(filters):
Fnus = np.zeros(len(begin), dtype = np.float64)
else:
Fnus = np.zeros((len(begin), len(filters)), dtype = np.float64)
model = models.define_model(F'BPASSv2.2.1.binary/{IMF}') # DEFINE SED GRID -
if extinction == 'default':
model.dust_ISM = ('simple', {'slope': -1.}) #Define dust curve for ISM
model.dust_BC = ('simple', {'slope': -1.}) #Define dust curve for birth cloud component
elif extinction == 'Calzetti':
model.dust_ISM = ('Starburst_Calzetti2000', {''})
model.dust_BC = ('Starburst_Calzetti2000', {''})
elif extinction == 'SMC':
model.dust_ISM = ('SMC_Pei92', {''})
model.dust_BC = ('SMC_Pei92', {''})
elif extinction == 'MW':
model.dust_ISM = ('MW_Pei92', {''})
model.dust_BC = ('MW_Pei92', {''})
elif extinction == 'N18':
model.dust_ISM = ('MW_N18', {''})
model.dust_BC = ('MW_N18', {''})
else: ValueError("Extinction type not recognised")
z = float(tag[5:].replace('p','.'))
F = FLARE.filters.add_filters(filters, new_lam = model.lam * (1. + z))
cosmo = FLARE.default_cosmo()
model.create_Fnu_grid(F, z, cosmo) # --- create new Fnu grid for each filter. In units of nJy/M_sol
for jj in range(len(begin)):
Masses = S_mass[begin[jj]:end[jj]]
Ages = S_age[begin[jj]:end[jj]]
Metallicities = S_Z[begin[jj]:end[jj]]
MetSurfaceDensities = S_los[begin[jj]:end[jj]]
# GMetallicities = G_Z[gbegin[jj]:gend[jj]]
#
# Mage = Masses*Ages/np.nansum(Masses)
# Z = np.nanmean(GMetallicities)
# if kappa == 0:
# tauVs = kappa * MetSurfaceDensities
# else:
# tauVs = DTM_fit(Z, Mage) * MetSurfaceDensities
if Type == 'Total':
tauVs_ISM = kappa * MetSurfaceDensities # --- calculate V-band (550nm) optical depth for each star particle
tauVs_BC = BC_fac * (Metallicities/0.01)
fesc = 0.0
elif Type == 'Pure-stellar':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = np.zeros(len(Masses))
fesc = 1.0
elif Type == 'Intrinsic':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = np.zeros(len(Masses))
fesc = 0.0
elif Type == 'Only-BC':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = BC_fac * (Metallicities/0.01)
fesc = 0.0
else:
ValueError(F"Undefined Type {Type}")
Fnu = models.generate_Fnu(model, Masses, Ages, Metallicities, tauVs_ISM, tauVs_BC, F, fesc = fesc, log10t_BC = log10t_BC) # --- calculate rest-frame flux of each object in nJy
Fnus[jj] = list(Fnu.values())
return Fnus
def get_lines(sim, kappa, tag, BC_fac, inp = 'FLARES', IMF = 'Chabrier_300', LF = False, lines = 'HI6563', Type = 'Total', log10t_BC = 7., extinction = 'default'):
S_mass, S_Z, S_age, S_los, G_Z, S_len, G_len, begin, end, gbegin, gend = get_data(sim, tag, inp)
# --- calculate intrinsic quantities
if extinction == 'default':
dust_ISM = ('simple', {'slope': -1.}) #Define dust curve for ISM
dust_BC = ('simple', {'slope': -1.}) #Define dust curve for birth cloud component
elif extinction == 'Calzetti':
dust_ISM = ('Starburst_Calzetti2000', {''})
dust_BC = ('Starburst_Calzetti2000', {''})
elif extinction == 'SMC':
dust_ISM = ('SMC_Pei92', {''})
dust_BC = ('SMC_Pei92', {''})
elif extinction == 'MW':
dust_ISM = ('MW_Pei92', {''})
dust_BC = ('MW_Pei92', {''})
elif extinction == 'N18':
dust_ISM = ('MW_N18', {''})
dust_BC = ('MW_N18', {''})
else: ValueError("Extinction type not recognised")
lum = np.zeros(len(begin), dtype = np.float64)
EW = np.zeros(len(begin), dtype = np.float64)
# --- initialise model with SPS model and IMF. Set verbose = True to see a list of available lines.
m = models.EmissionLines(F'BPASSv2.2.1.binary/{IMF}', dust_BC = dust_BC, dust_ISM = dust_ISM, verbose = False)
for jj in range(len(begin)):
Masses = S_mass[begin[jj]:end[jj]]
Ages = S_age[begin[jj]:end[jj]]
Metallicities = S_Z[begin[jj]:end[jj]]
MetSurfaceDensities = S_los[begin[jj]:end[jj]]
if Type == 'Total':
tauVs_ISM = kappa * MetSurfaceDensities # --- calculate V-band (550nm) optical depth for each star particle
tauVs_BC = BC_fac * (Metallicities/0.01)
fesc = 0.0
elif Type == 'Pure-stellar':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = np.zeros(len(Masses))
fesc = 1.0
elif Type == 'Intrinsic':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = np.zeros(len(Masses))
fesc = 0.0
elif Type == 'Only-BC':
tauVs_ISM = np.zeros(len(Masses))
tauVs_BC = BC_fac * (Metallicities/0.01)
fesc = 0.0
else:
ValueError(F"Undefined Type {Type}")
o = m.get_line_luminosity(lines, Masses, Ages, Metallicities, tauVs_BC = tauVs_BC, tauVs_ISM = tauVs_ISM, verbose = False, log10t_BC = log10t_BC)
lum[jj] = o['luminosity']
EW[jj] = o['EW']
return lum, EW
def get_lum(sim, kappa, tag, BC_fac, IMF = 'Chabrier_300', bins = np.arange(-24, -16, 0.5), inp = 'FLARES', LF = True, filters = ['FAKE.TH.FUV'], Type = 'Total', log10t_BC = 7., extinction = 'default'):
try:
Lums = lum(sim, kappa, tag, BC_fac = BC_fac, IMF=IMF, inp=inp, LF=LF, filters=filters, Type = Type, log10t_BC = log10t_BC, extinction = extinction)
except Exception as e:
Lums = np.ones(len(filters))*np.nan
print (e)
if LF:
tmp, edges = np.histogram(lum_to_M(Lums), bins = bins)
return tmp
else:
return Lums
def get_lum_all(kappa, tag, BC_fac, IMF = 'Chabrier_300', bins = np.arange(-24, -16, 0.5), inp = 'FLARES', LF = True, filters = ['FAKE.TH.FUV'], Type = 'Total', log10t_BC = 7., extinction = 'default'):
print (f"Getting luminosities for tag {tag} with kappa = {kappa}")
if inp == 'FLARES':
df = pd.read_csv('weight_files/weights_grid.txt')
weights = np.array(df['weights'])
sims = np.arange(0,len(weights))
calc = partial(get_lum, kappa = kappa, tag = tag, BC_fac = BC_fac, IMF = IMF, bins = bins, inp = inp, LF = LF, filters = filters, Type = Type, log10t_BC = log10t_BC, extinction = extinction)
pool = schwimmbad.MultiPool(processes=8)
dat = np.array(list(pool.map(calc, sims)))
pool.close()
if LF:
hist = np.sum(dat, axis = 0)
out = np.zeros(len(bins)-1)
err = np.zeros(len(bins)-1)
for ii, sim in enumerate(sims):
err+=np.square(np.sqrt(dat[ii])*weights[ii])
out+=dat[ii]*weights[ii]
return out, hist, np.sqrt(err)
else:
return dat
else:
out = get_lum(00, kappa = kappa, tag = tag, BC_fac = BC_fac, IMF = IMF, bins = bins, inp = inp, LF = LF, filters = filters, Type = Type, log10t_BC = log10t_BC, extinction = extinction)
return out
def get_flux(sim, kappa, tag, BC_fac, IMF = 'Chabrier_300', inp = 'FLARES', filters = FLARE.filters.NIRCam, Type = 'Total', log10t_BC = 7., extinction = 'default'):
try:
Fnus = flux(sim, kappa, tag, BC_fac = BC_fac, IMF=IMF, inp=inp, filters=filters, Type = Type, log10t_BC = log10t_BC, extinction = extinction)
except Exception as e:
Fnus = np.ones(len(filters))*np.nan
print (e)
return Fnus
def get_flux_all(kappa, tag, BC_fac, IMF = 'Chabrier_300', inp = 'FLARES', filters = FLARE.filters.NIRCam, Type = 'Total', log10t_BC = 7., extinction = 'default'):
print (f"Getting fluxes for tag {tag} with kappa = {kappa}")
if inp == 'FLARES':
df = pd.read_csv('weight_files/weights_grid.txt')
weights = np.array(df['weights'])
sims = np.arange(0,len(weights))
calc = partial(get_flux, kappa = kappa, tag = tag, BC_fac = BC_fac, IMF = IMF, inp = inp, filters = filters, Type = Type, log10t_BC = log10t_BC, extinction = extinction)
pool = schwimmbad.MultiPool(processes=8)
out = np.array(list(pool.map(calc, sims)))
pool.close()
else:
out = get_flux(00, kappa = kappa, tag = tag, BC_fac = BC_fac, IMF = IMF, inp = inp, filters = filters, Type = Type, log10t_BC = log10t_BC, extinction = extinction)
return out