-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsin_ifu_clean.py
executable file
·2466 lines (2269 loc) · 91.3 KB
/
sin_ifu_clean.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import gzip
import shutil
import warnings
import numpy as np
import multiprocessing as mp
import illustris_python as il
from os import remove
from astropy.io import fits
from scipy.interpolate import interp1d
from scipy.spatial.distance import cdist
from astropy.cosmology import Planck15 as cosmo
warnings.filterwarnings("ignore")
M_proton = 1.67262192e-24 # Proton mass [gr]
X_h = 0.76 # hydrogen mass fraction
k_B = 1.3807e-16 # Boltzmann constant in cgs [cm**2 g s**-2 K**-1]
gamma = 5/3 # adiabatic index
M_unit__E_unit = 1e10 #UnitMass/UnitEnergy in cgs,
#UnitEnergy = UnitMass * UnitLength^2 / UnitTime^2
#(UnitLength is 1 kpc, UnitTime is 1 Gyr), so their ratio is 10**10
def compress_gzip(file, compresslevel=6):
with open(file, 'rb') as f_in:
with gzip.open(f'{file}.gz', mode='wb', compresslevel=compresslevel) as f_comp:
shutil.copyfileobj(f_in, f_comp)
remove(file)
def periodicfix(x, boxsize=35000):
if (np.min(x) < boxsize/10) & (np.max(x) > boxsize - boxsize/10):
x = x + boxsize/2
for j in range(3):
for i in range(len(x)):
if x[i,j] > boxsize:
x[i,j] = x[i,j]- boxsize
x = x - boxsize/2
return(x)
def periodicfix_cm(x, cm, boxsize=35000):
if (np.min(x) < boxsize/10) & (np.max(x) > boxsize - boxsize/10):
cm = cm + boxsize/2
for i in range(3):
if cm[i] > boxsize:
cm[i] = cm[i] - boxsize
cm = cm - boxsize/2
return(cm)
def mk_particle_files(subhalo_id, snap, basePath, ex=[1,0,0], FOV=19, overwrite=True, view=0, outdir=''):
"""
Makes the stellar particle and gas cells files for a subhalo living in
snapshot snap, observed in ex direction covering a field of view
of 2FOV of diameter.
Arguments:
----------
subhalo_id: subhalo index in the snapshot. (integer)
snap: snapshot number. (integer with value in [1;99])
basePath: path to simulation data. (string)
ex (=[1,0,0]): unitary 3-D vector indicating the direction in which
the observer is placed. (2-sized float array)
FOV (=19): radius of the circular field of view in arcsec. (float)
view (=0): view identifier. (integer)
overwrite: (bool)
outdir: path where the output files are saved. (string)
Returns:
-------
-
Outputs:
-------
Stellar particles and gas cells information in two individual
files:
'snap'+snap+'_shalo'+subhalo_id+'_'+view+'_stars.dat'
Contains as many rows as stellar particles in the FOV, columns are defined as:
- x, y, z coordinates relative to the observer in physical kpcs
(z in the direction of the observer).
- vx, vy, vz velocity components relative to the volume in km/s.
- age in Gyrs.
- metallicity in Z/H.
- mass in solar masses.
'snap'+snap+'_shalo'+subhalo_id+'_'+view+'_gas.dat'
Contains as many rows as gas cells in the FOV, columns are defined as:
- x, y, z coordinates relative to the observer in physical kpcs
(z in the direction of the observer).
- vx, vy, vz velocity components relative to the volume in km/s.
- metallicity in Z/H.
- volume in kpc**3.
- density in solar masses/ kpc**3.
- star formation rate in solar masses per yr.
- temperature in K.
- Av extinction index.
- mass in solar masses.
"""
vx_ = [1,0,0]
vy_ = [0,1,0]
vz_ = [0,0,1]
R3_ = np.array([[1,0,0],[0,1,0],[0,0,1]])
Ev = np.transpose(np.array([vx_,vy_,vz_]))
snapz_dict = {99:0., 98:0.012, 97:0.023, 96:0.035, 95:0.048, 94:0.06,
93:0.073, 92:0.086, 91:0.1, 90:0.11, 89:0.13, 88:0.14, 87:0.15,
86:0.17, 85:0.18}
snapa_dict = {99:1., 98:0.9885, 97:0.9771, 96:0.9657, 95:0.9545, 94:0.9433,
93:0.9322, 92:0.9212, 91:0.9091, 90:0.8993, 89:0.8885, 88:0.8778,
87:0.8671, 86:0.8564, 85:0.8459}
snapt_dict = {87:0.8674917093619414, 88:0.8757516765159388, 89:0.8882893272206793,
90:0.9010064725120812, 91:0.9095855560793044, 92:0.9226075876597282,
93:0.9313923498515226, 94:0.9447265771954694, 95:0.9537219490392906,
96:0.9673758568617342, 97:0.9765868876036025, 98:0.99056814006128}
h = cosmo.H0.value * 1e-2
fields_s = ['GFM_StellarFormationTime', 'Masses', 'GFM_Metallicity', \
'Coordinates', 'Velocities']
fields_g = ['StarFormationRate', 'Coordinates', 'Velocities', 'Density', \
'GFM_Metallicity', 'Masses', 'InternalEnergy', 'ElectronAbundance']
halo_all = il.groupcat.loadSubhalos(basePath, snap, fields=['SubhaloGrNr'])
halo_id = halo_all[subhalo_id]
redshift = snapz_dict[snap]
a = snapa_dict[snap]
box_side_half_kpc = FOV * cosmo.kpc_proper_per_arcmin(redshift).value/60.
dist = cosmo.comoving_distance(redshift).value * 1e3
Halo_stars = il.snapshot.loadHalo(basePath, snap, halo_id, partType=4, fields=fields_s)
#Halo_stars = il.subhalo.subfind(basePath, snap, subhalo, partType=4, fields=fields_s)
Halo_stars_age_orig = Halo_stars['GFM_StellarFormationTime'][:]
Halo_stars_mass = Halo_stars['Masses'][Halo_stars_age_orig>=0] * 1e10 / h
Halo_stars_coord = periodicfix(Halo_stars['Coordinates'][Halo_stars_age_orig>=0, :]) * a / h
Halo_stars_vel = Halo_stars['Velocities'][Halo_stars_age_orig>=0, :] * np.sqrt(a)
vx, vy, vz = Halo_stars_vel[:,0], Halo_stars_vel[:,1], Halo_stars_vel[:,2]
Halo_stars_met = Halo_stars['GFM_Metallicity'][Halo_stars_age_orig>=0]
Halo_stars_age = (1-Halo_stars_age_orig[Halo_stars_age_orig>=0])*cosmo.age(1/snapt_dict[snap]-1).value
Halo_gas = il.snapshot.loadHalo(basePath, snap, halo_id, partType=0, fields=fields_g)
Halo_gas_mass = Halo_gas['Masses'][:] * 1e10 / h
Halo_gas_coord = periodicfix(Halo_gas['Coordinates'][:, :]) * a / h
Halo_gas_vel = Halo_gas['Velocities'][:, :] * np.sqrt(a)
vx_g, vy_g, vz_g = Halo_gas_vel[:,0], Halo_gas_vel[:,1], Halo_gas_vel[:,2]
Halo_gas_met = Halo_gas['GFM_Metallicity'][:]
Halo_gas_dens = Halo_gas['Density'][:] * 1e10 * h**2 / a**3
Halo_gas_vol = Halo_gas_mass / Halo_gas_dens
Halo_gas_vol = (Halo_gas_vol/(4.0*np.pi/3.0))**(1./3.0)*(3.08567758e19*100)
Halo_gas_dens = Halo_gas_dens/(3.08567758e19*100)**3.0*1.9891e30/1.67262178e-27
Halo_sfri = Halo_gas['StarFormationRate'][:]
TE = Halo_gas['InternalEnergy'][:]
EA = Halo_gas['ElectronAbundance'][:]
MMW = M_proton * 4. / (1. + 3.*X_h + 4.*X_h*EA)
temp_g = (gamma-1.) * TE * MMW * M_unit__E_unit / k_B
Halo_Av_g = Halo_gas_met*(3.0*1.67262e-24*np.pi*Halo_gas_dens*Halo_gas_vol)/(4.0*np.log(10.)*3.0*5494e-8)
Halo_Av_g = np.where(Halo_gas_met > (10.0**(-0.59)*0.0127), \
Halo_Av_g/(10.0**(2.21-1.0)), \
Halo_Av_g/(10.0**(2.21-1.0)/(Halo_gas_met/0.0127)**(3.1-1.0)))
cm = periodicfix_cm(Halo_stars['Coordinates'][Halo_stars_age_orig>=0, :], il.groupcat.loadSingle(basePath,snap,subhaloID=subhalo_id)["SubhaloPos"]) * a / h
xyz = (Halo_stars_coord - cm)
x = xyz[:,0]
y = xyz[:,1]
z = xyz[:,2]
xyz_g = (Halo_gas_coord - cm)
x_g = xyz_g[:,0]
y_g = xyz_g[:,1]
z_g = xyz_g[:,2]
if not overwrite:
if os.path.exists(outdir + '/snap_'+str(snap)+'_shalo'+str(subhalo_id)+'_0_stars.dat') &\
os.path.exists(outdir + '/snap_'+str(snap)+'shalo'+str(subhalo_id)+'_0_gas.dat'):
print('Output files already exist and overwrite option is off.')
else:
try:
print('For snap-'+str(snap)+' running subhalo '+str(subhalo_id)+' in halo '+str(halo_id))
obs = np.dot(np.dot(Ev,R3_),ex)*dist
xyz0 = obs
x0 = xyz0[0]
y0 = xyz0[1]
z0 = xyz0[2]
Rc = dist #np.sqrt(np.sum(xyz0**2))
red_0 = reds_cos(Rc/1e3)
Ra = Rc #/(1+red_0)
A1 = np.arctan2(y0,z0)
A2 = np.arcsin(x0/Ra)
R1 = np.array([[1,0,0],[0,np.cos(A1),-np.sin(A1)],[0,np.sin(A1),np.cos(A1)]])
R2 = np.array([[np.cos(A2),0,-np.sin(A2)],[0,1,0],[np.sin(A2),0,np.cos(A2)]])
R3 = np.array([[np.cos(A2),-np.sin(A2),0],[np.sin(A2),np.cos(A2),0],[0,0,1]])
Ve = np.array([x,y,z])
Vf = np.dot(np.dot(R2,R1),Ve)
stars_in_brick = np.nonzero((np.abs(Vf[0])<box_side_half_kpc) & (np.abs(Vf[1])<box_side_half_kpc))[0]
stars_in_tube = stars_in_brick[(Vf[0][stars_in_brick]**2+Vf[1][stars_in_brick]**2)<box_side_half_kpc**2]
mass_b = Halo_stars_mass[stars_in_tube]
meta_b = Halo_stars_met[stars_in_tube]
age_s_b = Halo_stars_age[stars_in_tube]
x_b = Vf[0][stars_in_tube]
y_b = Vf[1][stars_in_tube]
z_b = Vf[2][stars_in_tube]
Ve = np.array([vx,vy,vz])
Vf = np.dot(np.dot(R2,R1),Ve)
vx_b = Vf[0][stars_in_tube]
vy_b = Vf[1][stars_in_tube]
vz_b = Vf[2][stars_in_tube]
Ve = np.array([x_g,y_g,z_g])
Vf = np.dot(np.dot(R2,R1),Ve)
gas_in_brick = np.nonzero((np.abs(Vf[0])<box_side_half_kpc) & (np.abs(Vf[1])<box_side_half_kpc))[0]
gas_in_tube = gas_in_brick[(Vf[0][gas_in_brick]**2+Vf[1][gas_in_brick]**2)<box_side_half_kpc**2]
mass_g_b = Halo_gas_mass[gas_in_tube]
meta_g_b = Halo_gas_met[gas_in_tube]
temp_g_b = temp_g[gas_in_tube]
volm_b = Halo_gas_vol[gas_in_tube]
dens_b = Halo_gas_dens[gas_in_tube]
sfri_b = Halo_sfri[gas_in_tube]
Av_g_b = Halo_Av_g[gas_in_tube]
x_g_b = Vf[0][gas_in_tube]
y_g_b = Vf[1][gas_in_tube]
z_g_b = Vf[2][gas_in_tube]
Ve = np.array([vx_g,vy_g,vz_g])
Vf = np.dot(np.dot(R2,R1),Ve)
vx_g_b = Vf[0][gas_in_tube]
vy_g_b = Vf[1][gas_in_tube]
vz_g_b = Vf[2][gas_in_tube]
total = np.array(np.column_stack((x_b,y_b,z_b,vx_b,vy_b,vz_b,age_s_b,meta_b,mass_b)), dtype=np.float32)
np.savetxt(outdir + '/snap'+str(snap)+'_shalo'+str(subhalo_id)+'_'+str(view)+'_stars.dat', total, delimiter = ' ')
totalg = np.array(np.column_stack((x_g_b,y_g_b,z_g_b,vx_g_b,vy_g_b,vz_g_b,meta_g_b,volm_b,dens_b,sfri_b,temp_g_b,Av_g_b,mass_g_b)), dtype=np.float32)
np.savetxt(outdir + '/snap'+str(snap)+'_shalo'+str(subhalo_id)+'_'+str(view)+'_gas.dat', totalg, delimiter = ' ')
except OSError:
print('Disk quota exceeded')
def get_F0(RSS_127, R_eff_kpc, kpc_per_arcsec, wl, n_radii=2.):
"""
Calculates the average flux in the wavelngth range 5415-6989 Ang
at a n_radii*R_eff_kpc distance from the centre of the IFU.
Calculated of the fiber spectra.
Arguments:
----------
RSS_127: Raw stacked spectrum for the largest IFU. ((381,w)-sized float array)
R_eff_kpc: Effective radius in kpc. (float)
kpc_per_arcsec: kpc per arcsec scale. (float)
wl: wavelength array. (w-sized float array)
n_radii: multiplicative factor to determine at what distrance from the centre F0
should be calculated. (float)
Returns:
-------
F0: average flux in the wavelngth range 5415-6989 Ang at a n_radii*R_eff_kpc
distance from the centre of the IFU in the same units as RSS_127.
"""
fib_index= {#2: np.array([5,7,18,19,30,31]),
3: np.array([4,8,17,20,29,32,41,42,43,52,53,54]),
4: np.array([3,9,16,21,28,33,40,44,51,55,62,63,64,65,72,73,74,75]),
5: np.array([2,10,15,22,27,34,39,45,50,56,61,66,71,76,81,82,83,84,85,90,91,92,93,94]),
6: np.array([1,11,14,23,26,35,38,46,49,57,60,67,70,77,80,86,89,95,98,99,100,101,102,103,106,107,108,109,110,111]),
7: np.array([0,12,13,24,25,36,37,47,48,58,59,68,69,78,79,87,88,96,97,104,105]+list(np.arange(112,127)))}
manga_ifu_designs = np.arange(3,8)
manga_ifu_diameters_arcsec = np.array([12.5,17.5,22.5,27.5,32.5])
R_arcsec = n_radii * R_eff_kpc / kpc_per_arcsec
n_fib_arg = np.argmin(np.abs(2*R_arcsec-manga_ifu_diameters_arcsec))
n_fib = manga_ifu_designs[n_fib_arg]
print(n_fib)
fib_ind_donut = np.concatenate([fib_index[n_fib], fib_index[n_fib]+127, fib_index[n_fib]+254])
min_r = np.searchsorted(wl, 5415.)
max_r = np.searchsorted(wl, 6989.)
RSS_127_ = np.where(RSS_127==0, np.nan, RSS_127)
F0 = np.nanmean(RSS_127_[min_r:max_r, fib_ind_donut])
return F0
def noise_sig(wave):
"""
Source: https://github.com/hjibarram/mock_ifu
"""
w1=3900
w2=10100
dw2=100
dw1=100
s=1./(1.+np.exp(-(wave-w1)/dw1))/(1.+np.exp((wave-w2)/dw2))+1.0
return s
def get_noise(wl, F0, nspec, SN=5., realization=True):
"""
"""
s = noise_sig(wl)
SN = SN/1.7361 #factor due to recombination enhancement of SN
if realization:
return 2. * F0 * 1.5 / SN * np.random.randn(nspec, wl.size) / np.tile(s, (nspec,1))
else:
return 2. * F0 * 1.5 / SN / np.tile(s, (nspec,1))
def arg_ages(age_s):
"""
Source: https://github.com/hjibarram/mock_ifu
"""
age_a=[]
nssp=len(age_s)
ban=0
age_t=sorted(age_s)
age_a.extend([age_t[0]])
for i in range(1, nssp):
if age_t[i-1] > age_t[i]:
ban =1
if age_t[i-1] < age_t[i] and ban == 0:
age_a.extend([age_t[i]])
return age_a[::-1]
def num_ages(age_s):
"""
Source: https://github.com/hjibarram/mock_ifu
"""
age_a=[]
nssp=len(age_s)
ban=0
age_t=sorted(age_s)
age_a.extend([age_t[0]])
for i in range(1, nssp):
if age_t[i-1] > age_t[i]:
ban =1
if age_t[i-1] < age_t[i] and ban == 0:
age_a.extend([age_t[i]])
n_age=len(age_a)
return n_age
def shifts(spect_s, wave, dlam):
"""
Doppler shifts a given spectrum.
Arguments:
----------
spect_s: spectrum to shift. (w-sized float array)
wave: wavelengths associeted to the spec. (w-sized float array)
dlam: shift in wavelength. (float)
Returns:
-------
spect_f: shifted spectrum. (w-sized float array)
Source: https://github.com/hjibarram/mock_ifu
"""
wave_f = wave * dlam
spect_f = interp1d(wave_f, spect_s, bounds_error=False, fill_value=0.)(wave)
nt = np.where(spect_f == 0)[0]
return spect_f
def cube_conv_lsf(wavelengths, spec, resolution, delta_wl=100):
"""
Calculates the convolution between a spectrum and a light spread
function that is wavelength dependent.
Arguments
----------
wavelengths: float array
Set of wavelengths associated with the input spectrum
[]
spec: float array
The spectrum.
resolution:
'MaNGA', manga median resolution
np.single, fixed resolution per wl
float array, same shape as wavelengths
Defines the light spread function resolution as FWHM.
[-]
Returns
-------
convolution: float array
The convolved spectrum.
"""
if spec.size!=wavelengths.size:
print('Spec size ',spec.size,' does not match wavelengths size ', wavelengths.size)
if resolution=='MaNGA':
manga_wave = np.load('libs/MaNGA_wl_LIN.npy')
median_resolution = np.load('libs/MaNGA_median_spec_res_LIN.npy')
resolution = np.ones_like(wavelengths) * 2000. # 2000 is aprox the mean resolution, will be used for edges
int_func_res = interp1d(manga_wave, median_resolution)
min_index = np.searchsorted(wavelengths, manga_wave[0], side='left')
max_index = np.searchsorted(wavelengths, manga_wave[-1], side='right')
int_res = int_func_res(wavelengths[min_index:max_index-1])
resolution[min_index:max_index-1] = int_res
elif np.array(resolution).size==1:
resolution = resolution * np.ones_like(wavelengths)
convolution = np.zeros_like(spec)
for ii in range(len(wavelengths)-2):
initial_ind = ii - np.min([ii, delta_wl])
final_ind = np.min([ii+delta_wl, len(wavelengths)-1])
lsf = line_spread_function(wavelengths[initial_ind:final_ind], resolution[ii], wavelengths[ii])
convolution[ii] = simpson_r(lsf * spec[initial_ind:final_ind], wavelengths[initial_ind:final_ind], 0, wavelengths[initial_ind:final_ind].size-2)
return convolution
def line_spread_function(x, res, x0):
"""
Calculates the LSF as a gaussian at xo for a range of x,
given the resolution.
Arguments
----------
x: (float array) wavelengths
res: (float) resolution as FWHM at x0
x0: (float) central wavelength
Returns
-------
lsf: (float array) line spread function at each x contributed at x0
"""
sigma = x0 / res # if res is FWHM add this * 2. * np.sqrt(2.*np.log(2.)))
lsf = np.exp(-(x-x0)**2 / (2.*sigma**2)) #/ (sigma * np.sqrt(np.pi*2.))
lsf = lsf / simpson_r(lsf, x, 0, x.size-2)
return lsf
def simpson_r(f,x,i1,i2,typ=0):
"""
Integral calculation with Simpson method.
Arguments:
----------
f: function to integrate. (n-sized float array)
x: domain of f. (n-sized float array)
i1: initial integration index. (integer)
i2: final integration index. (integer)
Returns:
-------
Area under the function f with Simpson's numerical approximation.
Source: https://github.com/hjibarram/mock_ifu
"""
n = (i2-i1) * 1.0
if n % 2:
n = n + 1.0
i2 = i2 + 1
b = x[i2]
a = x[i1]
h = (b-a) / n
s = f[i1] + f[i2]
n = np.int32(n)
dx = b - a
for ii in range(1, n, 2):
s += 4 * f[i1+ii]
for i in range(2, n-1, 2):
s += 2 * f[i1+ii]
if typ == 0:
return s * h / 3.0
if typ == 1:
return s * h / 3.0 / dx
def A_l(Rv,l):
"""
Source: https://github.com/hjibarram/mock_ifu
based in Cardelli+()
"""
l = l/10000.; #Amstrongs to Microns
x = 1.0/l
Arat = np.zeros(len(x))
for i in range(0, len(x)):
if x[i] > 1.1 and x[i] <= 3.3:
y = (x[i]-1.82)
ax = 1+0.17699*y-0.50447*y**2-0.02427*y**3+0.72085*y**4+0.01979*y**5-0.77530*y**6+0.32999*y**7
bx = 1.41338*y+2.28305*y**2+1.07233*y**3-5.38434*y**4-0.62251*y**5+5.30260*y**6-2.09002*y**7
if x[i] <= 1.1 and x[i] > 0.3:
ax = 0.574*x[i]**1.61
bx = -0.527*x[i]**1.61
if x[i] > 3.3 and x[i] <= 8.0:
if x[i] > 5.9 and x[i] <= 8.0:
Fa = -0.04473*(x[i]-5.9)**2.0-0.009779*(x[i]-5.9)**3.0
Fb = 0.2130*(x[i]-5.9)**2.0+0.1207*(x[i]-5.9)**3.0
else:
Fa = 0.0
Fb = 0.0
ax = 1.752-0.316*x[i]-0.104/((x[i]-4.67)**2.0+0.341)+Fa
bx = -3.090+1.825*x[i]+1.206/((x[i]-4.62)**2.0+0.263)+Fb
if x[i] > 8.0:
ax = -1.073-0.628*(x[i]-8.0)+0.137*(x[i]-8.0)**2.0-0.070*(x[i]-8.0)**3.0
bx = 13.670+4.257*(x[i]-8.0)-0.420*(x[i]-8.0)**2.0+0.374*(x[i]-8.0)**3.0
val = ax+bx/Rv
if val < 0:
val = 0
Arat[i] = val
return Arat
def reds_cos(dis):
"""
Source: https://github.com/hjibarram/mock_ifu
"""
red = np.arange(0, 3, .01)
dist = cosmo.lookback_time(red).value * 1e3 * 0.307
#dist = cosmo.comoving_distance(red).value
z = interp1d(dist, red, kind='linear', bounds_error=False)(dis)
return z
def val_definition_l(val, val_ssp):
"""
Source: https://github.com/hjibarram/mock_ifu
"""
val_l = np.array(val)
n_val = len(val_ssp)
ind = []
for i in range(0, n_val):
if i < n_val-1:
dval = (val_ssp[i+1]+val_ssp[i])/2.
else:
dval = val_ssp[i]+1.0
if i == 0:
val1 = 0
else:
val1 = val2
val2 = dval
nt = np.where((val_l > val1) & (val_l <= val2))
ind.extend([nt[0]])
return ind
def associate_ssp(age_s, met_s, age, met):
"""
Given the n-stellar particles' ages and metallicities, associate to the
template's m-ages and metallicities.
Arguments:
----------
age_s: stellar particles ages in Gyrs. (n-sized float array)
met_s: stellar particles metallicities in Z/H. (n-sized float array)
age: template ages in Gyrs. (m-sized float array)
met: template metallicities in Z/H. (m-sized float array)
Returns:
-------
ind_ssp: indices in the SSP template per particle. (n-sized integer array
with values in [0; m])
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
age_a = []
met_a = []
nssp = len(met_s)
ban = 0
ban1 = 0
age_t = sorted(age_s)
met_t = met_s
age_a.extend([age_t[0]])
met_a.extend([met_t[0]])
ind_ssp = np.zeros((len(age)), dtype=np.int64)
#ind_ssp[:] = np.nan
for ii in range(1, nssp):
if age_t[ii-1] > age_t[ii]:
ban =1
if age_t[ii-1] < age_t[ii] and ban == 0:
age_a.extend([age_t[ii]])
if met_t[ii-1] > met_t[ii]:
ban1 =1
if met_t[ii-1] < met_t[ii] and ban1 == 0:
met_a.extend([met_t[ii]])
ind_age = val_definition_l(age,age_a)
n_age = len(age_a)
n_met = len(met_a)
for ii in range(0, n_age):
if len(ind_age[ii]) > 0:
ind_met = val_definition_l(met[ind_age[ii]], met_a)
for jj in range(0, n_met):
if len(ind_met[jj]) > 0:
nt = np.where((age_s == age_a[ii]) & (met_s == met_a[jj]))[0]
ind_ssp[ind_age[ii][ind_met[jj]]] = nt[0]
return ind_ssp
def associate_gas(phot_s, met_s, den_s, tem_s, phot, met, den, tem):
"""
Given the n-gas cells' phot-io, metallicities, densities and temperatures,
associate to the template's m-phot-io, metallicities, densities and temperatures.
Arguments:
----------
phot: gas cells photo-ionization factor. (n-sized float array)
met: gas cells metallicities in Z/H. (n-sized float array)
den: gas cells densities in
tem: gas cells temperatures in K. (n-sized float array)
phot_s: template photo-ionization factor. (m-sized float array)
met_s: template metallicities in Z/H. (m-sized float array)
den_s: template desities
tem_s: template temperatures in K. (m-sized float array)
Returns:
-------
ind_gas: indices in the gas template per gas cell. (n-sized integer array
with values in [0; m])
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
phot_s = np.array(phot_s)
met_s= np.array(met_s)
den_s= np.array(den_s)
tem_s= np.array(tem_s)
met_s = met_s*0.02#127
phot_a = []
met_a = []
den_a = []
tem_a = []
nssp = len(met_s)
ban = 0
ban1 = 0
ban2 = 0
ban3 = 0
phot_t = sorted(phot_s)
met_t = sorted(met_s)
den_t = sorted(den_s)
tem_t = sorted(tem_s)
phot_a.extend([phot_t[0]])
met_a.extend([met_t[0]])
den_a.extend([den_t[0]])
tem_a.extend([tem_t[0]])
ind_gas = np.zeros((len(met)), dtype = np.int64)
ind_gas[:] = -100
for i in range(1, nssp):
if phot_t[i-1] > phot_t[i]:
ban = 1
if phot_t[i-1] < phot_t[i] and ban == 0:
phot_a.extend([phot_t[i]])
if met_t[i-1] > met_t[i]:
ban1 = 1
if met_t[i-1] < met_t[i] and ban1 == 0:
met_a.extend([met_t[i]])
if den_t[i-1] > den_t[i]:
ban2 = 1
if den_t[i-1] < den_t[i] and ban2 == 0:
den_a.extend([den_t[i]])
if tem_t[i-1] > tem_t[i]:
ban3 = 1
if tem_t[i-1] < tem_t[i] and ban3 == 0:
tem_a.extend([tem_t[i]])
n_phot = len(phot_a)
n_met = len(met_a)
n_den = len(den_a)
n_tem = len(tem_a)
ind_phot = val_definition_l(phot, phot_a)
for i in range(0, n_phot):
if len(ind_phot[i]) > 0:
ind_met = val_definition_l(met[ind_phot[i]],met_a)
for j in range(0, n_met):
if len(ind_met[j]) > 0:
ind_den = val_definition_l(den[ind_phot[i][ind_met[j]]],den_a)
for k in range(0, n_den):
if len(ind_den[k]) > 0:
ind_tem = val_definition_l(tem[ind_phot[i][ind_met[j][ind_den[k]]]],tem_a)
for h in range(0, n_tem):
if len(ind_tem[h]) > 0:
nt = np.nonzero((phot_s == phot_a[i]) & (met_s == met_a[j]) & (den_s == den_a[k]) & (tem_s == tem_a[h]))[0]
ind_gas[ind_phot[i][ind_met[j][ind_den[k][ind_tem[h]]]]]=nt[0]
return ind_gas
def associate_pho(ssp_temp, wave, age_s, met_s, ml, mass, met, \
Rs=1, n_h=1, wl_i=3540.0, wl_f=5717.0):
"""
Given the n-gas cells' ages, metallicities and masses, this function
associates to the mass-weighted SSP template's m-ages and metallicities
to obtain a spectrum produced by the new-born stars. Calculates the
photo-ionization factor from the energy emitted in the blue wavelength
range.
Arguments:
----------
ssp_temp: SSP template flux. ((m,w)-sized float array)
wave: wavelength associated with the SSP spectra in Ang. (w-sized float array)
age_s: template ages in Gyrs. (m-sized float array)
met_s: template metallicities in Z/H. (m-sized float array)
ml: mass-luminosity weighting factor. (m-sized float array)
met: star forming gas cells metallicities in Z/H. (n-sized float array)
mass: star forming gas cells masses in solar mass. (n-sized float array)
Rs: Stromgren radius (not used).
n_h: (not used)
wl_i (=3540 Ang): initial integration wavelength. (float)
wl_f (=5717 Ang): final integration wavelength. (float)
Returns:
-------
Photo-ionizing factor in log-scale (n-sized float array)
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
vel_light = 299792458.0
h_p = 6.62607004e-34
age = np.ones(len(met))*2.5e6/1e9
age_a = []
met_a = []
nssp = len(met_s)
ban = 0
ban1 = 0
age_t = sorted(age_s)
met_t = met_s
age_a.extend([age_t[0]])
met_a.extend([met_t[0]])
ind_ssp = np.zeros((len(age)), dtype=np.int64)
photo = np.zeros(len(age))
ind_ssp[:] = -100
for ii in range(1, nssp):
if age_t[ii-1] > age_t[ii]:
ban = 1
if age_t[ii-1] < age_t[ii] and ban == 0:
age_a.extend([age_t[ii]])
if met_t[ii-1] > met_t[ii]:
ban1 = 1
if met_t[ii-1] < met_t[ii] and ban1 == 0:
met_a.extend([met_t[ii]])
ind_age = val_definition_l(age,age_a)
n_age = len(age_a)
n_met = len(met_a)
for ii in range(0, n_age):
if len(ind_age[ii]) > 0:
ind_met = val_definition_l(met[ind_age[ii]],met_a)
for jj in range(0, n_met):
if len(ind_met[jj]) > 0:
nt = np.where((age_s == age_a[ii]) & (met_s == met_a[jj]))[0]
ind_ssp[ind_age[ii][ind_met[jj]]]=nt[0]
flux_0 = ssp_temp[nt[0],:]/ml[nt[0]]/(h_p*vel_light/wave/1e-10/1e-7)*3.846e33
j1 = np.searchsorted(wave, wl_i, side='left')#0#int(0.47*n_c)
j2 = np.searchsorted(wave, wl_f, side='left')#int(0.63*len(wave))
norm = simpson_r(flux_0, wave, j1, j2)
photo[ind_age[ii][ind_met[jj]]]=norm*mass[ind_age[ii][ind_met[jj]]]+1#/(4.0*np.pi*Rs[ind_age[i][ind_met[j]]]**2.0*n_h[ind_age[i][ind_met[j]]])+1
return np.log10(photo)
def associate_mets_ages(age_s, met_s, age, met, mass):
"""
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
age_a = []
met_a = []
nssp = len(met_s)
ban = 0
ban1 = 0
age_t = sorted(age_s)
met_t = met_s
age_a.extend([age_t[0]])
met_a.extend([met_t[0]])
for i in range(1, nssp):
if age_t[i-1] > age_t[i]:
ban = 1
if age_t[i-1] < age_t[i] and ban == 0:
age_a.extend([age_t[i]])
if met_t[i-1] > met_t[i]:
ban1 = 1
if met_t[i-1] < met_t[i] and ban1 == 0:
met_a.extend([met_t[i]])
ind_age = val_definition_l(age, age_a)
n_age = len(age_a)
n_met = len(met_a)
mass_f = np.zeros([n_age, n_met])
for i in range(0, n_age):
if len(ind_age[i]) > 0:
ind_met = val_definition_l(met[ind_age[i]], met_a)
for j in range(0, n_met):
if len(ind_met[j]) > 0:
mass_f[n_age-1-i, j] = np.sum(mass[ind_age[i][ind_met[j]]])
return mass_f
def associate_mets_ages_flux(age_s, met_s, ml_s, age, met, mass):
"""
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
age_a=[]
met_a=[]
nssp=len(met_s)
ban=0
ban1=0
age_t=sorted(age_s)
met_t=met_s
age_a.extend([age_t[0]])
met_a.extend([met_t[0]])
for i in range(1, nssp):
if age_t[i-1] > age_t[i]:
ban =1
if age_t[i-1] < age_t[i] and ban == 0:
age_a.extend([age_t[i]])
if met_t[i-1] > met_t[i]:
ban1 =1
if met_t[i-1] < met_t[i] and ban1 == 0:
met_a.extend([met_t[i]])
ind_age=val_definition_l(age,age_a)
n_age=len(age_a)
n_met=len(met_a)
light_f=np.zeros([n_age,n_met])
mass_f = np.zeros([n_age, n_met])
for i in range(0,n_age):
if len(ind_age[i]) > 0:
ind_met = val_definition_l(met[ind_age[i]], met_a)
for j in range(0, n_met):
if len(ind_met[j]) > 0:
mass_f[n_age-1-i, j] = np.sum(mass[ind_age[i][ind_met[j]]])
nt=np.where((age_s == age_a[i]) & (met_s == met_a[j]))[0]
light_f[n_age-1-i, j]=np.sum(mass[ind_age[i][ind_met[j]]]/ml_s[nt[0]])
return light_f, mass_f
def associate_ages(age_s,age,mass):
age_a=[]
nssp=len(age_s)
ban=0
age_t=sorted(age_s)
age_a.extend([age_t[0]])
for i in range(1, nssp):
if age_t[i-1] > age_t[i]:
ban =1
if age_t[i-1] < age_t[i] and ban == 0:
age_a.extend([age_t[i]])
ind_age=val_definition_l(age,age_a)
n_age=len(age_a)
mass_f=np.zeros(n_age)
for i in range(0, n_age):
if len(ind_age[i]) > 0:
mass_f[i]=np.sum(mass[ind_age[i]])
return mass_f[::-1]
def ssp_extract(template):
"""
Extract from a SSP template the fluxes, corresponding ages and
metallicities, wavelength range and mass-luminosity weighting
factors.
Arguments:
----------
template : SSP template name. (string)
Returns:
-------
pdl_flux_c_ini: fluxes. ((m,w)-sized float array)
wave_c: wavelengths. (w-sized float array)
age_mod: template ages in Gyrs. (m-sized float array)
met_mod: template metallicities in Z/H. (m-sized float array)
Ha: H-alpha mass-luminosity weighting factors per spectrum.
(m-sized float array)
crval: Axis1 value from template header. (float)
cdelt: Axis1 value from template header. (float)
crpix: Axis1 value from template header. (float)
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
pdl_flux_c_ini, hdr = fits.getdata(template, 0, header=True)
nf, n_c = pdl_flux_c_ini.shape
coeffs = np.zeros([nf,3])
crpix = hdr['CRPIX1']
cdelt = hdr['CDELT1']
crval = hdr['CRVAL1']
age_mod = []
met_mod = []
ml = []
name = []
for iii in range(0, nf):
header = 'NAME' + str(iii)
name.extend([hdr[header]]);
name_min = name[iii]
name_min = name_min.replace('spec_ssp_','')
name_min = name_min.replace('.spec','')
name_min = name_min.replace('.dat','')
data = name_min.split('_')
AGE = data[0]
MET = data[1]
if 'Myr' in AGE:
age = AGE.replace('Myr','')
age = np.single(age)/1000.
else:
age = AGE.replace('Gyr','')
age = np.single(age)
met = np.single(MET.replace('z','0.'))
age_mod.extend([age])
met_mod.extend([met])
header = 'NORM' + str(iii)
val_ml = np.single(hdr[header])
if val_ml != 0:
ml.extend([1/val_ml])
else:
ml.extend([1])
wave_c = []
dpix_c_val = []
for jj in range(0, n_c):
wave_c.extend([(crval+cdelt*(jj+1-crpix))])
if jj > 0:
dpix_c_val.extend([wave_c[jj]-wave_c[jj-1]])
wave_c = np.array(wave_c)
ml = np.array(ml)
age_mod = np.array(age_mod)
met_mod = np.array(met_mod)
return pdl_flux_c_ini, wave_c, age_mod, met_mod, ml, crval, cdelt, crpix
def gas_extract(template):
"""
Extract from a gas template the fluxes, corresponding ages and
metallicities, wavelength range and mass-luminosity weighting
factors.
Arguments:
----------
template : SSP template name. (string)
Returns:
-------
pdl_flux_c_ini: fluxes. ((m,w)-sized float array)
wave_c: wavelengths. (w-sized float array)
pht_mod: template photo-ionization values. (m-sized float array)
met_mod: template metallicity values. (m-sized float array)
den_mod: template density values. (m-sized float array)
tem_mod: template temperature values. (m-sized float array)
ml: mass-luminosity weighting factors per spectrum.(m-sized np.single
array)
crval: Axis1 value from template header. (float)
cdelt: Axis1 value from template header. (float)
crpix: Axis1 value from template header. (float)
Source: https://github.com/hjibarram/mock_ifu with minor changes
"""
pdl_flux_c_ini,hdr = fits.getdata(template, 0, header=True)
nf,n_c = pdl_flux_c_ini.shape
coeffs = np.zeros([nf,3])
crpix = hdr['CRPIX1']
cdelt = hdr['CDELT1']
crval = hdr['CRVAL1']
tem_mod = []
pht_mod = []
den_mod = []
met_mod = []
Ha = []
name = []
for iii in range(0, nf):
header = 'NAME' + str(iii)
name.extend([hdr[header]]);
name_min = name[iii]
name_min = name_min.replace('spec_gas_', '')
name_min = name_min.replace('.spec', '')
name_min = name_min.replace('.dat', '')
data = name_min.split('_')
TEM = data[3]
PHT = data[2]
DEN = data[1]
MET = data[0]
tem = np.single(TEM.replace('t', ''))
pht = np.single(PHT.replace('q', ''))
den = np.single(DEN.replace('n', ''))
met = np.single(MET.replace('z', ''))
tem_mod.extend([tem])
pht_mod.extend([pht])
den_mod.extend([den])
met_mod.extend([met])
header = 'NORM' + str(iii)
val_ml = np.single(hdr[header])
Ha.extend([val_ml])
wave_c = []
dpix_c_val = []
for j in range(0, n_c):
wave_c.extend([(crval+cdelt*(j+1-crpix))])
if j > 0:
dpix_c_val.extend([wave_c[j]-wave_c[j-1]])
wave_c = np.array(wave_c)
return pdl_flux_c_ini, wave_c, pht_mod, met_mod, den_mod, tem_mod,\
Ha, crval, cdelt, crpix
def thread_dither(args):
"""
Generates one fiber spectrum.
"""
seeing, ns, ndt, rad, i, j, xifu, yifu, dit, phi, the, phi_g, the_g, fibB,\
scalep, nw_s, nw, nw_g, age_ssp3, met_ssp3, ml_ssp3, age_s, met_s,\
mass_s, facto, d_r, rad_g, Av_g, in_gas, in_ssp, band_g, gas_template, n_ages,\
n_mets, v_rad, v_rad_g, n_lib_mod, dust_rat_ssp, ssp_template, ml_ssp, radL, wave,\
dlam, dlam_g, sigma_inst, sp_res, wave_f, sfri, wave_g, dust_rat_gas, ha_gas, \
radL_g, met_g, age_ssp, met_ssp = args
con = i * ns + j
spec_ifu = np.zeros([nw])
spec_ifu_e = np.zeros([nw])
spec_val = np.zeros([41])