-
Notifications
You must be signed in to change notification settings - Fork 0
/
spec.py
1280 lines (1137 loc) · 40.1 KB
/
spec.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
from __future__ import print_function
# S.Rodney
# 2010.06.04
# working with 1-d fits files of spectra
from matplotlib import pyplot as pl
import numpy as np
import os
import exceptions
from astropy.io import fits as pyfits
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
# TODO: Improve the MultiSpectrum class, for stitching together spectra of the same object covering different wavelength ranges (see TODO items in the class definition below)
# TODO: add more info to the interactive output plots, like the linelist, z, etc.
# TODO : handle the flux uncertainty properly when plotting
# TODO : handle the flux uncertainty properly when binning
# TODO : don't plot line labels that are beyond the extent of the min and max wavelength for plotting
class Spectrum(object):
"""A class for a 1-d spectrum object"""
def __init__(self, filename=None, **kwargs):
self.filename = filename
self.wave = np.array([])
self.flux = np.array([])
self.fluxerror = np.array([])
self.waveunit = None
if filename is not None:
if not os.path.isfile(filename):
raise exceptions.RuntimeError("No file %s"%filename)
if self.filename.endswith('.fits'):
self.rdspecfits(**kwargs)
elif self.filename.endswith('.dat') or self.filename.endswith('.txt'):
self.rdspecdat(**kwargs)
def rdspecfits(self, ext='SCI', verbose=False ):
"""
read in a 1-d spectrum from a fits file.
stores wavelength and flux as numpy arrays
"""
# TODO : read in flux uncertainty array when available
hdulist = pyfits.open(self.filename)
try :
# reading a DEEP2/DEEP3 spectrum
extroot='BXSPF'
wb,fb,eb = hdulist['%s-B'%extroot].data[0][1], hdulist['%s-B'%extroot].data[0][0], hdulist['%s-B'%extroot].data[0][2]
wr,fr,er = hdulist['%s-R'%extroot].data[0][1], hdulist['%s-R'%extroot].data[0][0], hdulist['%s-R'%extroot].data[0][2]
return( np.append( wb, wr ), np.append( fb,fr ), np.append( eb,er) )
except :
pass
# determine the wavelength range
# covered by this spectrum
if len(hdulist) == 1 : ext = 0
refwave = hdulist[ext].header['CRVAL1']
refpix = hdulist[ext].header['CRPIX1']
if 'CD1_1' in hdulist[ext].header.keys() :
dwave = hdulist[ext].header['CD1_1']
elif 'CDELT1' in hdulist[ext].header.keys() :
dwave = hdulist[ext].header['CDELT1']
else :
raise exceptions.RuntimeError(
"wavelength step keyword not found")
nwave = hdulist[ext].header['NAXIS1']
nap = hdulist[ext].header['NAXIS']
widx = np.arange( nwave )
wave = (widx - (refpix-1))*dwave + refwave
flux = []
if nap>1:
for i in range( nap ):
flux.append( hdulist[ext].data[i] )
else :
flux = hdulist[ext].data
self.wave = wave
self.flux = flux
# TODO : check for flux uncertainty array
self.fluxerror = np.zeros(len(self.flux))
return
def rdspecdat(self):
"""Read in a 1-D spectrum from a .dat or .txt file -- an ASCII text
file with 2 or 3 columns, holding the wavelength, flux and optionally
the flux uncertainty.
"""
# TODO : ugh. this is crude. Should have some checks for file format
# and probably better to use the astropy.io functions now.
try:
w, f, e = np.loadtxt(self.filename, unpack=True)
except:
w, f = np.loadtxt(self.filename, unpack=True)
e = []
def plotlines_interactive( self, skyfile=None, z=0.0, lineset='sdss',
smooth=0, showerr=False):
"""Interactive line matching.
h for help, q to quit"""
specfile = self.filename
pl.ion()
pl.clf()
self.plotspec(skyfile=skyfile, smoothwindow=smooth)
userin=''
print( __doc__ )
print("z=%.3f %s"%(z,lineset))
while userin!='q' :
userin=raw_input('')
if userin=='q': break
elif userin.startswith('z') :
z = float( userin.split()[1] )
pl.clf()
self.plotspec(skyfile, smoothwindow=smooth, showerr=showerr)
if lineset!='none':marklines( z, lineset )
pl.draw()
print("re-plottd at z=%.3f"%z)
elif userin.startswith('l') :
lineset = userin.split()[1]
pl.clf()
self.plotspec(skyfile, smoothwindow=smooth, showerr=showerr)
if lineset != 'none' : marklines( z, lineset )
elif userin.startswith('s') :
smooth = int( userin.split()[1] )
pl.clf()
self.plotspec(skyfile, smoothwindow=smooth, showerr=showerr)
if lineset!='none': marklines( z, lineset )
elif userin=='h':
print("""
q : quit
h : help
z <zval> : set z
l <linelist> : set line list [sdss,abs,em,sky,CuAr,none,SNIa]
s <npix> : apply median smoothing, radius N pix
""")
return( z )
def bin( self, binwidth=10, wstart=0, wend=0 ):
""" bin the spectrum in units of width binwidth
binwidth is in the wavelength units of the spectrum
(typically Angstroms)
"""
# TODO : handle units more robustly -- ask user for units, check
# against the units specfied in the input file or by the user, etc.
w = self.wave
f = self.flux
e = self.fluxerror
wbinned, dw, fbinned, df = binspecdat(
w, f, e, binwidth=binwidth, wstart=wstart,wend=wend)
self.wave_binned = wbinned
self.flux_binned = fbinned
self.fluxerror_binned = df
self.wave_binsize = dw
return
def plotspec(self, skyfile='', smooth=False,
smoothwindow=0, showerr=False,
zlines=0.0, lineset='none',
plotwavemin=0, plotwavemax=0,
plotfluxmin=0, plotfluxmax=0):
""" plot the source spectrum and the sky spectrum """
# medsmooth = lambda f,N : array( [ median( f[max(0,i-N):min(len(f),max(0,i-N)+2*N)]) for i in range(len(f)) ] )
pl.clf()
lineset= lineset.lower()
# TODO: this should be more general
if skyfile :
# lower axes : sky
ax2 = pl.axes([0.03,0.05,0.95,0.2])
skywave, skyflux = np.loadtxt( skyfile, unpack=True, usecols=[0,1] )
pl.plot( skywave, skyflux , color='darkgreen',
ls='-', drawstyle='steps' )
ax1 = pl.axes([0.03,0.25,0.95,0.63], sharex=ax2)
# upper axes : source
# TODO : better smoothing !!!
# if smoothwindow : flux = medsmooth( flux, smoothwindow )
if smooth :
if smoothwindow<5 :
smoothwindow=5
order=3
print("raising S-G smoothwindow window to 5, order 3.")
if smoothwindow<7 :
order=3
else :
order=5
flux = savitzky_golay(self.flux, smoothwindow, order=order)
else :
flux = self.flux
if showerr :
pl.errorbar( self.wave, flux/np.median(flux),
self.fluxerror/np.median(flux),
marker=' ', color='k', ls='-', drawstyle='steps' )
else :
pl.plot( self.wave, flux/np.median(flux),
marker=' ', color='k', ls='-', drawstyle='steps' )
if lineset!='none':
marklines( zlines, lineset )
if plotwavemin==0:
plotwavemin = self.wave.min()
if plotwavemax==0:
plotwavemin = self.wave.max()
if plotfluxmin==0:
plotfluxmin = -np.std(flux)
if plotfluxmax==0:
plotfluxmax = flux.max() + np.std(flux)
ax = pl.gca()
ax.set_xlim(plotwavemin, plotwavemax)
ax.set_ylim(plotfluxmin, plotfluxmax)
#pl.draw()
#pl.show()
return
def matchlines(self, zlines=1.0, lineset='sdss',
smooth=False, smoothwindow=11, showerr=False):
interact(
self.plotspec,
zlines=widgets.FloatSlider(min=0.0, max=11.0, step=0.1,
value=zlines,
description='Redshift guess'),
lineset=widgets.Select(
options=['sdss','sn','ia','abs','agn','em','sky','CuAr'],
description='Line list:',
value=lineset,
disabled = False),
smooth=smooth,
smoothwindow=widgets.IntSlider(
min=5,max=75,step=2,value=smoothwindow),
showerr=showerr,
plotfluxmin=-np.std(self.flux),
plotfluxmax=np.max(self.flux)+np.std(self.flux),
plotwavemin=self.wave.min(), plotwavemax=self.wave.max()
)
class MultiSpectrum(Spectrum):
"""A spectrum with data drawn from multiple data files"""
def __init__(self, specfilelist, **kwargs):
self.filename = None
self.filenamelist = specfilelist
self.wave = np.array([])
self.flux = np.array([])
self.fluxerror = np.array([])
self.waveunit = None
# TODO : make this more robust:
# TODO: check input wavelength range,
# TODO: check for wavelength overlap
# TODO: allow user to clip the input spectra
# TODO: apply a flux normalization to smoothly join spectra
# TODO: allow user to specify flux normalization
for specfile in specfilelist:
inputspec = Spectrum(specfile, **kwargs)
self.wave = np.append(self.wave, inputspec.wave)
self.flux = np.append(self.flux, inputspec.flux)
self.fluxerror = np.append(self.fluxerror, inputspec.fluxerror)
def binspecdat( wavelength, flux, fluxerr=[], binwidth=10, sigclip=0, sumerrs=False,
wstart=0, wend=0 ):
""" bin up the given wavelength and flux arrays
and return the binned values.
binwidth is in the wavelength units of the wavelength
array (typically Angstroms)
"""
w,f = wavelength, flux
wbinned, fbinned = [], []
wbin,fbin,dfbin = np.array([]), np.array([]), np.array([])
dw, df = [], []
if wstart : istart = np.where( w>wstart )[0][0]
else : istart = 0
if wend : iend = np.where( w<wend )[0][-1]
else : iend = len(w)
w0 = w[istart]
for i in range(istart,iend):
fullbin = False
if wend and w[i]>wend : break
if w[i]>w0+binwidth :
# determine the mean value in this bin
w0 = w[i]
igoodval = []
if sigclip :
# use sigma clipping to reject outliers
igoodval = isigclip( fbin, sigclip )
if len(igoodval) :
wbinval = np.mean( wbin[igoodval] )
fbinval = np.mean( fbin[igoodval] )
dwbinval = (wbin[igoodval].max() - wbin[igoodval].min())/2.
#dwbinval = (wbin.max() - wbin.min())/2.
if sumerrs :
# flux uncertainty is the quadratic sum of the mean flux error
# and the error of the mean
dfbinval1 = np.std( fbin[igoodval] ) / np.sqrt(len(igoodval)-2)
dfbinval2 = np.mean( dfbin[igoodval] ) / np.sqrt(len(igoodval)-2)
dfbinval = np.sqrt( dfbinval1**2 + dfbinval2**2 )
else :
# flux uncertainty is the std error of the mean
dfbinval = np.std( fbin[igoodval] ) / np.sqrt(len(igoodval)-2)
fullbin = True
# note: if the binning is not successful, we continue building the bin
else :
# use a straight median
wbinval = np.median( wbin )
fbinval = np.median( fbin )
dwbinval = (wbin[-1]-wbin[0])/2.
if sumerrs :
# flux uncertainty is the quadratic sum of the mean flux error
# and the error of the mean
dfbinval1 = np.std( fbin )/np.sqrt(len(fbin)-2)
dfbinval2 = np.mean( dfbin )
dfbinval = np.sqrt( dfbinval1**2 + dfbinval2**2 )
else :
# flux uncertainty is the std error of the mean
dfbinval = np.std( fbin ) / np.sqrt(max(1,len(fbin)))
fullbin = True
if fullbin :
wbinned.append( wbinval )
fbinned.append( fbinval )
dw.append( dwbinval )
df.append( dfbinval )
# start a new bin
wbin,fbin,dfbin = np.array([]), np.array([]), np.array([])
# add a new data point to the bin
wbin = np.append( wbin, w[i] )
fbin = np.append( fbin, f[i] )
if len(fluxerr):
dfbin = np.append( dfbin, fluxerr[i] )
else : dfbin = np.append( dfbin, 0 )
return( np.array( wbinned ), np.array(dw), np.array(fbinned), np.array(df) )
def binspecdattomatch( wavelength, flux, wavetomatch, fluxerr=[], sigclip=0,
sumerrs=False ):
""" bin up the given wavelength and flux arrays
and return the binned values.
binwidth is in the wavelength units of the wavelength
array (typically Angstroms)
"""
w,f = wavelength, flux
if len(fluxerr):
df = fluxerr
else :
df=np.zeros(len(f))
wavetomatch = np.asarray(wavetomatch)
wavetomatch_halfbinwidth = np.diff(wavetomatch)/2.
lastbinlow = wavetomatch[-1] - wavetomatch_halfbinwidth[-1]
lastbinhigh = wavetomatch[-1] + wavetomatch_halfbinwidth[-1]
wavebinedges = np.append( wavetomatch[:-1]-wavetomatch_halfbinwidth,
np.array([lastbinlow,lastbinhigh]))
wbinned, dwbinned, fbinned, dfbinned = [], [], [], []
for i in range(len(wavebinedges)-1):
wavebinmin=wavebinedges[i]
wavebinmax=wavebinedges[i+1]
iinbin = np.where((w>=wavebinmin)&(w<wavebinmax))
winbin = w[iinbin]
finbin = f[iinbin]
dfinbin = df[iinbin]
if sigclip :
# use sigma clipping to reject outliers
igoodval = isigclip( finbin, sigclip )
if len(igoodval) :
wbinval = np.mean( winbin[igoodval] )
fbinval = np.mean( finbin[igoodval] )
dwbinval = (winbin[igoodval].max() - winbin[igoodval].min())/2.
#dwbinval = (wbin.max() - wbin.min())/2.
if sumerrs :
# flux uncertainty is the quadratic sum of the mean flux error
# and the error of the mean
dfbinval1 = np.std( finbin[igoodval] ) / np.sqrt(len(igoodval)-2)
dfbinval2 = np.mean( dfinbin[igoodval] ) / np.sqrt(len(igoodval)-2)
dfbinval = np.sqrt( dfbinval1**2 + dfbinval2**2 )
else :
# flux uncertainty is the std error of the mean
dfbinval = np.std( finbin[igoodval] ) / np.sqrt(len(igoodval)-2)
else :
# use a straight median
wbinval = np.median( winbin )
fbinval = np.median( finbin )
dwbinval = (winbin[-1]-winbin[0])/2.
if sumerrs :
# flux uncertainty is the quadratic sum of the mean flux error
# and the error of the mean
dfbinval1 = np.std( finbin )/np.sqrt(len(finbin)-2)
dfbinval2 = np.mean( dfinbin )
dfbinval = np.sqrt( dfbinval1**2 + dfbinval2**2 )
else :
# flux uncertainty is the std error of the mean
dfbinval = np.std( finbin ) / np.sqrt(max(1,len(finbin)))
wbinned.append( wbinval )
fbinned.append( fbinval )
dwbinned.append( dwbinval )
dfbinned.append( dfbinval )
return( np.array( wbinned ), np.array(dwbinned), np.array(fbinned), np.array(dfbinned) )
def isigclip( valarray, sigclip, igood=[], maxiter=10, thisiter=0 ) :
""" find the indices of valarray that
survive after a clipping all values more than
sigclip from the mean. recursively iterative """
if not type(valarray)==np.ndarray :
valarray = np.array( valarray )
if not len(igood) : igood = range(len(valarray))
Ngood = len(igood)
mnval = np.mean( valarray[igood] )
sigma = np.std( valarray[igood] )
igood = np.where( (np.abs(valarray-mnval)<(sigclip*sigma)) )[0]
# import pdb; pdb.set_trace()
if len(igood) == Ngood : return( igood )
if thisiter>=maxiter :
print("WARNING : Stopping after %i recursions"%maxiter)
return( igood )
thisiter+=1
igood = isigclip( valarray, sigclip, igood=igood, maxiter=maxiter, thisiter=thisiter )
return( igood )
def specfits2dat( specfitsfile, specdatfile ):
""" convert a 1-d spectrum fits file directly
to a two-column ascii data text file """
spec = Spectrum( specfitsfile )
wspec2dat( spec.wave, spec.flux, specdatfile )
return( specdatfile )
def wspec2dat( wave, flux, specdatfile, err=None):
""" write wavelength and flux
into a two-column ascii data text file """
fout = open( specdatfile, 'w' )
if err is not None :
for w,f,e in zip( wave, flux, err ):
print >>fout, "%8.5e %8.5e %8.5e"%(w,f,e)
fout.close()
else :
for w,f in zip( wave, flux ):
print >>fout, "%8.5e %8.5e"%(w,f)
fout.close()
def getSNIa( age=0, z=1 ):
""" read in and return a SNIa spec file"""
import os
import numpy as np
import sys
thisfile = sys.argv[0]
if 'ipython' in thisfile : thisfile = __file__
thispath = os.path.abspath( os.path.dirname( thisfile ) )
sedfile = os.path.join( thispath, 'Hsiao07.dat')
d,w,f = np.loadtxt( sedfile, unpack=True )
#d = d.astype(int)
uniquedays = np.unique( d )
ibestday = np.abs( uniquedays-age ).argmin()
iday = np.where( d==uniquedays[ibestday] )
dbest = d[ iday ]
wbest = w[ iday ]
fbest = f[ iday ]
return( wbest*(1+z), fbest )
def matchSNIa( specfile, age=0, z=1.0, smooth=0, showerr=False):
""" interactive chi-by-eye SN spec fitting """
pl.ion()
pl.clf()
snfile = getSNIa( age=age, z=z )
ax1,ax2 = plotspecSNIa( specfile, age=age, z=z, smooth=smooth, showerr=showerr )
ax1.set_xlim( 3500*(1+z), 9000*(1+z) )
ax2.set_xlim( 3500, 9000 )
userin=''
print("age=%i z=%.3f"%(age, z))
print("""
q : quit
h : help
z <zval> : set z
a <age> : set age in rest-frame days from peak
s <npix> : apply median smoothing, radius N pix (odd numbers only)
""")
while userin!='q' :
userin=raw_input('')
if userin=='q': break
elif userin.startswith('z') :
z = float( userin.split()[1] )
pl.clf()
plotspecSNIa( specfile, age=age, z=z, smooth=smooth, showerr=showerr )
pl.draw()
print("re-plottd at z=%.3f"%z)
elif userin.startswith('a') :
age = int( userin.split()[1] )
pl.clf()
plotspecSNIa( specfile, age=age, z=z, smooth=smooth, showerr=showerr )
pl.draw()
print("re-plottd at age=%i"%age)
elif userin.startswith('s') :
smooth = int( userin.split()[1] )
pl.clf()
plotspecSNIa( specfile, age=age, z=z, smooth=smooth, showerr=showerr )
print("re-plottd with smoothgin=%i"%smooth)
elif userin=='h':
print("""
q : quit
h : help
z <zval> : set z
a <age> : set age in rest-frame days from peak
s <npix> : apply median smoothing, radius N pix (odd numbers only)
""")
return( z )
def plotspecSNIa( specfile, age=0, z=1, smooth=0, showerr=False, scale=0, color='k' ):
""" plot the source spectrum and overlay a SN spectrum """
import numpy as np
from scipy import interpolate as scint
medsmooth = lambda f,N : np.array( [ np.median( f[max(0,i-N):min(len(f),max(0,i-N)+2*N)]) for i in range(len(f)) ] )
try :
wave, flux, fluxerr = np.loadtxt( specfile, unpack=True, usecols=[0,1,2] )
# fluxerr = fluxerr / 5.
except :
wave, flux = np.loadtxt( specfile, unpack=True, usecols=[0,1] )
fluxerr = np.ones( len(flux) )
showerr=False
snwave, snflux = getSNIa( age, z )
snfinterp = scint.interp1d( snwave, snflux, bounds_error=False, fill_value=0 )
snf = snfinterp( wave )
if smooth>0 :
if smooth<5 :
smooth=5
order=3
print("raising S-G smooth window to 5, order 3.")
if smooth<7 :
order=3
else :
order=5
flux = savitzky_golay( flux, smooth, order=order )
elif smooth<0:
flux = medsmooth( flux, abs(smooth) )
if scale :
if showerr :
pl.errorbar( wave, flux, fluxerr, marker=' ', color=color, ls='-', drawstyle='steps-mid', capsize=0, lw=0.5, scalex=False )
else :
pl.plot( wave, flux, marker=' ', color=color, ls='-', drawstyle='steps', lw=0.5, ) # , scalex=False )
pl.plot( snwave, snflux * scale , marker=' ', color='r', ls='-', lw=1.5, scalex=False )
else :
num = np.sum( snf*flux / fluxerr**2 )
denom = np.sum( snf**2./ fluxerr**2 )
scale = num / denom
if showerr :
pl.errorbar( wave, flux/np.median(flux), fluxerr/np.median(flux), marker=' ', color=color, ls='-', drawstyle='steps-mid', capsize=0, lw=0.5, scalex=False )
else :
pl.plot( wave, flux/np.median(flux), marker=' ', color=color, ls='-', drawstyle='steps', lw=0.5, ) # , scalex=False )
pl.plot( snwave, snflux * scale / np.median(flux) , marker=' ', color='r', ls='-', lw=1.5, scalex=False )
ax1 = pl.gca()
ax2 = ax1.twiny()
ax2.set_xlim( ax1.get_xlim()[0] / (1+z), ax1.get_xlim()[1] / (1+z) )
ax1.set_xlabel('Observed Wavelength (\AA)')
ax2.set_xlabel('Rest Wavelength (\AA)')
return(ax1,ax2)
def savitzky_golay(y, window_size=5, order=3, deriv=0):
r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
The Savitzky-Golay filter removes high frequency noise from data.
It has the advantage of preserving the original shape and
features of the signal better than other types of filtering
approaches, such as moving averages techhniques.
Parameters
----------
y : array_like, shape (N,)
the values of the time history of the signal.
window_size : int
the length of the window. Must be an odd integer number.
order : int
the order of the polynomial used in the filtering.
Must be less then `window_size` - 1.
deriv: int
the order of the derivative to compute (default = 0 means only smoothing)
Returns
-------
ys : ndarray, shape (N)
the smoothed signal (or it's n-th derivative).
Notes
-----
The Savitzky-Golay is a type of low-pass filter, particularly
suited for smoothing noisy data. The main idea behind this
approach is to make for each point a least-square fit with a
polynomial of high order over a odd-sized window centered at
the point.
Examples
--------
t = np.linspace(-4, 4, 500)
y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape)
ysg = savitzky_golay(y, window_size=31, order=4)
import matplotlib.pyplot as plt
plt.plot(t, y, label='Noisy signal')
plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal')
plt.plot(t, ysg, 'r', label='Filtered signal')
plt.legend()
plt.show()
References
----------
.. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of
Data by Simplified Least Squares Procedures. Analytical
Chemistry, 1964, 36 (8), pp 1627-1639.
.. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing
W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery
Cambridge University Press ISBN-13: 9780521880688
"""
try:
window_size = np.abs(np.int(window_size))
order = np.abs(np.int(order))
except ValueError, msg:
raise ValueError("window_size and order have to be of type int")
if window_size % 2 != 1 or window_size < 1:
raise TypeError("window_size size must be a positive odd number")
if window_size < order + 2:
raise TypeError("window_size is too small for the polynomials order")
order_range = range(order+1)
half_window = (window_size -1) // 2
# precompute coefficients
b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
m = np.linalg.pinv(b).A[deriv]
# pad the signal at the extremes with
# values taken from the signal itself
firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
y = np.concatenate((firstvals, y, lastvals))
return np.convolve( m, y, mode='valid')
def ccm_unred(wave, flux, ebv, r_v=""):
"""ccm_unred(wave, flux, ebv, r_v="")
Deredden a flux vector using the CCM 1989 parameterization
Returns an array of the unreddened flux
INPUTS:
wave - array of wavelengths (in Angstroms)
dec - calibrated flux array, same number of elements as wave
ebv - colour excess E(B-V) float. If a negative ebv is supplied
fluxes will be reddened rather than dereddened
OPTIONAL INPUT:
r_v - float specifying the ratio of total selective
extinction R(V) = A(V)/E(B-V). If not specified,
then r_v = 3.1
OUTPUTS:
funred - unreddened calibrated flux array, same number of
elements as wave
NOTES:
1. This function was converted from the IDL Astrolib procedure
last updated in April 1998. All notes from that function
(provided below) are relevant to this function
2. (From IDL:) The CCM curve shows good agreement with the Savage & Mathis (1979)
ultraviolet curve shortward of 1400 A, but is probably
preferable between 1200 and 1400 A.
3. (From IDL:) Many sightlines with peculiar ultraviolet interstellar extinction
can be represented with a CCM curve, if the proper value of
R(V) is supplied.
4. (From IDL:) Curve is extrapolated between 912 and 1000 A as suggested by
Longo et al. (1989, ApJ, 339,474)
5. (From IDL:) Use the 4 parameter calling sequence if you wish to save the
original flux vector.
6. (From IDL:) Valencic et al. (2004, ApJ, 616, 912) revise the ultraviolet CCM
curve (3.3 -- 8.0 um-1). But since their revised curve does
not connect smoothly with longer and shorter wavelengths, it is
not included here.
7. For the optical/NIR transformation, the coefficients from
O'Donnell (1994) are used
>>> ccm_unred([1000, 2000, 3000], [1, 1, 1], 2 )
array([9.7976e+012, 1.12064e+07, 32287.1])
"""
import numpy as np
wave = np.array(wave, float)
flux = np.array(flux, float)
if wave.size != flux.size: raise TypeError, 'ERROR - wave and flux vectors must be the same size'
if not bool(r_v): r_v = 3.1
x = 10000.0/wave
npts = wave.size
a = np.zeros(npts, float)
b = np.zeros(npts, float)
###############################
#Infrared
good = np.where( (x > 0.3) & (x < 1.1) )
a[good] = 0.574 * x[good]**(1.61)
b[good] = -0.527 * x[good]**(1.61)
###############################
# Optical & Near IR
good = np.where( (x >= 1.1) & (x < 3.3) )
y = x[good] - 1.82
c1 = np.array([ 1.0 , 0.104, -0.609, 0.701, 1.137, \
-1.718, -0.827, 1.647, -0.505 ])
c2 = np.array([ 0.0, 1.952, 2.908, -3.989, -7.985, \
11.102, 5.491, -10.805, 3.347 ] )
a[good] = np.polyval(c1[::-1], y)
b[good] = np.polyval(c2[::-1], y)
###############################
# Mid-UV
good = np.where( (x >= 3.3) & (x < 8) )
y = x[good]
F_a = np.zeros(np.size(good),float)
F_b = np.zeros(np.size(good),float)
good1 = np.where( y > 5.9 )
if np.size(good1) > 0:
y1 = y[good1] - 5.9
F_a[ good1] = -0.04473 * y1**2 - 0.009779 * y1**3
F_b[ good1] = 0.2130 * y1**2 + 0.1207 * y1**3
a[good] = 1.752 - 0.316*y - (0.104 / ( (y-4.67)**2 + 0.341 )) + F_a
b[good] = -3.090 + 1.825*y + (1.206 / ( (y-4.62)**2 + 0.263 )) + F_b
###############################
# Far-UV
good = np.where( (x >= 8) & (x <= 11) )
y = x[good] - 8.0
c1 = [ -1.073, -0.628, 0.137, -0.070 ]
c2 = [ 13.670, 4.257, -0.420, 0.374 ]
a[good] = np.polyval(c1[::-1], y)
b[good] = np.polyval(c2[::-1], y)
# Applying Extinction Correction
a_v = r_v * ebv
a_lambda = a_v * (a + b/r_v)
funred = flux * 10.0**(0.4*a_lambda)
return funred
def marklines( z, lineset, telluric=True ):
if lineset=='sdss' : lineset = sdsslines
elif lineset=='sn' : lineset = snialines
elif lineset=='ia' : lineset = snialines
elif lineset=='abs' : lineset = abslines
elif lineset=='agn' : lineset = agnlines
elif lineset=='em' : lineset = emissionlines
elif lineset=='sky' : lineset = skylines
elif lineset=='CuAr' : lineset = CuArlines
ax = pl.gca()
ax.set_autoscale_on(False)
ymin = ax.get_ylim()[0]
ymax = ax.get_ylim()[1]
y = 0.8
i=0
for linepair in lineset :
if i==0: c,y='r',0.8
elif i==1: c,y='g',0.75
elif i==2: c,y='b',0.70
i+=1
if i>2: i=0
w = linepair[0]
name = linepair[1]
ax.axvline( w * (1+z), color=c )
ax.text( w * (1+z)+10, y*(ymax-ymin)+ymin, name, color=c)
if telluric :
ax.bar(7589,2*(ymax-ymin), bottom=ymin-ymax,
width=70, alpha=0.1, color='k' )
ax.text( 7593, ymin+(ymax-ymin)/2, r'$\bigoplus$',color='k')
#show()
return()
agnlines = [
[1033.30004882812, 'OVI'],
[1215.67004394531, r'Ly$\alpha$'],
[1239.42004394531, 'NV'],
[1305.53002929688, 'OI'],
[1335.52001953125, 'CII'],
[1399.80004882812, 'SiIV,OIV'],
[1545.85998535156, 'CIV'],
[1640.40002441406, 'HeII'],
[1665.84997558594, 'OIII'],
[1857.40002441406, 'AlIII'],
[1908.27001953125, 'CIII'],
[2326.0, 'CII'],
[2439.5, 'NeIV'],
[2800.32006835938, 'MgII'],
[3346.7900390625, 'NeV'],
[3426.85009765625, 'NeV'],
[3728.30004882812, 'OII'],
[3798.97607421875, 'H$\theta$'],
[3836.46997070312, 'He'],
[3889.0, 'HeI'],
[4072.30004882812, 'SII'],
[4102.89013671875, 'Hd'],
[4341.68017578125, 'Hg'],
[4364.43603515625, 'OIII'],
[4686, 'HeII'],
[4862.68017578125, r'H$\beta$'],
[4960.294921875, 'OIII'],
[5008.240234375, 'OIII'],
[6302.0458984375, 'OI'],
[6365.5361328125, ''],
[6549.85986328125, ''],
[6564.60986328125, ''],
[6585.27001953125, r'H$\alpha$,NII'],
[6718.2900390625, ''],
[6732.669921875, 'SII'],
]
snialines = [
[3850,'CaII H&K'],
[4000,'SiII'],
[4300,'MgII'],
[4800,'FeII'],
[5400,'SiII-W'],
[5800,'SiII'],
[6150,'SiII 6150'],
[8100,'CaII IR'],
]
abslines = [
[3241.98388671875, 'TI_II'],
[3302.36889648438, 'NA_I'],
[3302.97900390625, 'NA_I'],
[3383.76098632812, 'TI_II'],
[3933.6630859375, 'CA_II'],
[3968.46801757812, 'CA_II'],
[4102.89013671875, 'H_delta'],
[4226.72802734375, 'CA_I'],
[4276.830078125, '[FeII]'],
[4287.39990234375, '[FeII]'],
[4341.68017578125, 'H_gamma'],
[4364.43603515625, 'OIII'],
[4686.0, 'HeII4686'],
[4862.68017578125, 'H_beta'],
[5176.7001953125, 'Mg'],
[5876.0, '[HeI]5876'],
[5889.9501953125, 'NA_I'],
[5895.923828125, 'NA_I'],
[6564.60986328125, 'H_alpha'],
[7664.89892578125, 'K_I'],
[7698.958984375, 'K_I'],
]
sdsslines = [
[1033.30004882812, 'OVI'],
[1215.67004394531, 'Ly_alpha'],
[1239.42004394531, 'NV'],
[1305.53002929688, 'OI'],
[1335.52001953125, 'CII'],
[1399.80004882812, 'SiIV+OIV'],
[1545.85998535156, 'CIV'],
[1640.40002441406, 'HeII'],
[1665.84997558594, 'OIII'],
[1857.40002441406, 'AlIII'],
[1908.27001953125, 'CIII'],
[2326.0, 'CII'],
[2439.5, 'NeIV'],
[2800.32006835938, 'MgII'],
[3346.7900390625, 'NeV'],
[3426.85009765625, 'NeV'],
[3728.30004882812, 'OII'],
[3798.97607421875, 'H_theta'],
[3836.46997070312, 'H_eta'],
[3889.0, 'HeI'],
[3934.77709960938, 'K'],
[3969.587890625, 'H'],
[4072.30004882812, 'SII'],
[4102.89013671875, 'H_delta'],
[4305.60986328125, 'G'],
[4341.68017578125, 'H_gamma'],
[4364.43603515625, 'OIII'],
[4862.68017578125, 'H_beta'],
[4960.294921875, 'OIII'],
[5008.240234375, 'OIII'],
[5176.7001953125, 'Mg'],
[5895.60009765625, 'Na'],
[6302.0458984375, 'OI'],
[6365.5361328125, 'OI'],
[6549.85986328125, 'NII'],
[6564.60986328125, 'H_alpha'],
[6585.27001953125, 'NII'],
[6707.89013671875, 'Li'],
[6718.2900390625, 'SII'],
[6732.669921875, 'SII'],
]
emissionlines = [
[3726.15991210938, '[OII]'],
[3728.90991210938, '[OII]'],
[4101.0, 'HDELTA'],
[4276.830078125, '[FeII]'],
[4287.39990234375, '[FeII]'],
[4319.6201171875, '[FeII]'],
[4340.4677734375, 'HGAMMA'],
[4363.2099609375, '[OIII]4363'],
[4413.77978515625, '[FeII]'],
[4416.27001953125, '[FeII]'],
[4686.0, 'HeII4686'],
[4861.31982421875, 'HBETA'],
[4889.6201171875, '[FeII]'],
[4905.33984375, '[FeII]'],
[4958.91015625, '[OIII]4959'],
[5006.83984375, '[OIII]5007'],
[5111.6298828125, '[FeII]'],
[5158.77978515625, '[FeII]'],
[5199.60009765625, '[NI]'],
[5261.6201171875, '[FeII]'],
[5577.31005859375, '[OI]'],
[5876.0, '[HeI]5876'],
[6300.2998046875, '[OI]'],
[6363.77978515625, '[OI]'],
[6548.10009765625, '[NII]6548'],
[6562.81689453125, 'HALPHA'],
[6583.60009765625, '[NII]6584'],
[6716.47021484375, '[SII]6717'],
[6730.85009765625, '[SII]6731'],
[7002.0, 'OI'],
[7005.7001953125, '[ArV]'],
[7065.2998046875, 'HeI'],
[7135.7998046875, '[ArIII]'],
[7236.2001953125, 'CII'],
[7254.39990234375, 'OI'],
[7281.2998046875, 'HeI'],
[7291.4599609375, '[CaII]'],
[7319.60009765625, '[OII]'],
[7323.8798828125, '[CaII]'],
[7330.2001953125, '[OIII]'],
[7377.7998046875, '[NiII]'],
[7452.5, '[FeII]'],
[7468.2998046875, 'NI'],
[7751.10009765625, '[ArIII]'],
[7816.2001953125, 'HeI'],