-
Notifications
You must be signed in to change notification settings - Fork 0
/
floyds.py
309 lines (252 loc) · 9.96 KB
/
floyds.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
####################################################################################
# Script to simulate LCOGT FLOYDS results
# Katie O'Neill, Liam Kirkpatrick (with some help from jswift)
#
# KO 3/29/16: Divided into two preliminary functions, read_spectra and bin_spectra
# KO/LK 3/29/16: Met study hall to discuss progress/next steps
# KO/LK 4/4/16: Met study hall to regrid_spectra
# KO/LK 4/5/16: Met study hall to revise regrid_spectra
# KO 4/7/16: Tried to fix regrid_spectra, failed. Started get_logg
# KO/LK 4/12/16: added poisson noise to bin_spectra
# KO 4/13/16: started work on get_values, combined get_values and get_logg
# KO 4/19/16: started get_snr
# KO 4/20/16: added comments, cleaned up
# jswift 4/24/16: general clean up, separated add_noise function from rebin_spectrum,
# import homegrown constants (in utils) instead of scipy constants,
# smooth_spectrum, and flatten_spectrum added as key elements in
# preparation for autocorrelation
# KO/LK 5/5/16: Started cross_correlate
# jswift 5/6/16: Bug fixes. There was a bug involving numerical error in regrid_spec
# KO 5/8/16: Started work on velocity x-axis conversion in cross_correlate
# KO/LK 5/9/16: Continued x-axis conversion
# KO 5/10/16: Minor changes, worked on muliplication problem
# KO/LK/js 5/22/16: Completed cross_correlate()
####################################################################################
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from scipy.signal import resample
from scipy import interpolate
import pdb
import constants as c
import matplotlib.patches as mpatches
import glob as glob
import math
from scipy.signal import savgol_filter
from scipy.signal import correlate
def read_spectrum(specfile='lte03800-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits',
wavefile='WAVE_PHOENIX-ACES-AGSS-COND-2011.fits', plot=False):
'''
Read spectrum and plot (no frills version)
'''
spec,spech = fits.getdata(specfile,header=True)
wave,waveh = fits.getdata(wavefile,header=True)
if plot:
plt.ion()
plt.figure(1)
plt.clf()
plt.plot(wave,spec)
plt.xlabel('Wavelength')
plt.ylabel('Flux')
return wave, spec
######################################################################
def bin_spectrum(wave,spec, R=550,plot=False):
'''
Read spectrum and plot, limited to FLOYDS wavelength values
(js: you will want noise addition to be a separate procedure)
'''
inds, = np.where((wave >= 5400) & (wave <= 10000))
plt.figure(3)
plt.clf()
plt.plot(wave[inds],spec[inds])
dl = np.median(wave[inds])/R
num = np.int(np.round((np.max(wave[inds])-np.min(wave[inds]))/dl))
wave_resamp = []
spec_resamp = []
for i in range(num):
try:
bin, = np.where( (wave >= np.min(wave[inds])+ dl*i) &
(wave < np.min(wave[inds]) + dl*(i+1)) )
wave_resamp = np.append(wave_resamp,np.mean(wave[bin]))
spec_resamp = np.append(spec_resamp,np.mean(spec[bin]))
except:
print 'Skipping iteration '+str(i)
if plot:
plt.ion()
plt.figure(2)
plt.clf()
plt.plot(wave,spec,'k-')
plt.plot(wave_resamp,spec_resamp,'r-')
plt.xlabel('Wavelength')
plt.ylabel('Flux')
black_patch = mpatches.Patch(color='K', label = 'Original')
blue_patch = mpatches.Patch(color='R', label = 'Re-binned')
plt.legend(handles=[black_patch,blue_patch], loc=4)
plt.xlim(np.min(wave[inds]),np.max(wave[inds]))
plt.show()
return wave_resamp, spec_resamp
######################################################################
def add_noise(wave,spec,SNR=50.0,plot=False):
'''
Add poisson noise to a binned spectrum
'''
scale = SNR**2
scaled_s = (scale*spec)/(np.median(spec))
noisy_spec = np.random.poisson(scaled_s)
if plot:
plt.ion()
plt.figure(3)
plt.clf()
plt.plot(wave,scaled_s,'k-')
plt.plot(wave,noisy_spec,'r-')
plt.xlabel('Wavelength')
plt.ylabel('Flux')
black_patch = mpatches.Patch(color='K', label = 'Original')
red_patch = mpatches.Patch(color='R', label = 'Noisy')
plt.legend(handles=[black_patch,red_patch], loc=4)
plt.xlim(np.min(wave),np.max(wave))
plt.show()
return wave, noisy_spec
######################################################################
def regrid_spectrum(wave,spec,plot=False):
"""
Resample spectrum into logspace
"""
startwave = np.min(wave)
stopwave = np.max(wave)
lnwave = np.linspace(np.log(startwave),np.log(stopwave),len(wave))
wave_logspace = np.exp(lnwave)
# Fix for numerical errors in going to log and normal space
if np.min(wave_logspace) < startwave:
wave_logspace[0] = startwave
if np.max(wave_logspace) > stopwave:
wave_logspace[-1] = stopwave
wave_interpolate = interpolate.interp1d(wave, spec)
wave_final = wave_interpolate(wave_logspace)
if plot:
plt.ion()
plt.clf()
plt.figure(4)
plt.plot(wave_final,spec,'r-')
plt.xlim(np.min(wave[inds]),np.max(wave[inds]))
return wave_logspace, wave_final
######################################################################
def smooth_spectrum(spec,window=45,polyorder=3):
'''
Smooth spectrum so that it may be "flattened" in preparation for
cross correlation
'''
if window % 2 == 0:
print('Filter window must be odd!')
return None
smooth_spec = savgol_filter(spec,window,polyorder)
return smooth_spec
######################################################################
def flatten_spec(spec,window=45,polyorder=3,plot=False):
'''
Flatten given spectrum using a Savitzky-Golay filter
'''
smooth_spec = smooth_spectrum(spec,window=window,polyorder=polyorder)
flat_spec = spec/smooth_spec - 1
if plot:
plt.ion()
plt.figure(5)
plt.clf()
plt.plot(spec/np.median(spec)-1,'k-')
plt.plot(flat_spec,'r-')
plt.axhline(y=0,color='g',linestyle='--')
plt.xlabel('Pixel')
plt.ylabel('Flux')
black_patch = mpatches.Patch(color='K', label = 'Original')
red_patch = mpatches.Patch(color='R', label = 'Flattened')
plt.legend(handles=[black_patch,red_patch], loc=4)
plt.show()
return flat_spec
######################################################################
def get_logg(mass,radius):
'''
Return the value of logg based on mass and radius of star (in solar units)
'''
G = c.G
M = c.Msun * mass
R = c.Rsun * radius
return np.log10((G*M)/(R**2))
######################################################################
def get_values(specfile='lte03800-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'):
"""
Returns values of temp, logg, and metallicity from PHOENIX file
should eventually read the header of the file
"""
temp = float(specfile[3:-48])
logg = float(specfile[9:-44])
metal = float(specfile[14:-39])
return temp, logg, metal
######################################################################
def get_snr(time=700,mag=15):
"""
Calculates expected FLOYDS SNR based on given time and magnitude
"""
B = 1889.9
T = np.sqrt(time)
M = 10**(-0.2 * mag)
SNR = B * T * M
return SNR
######################################################################
def get_inttime(mag=15,SNR=20):
"""
Calculates integration time needed to acheive a specified SNR for a
star of a given a magnitude.
"""
return 10**(0.4*mag)*(SNR/1889.9)**2
######################################################################
def cross_correlate(SNR=10.0):
wave,spec = read_spectrum()
wave_resamp, spec_resamp = bin_spectrum(wave,spec)
#With noise
wave_resamp, noisy_spec = add_noise(wave_resamp, spec_resamp, SNR=SNR)
flat_spec_noise = flatten_spec(noisy_spec)
wave_logspace_noise, flat_spec_log_noise = regrid_spectrum(wave_resamp, flat_spec_noise)
#Without noise
flat_spec_no_noise = flatten_spec(spec_resamp)
wave_logspace_no_noise, flat_spec_log = regrid_spectrum(wave_resamp,flat_spec_no_noise)
#Plot with noise and without noise, both flattened and regridded into logspace
plt.ion()
plt.figure(1)
plt.clf()
plt.plot(wave_logspace_noise,flat_spec_log_noise)
plt.plot(wave_logspace_no_noise,flat_spec_log)
#Cross correlate
#(Need to check if this is the right order for np.correlate)
cor = correlate(flat_spec_log_noise,flat_spec_log, mode='full' )
plt.ion()
plt.figure(2)
plt.clf()
plt.plot(cor)
#Cross correlate with velocity on x-axis
#delta_lnwave = np.log(wave_logspace_noise)
#take median of difference and convert to meters from angstroms
#diff = np.median((np.diff(delta_lnwave)))/(1e10)
# set value speed light in m/s
c = 2.99792458e8
dv=(((wave_logspace_noise[1]-wave_logspace_noise[0])/(wave_logspace_noise[0]))*c)
# recenter cor
l = len(cor)
ran = np.array(range(l))
n_init = ((l-1)/2.0)
n_fin = ran - n_init
#creates graph with peak centered at 0
plt.ion()
plt.figure(4)
plt.clf()
plt.plot(n_fin, cor)
#error here, says operands could not be broadcast together with shapes (328,) (657,)
n_arr = np.array(n_fin)
v = (dv * n_arr)/1000.
plt.ion()
plt.figure(3)
plt.clf()
plt.plot(v, cor, 'o')
plt.plot(v,cor)
plt.xlabel('Velocity km/s')
plt.ylabel('Correlation Amplitude')
return