forked from mike-a-yen/bpz-1.99.3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bpz_tools.py
1535 lines (1318 loc) · 49.3 KB
/
bpz_tools.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
#!/usr/local/bin/python
""" bpz_tools.py: Contains useful functions for I/O and math.
TO DO:
Include higher order interpolations
"""
#from Numeric import *
from numpy import *
from MLab_coe import *
from useful import *
from string import *
import os,sys
clight_AHz=2.99792458e18
Vega='Vega_reference'
#Smallest number accepted by python
eps=1e-300
eeps=log(eps)
from MLab_coe import log10 as log10a
def log10(x):
return log10a(x+eps)
#return log10clip(x, -33)
#This quantities are used by the AB files
zmax_ab=12.
#zmax_ab=4.
dz_ab=0.01
ab_clip=1e-6
#Initialize path info
bpz_dir=os.getenv('BPZPATH')
fil_dir=bpz_dir+'/FILTER/'
sed_dir=bpz_dir+'/SED/'
ab_dir=bpz_dir+'/AB/'
#Auxiliary synthetic photometry functions
def flux(xsr,ys,yr,ccd='yes',units='nu'):
""" Flux of spectrum ys observed through response yr,
both defined on xsr
Both f_nu and f_lambda have to be defined over lambda
If units=nu, it gives f_nu as the output
"""
if ccd=='yes': yr=yr*xsr
norm=trapz(yr,xsr)
f_l=trapz(ys*yr,xsr)/norm
if units=='nu':
lp=sqrt(norm/trapz(yr/xsr/xsr,xsr)) #Pivotal wavelenght
return f_l*lp**2/clight_AHz
else: return f_l
def ABtofl(ABmag,filter,ccd='yes'):
"""Converts AB magnitudes to flux in ergs s^-1 cm^-2 AA^-1"""
lp=pivotal_wl(filter,ccd)
f=AB2Jy(ABmag)
return f/lp**2*clight_AHz*1e23
def pivotal_wl(filter,ccd='yes'):
xr,yr=get_filter(filter)
if ccd=='yes': yr=yr*xr
norm=trapz(yr,xr)
return sqrt(norm/trapz(yr/xr/xr,xr))
def filter_center(filter,ccd='yes'):
"""Estimates the central wavelenght of the filter"""
if type(filter)==type(""):
xr,yr=get_filter(filter)
else:
xr=filter[0]
yr=filter[1]
if ccd=='yes': yr=yr*xr
return trapz(yr*xr,xr)/trapz(yr,xr)
def filter_fwhm(filter,ccd='yes'):
xr,yr=get_filter(filter)
if ccd=='yes': yr=yr*xr/mean(xr)
imax=argmax(yr)
ymax=yr[imax]
xmax=xr[imax]
ih_1=argmin(abs(yr[:imax]-ymax/2.))
ih_2=argmin(abs(yr[imax:]-ymax/2.))+imax
return xr[ih_2]-xr[ih_1]
def AB(flux):
"""AB magnitude from f_nu"""
return -2.5*log10(flux)-48.60
def flux2mag(flux):
"""Convert arbitrary flux to magnitude"""
return -2.5*log10(flux)
def Jy2AB(flux):
"""Convert flux in Jy to AB magnitudes"""
return -2.5*log10(flux*1e-23)-48.60
def AB2Jy(ABmag):
"""Convert AB magnitudes to Jansky"""
return 10.**(-0.4*(ABmag+48.60))/1e-23
def mag2flux(mag):
"""Convert flux to arbitrary flux units"""
return 10.**(-.4*mag)
def e_frac2mag(fracerr):
"""Convert fractionary flux error to mag error"""
return 2.5*log10(1.+fracerr)
def e_mag2frac(errmag):
"""Convert mag error to fractionary flux error"""
return 10.**(.4*errmag)-1.
def flux_det(aperture,pixelnoise,s2noise=1):
"""Given an aperture, the noise per pixel and the
signal to noise, it estimates the detection flux limit"""
npixels=pi*(aperture/2.)**2
totalnoise=sqrt(npixels)*pixelnoise
return s2noise*totalnoise
def get_limitingmagnitude(m,dm,sigma=1.,dm_int=0.2):
"""Given a list of magnitudes and magnitude errors,
calculate by extrapolation the 1-sigma error limit"""
g=less(m,99.)*greater(m,-99.)
x,y=autobin_stats(compress(g,m),compress(g,dm),n_points=11,stat="median")
return match_resol(y,x,dm_int)-flux2mag(1./sigma/e_mag2frac(dm_int))
#Synthetic photometry functions
def etau_madau(wl,z):
"""
Madau 1995 extinction for a galaxy spectrum at redshift z
defined on a wavelenght grid wl
"""
n=len(wl)
l=array([1216.,1026.,973.,950.])
xe=1.+z
#If all the spectrum is redder than (1+z)*wl_lyman_alfa
if wl[0]> l[0]*xe: return zeros(n)+1.
#Madau coefficients
c=array([3.6e-3,1.7e-3,1.2e-3,9.3e-4])
ll=912.
tau=wl*0.
i1=searchsorted(wl,ll)
i2=n-1
#Lyman series absorption
for i in range(len(l)):
i2=searchsorted(wl[i1:i2],l[i]*xe)
tau[i1:i2]=tau[i1:i2]+c[i]*(wl[i1:i2]/l[i])**3.46
if ll*xe < wl[0]:
return exp(-tau)
#Photoelectric absorption
xe=1.+z
i2=searchsorted(wl,ll*xe)
xc=wl[i1:i2]/ll
xc3=xc**3
tau[i1:i2]=tau[i1:i2]+\
(0.25*xc3*(xe**.46-xc**0.46)\
+9.4*xc**1.5*(xe**0.18-xc**0.18)\
-0.7*xc3*(xc**(-1.32)-xe**(-1.32))\
-0.023*(xe**1.68-xc**1.68))
tau = clip(tau, 0, 700)
return exp(-tau)
# if tau>700. : return 0.
# else: return exp(-tau)
def etau(wl,z):
"""
Madau 1995 and Scott 2000 extinction for a galaxy spectrum
at redshift z observed on a wavelenght grid wl
"""
n=len(wl)
l=array([1216.,1026.,973.,950.])
xe=1.+z
#If all the spectrum is redder than (1+z)*wl_lyman_alfa
if wl[0]> l[0]*xe: return zeros(n)+1.
#Extinction coefficients
c=array([1.,0.47,0.33,0.26])
if z>4.:
#Numbers from Madau paper
coeff=0.0036
gamma=2.46
elif z<3:
#Numbers from Scott et al. 2000 paper
coeff=0.00759
gamma=1.35
else:
#Interpolate between two numbers
coeff=.00759+(0.0036-0.00759)*(z-3.)
gamma=1.35+(2.46-1.35)*(z-3.)
c=coeff*c
ll=912.
tau=wl*0.
i1=searchsorted(wl,ll)
i2=n-1
#Lyman series absorption
for i in range(len(l)):
i2=searchsorted(wl[i1:i2],l[i]*xe)
tau[i1:i2]=tau[i1:i2]+c[i]*(wl[i1:i2]/l[i])**(1.+gamma)
if ll*xe < wl[0]: return exp(-tau)
#Photoelectric absorption
xe=1.+z
i2=searchsorted(wl,ll*xe)
xc=wl[i1:i2]/ll
xc3=xc**3
tau[i1:i2]=tau[i1:i2]+\
(0.25*xc3*(xe**.46-xc**0.46)\
+9.4*xc**1.5*(xe**0.18-xc**0.18)\
-0.7*xc3*(xc**(-1.32)-xe**(-1.32))\
-0.023*(xe**1.68-xc**1.68))
return exp(-tau)
def get_sednfilter(sed,filter):
#Gets a pair of SED and filter from the database
#And matches the filter resolution to that of the spectrum
#where they overlap
"""Usage:
xs,ys,yr=get_sednfilter(sed,filter)
"""
#Figure out the correct names
if filter[-4:]<>'.res':filter=filter+'.res'
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
filter=fil_dir+filter
#Get the data
x_sed,y_sed=get_data(sed,range(2))
nsed=len(x_sed)
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
if not ascend(x_sed):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % sed
print 'They should start with the shortest lambda and end with the longest'
if not ascend(x_res):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % filter
print 'They should start with the shortest lambda and end with the longest'
#Define the limits of interest in wavelenght
i1=searchsorted(x_sed,x_res[0])-1
i1=maximum(i1,0)
i2=searchsorted(x_sed,x_res[nres-1])+1
i2=minimum(i2,nsed-1)
r=match_resol(x_res,y_res,x_sed[i1:i2])
r=where(less(r,0.),0.,r) #Transmission must be >=0
return x_sed[i1:i2],y_sed[i1:i2],r
def get_sed(sed):
#Get x_sed,y_sed from a database spectrum
"""Usage:
xs,ys=get_sed(sed)
"""
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
#Get the data
x,y=get_data(sed,range(2))
if not ascend(x):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % sed
print 'They should start with the shortest lambda and end with the longest'
return x,y
def get_filter(filter):
#Get x_res,y_res from a database spectrum
"""Usage:
xres,yres=get_filter(filter)
"""
#Figure out the correct names
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
#Get the data
x,y= get_data(filter,range(2))
if not ascend(x):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % filter
print 'They should start with the shortest lambda and end with the longest'
return x,y
def redshift(wl,flux,z):
""" Redshift spectrum y defined on axis x
to redshift z
Usage:
y_z=redshift(wl,flux,z)
"""
if z==0.: return flux
else:
f=match_resol(wl,flux,wl/(1.+z))
return where(less(f,0.),0.,f)
def normalize(x_sed,y_sed,m,filter='F814W_WFPC2',units='nu'):
"""Normalizes a spectrum (defined on lambda) to
a broad band (AB) magnitude and transforms the
spectrum to nu units""
Usage:
normflux=normalize(wl,spectrum,m,filter='F814W_WFPC2')
"""
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
nsed=len(x_sed)
i1=searchsorted(x_sed,x_res[0])-1
i1=maximum(i1,0)
i2=searchsorted(x_sed,x_res[nres-1])+1
i2=minimum(i2,nsed-1)
r=match_resol(x_res,y_res,x_sed[i1:i2])
r=where(less(r,0.),0.,r) #Transmission must be >=0
flujo=flux(x_sed[i1:i2],y_sed[i1:i2],r,ccd='yes',units='nu')
norm=flujo/mag2flux(m)
if units=='nu':
return y_sed*x_sed*x_sed/clight_AHz/norm
else:
return y_sed/norm
class Normalize:
def __init__(self,x_sed,y_sed,m,filter='F814W_WFPC2',units='nu'):
"""Normalizes a spectrum (defined on lambda) to
a broad band (AB) magnitude and transforms the
spectrum to nu units""
Usage:
normflux=normalize(wl,spectrum,m,filter='F814W_WFPC2')
"""
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
nsed=len(x_sed)
i1=searchsorted(x_sed,x_res[0])-1
i1=maximum(i1,0)
i2=searchsorted(x_sed,x_res[nres-1])+1
i2=minimum(i2,nsed-1)
r=match_resol(x_res,y_res,x_sed[i1:i2])
r=where(less(r,0.),0.,r) #Transmission must be >=0
flujo=flux(x_sed[i1:i2],y_sed[i1:i2],r,ccd='yes',units='nu')
self.norm=flujo/mag2flux(m)
if units=='nu': self.flux_norm = y_sed*x_sed*x_sed/clight_AHz/self.norm
else: self.flux_norm = y_sed/self.norm
def obs_spectrum(sed,z,madau=1):
"""Generate a redshifted and madau extincted spectrum"""
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
#Get the data
x_sed,y_sed=get_data(sed,range(2))
#ys_z will be the redshifted and corrected spectrum
ys_z=match_resol(x_sed,y_sed,x_sed/(1.+z))
if madau: ys_z=etau_madau(x_sed,z)*ys_z
return x_sed,ys_z
def nf_z_sed(sed,filter,z=array([0.]),ccd='yes',units='lambda',madau='yes'):
"""Returns array f with f_lambda(z) or f_nu(z) through a given filter
Takes into account intergalactic extinction.
Flux normalization at each redshift is arbitrary
"""
if type(z)==type(0.): z=array([z])
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
#Get the data
x_sed,y_sed=get_data(sed,range(2))
nsed=len(x_sed)
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
#Wavelenght range of interest as a function of z
wl_1=x_res[0]/(1.+z)
wl_2=x_res[-1]/(1.+z)
n1=clip(searchsorted(x_sed,wl_1)-1,0,1000000)
n2=clip(searchsorted(x_sed,wl_2)+1,0,nsed-1)
#Change resolution of filter
x_r=x_sed[n1[0]:n2[0]]
r=match_resol(x_res,y_res,x_r)
r=where(less(r,0.),0.,r) #Transmission must be >=0
#Operations necessary for normalization and ccd effects
if ccd=='yes': r=r*x_r
norm_r=trapz(r,x_r)
if units=='nu': const=norm_r/trapz(r/x_r/x_r,x_r)/clight_AHz
else: const=1.
const=const/norm_r
nz=len(z)
f=zeros(nz)*1.
for i in range(nz):
i1,i2=n1[i],n2[i]
ys_z=match_resol(x_sed[i1:i2],y_sed[i1:i2],x_r/(1.+z[i]))
if madau<>'no': ys_z=etau_madau(x_r,z[i])*ys_z
f[i]=trapz(ys_z*r,x_r)*const
if nz==1: return f[0]
else: return f
def lf_z_sed(sed,filter,z=array([0.]),ccd='yes',units='lambda',madau='yes'):
"""
Returns array f with f_lambda(z) or f_nu(z) through a given filter
Takes into account intergalactic extinction.
Flux normalization at each redshift is arbitrary
"""
if type(z)==type(0.): z=array([z])
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
#Get the data
x_sed,y_sed=get_data(sed,range(2))
nsed=len(x_sed)
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
if not ascend(x_sed):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % sed
print 'They should start with the shortest lambda and end with the longest'
print 'This will probably crash the program'
if not ascend(x_res):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % filter
print 'They should start with the shortest lambda and end with the longest'
print 'This will probably crash the program'
if x_sed[-1]<x_res[-1]: #The SED does not cover the whole filter interval
print 'Extrapolating the spectrum'
#Linear extrapolation of the flux using the last 4 points
#slope=mean(y_sed[-4:]/x_sed[-4:])
d_extrap=(x_sed[-1]-x_sed[0])/len(x_sed)
x_extrap=arange(x_sed[-1]+d_extrap,x_res[-1]+d_extrap,d_extrap)
extrap=lsq(x_sed[-5:],y_sed[-5:])
y_extrap=extrap.fit(x_extrap)
y_extrap=clip(y_extrap,0.,max(y_sed[-5:]))
x_sed=concatenate((x_sed,x_extrap))
y_sed=concatenate((y_sed,y_extrap))
#connect(x_sed,y_sed)
#connect(x_res,y_res)
#Wavelenght range of interest as a function of z
wl_1=x_res[0]/(1.+z)
wl_2=x_res[-1]/(1.+z)
n1=clip(searchsorted(x_sed,wl_1)-1,0,100000)
n2=clip(searchsorted(x_sed,wl_2)+1,0,nsed-1)
#Typical delta lambda
delta_sed=(x_sed[-1]-x_sed[0])/len(x_sed)
delta_res=(x_res[-1]-x_res[0])/len(x_res)
#Change resolution of filter
if delta_res>delta_sed:
x_r=arange(x_res[0],x_res[-1]+delta_sed,delta_sed)
#print 'Changing filter resolution from %.2f AA to %.2f AA' % (delta_res,delta_sed)
r=match_resol(x_res,y_res,x_r)
r=where(less(r,0.),0.,r) #Transmission must be >=0
else:
x_r,r=x_res,y_res
#Operations necessary for normalization and ccd effects
if ccd=='yes': r=r*x_r
norm_r=trapz(r,x_r)
if units=='nu': const=norm_r/trapz(r/x_r/x_r,x_r)/clight_AHz
else: const=1.
const=const/norm_r
nz=len(z)
f=zeros(nz)*1.
for i in range(nz):
i1,i2=n1[i],n2[i]
ys_z=match_resol(x_sed[i1:i2],y_sed[i1:i2],x_r/(1.+z[i]))
#p=FramedPlot();p.add(Curve(x_r,ys_z));p.show()
if madau<>'no': ys_z=etau_madau(x_r,z[i])*ys_z
#pp=FramedPlot();pp.add(Curve(x_r,ys_z*etau_madau(x_r,z[i])));pp.show()
#ask('More?')
f[i]=trapz(ys_z*r,x_r)*const
if nz==1: return f[0]
else: return f
def of_z_sed(sed,filter,z=array([0.]),ccd='yes',units='lambda',madau='yes'):
"""Returns array f with f_lambda(z) or f_nu(z) through a given filter
Takes into account intergalactic extinction.
Flux normalization at each redshift is arbitrary
"""
if type(z)==type(0.): z=array([z])
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
#Get the data
x_sed,y_sed=get_data(sed,range(2))
nsed=len(x_sed)
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
#Define the limits of interest in wl
i1=searchsorted(x_sed,x_res[0])-1
i1=maximum(i1,0)
i2=searchsorted(x_sed,x_res[-1])+1
i2=minimum(i2,nsed-1)
if x_sed[-1]<x_res[-1]: #The SED does not cover the whole filter interval
#Linear extrapolation of the flux using the last 4 points
#slope=mean(y_sed[-4:]/x_sed[-4:])
d_extrap=(x_sed[-1]-x_sed[0])/len(x_sed)
x_extrap=arange(x_sed[-1]+d_extrap,x_res[-1]+d_extrap,d_extrap)
extrap=lsq(x_sed[-5:],y_sed[-5:])
y_extrap=extrap.fit(x_extrap)
y_extrap=clip(y_extrap,0.,max(y_sed[-5:]))
x_sed=concatenate((x_sed,x_extrap))
y_sed=concatenate((y_sed,y_extrap))
i2=len(y_sed)-1
r=match_resol(x_res,y_res,x_sed[i1:i2])
r=where(less(r,0.),0.,r) #Transmission must be >=0
nz=len(z)
f=zeros(nz)*1.
for i in range(nz):
ys_z=match_resol(x_sed,y_sed,x_sed/(1.+z[i]))
if madau<>'no': ys_z[i1:i2]=etau_madau(x_sed[i1:i2],z[i])*ys_z[i1:i2]
f[i]=flux(x_sed[i1:i2],ys_z[i1:i2],r,ccd,units)
if nz==1: return f[0]
else: return f
f_z_sed=lf_z_sed
#f_z_sed=nf_z_sed
#f_z_sed=of_z_sed
def f_z_sed_AB(sed,filter,z=array([0.]),units='lambda'):
#It assumes ccd=yes,madau=yes by default
z_ab=arange(0.,zmax_ab,dz_ab) #zmax_ab and dz_ab are def. in bpz_tools
lp=pivotal_wl(filter)
#AB filter
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
ab_file=ab_dir+sed[:-4]+'.'
if filter[-4:]<>'.res':filter=filter+'.res'
ab_file+=filter[:-4]+'.AB'
#print 'AB file',ab_file
if not os.path.exists(ab_file):
ABflux(sed,filter)
z_ab,f_ab=get_data(ab_file,range(2))
fnu=match_resol(z_ab,f_ab,z)
if units=='nu': return fnu
elif units=='lambda': return fnu/lp**2*clight_AHz
else:
print 'Units not valid'
def ABflux(sed,filter,madau='yes'):
"""
Calculates a AB file like the ones used by bpz
It will set to zero all fluxes
which are ab_clip times smaller than the maximum flux.
This eliminates residual flux which gives absurd
colors at very high-z
"""
print sed, filter
ccd='yes'
units='nu'
madau=madau
z_ab=arange(0.,zmax_ab,dz_ab) #zmax_ab and dz_ab are def. in bpz_tools
#Figure out the correct names
if sed[-4:]<>'.sed':sed=sed+'.sed'
sed=sed_dir+sed
if filter[-4:]<>'.res':filter=filter+'.res'
filter=fil_dir+filter
#Get the data
x_sed,y_sed=get_data(sed,range(2))
nsed=len(x_sed)
x_res,y_res=get_data(filter,range(2))
nres=len(x_res)
if not ascend(x_sed):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % sed
print 'They should start with the shortest lambda and end with the longest'
print 'This will probably crash the program'
if not ascend(x_res):
print
print 'Warning!!!'
print 'The wavelenghts in %s are not properly ordered' % filter
print 'They should start with the shortest lambda and end with the longest'
print 'This will probably crash the program'
if x_sed[-1]<x_res[-1]: #The SED does not cover the whole filter interval
print 'Extrapolating the spectrum'
#Linear extrapolation of the flux using the last 4 points
#slope=mean(y_sed[-4:]/x_sed[-4:])
d_extrap=(x_sed[-1]-x_sed[0])/len(x_sed)
x_extrap=arange(x_sed[-1]+d_extrap,x_res[-1]+d_extrap,d_extrap)
extrap=lsq(x_sed[-5:],y_sed[-5:])
y_extrap=extrap.fit(x_extrap)
y_extrap=clip(y_extrap,0.,max(y_sed[-5:]))
x_sed=concatenate((x_sed,x_extrap))
y_sed=concatenate((y_sed,y_extrap))
#connect(x_sed,y_sed)
#connect(x_res,y_res)
#Wavelenght range of interest as a function of z_ab
wl_1=x_res[0]/(1.+z_ab)
wl_2=x_res[-1]/(1.+z_ab)
#print 'wl', wl_1, wl_2
#print 'x_res', x_res
print 'x_res[0]', x_res[0]
print 'x_res[-1]', x_res[-1]
n1=clip(searchsorted(x_sed,wl_1)-1,0,100000)
n2=clip(searchsorted(x_sed,wl_2)+1,0,nsed-1)
#Typical delta lambda
delta_sed=(x_sed[-1]-x_sed[0])/len(x_sed)
delta_res=(x_res[-1]-x_res[0])/len(x_res)
#Change resolution of filter
if delta_res>delta_sed:
x_r=arange(x_res[0],x_res[-1]+delta_sed,delta_sed)
print 'Changing filter resolution from %.2f AA to %.2f' % (delta_res,delta_sed)
r=match_resol(x_res,y_res,x_r)
r=where(less(r,0.),0.,r) #Transmission must be >=0
else:
x_r,r=x_res,y_res
#Operations necessary for normalization and ccd effects
if ccd=='yes': r=r*x_r
norm_r=trapz(r,x_r)
if units=='nu': const=norm_r/trapz(r/x_r/x_r,x_r)/clight_AHz
else: const=1.
const=const/norm_r
nz_ab=len(z_ab)
f=zeros(nz_ab)*1.
for i in range(nz_ab):
i1,i2=n1[i],n2[i]
#if (x_sed[i1] > max(x_r/(1.+z_ab[i]))) or (x_sed[i2] < min(x_r/(1.+z_ab[i]))):
if (x_sed[i1] > x_r[-1]/(1.+z_ab[i])) or (x_sed[i2-1] < x_r[0]/(1.+z_ab[i])) or (i2-i1<2):
print 'bpz_tools.ABflux:'
print "YOUR FILTER RANGE DOESN'T OVERLAP AT ALL WITH THE REDSHIFTED TEMPLATE"
print "THIS REDSHIFT IS OFF LIMITS TO YOU:"
print 'z = ', z_ab[i]
print i1, i2
print x_sed[i1], x_sed[i2]
print y_sed[i1], y_sed[i2]
print min(x_r/(1.+z_ab[i])), max(x_r/(1.+z_ab[i]))
# NOTE: x_sed[i1:i2] NEEDS TO COVER x_r(1.+z_ab[i])
# IF THEY DON'T OVERLAP AT ALL, THE PROGRAM WILL CRASH
#sys.exit(1)
else:
try:
ys_z=match_resol(x_sed[i1:i2],y_sed[i1:i2],x_r/(1.+z_ab[i]))
except:
print i1, i2
print x_sed[i1], x_sed[i2-1]
print y_sed[i1], y_sed[i2-1]
print min(x_r/(1.+z_ab[i])), max(x_r/(1.+z_ab[i]))
print x_r[1]/(1.+z_ab[i]), x_r[-2]/(1.+z_ab[i])
print x_sed[i1:i2]
print x_r/(1.+z_ab[i])
pause()
if madau<>'no': ys_z=etau_madau(x_r,z_ab[i])*ys_z
f[i]=trapz(ys_z*r,x_r)*const
ABoutput=ab_dir+split(sed,'/')[-1][:-4]+'.'+split(filter,'/')[-1][:-4]+'.AB'
#print "Clipping the AB file"
#fmax=max(f)
#f=where(less(f,fmax*ab_clip),0.,f)
print 'Writing AB file ',ABoutput
put_data(ABoutput,(z_ab,f))
def VegatoAB(m_vega,filter,Vega=Vega):
cons=AB(f_z_sed(Vega,filter,z=0.,units='nu',ccd='yes'))
return m_vega+cons
def ABtoVega(m_ab,filter,Vega=Vega):
cons=AB(f_z_sed(Vega,filter,z=0.,units='nu',ccd='yes'))
return m_ab-cons
#Photometric redshift functions
def likelihood(f,ef,ft_z):
"""
Usage: ps[:nz,:nt]=likelihood(f[:nf],ef[:nf],ft_z[:nz,:nt,:nf])
"""
global minchi2
axis=ft_z.shape
nz=axis[0]
nt=axis[1]
chi2=zeros((nz,nt),float)
ftt=zeros((nz,nt),float)
fgt=zeros((nz,nt),float)
ief2=1./(ef*ef)
fgg=add.reduce(f*f*ief2)
factor=ft_z[:nz,:nt,:]*ief2
ftt[:nz,:nt]=add.reduce(ft_z[:nz,:nt,:]*factor,-1)
fgt[:nz,:nt]=add.reduce(f[:]*factor,-1)
chi2[:nz,:nt]=fgg-power(fgt[:nz,:nt],2)/ftt[:nz,:nt]
min_chi2=min(chi2)
minchi2=min(min_chi2)
# chi2=chi2-minchi2
chi2=clip(chi2,0.,-2.*eeps)
p=where(greater_equal(chi2,-2.*eeps),0.,exp(-chi2/2.))
norm=add.reduce(add.reduce(p))
return p/norm
def new_likelihood(f,ef,ft_z):
"""
Usage: ps[:nz,:nt]=likelihood(f[:nf],ef[:nf],ft_z[:nz,:nt,:nf])
"""
global minchi2
rolex=reloj()
rolex.set()
nz,nt,nf=ft_z.shape
foo=add.reduce((f/ef)**2)
fgt=add.reduce(
#f[NewAxis,NewAxis,:nf]*ft_z[:nz,:nt,:nf]/ef[NewAxis,NewAxis,:nf]**2
reshape(f, (1, 1, nf)) * ft_z / reshape(ef, (1, 1, nf))**2
,-1)
ftt=add.reduce(
#ft_z[:nz,:nt,:nf]*ft_z[:nz,:nt,:nf]/ef[NewAxis,NewAxis,:nf]**2
ft_z**2 / reshape(ef, (1, 1, nf))**2
,-1)
ao=fgt/ftt
# print mean(ao),std(ao)
chi2=foo-fgt**2/ftt+(1.-ao)**2*ftt
minchi2=min(min(chi2))
chi2=chi2-minchi2
chi2=clip(chi2,0.,-2.*eeps)
p=exp(-chi2/2.)
norm=add.reduce(add.reduce(p))
return p/norm
#class p_c_z_t:
# def __init__(self,f,ef,ft_z):
# self.nz,self.nt,self.nf=ft_z.shape
# self.foo=add.reduce((f/ef)**2)
# self.fgt=add.reduce(
# f[NewAxis,NewAxis,:]*ft_z[:,:,:]/ef[NewAxis,NewAxis,:]**2
# ,-1)
# self.ftt=add.reduce(
# ft_z[:,:,:]*ft_z[:,:,:]/ef[NewAxis,NewAxis,:]**2
# ,-1)
# #When all the model fluxes are equal to zero
# self.chi2=self.foo-(self.fgt**2+1e-100)/(self.ftt+1e-100)
# self.chi2_minima=loc2d(self.chi2[:self.nz,:self.nt],'min')
# self.i_z_ml=self.chi2_minima[0]
# self.i_t_ml=self.chi2_minima[1]
# self.min_chi2=self.chi2[self.i_z_ml,self.i_t_ml]
# self.likelihood=exp(-0.5*clip((self.chi2-self.min_chi2),0.,1400.))
# self.likelihood=where(equal(self.chi2,1400.),0.,self.likelihood)
# #Add the f_tt^-1/2 multiplicative factor in the exponential
# self.chi2+=-0.5*log(self.ftt+1e-100)
# min_chi2=min(min(self.chi2))
# self.Bayes_likelihood=exp(-0.5*clip((self.chi2-min_chi2),0.,1400.))
# self.Bayes_likelihood=where(equal(self.chi2,1400.),0.,self.Bayes_likelihood)
#
# #plo=FramedPlot()
# #for i in range(self.ftt.shape[1]):
# # norm=sqrt(max(self.ftt[:,i]))
# # # plo.add(Curve(arange(self.ftt.shape[0]),self.ftt[:,i]**(0.5)))
# # plo.add(Curve(arange(self.ftt.shape[0]),self.likelihood[:,i],color='red'))
# # plo.add(Curve(arange(self.ftt.shape[0]),self.likelihood[:,i]*sqrt(self.ftt[:,i])/norm))
# #plo.show()#
#
# def bayes_likelihood(self):
# return self.Bayes_likelihood
class p_c_z_t:
def __init__(self,f,ef,ft_z):
self.nz,self.nt,self.nf=ft_z.shape
#Get true minimum of the input data (excluding zero values)
#maximo=max(f)
#minimo=min(where(equal(f,0.),maximo,f))
#print 'minimo=',minimo
#maximo=max(ft_z)
#minimo=min(min(min(where(equal(ft_z,0.),maximo,ft_z))))
#print 'minimo=',minimo
#minerror=min(f)
#maxerror=max(ef)
#maxerror=max(where(equal(ef,maxerror),minerror,ef))
#print 'maxerror',maxerror
#Define likelihood quantities taking into account non-observed objects
self.foo=add.reduce(where(less(f/ef,1e-4),0.,(f/ef)**2))
#nonobs=less(f[NewAxis,NewAxis,:]/ef[NewAxis,NewAxis,:]+ft_z[:,:,:]*0.,1e-4)
#nonobs=less(reshape(f, (1, 1, self.nf)) / reshape(ef, (1, 1, self.nf)) + ft_z*0., 1e-4)
# Above was wrong: non-detections were ignored as non-observed --DC
nonobs=greater(reshape(ef, (1, 1, self.nf)) + ft_z*0., 1.0)
self.fot=add.reduce(
#where(nonobs,0.,f[NewAxis,NewAxis,:]*ft_z[:,:,:]/ef[NewAxis,NewAxis,:]**2)
where(nonobs,0.,reshape(f, (1, 1, self.nf)) * ft_z / reshape(ef, (1, 1, self.nf))**2)
,-1)
self.ftt=add.reduce(
#where(nonobs,0.,ft_z[:,:,:]*ft_z[:,:,:]/ef[NewAxis,NewAxis,:]**2)
where(nonobs,0.,ft_z**2 / reshape(ef, (1, 1, self.nf))**2)
,-1)
#############################################
#Old definitions
#############################################
#self.foo=add.reduce((f/ef)**2)
#self.fot=add.reduce(
# f[NewAxis,NewAxis,:]*ft_z[:,:,:]/ef[NewAxis,NewAxis,:]**2
# ,-1)
#self.ftt=add.reduce(
# ft_z[:,:,:]*ft_z[:,:,:]/ef[NewAxis,NewAxis,:]**2
# ,-1)
################################################
#Define chi2 adding eps to the ftt denominator to avoid overflows
self.chi2=where(equal(self.ftt,0.),
self.foo,
self.foo-(self.fot**2)/(self.ftt+eps))
self.chi2_minima=loc2d(self.chi2[:self.nz,:self.nt],'min')
self.i_z_ml=self.chi2_minima[0]
self.i_t_ml=self.chi2_minima[1]
self.min_chi2=self.chi2[self.i_z_ml,self.i_t_ml]
self.likelihood=exp(-0.5*clip((self.chi2-self.min_chi2),0.,-2*eeps))
#self.likelihood=where(equal(self.chi2,1400.),0.,self.likelihood)
#Now we add the Bayesian f_tt^-1/2 multiplicative factor to the exponential
#(we don't multiply it by 0.5 since it is done below together with the chi^2
#To deal with zero values of ftt we again add an epsilon value.
self.expo=where(
equal(self.ftt,0.),
self.chi2,
self.chi2+log(self.ftt+eps)
)
#Renormalize the exponent to preserve dynamical range
self.expo_minima=loc2d(self.expo,'min')
self.min_expo=self.expo[self.expo_minima[0],self.expo_minima[1]]
self.expo-=self.min_expo
self.expo=clip(self.expo,0.,-2.*eeps)
#Clip very low values of the probability
self.Bayes_likelihood=where(
equal(self.expo,-2.*eeps),
0.,
exp(-0.5*self.expo))
def bayes_likelihood(self):
return self.Bayes_likelihood
def various_plots(self):
#Normalize and collapse likelihoods (without prior)
norm=add.reduce(add.reduce(self.Bayes_likelihood))
bl=add.reduce(self.Bayes_likelihood/norm,-1)
norm=add.reduce(add.reduce(self.likelihood))
l=add.reduce(self.likelihood/norm,-1)
plo=FramedPlot()
plo.add(Curve(arange(self.nz),bl,color='blue'))
plo.add(Curve(arange(self.nz),l,color='red'))
plo.show()
#plo2=FramedPlot()
#for i in range(self.ftt.shape[1]):
#for i in range(2):
# #plo2.add(Curve(arange(self.nz),log(self.fot[:,i]*self.fot[:,i])))
# plo2.add(Curve(arange(self.nz),log(self.ftt[:,i])))
#plo2.show()
#for i in range(self.ftt.shape[1]):
#for i in range(2):
# plo2.add(Curve(arange(self.nz),-0.5*(self.fot[:,i]*self.fot[:,i]/self.ftt[:,i]+log(self.ftt[:,i]))))
# plo2.add(Curve(arange(self.nz),-0.5*(self.fot[:,i]*self.fot[:,i]/self.ftt[:,i]),color='red'))
#plo2.show()
#plo3=FramedPlot()
#for i in range(self.ftt.shape[1]):
# norm=sqrt(max(self.ftt[:,i]))
# plo3.add(Curve(arange(self.nz),self.fot[:,i]*self.fot[:,i]/self.ftt[:,i]))
#plo3.show()
ask('More?')
class p_c_z_t_color:
def __init__(self,f,ef,ft_z):
self.nz,self.nt,self.nf=ft_z.shape
self.chi2=add.reduce(
#((f[NewAxis,NewAxis,:]-ft_z[:,:,:])/ef[NewAxis,NewAxis,:])**2
((reshape(f, (1, 1, self.nf)) - ft_z) / reshape(ef, (1, 1, self.nf)))**2
,-1)
self.chi2_minima=loc2d(self.chi2[:self.nz,:self.nt],'min')
self.i_z_ml=self.chi2_minima[0]
self.i_t_ml=self.chi2_minima[1]
self.min_chi2=self.chi2[self.i_z_ml,self.i_t_ml]
self.likelihood=exp(-0.5*clip((self.chi2-self.min_chi2),0.,1400.))
def bayes_likelihood(self):
return self.likelihood
#def gr_likelihood(f,ef,ft_z):
# #Color-redshift Likelihood a la Rychards et al. (SDSS QSOs)
# global minchi2
# nf=f.shape[0]
# nz=ft_z.shape[0]
# nt=ft_z.shape[1]
# print f,ef,ft_z[:10,0,:]
# chi2=add.reduce(
# ((f[NewAxis,NewAxis,:nf]-ft_z[:nz,:nt,:nf])/ef[NewAxis,NewAxis,:nf])**2
# ,-1)
# minchi2=min(min(chi2))
# chi2=chi2-minchi2
# chi2=clip(chi2,0.,1400.)
# p=exp(-chi2/2.)
# norm=add.reduce(add.reduce(p))
# return p/norm
#def p_and_minchi2(f,ef,ft_z):
# p=gr_likelihood(f,ef,ft_z)
# return p,minchi2
#def new_p_and_minchi2(f,ef,ct):
# p=color_likelihood(f,ef,ct)
# return p,minchi2
def prior(z,m,info='hdfn',nt=6,ninterp=0,x=None,y=None):
"""Given the magnitude m, produces the prior p(z|T,m)
Usage: pi[:nz,:nt]=prior(z[:nz],m,info=('hdfn',nt))
"""
if info=='none' or info=='flat': return
#We estimate the priors at m_step intervals
#and keep them in a dictionary, and then
#interpolate them for other values
m_step=0.1
accuracy=str(len(str(int(1./m_step)))-1)#number of decimals kept
exec('from prior_%s import *'%info)
global prior_dict
try:
len(prior_dict)
except NameError:
prior_dict={}
#The dictionary keys are values of the
#magnitud quantized to mstep mags
#The values of the dictionary are the corresponding
#prior probabilities.They are only calculated once
#and kept in the dictionary for future
#use if needed.