-
Notifications
You must be signed in to change notification settings - Fork 0
/
eazyPy_mod.py
2559 lines (2086 loc) · 94 KB
/
eazyPy_mod.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
"""
eazyPy: routines for reading and plotting Eazy output
EazyParam
readEazyBinary
getEazySED
getEazyPz
plotExampleSED
nMAD
zPhot_zSpec
"""
import os
import string
try:
import astropy.io.fits as pyfits
except:
import pyfits
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib import rc
import pylab
import pdb, pandas as pd
from astropy.table import Table
from astropy.stats.funcs import biweight_location as bl
from astropy.stats.funcs import biweight_midvariance as bs
import threedhst.catIO as catIO
plt.rc('text', usetex=True)
plt.rc('font', family='palatino')
class FilterDefinition:
def __init__(self, bp=None):
"""
Placeholder for the filter definition information.
"""
self.name = None
self.wavelength = None
self.transmission = None
if bp is not None:
self.wavelength = np.cast[np.double](bp.wave)
self.transmission = np.cast[np.double](bp.throughput)
self.name = bp.name
def extinction_correction(self, EBV, Rv=3.1, mag=True, source_lam=None, source_flux = None):
"""
Get the MW extinction correction within the filter.
Optionally supply a source spectrum.
"""
if self.wavelength is None:
print 'Filter not defined.'
return False
if source_flux is None:
source_flux = self.transmission*0.+1
else:
source_flux = np.interp(self.wavelength, source_lam, source_flux, left=0, right=0)
Av = EBV*Rv
Alambda = milkyway_extinction(lamb = self.wavelength, Rv=Rv)
delta = np.trapz(self.transmission*source_flux*10**(-0.4*Alambda*Av), self.wavelength) / np.trapz(self.transmission*source_flux, self.wavelength)
if mag:
return 2.5*np.log10(delta)
else:
return 1./delta
def ABVega(self):
"""
Compute AB-Vega conversion
"""
try:
import pysynphot as S
except:
print 'Failed to import "pysynphot"'
return False
vega=S.FileSpectrum(S.locations.VegaFile)
abmag=S.FlatSpectrum(0,fluxunits='abmag')
#xy, yy = np.loadtxt('hawki_y_ETC.dat', unpack=True)
bp = S.ArrayBandpass(wave=self.wavelength, throughput=self.transmission, name='')
ovega = S.Observation(vega, bp)
oab = S.Observation(abmag, bp)
return -2.5*np.log10(ovega.integrate()/oab.integrate())
def pivot(self):
"""
PySynphot pivot wavelength
"""
try:
import pysynphot as S
except:
print 'Failed to import "pysynphot"'
return False
self.bp = S.ArrayBandpass(wave=self.wavelength, throughput=self.transmission, name='')
return self.bp.pivot()
def rectwidth(self):
"""
Synphot filter rectangular width
"""
try:
import pysynphot as S
except:
print 'Failed to import "pysynphot"'
return False
self.bp = S.ArrayBandpass(wave=self.wavelength, throughput=self.transmission, name='')
return self.bp.rectwidth()
#
def ctw95(self):
"""
95% cumulative throughput width
http://www.stsci.edu/hst/acs/analysis/bandwidths/#keywords
"""
dl = np.diff(self.wavelength)
filt = np.cumsum((self.wavelength*self.transmission)[1:]*dl)
ctw95 = np.interp([0.025, 0.975], filt/filt.max(), self.wavelength[1:])
return np.diff(ctw95)
class FilterFile:
def __init__(self, file='FILTER.RES.v8.R300'):
"""
Read a EAZY (HYPERZ) filter file.
"""
fp = open(file)
lines = fp.readlines()
fp.close()
filters = []
wave = []
for line in lines:
if 'lambda_c' in line:
if len(wave) > 0:
new_filter = FilterDefinition()
new_filter.name = header
new_filter.wavelength = np.cast[float](wave)
new_filter.transmission = np.cast[float](trans)
filters.append(new_filter)
header = ' '.join(line.split()[1:])
wave = []
trans = []
else:
lspl = np.cast[float](line.split())
wave.append(lspl[1])
trans.append(lspl[2])
# last one
new_filter = FilterDefinition()
new_filter.name = header
new_filter.wavelength = np.cast[float](wave)
new_filter.transmission = np.cast[float](trans)
filters.append(new_filter)
self.filters = filters
self.NFILT = len(filters)
def names(self, verbose=True):
"""
Print the filter names.
"""
if verbose:
for i in range(len(self.filters)):
print '%5d %s' %(i+1, self.filters[i].name)
else:
string_list = ['%5d %s\n' %(i+1, self.filters[i].name) for i in range(len(self.filters))]
return string_list
def write(self, file='xxx.res', verbose=True):
"""
Dump the filter information to a filter file.
"""
fp = open(file,'w')
for filter in self.filters:
fp.write('%6d %s\n' %(len(filter.wavelength), filter.name))
for i in range(len(filter.wavelength)):
fp.write('%-6d %.5e %.5e\n' %(i+1, filter.wavelength[i], filter.transmission[i]))
fp.close()
string_list = self.names(verbose=False)
fp = open(file+'.info', 'w')
fp.writelines(string_list)
fp.close()
if verbose:
print 'Wrote <%s[.info]>' %(file)
def search(self, search_string, case=True, verbose=True):
"""
Search filter names for `search_string`. If `case` is True, then
match case.
"""
import re
if not case:
search_string = search_string.upper()
matched = []
for i in range(len(self.filters)):
filt_name = self.filters[i].name
if not case:
filt_name = filt_name.upper()
if re.search(search_string, filt_name) is not None:
if verbose:
print '%5d %s' %(i+1, self.filters[i].name)
matched.append(i)
return np.array(matched)
class ParamFilter(FilterDefinition):
def __init__(self, line='# Filter #20, RES#78: COSMOS/SUBARU_filter_B.txt - lambda_c=4458.276253'):
self.lambda_c = float(line.split('lambda_c=')[1])
self.name = line.split()[4]
self.fnumber = int(line.split('RES#')[1].split(':')[0])
self.cnumber = int(line.split('Filter #')[1].split(',')[0])
class EazyParam():
"""
Read an Eazy zphot.param file.
Example:
>>> params = EazyParam(PARAM_FILE='zphot.param')
>>> params['Z_STEP']
'0.010'
"""
def __init__(self, PARAM_FILE='zphot.param', READ_FILTERS=False,
read_templates=False):
self.filename = PARAM_FILE
self.param_path = os.path.dirname(PARAM_FILE)
f = open(PARAM_FILE,'r')
self.lines = f.readlines()
f.close()
self._process_params()
filters = []
templates = []
for line in self.lines:
if line.startswith('# Filter'):
filters.append(ParamFilter(line))
if line.startswith('# Template'):
templates.append(line.split()[3])
self.NFILT = len(filters)
self.filters = filters
self.templates = templates
if READ_FILTERS:
RES = FilterFile(self.params['FILTERS_RES'])
for i in range(self.NFILT):
filters[i].wavelength = RES.filters[filters[i].fnumber-1].wavelength
filters[i].transmission = RES.filters[filters[i].fnumber-1].transmission
if read_templates:
self.read_templates(templates_file=self.params['TEMPLATES_FILE'])
def read_templates(self, templates_file=None):
lines = open(templates_file).readlines()
self.templ = []
for line in lines:
if line.strip().startswith('#'):
continue
template_file = line.split()[1]
templ = Template(file=template_file)
templ.wavelength *= float(line.split()[2])
templ.set_fnu()
self.templ.append(templ)
def show_templates(self, interp_wave=None, ax=None, fnu=False):
if ax is None:
ax = plt
for templ in self.templ:
if fnu:
flux = templ.flux_fnu
else:
flux = templ.flux
if interp_wave is not None:
y0 = np.interp(interp_wave, templ.wavelength, flux)
else:
y0 = 1.
plt.plot(templ.wavelength, flux / y0, label=templ.name)
def _process_params(self):
params = {}
formats = {}
self.param_names = []
for line in self.lines:
if line.startswith('#') is False:
lsplit = line.split()
if lsplit.__len__() >= 2:
params[lsplit[0]] = lsplit[1]
self.param_names.append(lsplit[0])
try:
flt = float(lsplit[1])
formats[lsplit[0]] = 'f'
params[lsplit[0]] = flt
except:
formats[lsplit[0]] = 's'
self.params = params
#self.param_names = params.keys()
self.formats = formats
def show_filters(self):
for filter in self.filters:
print ' F%d, %s, lc=%f' %(filter.fnumber, filter.name, filter.lambda_c)
def write(self, file=None):
if file == None:
print 'No output file specified...'
else:
fp = open(file,'w')
for param in self.param_names:
if isinstance(self.params[param], np.str):
fp.write('%-25s %s\n' %(param, self.params[param]))
else:
fp.write('%-25s %f\n' %(param, self.params[param]))
#str = '%-25s %'+self.formats[param]+'\n'
#
fp.close()
#
def __getitem__(self, param_name):
"""
__getitem__(param_name)
>>> cat = mySexCat('drz.cat')
>>> print cat['NUMBER']
"""
if param_name not in self.param_names:
print ('Column %s not found. Check `column_names` attribute.'
%column_name)
return None
else:
#str = 'out = self.%s*1' %column_name
#exec(str)
return self.params[param_name]
def __setitem__(self, param_name, value):
self.params[param_name] = value
class TranslateFile():
def __init__(self, file='zphot.translate'):
self.file=file
self.ordered_keys = []
lines = open(file).readlines()
self.trans = {}
self.error = {}
for line in lines:
spl = line.split()
key = spl[0]
self.ordered_keys.append(key)
self.trans[key] = spl[1]
if len(spl) == 3:
self.error[key] = float(spl[2])
else:
self.error[key] = 1.
#
def change_error(self, filter=88, value=1.e8):
if isinstance(filter, str):
if 'f_' in filter:
err_filt = filter.replace('f_','e_')
else:
err_filt = 'e'+filter
if err_filt in self.ordered_keys:
self.error[err_filt] = value
return True
if isinstance(filter, int):
for key in self.trans.keys():
if self.trans[key] == 'E%0d' %(filter):
self.error[key] = value
return True
print 'Filter %s not found in list.' %(str(filter))
def write(self, file=None, show_ones=False):
lines = []
for key in self.ordered_keys:
line = '%s %s' %(key, self.trans[key])
if self.trans[key].startswith('E') & ((self.error[key] != 1.0) | show_ones):
line += ' %.1f' %(self.error[key])
lines.append(line+'\n')
if file is None:
file = self.file
if file:
fp = open(file,'w')
fp.writelines(lines)
fp.close()
else:
for line in lines:
print line[:-1]
def readRFBinary(file='OUTPUT/test.153-155.coeff'):
"""
Read Rest-frame coefficients file
"""
f = open(file, 'rb')
NOBJ, NFILT, NTEMP = np.fromfile(file=f,dtype=np.int32, count=3)
rftempfilt = np.fromfile(file=f,dtype=np.double,count=NFILT*NTEMP).reshape((NTEMP,NFILT)).transpose()
rfcoeff = np.fromfile(file=f,dtype=np.double,count=NOBJ*NTEMP).reshape((NOBJ, NTEMP)).transpose()
if NFILT == 1:
rftempfilt = rftempfilt.flatten()
f.close()
d = {'NOBJ':NOBJ, 'NFILT':NFILT, 'NTEMP':NTEMP, 'tempfilt':rftempfilt, 'coeffs':rfcoeff}
return d
def readEazyBinary(MAIN_OUTPUT_FILE='photz', OUTPUT_DIRECTORY='./OUTPUT', CACHE_FILE='Same'):
"""
tempfilt, coeffs, temp_sed, pz = readEazyBinary(MAIN_OUTPUT_FILE='photz', \
OUTPUT_DIRECTORY='./OUTPUT', \
CACHE_FILE = 'Same')
Read Eazy BINARY_OUTPUTS files into structure data.
If the BINARY_OUTPUTS files are not in './OUTPUT', provide either a relative or absolute path
in the OUTPUT_DIRECTORY keyword.
By default assumes that CACHE_FILE is MAIN_OUTPUT_FILE+'.tempfilt'.
Specify the full filename if otherwise.
"""
#root='COSMOS/OUTPUT/cat3.4_default_lines_zp33sspNoU'
root = OUTPUT_DIRECTORY+'/'+MAIN_OUTPUT_FILE
###### .tempfilt
if CACHE_FILE == 'Same':
CACHE_FILE = root+'.tempfilt'
if os.path.exists(CACHE_FILE) is False:
print ('File, %s, not found.' %(CACHE_FILE))
return -1,-1,-1,-1
f = open(CACHE_FILE,'rb')
s = np.fromfile(file=f,dtype=np.int32, count=4)
NFILT=s[0]
NTEMP=s[1]
NZ=s[2]
NOBJ=s[3]
tempfilt = np.fromfile(file=f,dtype=np.double,count=NFILT*NTEMP*NZ).reshape((NZ,NTEMP,NFILT)).transpose()
lc = np.fromfile(file=f,dtype=np.double,count=NFILT)
zgrid = np.fromfile(file=f,dtype=np.double,count=NZ)
fnu = np.fromfile(file=f,dtype=np.double,count=NFILT*NOBJ).reshape((NOBJ,NFILT)).transpose()
efnu = np.fromfile(file=f,dtype=np.double,count=NFILT*NOBJ).reshape((NOBJ,NFILT)).transpose()
f.close()
tempfilt = {'NFILT':NFILT,'NTEMP':NTEMP,'NZ':NZ,'NOBJ':NOBJ,\
'tempfilt':tempfilt,'lc':lc,'zgrid':zgrid,'fnu':fnu,'efnu':efnu}
###### .coeff
f = open(root+'.coeff','rb')
s = np.fromfile(file=f,dtype=np.int32, count=4)
NFILT=s[0]
NTEMP=s[1]
NZ=s[2]
NOBJ=s[3]
coeffs = np.fromfile(file=f,dtype=np.double,count=NTEMP*NOBJ).reshape((NOBJ,NTEMP)).transpose()
izbest = np.fromfile(file=f,dtype=np.int32,count=NOBJ)
tnorm = np.fromfile(file=f,dtype=np.double,count=NTEMP)
f.close()
coeffs = {'NFILT':NFILT,'NTEMP':NTEMP,'NZ':NZ,'NOBJ':NOBJ,\
'coeffs':coeffs,'izbest':izbest,'tnorm':tnorm}
###### .temp_sed
f = open(root+'.temp_sed','rb')
s = np.fromfile(file=f,dtype=np.int32, count=3)
NTEMP=s[0]
NTEMPL=s[1]
NZ=s[2]
templam = np.fromfile(file=f,dtype=np.double,count=NTEMPL)
temp_seds = np.fromfile(file=f,dtype=np.double,count=NTEMPL*NTEMP).reshape((NTEMP,NTEMPL)).transpose()
da = np.fromfile(file=f,dtype=np.double,count=NZ)
db = np.fromfile(file=f,dtype=np.double,count=NZ)
f.close()
temp_sed = {'NTEMP':NTEMP,'NTEMPL':NTEMPL,'NZ':NZ,\
'templam':templam,'temp_seds':temp_seds,'da':da,'db':db}
###### .pz
if os.path.exists(root+'.pz'):
f = open(root+'.pz','rb')
s = np.fromfile(file=f,dtype=np.int32, count=2)
NZ=s[0]
NOBJ=s[1]
chi2fit = np.fromfile(file=f,dtype=np.double,count=NZ*NOBJ).reshape((NOBJ,NZ)).transpose()
### This will break if APPLY_PRIOR No
s = np.fromfile(file=f,dtype=np.int32, count=1)
if len(s) > 0:
NK = s[0]
kbins = np.fromfile(file=f,dtype=np.double,count=NK)
priorzk = np.fromfile(file=f, dtype=np.double, count=NZ*NK).reshape((NK,NZ)).transpose()
kidx = np.fromfile(file=f,dtype=np.int32,count=NOBJ)
pz = {'NZ':NZ,'NOBJ':NOBJ,'NK':NK, 'chi2fit':chi2fit, 'kbins':kbins, 'priorzk':priorzk,'kidx':kidx}
else:
pz = None
f.close()
else:
pz = None
if False:
f = open(root+'.zbin','rb')
s = np.fromfile(file=f,dtype=np.int32, count=1)
NOBJ=s[0]
z_a = np.fromfile(file=f,dtype=np.double,count=NOBJ)
z_p = np.fromfile(file=f,dtype=np.double,count=NOBJ)
z_m1 = np.fromfile(file=f,dtype=np.double,count=NOBJ)
z_m2 = np.fromfile(file=f,dtype=np.double,count=NOBJ)
z_peak = np.fromfile(file=f,dtype=np.double,count=NOBJ)
f.close()
###### Done.
return tempfilt, coeffs, temp_sed, pz
def getEazySED(idx, MAIN_OUTPUT_FILE='photz', OUTPUT_DIRECTORY='./OUTPUT', CACHE_FILE='Same', scale_flambda=True, verbose=False, individual_templates=False):
"""
lambdaz, temp_sed, lci, obs_sed, fobs, efobs = \
getEazySED(idx, MAIN_OUTPUT_FILE='photz', OUTPUT_DIRECTORY='./OUTPUT', CACHE_FILE='Same')
Get best-fit Eazy template for object number 'idx' from the specified Eazy output files.
Output variables are as follows:
lambdaz: full best-fit template (observed) wavelength, interpolated at WAVELENGTH_GRID
temp_sed: " " flux (F_lambda)
lci: filter pivot wavelengths
fobs: observed fluxes, including zeropoint offsets if used, F_lambda
efobs: observed flux errors, " " " "
"""
tempfilt, coeffs, temp_seds, pz = readEazyBinary(MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, CACHE_FILE = CACHE_FILE)
##### Apply zeropoint factors
param = EazyParam(PARAM_FILE=OUTPUT_DIRECTORY+'/'+MAIN_OUTPUT_FILE+'.param')
fnumbers = np.zeros(len(param.filters), dtype=np.int)
for i in range(len(fnumbers)):
fnumbers[i] = int(param.filters[i].fnumber)
zpfile = OUTPUT_DIRECTORY+'/'+MAIN_OUTPUT_FILE+'.zeropoint'
if os.path.exists(zpfile):
zpfilts, zpf_file = np.loadtxt(zpfile, unpack=True, dtype=np.str)
zpf = np.ones(tempfilt['NFILT'])
for i in range(len(zpfilts)):
match = fnumbers == int(zpfilts[i][1:])
zpf[match] = np.float(zpf_file[i])
else:
zpf = np.ones(tempfilt['NFILT'])
zpfactors = np.dot(zpf.reshape(tempfilt['NFILT'],1),\
np.ones(tempfilt['NOBJ']).reshape(1,tempfilt['NOBJ']))
if verbose:
print zpf
tempfilt['fnu'] *= zpfactors
tempfilt['efnu'] *= zpfactors
lci = tempfilt['lc'].copy()
params = EazyParam(PARAM_FILE=OUTPUT_DIRECTORY+'/'+MAIN_OUTPUT_FILE+'.param')
abzp = np.float(params['PRIOR_ABZP'])
# fobs = tempfilt['fnu'][:,idx]/(lci/5500.)**2*flam_factor
# efobs = tempfilt['efnu'][:,idx]/(lci/5500.)**2*flam_factor
### Physical f_lambda fluxes, 10**-17 ergs / s / cm2 / A
if scale_flambda:
flam_factor = 10**(-0.4*(params['PRIOR_ABZP']+48.6))*3.e18/scale_flambda
else:
flam_factor = 5500.**2
missing = (tempfilt['fnu'][:,idx] < -99) | (tempfilt['efnu'][:,idx] < 0)
fobs = tempfilt['fnu'][:,idx]/lci**2*flam_factor
efobs = tempfilt['efnu'][:,idx]/lci**2*flam_factor
fobs[missing] = -99
efobs[missing] = -99
#print lci, tempfilt['fnu'][:,idx], tempfilt['efnu'][:,idx]
##### Broad-band SED
obs_sed = np.dot(tempfilt['tempfilt'][:,:,coeffs['izbest'][idx]],\
coeffs['coeffs'][:,idx])/(lci)**2*flam_factor
zi = tempfilt['zgrid'][coeffs['izbest'][idx]]
###### Full template SED, observed frame
lambdaz = temp_seds['templam']*(1+zi)
temp_sed = np.dot(temp_seds['temp_seds'],coeffs['coeffs'][:,idx])
if individual_templates:
temp_sed = temp_seds['temp_seds']*coeffs['coeffs'][:,idx]
temp_sed /= (1+zi)**2
temp_sed *= (1/5500.)**2*flam_factor
###### IGM absorption
lim1 = np.where(temp_seds['templam'] < 912)
lim2 = np.where((temp_seds['templam'] >= 912) & (temp_seds['templam'] < 1026))
lim3 = np.where((temp_seds['templam'] >= 1026) & (temp_seds['templam'] < 1216))
if lim1[0].size > 0: temp_sed[lim1] *= 0.
if lim2[0].size > 0: temp_sed[lim2] *= 1.-temp_seds['db'][coeffs['izbest'][idx]]
if lim3[0].size > 0: temp_sed[lim3] *= 1.-temp_seds['da'][coeffs['izbest'][idx]]
###### Done
return lambdaz, temp_sed, lci, obs_sed, fobs, efobs
def getAllPz(MAIN_OUTPUT_FILE='photz', OUTPUT_DIRECTORY='./OUTPUT', CACHE_FILE='Same'):
"""
Return a matrix with *all* normalized p(z) for a given catalog
"""
import threedhst.eazyPy as eazy
tempfilt, coeffs, temp_seds, pz = eazy.readEazyBinary(MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, CACHE_FILE = CACHE_FILE)
full_pz = np.zeros((pz['NZ'], pz['NOBJ']))
for i in xrange(pz['NOBJ']):
#print i
zz, pzi = eazy.getEazyPz(i, MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, CACHE_FILE=CACHE_FILE, binaries=(tempfilt, pz))
full_pz[:,i] = pzi
return zz, full_pz
def getEazyPz(idx, MAIN_OUTPUT_FILE='photz', OUTPUT_DIRECTORY='./OUTPUT', CACHE_FILE='Same', binaries=None, get_prior=False):
"""
zgrid, pz = getEazyPz(idx, \
MAIN_OUTPUT_FILE='photz', \
OUTPUT_DIRECTORY='./OUTPUT', \
CACHE_FILE='Same', binaries=None)
Get Eazy p(z) for object #idx.
To avoid re-reading the binary files, supply binaries = (tempfilt, pz)
"""
if binaries is None:
tempfilt, coeffs, temp_seds, pz = readEazyBinary(MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, \
OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, \
CACHE_FILE = CACHE_FILE)
else:
tempfilt, pz = binaries
if pz is None:
return None, None
###### Get p(z|m) from prior grid
kidx = pz['kidx'][idx]
#print kidx, pz['priorzk'].shape
if (kidx > 0) & (kidx < pz['priorzk'].shape[1]):
prior = pz['priorzk'][:,kidx]
else:
prior = np.ones(pz['NZ'])
###### Convert Chi2 to p(z)
pzi = np.exp(-0.5*(pz['chi2fit'][:,idx]-min(pz['chi2fit'][:,idx])))*prior#*(1+tempfilt['zgrid'])
if np.sum(pzi) > 0:
pzi/=np.trapz(pzi, tempfilt['zgrid'])
###### Done
if get_prior:
return tempfilt['zgrid'], pzi, prior
else:
return tempfilt['zgrid'], pzi
class TemplateError():
"""
Make an easy (spline) interpolator for the template error function
"""
def __init__(self, file='templates/TEMPLATE_ERROR.eazy_v1.0'):
from scipy import interpolate
self.te_x, self.te_y = np.loadtxt(file, unpack=True)
self._spline = interpolate.InterpolatedUnivariateSpline(self.te_x, self.te_y)
def interpolate(self, filter_wavelength, z):
"""
observed_wavelength is observed wavelength of photometric filters. But
these sample the *rest* wavelength of the template error function at lam/(1+z)
"""
return self._spline(filter_wavelength/(1+z))
class Template():
def __init__(self, sp=None, file=None, name=None):
self.wavelength = None
self.flux = None
self.flux_fnu = None
self.name = 'None'
if name is None:
if file is not None:
self.name = os.path.basename(file)
else:
self.name = name
if sp is not None:
self.wavelength = np.cast[np.double](sp.wave)
self.flux = np.cast[np.double](sp.flux)
self.flux_fnu = self.flux
if file is not None:
self.wavelength, self.flux = np.loadtxt(file, unpack=True)
self.set_fnu()
def set_fnu(self):
self.flux_fnu = self.flux * (self.wavelength/5500.)**2
def integrate_filter(self, filter, z=0):
"""
Integrate the template through a `FilterDefinition` filter object.
"unicorn" is part of a yet non-public module. np.interp can
stand in for the meantime.
"""
try:
import unicorn
temp_filter = unicorn.utils_c.interp_conserve_c(filter.wavelength,
self.wavelength*(1+z), self.flux_fnu)
except ImportError:
temp_filter = np.interp(filter.wavelength, self.wavelength*(1+z),
self.flux_fnu)
temp_int = np.trapz(filter.transmission*temp_filter/filter.wavelength, filter.wavelength) / np.trapz(filter.transmission/filter.wavelength, filter.wavelength)
#temp_int = np.trapz(filter.transmission*temp_filter, filter.wavelength) / np.trapz(filter.transmission, 1./filter.wavelength)
return temp_int
class TemplateInterpolator():
"""
Class to use scipy spline interpolator to interpolate pre-computed eazy template
photometry at arbitrary redshift(s).
"""
def __init__(self, bands=None, MAIN_OUTPUT_FILE='photz', OUTPUT_DIRECTORY='./OUTPUT', CACHE_FILE='Same', zout=None, f_lambda=True):
from scipy import interpolate
import threedhst.eazyPy as eazy
#### Read the files from the specified output
tempfilt, coeffs, temp_seds, pz = eazy.readEazyBinary(MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, CACHE_FILE = CACHE_FILE)
if bands is None:
self.bands = np.arange(tempfilt['NFILT'])
else:
self.bands = np.array(bands)
self.band_names = ['' for b in self.bands]
if zout is not None:
param = eazy.EazyParam(PARAM_FILE=zout.filename.replace('.zout','.param'))
self.band_names = [f.name for f in param.filters]
self.bands = np.array([f.fnumber-1 for f in param.filters])
self.NFILT = len(self.bands)
self.NTEMP = tempfilt['NTEMP']
self.lc = tempfilt['lc'][self.bands]
self.sed = temp_seds
self.templam = self.sed['templam']
self.temp_seds = self.sed['temp_seds']
# if True:
# import threedhst
# import unicorn
# threedhst.showMessage('Conroy model', warn=True)
# cvd12 = np.loadtxt(unicorn.GRISM_HOME+'/templates/cvd12_t11_solar_Chabrier.dat')
# self.temp_seds[:,0] = np.interp(self.templam, cvd12[:,0], cvd12[:,1])
self.in_zgrid = tempfilt['zgrid']
self.tempfilt = tempfilt['tempfilt'][self.bands, :, :]
if f_lambda:
for i in range(self.NFILT):
self.tempfilt[i,:,:] /= (self.lc[i]/5500.)**2
###### IGM absorption
self.igm_wave = []
self.igm_wave.append(self.templam < 912)
self.igm_wave.append((self.templam >= 912) & (self.templam < 1026))
self.igm_wave.append((self.templam >= 1026) & (self.templam < 1216))
self._spline_da = interpolate.InterpolatedUnivariateSpline(self.in_zgrid, temp_seds['da'])
self._spline_db = interpolate.InterpolatedUnivariateSpline(self.in_zgrid, temp_seds['db'])
#### Make a 2D list of the spline interpolators
self._interpolators = [range(self.NTEMP) for i in range(self.NFILT)]
for i in range(self.NFILT):
for j in range(self.NTEMP):
self._interpolators[i][j] = interpolate.InterpolatedUnivariateSpline(self.in_zgrid, self.tempfilt[i, j, :])
#
self.output = None
self.zout = None
def interpolate_photometry(self, zout):
"""
Interpolate the EAZY template photometry at `zout`, which can be a number or an
array.
The result is returned from the function and also stored in `self.output`.
"""
output = [range(self.NTEMP) for i in range(self.NFILT)]
for i in range(self.NFILT):
for j in range(self.NTEMP):
output[i][j] = self._interpolators[i][j](zout)
self.zgrid = np.array(zout)
self.output = np.array(output)
return self.output
def check_extrapolate(self):
"""
Check if any interpolated values are extrapolated from the original redshift grid
Result is both returned and stored in `self.extrapolated`
"""
if self.zout is None:
return False
self.extrapolated = np.zeros(self.output.shape, dtype=np.bool) ## False
bad = (self.zgrid < self.in_zgrid.min()) | (self.zgrid > self.in_zgrid.max())
self.extrapolated[:, :, bad] = True
return self.extrapolated
def get_IGM(self, z, matrix=False, silent=False):
"""
Retrieve the full SEDs with IGM absorption
"""
###### IGM absorption
# lim1 = self.templam < 912
# lim2 = (self.templam >= 912) & (self.templam < 1026)
# lim3 = (self.templam >= 1026) & (self.templam < 1216)
igm_factor = np.ones(self.templam.shape[0])
igm_factor[self.igm_wave[0]] = 0.
igm_factor[self.igm_wave[1]] = 1. - self._spline_db(z)
igm_factor[self.igm_wave[1]] = 1. - self._spline_da(z)
if matrix:
self.igm_factor = np.dot(igm_factor.reshape(-1,1), np.ones((1, self.NTEMP)))
else:
self.igm_factor = igm_factor
self.igm_z = z
self.igm_lambda = self.templam*(1+z)
if not silent:
return self.igm_lambda, self.igm_factor
#
def interpolate_tempfilt_loop(tempfilt, zgrid, zi, output):
"""
Linear interpolate an Eazy "tempfilt" grid at z=zi.
`tempfilt` is [NFILT, NTEMP, NZ] integrated flux matrix
`zgrid` is [NZ] redshift grid
`output` is empty [NFILT, NTEMP] grid to speed up execution
"""
sh = tempfilt.shape
NF, NT, NZ = sh[0], sh[1], sh[2]
#output = np.zeros((NF, NT))
for iz in range(NZ-1):
dz = zgrid[iz+1]-zgrid[iz]
fint = 1 - (zi-zgrid[iz])/dz
if (fint > 0) & (fint <= 1):
fint2 = 1 - (zgrid[iz+1]-zi)/dz
# print iz, zgrid[iz], fint, fint2
for ifilt in range(NF):
for itemp in range(NT):
#print ifilt, itemp
output[ifilt, itemp] = tempfilt[ifilt, itemp, iz]*fint + tempfilt[ifilt, itemp, iz+1]*fint2
break
return output
try:
from numba import double, jit
faster_interpolate_tempfilt = jit(double[:,:](double[:,:,:], double[:], double, double[:,:]))(interpolate_tempfilt_loop)
except:
faster_interpolate_tempfilt = interpolate_tempfilt_loop
#pass
def convert_chi_to_pdf(tempfilt, pz):
"""
Convert the `chi2fit` array in the `pz` structure to probability densities.
The `tempfilt` structure is needed to get the redshift grid.
"""
pdf = pz['chi2fit']*0.
for idx in range(pz['NOBJ']):
###### Get p(z|m) from prior grid
kidx = pz['kidx'][idx]
#print kidx, pz['priorzk'].shape
if (kidx > 0) & (kidx < pz['priorzk'].shape[1]):
prior = pz['priorzk'][:,kidx]
else:
prior = np.ones(pz['NZ'])
###### Convert Chi2 to p(z)
pzi = np.exp(-0.5*(pz['chi2fit'][:,idx]-min(pz['chi2fit'][:,idx])))*prior
if np.sum(pzi) > 0:
pzi/=np.trapz(pzi, tempfilt['zgrid'])
pdf[:,idx] = pzi
return tempfilt['zgrid']*1., pdf
def plotExampleSED(idx=20, writePNG=True, MAIN_OUTPUT_FILE = 'photz', OUTPUT_DIRECTORY = 'OUTPUT', CACHE_FILE = 'Same', lrange=[3000,8.e4], axes=None, individual_templates=False, fnu=False, show_pz=True, snlim=2, scale_flambda=1.e-17):
"""
PlotSEDExample(idx=20)
Plot an example Eazy best-fit SED.
"""
#zout = catIO.ReadASCIICat(OUTPUT_DIRECTORY+'/'+MAIN_OUTPUT_FILE+'.zout')
zout = catIO.Readfile(OUTPUT_DIRECTORY+'/'+MAIN_OUTPUT_FILE+'.zout')
#qz = np.where(zout.z_spec > 0)[0]
print zout.filename
qz = np.arange(len(zout.id))
lambdaz, temp_sed, lci, obs_sed, fobs, efobs = \
getEazySED(qz[idx], MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, \
OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, \
CACHE_FILE = CACHE_FILE, individual_templates=individual_templates, scale_flambda=scale_flambda)
zgrid, pz = getEazyPz(qz[idx], MAIN_OUTPUT_FILE=MAIN_OUTPUT_FILE, \
OUTPUT_DIRECTORY=OUTPUT_DIRECTORY, \
CACHE_FILE = CACHE_FILE)
##### plot defaults
#rc('font',**{'family':'serif','serif':['Times']})
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.serif'] = ['Helvetica']
#plt.rcParams['ps.useafm'] = True
plt.rcParams['patch.linewidth'] = 0.
plt.rcParams['patch.edgecolor'] = 'black'
#plt.rcParams['text.usetex'] = True
plt.rcParams['text.usetex'] = False
#plt.rcParams['text.latex.preamble'] = ''
##### start plot
if axes is None:
fig = plt.figure(figsize=[8,4],dpi=100)
fig.subplots_adjust(wspace=0.18, hspace=0.0,left=0.09,bottom=0.15,right=0.98,top=0.98)
#### Plot parameters
plotsize=35
alph=0.9
if fnu:
temp_sed *= (lambdaz / 5500.)**2
fobs *= (lci/5500.)**2
efobs *= (lci/5500.)**2
obs_sed *= (lci/5500.)**2
#### Full best-fit template
if axes is None:
ax = fig.add_subplot(121)
axp = fig.add_subplot(122)
else:
ax = axes[0]