forked from soar-telescope/goodman_pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredgoodman.py
executable file
·321 lines (276 loc) · 9.16 KB
/
redgoodman.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
#!/usr/bin/python3.4
"""
Simon Torres 2016-06-28
pipeline for GOODMAN spectra reduction.
"""
import sys
import os
import glob
#import pyfits as fits
import numpy as np
#import scipy.stats as stats
import re
#import subprocess
import time
import astropy.stats as asst
from astropy.io import fits
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import warnings
warnings.filterwarnings('ignore')
#cython stuff
#import pyximport; pyximport.install()
"""global variables"""
patt_over_trim = 'to_'
patt_bias_corr = 'bc_'
patt_flat_corr = 'fc_'
class night:
def __init__(self,date):
self.date = date
self.all = []
self.bias = []
self.flats_wg= []
self.flats_ng= []
self.sci = []
self.lamp = []
self.master_bias = ''
self.master_flat = ''
self.last_prefix = ''
#methods to store data
def add_bias(self,inbias):
self.bias.append(inbias)
self.all.append(inbias)
def add_flat_wg(self,inflat):
self.flats_wg.append(inflat)
self.all.append(inflat)
def add_flat_ng(self,inflat):
self.flats_ng.append(inflat)
self.all.append(inflat)
def add_sci(self,insci):
self.sci.append(insci)
self.all.append(insci)
def add_lamp(self,inlamp):
self.lamp.append(inlamp)
self.all.append(inlamp)
def set_master_bias(self,master):
self.master_bias = master
def set_master_flat(self,master):
self.master_flat = master
def set_last_prefix(prefix):
self.last_prefix = prefix
#methods to retrieve data
def get_bias(self):
return self.bias
def get_flats_wg(self):
return self.flats_wg
def get_flats_ng(self):
return self.flats_ng
def get_sci(self):
return self.sci
def get_lamp(self):
return self.lamp
def get_all(self):
return self.all
def get_file_list():
lista = sorted(glob.glob("0*.fits")) #will need work
try:
header0 = fits.getheader(lista[0])
this_night = night(header0["DATE"])
for i in lista:
#print("./" +i)
header = fits.getheader(i)
obstype = header["OBSTYPE"]
if obstype == "BIAS":
this_night.add_bias(i)
elif obstype == "FLAT":
grating = header["GRATING"]
if "NO GRATING" in grating:
this_night.add_flat_ng(i)
elif grating == "KOSI_600":
this_night.add_flat_wg(i)
else:
print("Unrecognized grating")
elif obstype == "OBJECT":
this_night.add_sci(i)
elif obstype == "COMP":
this_night.add_lamp(i)
return this_night
except IOError as err:
if str(err) == "Empty or corrupt FITS file":
print("Raised an IOError as ",err)
os.system("rem.csh")
sys.exit("Please run this script again")
else:
print(err)
sys.exit("Please correct the errors and try again")
#GET DATA
def get_data_header(file_name):
try:
hdu0 = fits.open(file_name)
scidata = hdu0[0].data
header = hdu0[0].header
scidata = scidata.byteswap().newbyteorder().astype('float64')
return scidata,header
except IOError as err:
debug("I/O error (get_data_header): %s"%err)
except TypeError as err:
debug("TypeError (get_data_header): %s : %s"%(file_name,err))
def overscan_trim_corr(list_all):
print_spacers("overscan and trim")
length = len(list_all)
for j in range(len(list_all)):
image = list_all[j]
raw_data,header = get_data_header(image)
#print(image," ",raw_data.shape)
data = raw_data[0]
x,y = data.shape
for i in range(x):
data[i] = data[i] - np.median(data[i][4114:4141])
trim_data = data[124:1669,17:4113]
out_image = patt_over_trim+image
fits.writeto(out_image,trim_data,header,clobber=True)
print_progress(j,length)
return True
def create_master_bias(bias_list):
print_spacers("Creating Master Bias")
length = len(bias_list)
stack = []
for i in range(len(bias_list)):
image = patt_over_trim+bias_list[i]
data,header = get_data_header(image)
stack.append(data)
print_progress(i,length)
#print(image)
header["OBJECT"] = "MASTERBIAS"
master = np.dstack(stack)
master = np.median(master,axis=2)
out_image = "master_bias.fits"
fits.writeto(out_image,master,header,clobber=True)
return out_image
def bias_correction(night):
print_spacers("Bias Correction")
bias,bheader = get_data_header(night.master_bias)
list_to_correct = night.flats_wg + night.flats_ng + night.sci + night.lamp
length = len(list_to_correct)
for i in range(len(list_to_correct)):
image = patt_over_trim + list_to_correct[i]
data,header = get_data_header(image)
bdata = data - bias
header["COMMENT"] = "Bias Corrected Image"
out_image = patt_bias_corr + list_to_correct[i]
fits.writeto(out_image,bdata,header,clobber=True)
print_progress(i,length)
return True
def create_master_flat(flat_list):
print_spacers("Create Master Flat For Spectroscopy")
length = len(flat_list)
stack = []
for i in range(len(flat_list)):
image = patt_bias_corr + flat_list[i]
print(image)
data,header = get_data_header(image)
stack.append(data)
print_progress(i,length)
header["OBJECT"] = "MASTERFLAT"
header["COMMENT"]= "Masterflat for spectroscopy"
master = np.dstack(stack)
master = np.median(master,axis=2)
nmaster= normalize_flat(master)
out_image = "master_flat_spec.fits"
fits.writeto(out_image,nmaster,header,clobber=True)
return out_image
def normalize_flat(master):
x,y = master.shape
#print(x,y,master.shape)
black_body = []
x_axis = []
for e in range(y):
black_body.append(np.median(master[:,e]))
x_axis.append(e+1)
print(len(black_body),len(x_axis))
fitted = fit_func(x_axis,black_body,"polynomial")
#normalizing
for l in range(x):
master[l,:] = master[l,:]/poly3(x_axis,*fitted)
#fits.writeto("normaflat.fits",master,clobber=True)
print(fitted)
print(len(fitted))
plt.title("Flat Normalization")
plt.xlabel("Dispersion Direction")
plt.ylabel("Intensity")
plt.plot(x_axis,black_body)
plt.plot(x_axis,poly3(x_axis,*fitted),label="Grade 3 Polynomial")
plt.legend()
plt.savefig("./img/flat_normalization_pol3.png",dpi=300,bbox_inches='tight')
plt.show()
plt.clf()
return master
#polynonmial of second order
def poly2(x,a,b,c,x0):
return a+b*(x-x0)+c*(x-x0)**2
def poly3(x,a,b,c,d,x0):
return a+b*(x-x0)+c*(x-x0)**2+d*(x-x0)**3
def fit_func(x,y,func="polynomial"):
if func == "polynomial":
a,b,c,d,x0 = 1,1,1,1,1
popt,pcov = curve_fit(poly3,x,y,p0=[a,b,c,d,x0])
return popt
elif func == "gauss":
print("gauss")
return True
def flat_correction(night):
print_spacers("Master Flat Correction")
list_to_correct = night.sci + night.lamp
length = len(list_to_correct)
master_flat = fits.getdata(night.master_flat)
for i in range(len(list_to_correct)):
image = patt_bias_corr + list_to_correct[i]
data,header = get_data_header(image)
cdata = data/master_flat
header["COMMENT"] = "Flat corrected image"
out_image = patt_flat_corr + list_to_correct[i]
print_progress(i,length)
fits.writeto(out_image,cdata,header,clobber=True)
return True
#miscelaneous functions
def print_spacers(message):
rows, columns = os.popen('stty size', 'r').read().split()
print(rows,columns)
if len(message)%2 == 1:
message = message+" "
bar_length = int(columns)
bar = "="*bar_length
blanks = bar_length - 2
blank_bar = "="+" "*blanks +"="
space_length = int((blanks-len(message))/2)
message_bar = "=" + " " * space_length + message + " " * space_length + "="
print(bar)
#print(blank_bar)
print(message_bar)
#print(blank_bar)
print(bar)
def print_progress(current,total):
if current == total:
sys.stdout.write("Progress {:.2%}\n".format(1.0*current/total))
else:
sys.stdout.write("Progress {:.2%}\r".format(1.0*current/total))
sys.stdout.flush()
return
if __name__ == '__main__':
this_night = get_file_list()
#apply overscan correction
overscan_trim_corr(this_night.all)
master_bias = create_master_bias(this_night.bias)
this_night.set_master_bias(master_bias)
#apply bias correction
bias_correction(this_night)
#create master flats for spectroscopy
master_flat = create_master_flat(this_night.flats_wg)
this_night.set_master_flat(master_flat)
flat_correction(this_night)
#bias_list = this_night.get_bias()
#print(bias_list)
#flat_1 = this_night.get_flats_wg()
#print(flat_1)
#flat_2 = this_night.get_flats_ng()
#print(flat_2)