varie.py 44.3 KB
Newer Older
Monica Rainer's avatar
Monica Rainer committed
1
2
3
4
5
6
7
"""
- badpix: bad pixels removals
- stdcombine: weights for flat and dark combiner
- optExtract: optimal extraction
- extract: extraction with pre-defined profiles
- UNe_linelist: read the lists of UNe lines
- UNe_calibrate: calibration with UNe lamps
Monica Rainer's avatar
Monica Rainer committed
8
9
10
11
12
- wcalib: apply wavelength calibration
- rebin_linear: linearly rebin the B nodding on the A wavelengths prior to combine them
- rebin2deg: parabolically rebin the B nodding on the A wavelengths prior to combine them
- rebin: call either rebin_linear or rebin2deg (to change manually)
- check_keyraw/check_keywords: check for keyword existence 
Monica Rainer's avatar
Monica Rainer committed
13
- berv: computation of barycentric velocity correction (to be updated)
Monica Rainer's avatar
Monica Rainer committed
14
- create_s1d: create s1d output
Monica Rainer's avatar
Monica Rainer committed
15
- random_id: create random string
Monica Rainer's avatar
Monica Rainer committed
16
17
18
"""

from drslib.config import CONFIG
Monica Rainer's avatar
Monica Rainer committed
19
#from drslib.berv import baryvel
Monica Rainer's avatar
Monica Rainer committed
20
21
22
23
24

from astropy import constants as const
from astropy import units as u
from astropy import coordinates as coord
from astropy.io import fits
Monica Rainer's avatar
Monica Rainer committed
25
26
27
from astropy.time import Time

import barycorrpy as bc
Monica Rainer's avatar
Monica Rainer committed
28
29

import numpy as np
30
import numpy.polynomial.polynomial as poly
Monica Rainer's avatar
Monica Rainer committed
31
32
import math
import warnings
Monica Rainer's avatar
Monica Rainer committed
33
import string, random
Monica Rainer's avatar
Monica Rainer committed
34

Monica Rainer's avatar
Monica Rainer committed
35
import matplotlib.pyplot as plt
Monica Rainer's avatar
Monica Rainer committed
36
#from scipy import optimize, interpolate, signal
37
from scipy import optimize, interpolate
Monica Rainer's avatar
Monica Rainer committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

from collections import OrderedDict
import time

#--------------------- Bad pixels removal -------------------

def badpix(image,bad_mask,inverse_mask):
    """
    Remove bad pixel, it requires the image,
    the bad pixel mask and the reverse mask as np.array
    """

    wfiltro = 41
    half = (wfiltro-1)/2
    peso = 1.0/(wfiltro-1)

    #t1 = time.time()
    filtrarray = np.array([peso]*(half)+[0]+[peso]*(half))
Monica Rainer's avatar
Monica Rainer committed
56
    print filtrarray
Monica Rainer's avatar
Monica Rainer committed
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

    #t2 = time.time()
    #print 'Creating the filter: %s ms' %  str((t2-t1)*1000)

    # mask the image using the badpix mask
    masked = np.ma.masked_array(image, mask=bad_mask)

    #t3 = time.time()
    #print 'Masking the data: %s ms' %  str((t3-t2)*1000)

    # filter the image with a x=wfiltro filter
    filtered = np.zeros(image.shape)
    for i in xrange(len(image)):
        filtered[i] = np.convolve(image[i],filtrarray,'same')

    #t4 = time.time()
    #print 'Convolve with the filter: %s ms' %  str((t4-t3)*1000)

    # mask the filtered image with the inverse of the mask
    filtered_masked = np.ma.masked_array(filtered, mask=inverse_mask)

    # substitute the bad pixel with the filtered values
    corrected = np.ma.filled(masked,0)+np.ma.filled(filtered_masked,0)

    filtered = None
    filtered_masked = None

    #t5 = time.time()
    #print 'Substitute bad pixels: %s ms' %  str((t5-t4)*1000)

    return corrected


#--------------------- Std used in combining images -------------------

def stdcombine(x,axis):
    #return np.ma.sqrt((np.ma.absolute(x- np.ma.mean(x)) /CONFIG['GAIN']) + ((CONFIG['RON']/CONFIG['GAIN']) ** 2))
Monica Rainer's avatar
Monica Rainer committed
94
    #return np.ma.sqrt(np.ma.mean((np.ma.absolute(x- np.ma.mean(x)) /CONFIG['GAIN']) + ((CONFIG['RON']/CONFIG['GAIN']) ** 2)))
Monica Rainer's avatar
Monica Rainer committed
95
96
    #return np.ma.sqrt(np.ma.mean((np.ma.absolute(x- np.ma.median(x)) /CONFIG['GAIN']) + ((CONFIG['RON']/CONFIG['GAIN']) ** 2)))
    return np.ma.sqrt(np.ma.mean((np.ma.absolute(x- np.ma.median(x)) /float(CONFIG['GAIN'])) + ((float(CONFIG['RON'])/float(CONFIG['GAIN'])) ** 2)))
Monica Rainer's avatar
Monica Rainer committed
97

98
99
#-------------- Define straighten option vertical shift -------------------
def shiftY(fdata):
100
101
102
103
104
105
106
107
108
109
    column = fdata[0:140,0] # the bottom 140 pixel of the first column on the left of the detector 
    background = np.sort(column)[20] # value of the 20th pixel after arranging them in ascending order
    #print column
    for i in xrange(len(column)):
        if column[i] > 3*background:
            if np.median(column[i+1:i+6]) > 3*background:
                shift = i
                return shift
    # if the shift computation fails, use the default definition
    return CONFIG['SHIFT_Y']
110

Monica Rainer's avatar
Monica Rainer committed
111
112
113
114
115
116

#--------------------- Build the extraction mask -------------------
def buildMaskC(fdata):

    maskC = np.ones((CONFIG['YCCD'],CONFIG['XCCD']), dtype='int')

Monica Rainer's avatar
Monica Rainer committed
117
    for x in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
118
        # order limits
Monica Rainer's avatar
Monica Rainer committed
119
120
        start = x*CONFIG['W_ORD']
        end = min(start+CONFIG['W_ORD'],CONFIG['YCCD'])
Monica Rainer's avatar
Monica Rainer committed
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

        # evaluate average background value for each order
        #background = []
        #background.append(np.median(fdata[start+2]))
        #background.append(np.median(fdata[start+3]))
        #background.append(np.median(fdata[end-2]))
        background = np.sort(fdata,axis=None)[0:CONFIG['YCCD']*3]
        back = np.median(background)

        # create mask for extraction

        for row in xrange(3,38,1):
            rrow = start + row
            if np.median(fdata[rrow]) > back*2:
                maskC[rrow] = 0

    cmask = np.asarray(maskC, dtype='int')
    #cm = cmask.to_hdu()
    hdu = fits.PrimaryHDU(data=cmask)
    cm = fits.HDUList([hdu])
    cm.writeto(CONFIG['MASK_C'],clobber=True)


#--------------------- Optimal extraction -------------------

def optExtract(data,gain,ron,slit_pos,ordine):
    """
    Optimal extraction following Horne 1986.
    """

    #warnings.simplefilter('error',RuntimeWarning)
    warnings.simplefilter("error", optimize.OptimizeWarning)

    # define gaussian function:
    def gaussian(x,p,c,sg):
Monica Rainer's avatar
Monica Rainer committed
156
        return p * np.exp(-((x-c)/float(sg))**2)
Monica Rainer's avatar
Monica Rainer committed
157
158
159

    # define variance function:
    def var(x):
Monica Rainer's avatar
Monica Rainer committed
160
        return (np.absolute(x)/float(gain)) + (ron/float(gain)) ** 2
Monica Rainer's avatar
Monica Rainer committed
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


    #t1 = time.time()

    # compute the variance
    variance = var(data)

    data[data==np.inf] = 0
    data[data==-np.inf] = 0
    data = np.nan_to_num(data)
    #data[data<0] = 0


    rows = data.shape[0]
    columns = data.shape[1]

    #plt.plot(data[:,1])
    #plt.show()

    meanprof = np.average(data, axis=1, weights=1./variance)
    meanprof[meanprof==np.inf] = 0
    meanprof[meanprof==-np.inf] = 0
    meanprof = np.nan_to_num(meanprof)
    meanprof[meanprof<0] = 0

    # giving initial gaussian parameters

    x0 = slit_pos
    sigmagauss = CONFIG['HWTM']
    peak = np.amax(meanprof)

    p0 = (peak,x0,sigmagauss)     
    xline = np.arange(len(meanprof))
    try:
        pars, pcov = optimize.curve_fit(gaussian,xline,meanprof,p0)
        peak = pars[0]
        x0 = pars[1]
        sigmagauss = pars[2]
    except:
        x0 = slit_pos
        sigmagauss = CONFIG['HWTM']

    hwtm = math.sqrt(2*math.log(10)) * abs(sigmagauss) # half-width at tenth-maximum

Monica Rainer's avatar
Monica Rainer committed
205
    if abs(x0 - slit_pos) > CONFIG['Y_POS']:
Monica Rainer's avatar
Monica Rainer committed
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
        x0 = slit_pos

    # if bad seeing, there can be overlapping between A and B
    # limit the value of hwtm to 5 (only in nodding mode)
    lower = 1
    upper = 2
    if slit_pos != CONFIG['C_POS']:
        if hwtm < 3 or hwtm > CONFIG['HWTM']:
            hwtm = CONFIG['HWTM']

    # define border of the order as x0 +/- hwtm
    x1 = int(max((x0-hwtm-lower),0))
    x2 = int(min((x0+hwtm+upper),rows))

    #t2 = time.time()
    #print 'Creation profile order %s: %s ms' %  (str(ordine+32),str((t2-t1)*1000))

    # standard extraction
    StdFlux = np.sum(data[x1:x2],axis=0)
    varStdFlux = np.sum(variance[x1:x2],axis=0)


    #t3 = time.time()
    #print 'Standard extraction order %s: %s ms' %  (str(ordine+32),str((t3-t2)*1000))

    # build spatial profile

    with np.errstate(divide='ignore', invalid='ignore'):
        profile = np.true_divide(data,StdFlux)

    #print profile.shape

    # enforce positivity - set profile to zero outside the order
    profile[0:x1] = 0
    profile[x2:rows] = 0
    profile[profile==np.inf] = 0
    profile[profile==-np.inf] = 0
    profile = np.nan_to_num(profile)
    profile[profile < 0] = 0

    # enforce normalization
    with np.errstate(divide='ignore', invalid='ignore'):
        profile = np.true_divide(profile,np.sum(profile,axis=0))
    profile[profile==np.inf] = 0
    profile[profile==-np.inf] = 0
    profile = np.nan_to_num(profile)

Monica Rainer's avatar
Monica Rainer committed
253
254
255
    #plt.plot(profile[x1:x2])
    #plt.show()

Monica Rainer's avatar
Monica Rainer committed
256
257
258
259
260
261
262
263
    # update variance
    variance = var(StdFlux*profile)

    # optimize the profiles
    for row in xrange(rows):
        stop = 0 
        outlier = True
        while outlier:
264
            #fitprofile = np.polyval(np.polyfit(np.arange(columns),profile[row],deg=2,w=1./np.sqrt(variance[row])),np.arange(columns))
Monica Rainer's avatar
Monica Rainer committed
265
            fitprofile = poly.polyval(np.arange(columns),poly.polyfit(np.arange(columns),profile[row],deg=2,w=1.0/np.sqrt(variance[row])))
Monica Rainer's avatar
Monica Rainer committed
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

            sigma = np.mean((profile[row]-fitprofile)**2)

            # reject all pixels outside (4 sigma) **2

            with np.errstate(divide='ignore', invalid='ignore'):
                badpixels = np.true_divide((profile[row]-fitprofile)**2,sigma)
            badpixels[badpixels==np.inf] = 0
            badpixels = np.nan_to_num(badpixels)

            # substitute the outliers with fitted data
            # exit if no more outliers are found or if it reaches 100 iterations

            if np.amax(badpixels) > 16:

                idx = np.nonzero(badpixels>16)

                for pix in xrange(len(idx[0])):
                    profile[row,idx[0][pix]] = fitprofile[idx[0][pix]]

                with np.errstate(divide='ignore', invalid='ignore'):
                    profile = np.true_divide(profile,np.sum(profile,axis=0))
                profile[profile==np.inf] = 0
                profile[profile==-np.inf] = 0
                profile = np.nan_to_num(profile)

                variance = var(StdFlux*profile)

            else:
                outlier = False               
            stop += 1
            if stop > 100:
                outlier = False
            
        profile[profile < 0] = 0

        #plt.plot(profile[row])
        #plt.plot(fitprofile)
        #plt.show()

    #plt.plot(profile)
Monica Rainer's avatar
Monica Rainer committed
307
    #plt.plot(profile[x1:x2])
Monica Rainer's avatar
Monica Rainer committed
308
309
310
311
312
313
314
315
316
    #plt.show()

    # enforce normalization
    with np.errstate(divide='ignore', invalid='ignore'):
        profile = np.true_divide(profile,np.sum(profile,axis=0))
    profile[profile==np.inf] = 0
    profile[profile==-np.inf] = 0
    profile = np.nan_to_num(profile)

Monica Rainer's avatar
Monica Rainer committed
317
318
319
    #plt.plot(profile[x1:x2])
    #plt.show()

Monica Rainer's avatar
Monica Rainer committed
320
321
322
323
324
325
326
327
328
329
330
331
    #plt.plot(profile)
    #plt.plot(fitprofile)
    #plt.show()

    #t4 = time.time()
    #print 'Profile optimization order %s: %s ms' %  (str(ordine+32),str((t4-t3)*1000))

    # update variance
    variance = var(StdFlux*profile)

    # first optimal extraction
    with np.errstate(divide='ignore', invalid='ignore', over='ignore'):
Monica Rainer's avatar
Monica Rainer committed
332
333
334
335
        #varOptFlux = 1.0/np.sum(((profile[x1:x2])**2)/variance[x1:x2],axis=0)
        varOptFlux = 1.0/np.sum(np.true_divide(((profile[x1:x2])**2),variance[x1:x2]),axis=0)
        #OptFlux = np.sum(profile[x1:x2]*data[x1:x2]/variance[x1:x2],axis=0)*varOptFlux
        OptFlux = np.sum(np.true_divide(profile[x1:x2]*data[x1:x2],variance[x1:x2]),axis=0)*varOptFlux
Monica Rainer's avatar
Monica Rainer committed
336
337
338
339
    OptFlux[OptFlux==np.inf] = 0
    OptFlux[OptFlux==-np.inf] = 0
    OptFlux = np.nan_to_num(OptFlux)

340
    OptFlux[OptFlux<0] = 0
Monica Rainer's avatar
Monica Rainer committed
341
342
343
344
345
346
347
348
349

    #t5 = time.time()
    #print 'First optimal extraction order %s: %s ms' %  (str(ordine+32),str((t5-t4)*1000))


    # cosmic removal
   
    model = OptFlux*profile
    variance = var(model)
Monica Rainer's avatar
Monica Rainer committed
350
351
352
353
354
355
    #variance = var(model[x1:x2])

    #plt.plot(np.sum(data[x1:x2], axis=0),'k:')
    #plt.plot(OptFlux,'b-.')
    #plt.plot(np.sum(model[x1:x2], axis=0),'r--')
    #plt.show()
Monica Rainer's avatar
Monica Rainer committed
356
357
358
359
360

    stop = 0 
    cosmic = True
    while cosmic:
        with np.errstate(divide='ignore', invalid='ignore', over='ignore'):
Monica Rainer's avatar
Monica Rainer committed
361
362
363
            #outliers = np.true_divide((data-model)**2,np.abs(variance))
            outliers = np.true_divide((data[x1:x2]-model[x1:x2])**2,np.abs(variance[x1:x2]))

Monica Rainer's avatar
Monica Rainer committed
364
365
366
        outliers[np.isnan(outliers)] = 50


Monica Rainer's avatar
Monica Rainer committed
367
368
369
370
371
372
373
374
375
        #if np.amax(outliers[x1:x2]) > 25:

        #    rworst = np.unravel_index(np.argmax(outliers[x1:x2]),outliers[x1:x2].shape)[0] + x1
        #    cworst = np.unravel_index(np.argmax(outliers[x1:x2]),outliers[x1:x2].shape)[1]

        if np.amax(outliers) > 25:

            rworst = np.unravel_index(np.argmax(outliers),outliers.shape)[0] + x1
            cworst = np.unravel_index(np.argmax(outliers),outliers.shape)[1]
Monica Rainer's avatar
Monica Rainer committed
376
377
378
379
380

            data[rworst,cworst] = np.median([data[rworst,max(cworst-4,0):min(cworst+5,CONFIG['XCCD'])]])
            profile[rworst,cworst] = np.median([profile[rworst,max(cworst-4,0):min(cworst+5,CONFIG['XCCD'])]])

            with np.errstate(divide='ignore', invalid='ignore', over='ignore'):
Monica Rainer's avatar
Monica Rainer committed
381
382
383
384
                #varOptFlux = 1.0/np.sum(((profile[x1:x2])**2)/variance[x1:x2],axis=0)
                varOptFlux = 1.0/np.sum(np.true_divide(((profile[x1:x2])**2),variance[x1:x2]),axis=0)
                #OptFlux = np.sum(profile[x1:x2]*data[x1:x2]/variance[x1:x2],axis=0)*varOptFlux
                OptFlux = np.sum(np.true_divide(profile[x1:x2]*data[x1:x2],variance[x1:x2]),axis=0)*varOptFlux
Monica Rainer's avatar
Monica Rainer committed
385
386
387
388
389

            OptFlux[OptFlux==np.inf] = 0
            OptFlux[OptFlux==-np.inf] = 0
            OptFlux = np.nan_to_num(OptFlux)

390
391
            OptFlux[OptFlux<0] = 0

Monica Rainer's avatar
Monica Rainer committed
392
393
394
395
396
            # update the model and its variance
            model = OptFlux*profile
            #model[rworst,cworst] = 0
            variance = var(model)

Monica Rainer's avatar
Monica Rainer committed
397
            stop += 1
Monica Rainer's avatar
Monica Rainer committed
398
399
#            if stop > 20:
            if stop > CONFIG['NCOSMIC']:
Monica Rainer's avatar
Monica Rainer committed
400
401
                cosmic = False

Monica Rainer's avatar
Monica Rainer committed
402
403
        else:
            cosmic = False               
Monica Rainer's avatar
Monica Rainer committed
404
405
406
407
408
        #stop += 1
        #if stop > 20:
        #    cosmic = False

    #print stop
Monica Rainer's avatar
Monica Rainer committed
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

    # clean the extracted spectra from NaN and infinite values

    OptFlux[OptFlux==np.inf] = 0
    OptFlux[OptFlux==-np.inf] = 0
    OptFlux = np.nan_to_num(OptFlux)

    StdFlux[StdFlux==np.inf] = 0
    StdFlux[StdFlux==-np.inf] = 0
    StdFlux = np.nan_to_num(StdFlux)


    #t6 = time.time()
    #print 'Cosmic removal order %s: %s ms' %  (str(ordine+32),str((t6-t5)*1000))

Monica Rainer's avatar
Monica Rainer committed
424
425
    #plt.plot(profile[x1:x2])
    #plt.show()
Monica Rainer's avatar
Monica Rainer committed
426
427
428
429
430
431
432
433

    #plt.plot(StdFlux)
    #plt.plot(OptFlux)
    #plt.show()

    #warnings.simplefilter('default',RuntimeWarning)
    warnings.simplefilter("default", optimize.OptimizeWarning)

Monica Rainer's avatar
Monica Rainer committed
434
    return OptFlux, varOptFlux, profile, x0, x1, x2, stop
Monica Rainer's avatar
Monica Rainer committed
435
436
437
438
439
440
441
442
443
444
445


#--------------------- Extraction with a pre-determined profile -------------------

def extract(data,optflux,x1,x2,profile,gain,ron):
    """
    Optimal extraction using the profile determined with optExtract.
    """

    # define variance function:
    def var(x):
Monica Rainer's avatar
Monica Rainer committed
446
        return (np.absolute(x)/float(gain)) + (ron/float(gain)) ** 2
Monica Rainer's avatar
Monica Rainer committed
447
448
449
450
451

    variance = var(optflux*profile)

    # optimal extraction
    with np.errstate(divide='ignore', invalid='ignore'):
Monica Rainer's avatar
Monica Rainer committed
452
453
454
455
        #varOptFlux = 1.0/np.sum(((profile[x1:x2])**2)/variance[x1:x2],axis=0)
        #OptFlux = np.sum(profile[x1:x2]*data[x1:x2]/variance[x1:x2],axis=0)*varOptFlux
        varOptFlux = 1.0/np.sum(np.true_divide(((profile[x1:x2])**2),variance[x1:x2]),axis=0)
        OptFlux = np.sum(np.true_divide(profile[x1:x2]*data[x1:x2],variance[x1:x2]),axis=0)*varOptFlux
Monica Rainer's avatar
Monica Rainer committed
456
457
458
459
460
461
462
463

    # clean the extracted spectrum from NaN and infinite values
    OptFlux[OptFlux==np.inf] = 0
    OptFlux[OptFlux==-np.inf] = 0
    OptFlux = np.nan_to_num(OptFlux)


    #plt.plot(OptFlux)
Monica Rainer's avatar
Monica Rainer committed
464
    #plt.axis([0,CONFIG['YCCD'],-20,2000])
Monica Rainer's avatar
Monica Rainer committed
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
    #plt.show()

    return OptFlux

#--------------------- Reading the UNe lines from files -------------------

def UNe_linelist():


    select_lines = OrderedDict()
    all_lines = OrderedDict()
    for o in xrange(32,82):
        select_lines[o] = OrderedDict()
        all_lines[o] = OrderedDict()

    with open(CONFIG['WAVE_SELECT'],'r') as selected:
        selected.next() # skip 1st row (header)
        selected.next() # skip 2nd row (header)
        selected.next() # skip 3rd row (header)
        selected.next() # skip 4th row (header)
        for line in selected:
            line = line.strip()
            columns = line.split()
            order = int(columns[0])
            pixel = float(columns[4])
            wave = float(columns[1])
            peak = float(columns[3])
            select_lines[order].update({pixel : {'wave':wave,'peak':peak}}) 

    with open(CONFIG['WAVE_ALL'],'r') as wlines:
        wlines.next() # skip 1st row (header)
        wlines.next() # skip 2nd row (header)
        wlines.next() # skip 3rd row (header)
        for line in wlines:
            line = line.strip()
            columns = line.split()
            try:
                order = int(columns[0])
                wave = float(columns[2])
                peak = float(columns[4])
                all_lines[order][wave] = peak
            except:
                continue

    return select_lines, all_lines

#--------------------- UNe calibration -------------------

Monica Rainer's avatar
Monica Rainer committed
513
def UNe_calibrate(lamp,order,select_lines,all_lines,use_oliva=CONFIG['CAL_FUNC']['Oliva'],use_poly=CONFIG['CAL_FUNC']['Poly3'],use_poly4=CONFIG['CAL_FUNC']['Poly4']):
Monica Rainer's avatar
Monica Rainer committed
514
515
516
517
518
519

    warnings.simplefilter('error',RuntimeWarning)
    warnings.simplefilter("ignore", optimize.OptimizeWarning)

    messages = []
    #print order
520
    calib_failed = False
Monica Rainer's avatar
Monica Rainer committed
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

    # define gaussian function:
    def gaussian(x,p,c,sg):
        return cont + p * np.exp(-((x-c)/sg)**2)

    # polynomial function for wavelength calibration (defined by E. Oliva):
    def lambdafit(x,lambda0,xc0):
        return lambda0 + k1*(x-xc0) + k2*(x-xc0)**2 + k3*(x-xc0)**3
    def lambdafit0(x,lambda0):
        return lambda0 + k1*(x-xc0) + k2*(x-xc0)**2 + k3*(x-xc0)**3

    xc0 = CONFIG['XC_GUESS'][order]
    lambda0 = CONFIG['L0_GUESS'][order]
    #lambda0 = select_lines[min(select_lines.keys(), key=lambda k: abs(k-xc0))]['wave']
    #print lambda0
    k3 = 1.780e-9/order
    k2 = -3.560e-5/order
    k1 = -0.8490*(1.0/order - 1.0/2150.0)
    #print k1,k2,k3

    pixels = []
    waves = []

    rejected = 0
    used = 0


# The pixel position in the line list start at 1, not 0 as the numpy array
# The fitting polynomials from Oliva are the same (first pixel=1, not 0).
# It has to be taken into account in the fitting procedure.

    for pixel in select_lines:

        wrange = CONFIG['WAVE_FIT']['wrange1']
        drift = CONFIG['WAVE_FIT']['drift']
        pix = pixel+drift
        wline = lamp[int(pix-wrange):int(pix+wrange)]
        xline = np.arange(int(pix-wrange),int(pix+wrange),1)

        peak = wline[wrange]
        x0 = pix
        cont = np.median(np.sort(wline)[0:3])
563
564
565
566
        #if cont < 0:
        #    wline = wline - cont
        #    cont = 0

Monica Rainer's avatar
Monica Rainer committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        sigmagauss = 2.0

        try:
            p0 = (peak,x0,sigmagauss)     

            pars, pcov = optimize.curve_fit(gaussian,xline,wline,p0)
            peak = pars[0]
            x0 = pars[1]
            sigmagauss = pars[2]

            fwhm = 2*math.sqrt(2*math.log(2)) * sigmagauss
            true_pixel = x0


        except:
582
583
            #print 'gauss 1 failed'
            #print select_lines[pixel]['wave']
Monica Rainer's avatar
Monica Rainer committed
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
            true_pixel = 0.0
            fwhm = 0.0

        #print pix
        #print true_pixel
        #print fwhm
        #x = np.arange(len(wline))
        #xg = np.linspace(int(pix-wrange),int(pix+wrange),100)
        #plt.plot(xline,wline,'bo',xg,gaussian(xg,peak,x0,sigmagauss),'r--')
        #plt.show()


        if CONFIG['WAVE_FIT']['low_fwhm'] < abs(fwhm) < CONFIG['WAVE_FIT']['high_fwhm'] and abs(true_pixel+1 - pix) < CONFIG['WAVE_FIT']['confidence1']:
            pixels.append(true_pixel+1)
            waves.append(select_lines[pixel]['wave'])
            used = used + 1


        else:
            #print 'REJECTED: fwhm: ' + str(fwhm)
            #print 'REJECTED: pixel: ' + str(pix) + ' - true pixel: ' + str(true_pixel)
            rejected = rejected + 1



    # first guess at calibration using Oliva's polynomial with Xc fixed

    waves = np.asarray(waves)
    pixels = np.asarray(pixels)

    # fit if there are the same or more points than variables, else apply default values
    # if fitting, check that the values are reasonable, else apply default values
    if used > 1:
        p0 = (lambda0,xc0)
        pars, pcov = optimize.curve_fit(lambdafit,pixels,waves,p0)
        lambda0 = pars[0]
        xc0 = pars[1]
        #print lambda0
        if abs(xc0-CONFIG['XC_GUESS'][order]) > CONFIG['WAVE_FIT']['xc_range']:
            #print ' **** FIT 1 order %s : xc0 fitted - xc0 tabulated: %s' % (str(order),str(xc0-CONFIG['XC_GUESS'][order]))
            xc0 = CONFIG['XC_GUESS'][order]
            try:
                p0 = lambda0
                pars, pcov = optimize.curve_fit(lambdafit0,pixels,waves,p0)
                lambda0 = pars[0]
            except:
                lambda0 = CONFIG['L0_GUESS'][order]

    else:
        #print ' Iter 1 **** WARNING **** Not enough lines for the calibration!'
        xc0 = CONFIG['XC_GUESS'][order]
        lambda0 = CONFIG['L0_GUESS'][order]

    #plt.plot(pixels,waves,'bo')
    #plt.plot(np.arange(CONFIG['XCCD']),lambdafit(np.arange(CONFIG['XCCD']),lambda0,xc0),'r--')
    #plt.show()

    # apply calibration to whole lamp range, the first pixel is 1, not 0
    pixrange = np.arange(len(lamp))+1
    calib = lambdafit(pixrange,lambda0,xc0)

    # search additional lines using the calibrated wavelength

    all_pixels = []
    all_waves = []

    rejected = 0
    used = 0

    for wave in all_lines:
        wpos = np.argmin(np.abs(calib-wave))

        # gaussian fit

        wrange = CONFIG['WAVE_FIT']['wrange2']
        wline = lamp[max(int(wpos-wrange),0):min(int(wpos+wrange),len(lamp))]
        xline = np.arange(max(int(wpos-wrange),0),min(int(wpos+wrange),len(lamp)),1)

        peak = lamp[int(wpos)]
        x0 = wpos
        #cont = min(wline)
        cont = np.median(np.sort(wline)[0:3])
666
667
668
669
670

        #if cont < 0:
        #    wline = wline - cont
        #    cont = 0

Monica Rainer's avatar
Monica Rainer committed
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
        sigmagauss = 2.0

        try:
            p0 = (peak,x0,sigmagauss)
            pars, pcov = optimize.curve_fit(gaussian,xline,wline,p0)
            peak = pars[0]
            x0 = pars[1]
            sigmagauss = pars[2]

            fwhm = 2*math.sqrt(2*math.log(2)) * sigmagauss
            true_pixel = x0

        except:
            true_pixel = 0.0
            fwhm = 0.0

        if CONFIG['WAVE_FIT']['low_fwhm'] < abs(fwhm) < CONFIG['WAVE_FIT']['high_fwhm'] and abs(true_pixel - wpos) < CONFIG['WAVE_FIT']['confidence2']:
            all_pixels.append(true_pixel+1)
            all_waves.append(wave)
            used = used + 1
        else:
            #print 'REJECTED: fwhm: ' + str(fwhm)
            #print 'REJECTED: pixel: ' + str(wpos) + ' - true pixel: ' + str(true_pixel)
            #x = np.arange(len(wline))
            #xg = np.linspace(max(int(wpos-wrange),0),min(int(wpos+wrange),len(lamp)),100)
            #plt.plot(xline,wline,'bo',xg,gaussian(xg,peak,x0,sigmagauss),'r--')
            #plt.show()
            rejected = rejected + 1

    #messages.append('Complete wavelength calibration of order %s: %s lines were used, %s lines were rejected.' % (str(order),str(used),str(rejected),))

    #print 'Complete wavelength calibration of order %s: %s lines were used, %s lines were rejected.' % (str(order), str(used), str(rejected),)

    # ultimate fit
    all_waves = np.asarray(all_waves)
    all_pixels = np.asarray(all_pixels)

    # fit if there are the same or more points than variables
    # if fitting, check that the values are reasonable
    # then apply the calibration to the whole pixel range

712
713
    coeffs = OrderedDict()

Monica Rainer's avatar
Monica Rainer committed
714
    if used > 1:
715

Monica Rainer's avatar
Monica Rainer committed
716
717
718
719
720
721
722
723
        xc0 = CONFIG['XC_GUESS'][order]
        p0 = (lambda0,xc0)
        pars, pcov = optimize.curve_fit(lambdafit,all_pixels,all_waves,p0)
        lambda0 = pars[0]
        xc0 = pars[1]

        #print order
        #print ' **** FIT order %s : xc0 fitted - xc0 tabulated: %s' % (str(order),str(xc0-CONFIG['XC_GUESS'][order]))
724

Monica Rainer's avatar
Monica Rainer committed
725
726
727
728
729
        if abs(xc0-CONFIG['XC_GUESS'][order]) > CONFIG['WAVE_FIT']['xc_range']:
            #print ' **** FIT def. order %s : xc0 fitted - xc0 tabulated: %s' % (str(order),str(xc0-CONFIG['XC_GUESS'][order]))
            #calib = np.zeros(len(pixrange))
            messages.append('Calibration failed for order %s.' % (str(order),))

730
731
732
733
734
735
            if use_oliva:
                #coeffs = OrderedDict({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
                coeffs.update({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
                calib_failed = True
            #coeffs = OrderedDict()
    
Monica Rainer's avatar
Monica Rainer committed
736
737
738
739
740
741
742
743
744
745
746
747
748
749
            #plt.plot(all_pixels,all_waves,'bo')
            #plt.plot(np.arange(len(pixrange)),lambdafit(np.arange(len(pixrange))),'r-')
            #plt.show()

        else:
            #calib = lambdafit(pixrange,lambda0,xc0)
            chisq=((lambdafit(all_pixels,lambda0,xc0)-all_waves)**2).sum()
            rvchisq=(((lambdafit(all_pixels,lambda0,xc0)-all_waves)/all_waves)**2).sum()
            # dof is degrees of freedom (number of data - number of parameters)
            dof=max(len(all_pixels)-2,1)
            rmse=np.sqrt(chisq/dof)
            rvrmse=np.sqrt(rvchisq/dof)*const.c
            #messages.append('RMS of the calibration for order %s: %s' % (str(order),str(rvrmse),))
            #print 'RMS of the calibration for order %s: %s' % (str(order),str(rvrmse),)
750
751
752
753
754
755
756
757
758
759
760
761
            #coeffk1 = float('%.5e' % k1)
            #coeffk2 = float('%.5e' % k2)
            #coeffk3 = float('%.5e' % k3)
            #coeffl0 = round(lambda0,5)
            #coeffxc0 = round(xc0,5)
            #coeffrms = round(rvrmse.value,2)

            coeffk1 = float(k1)
            coeffk2 = float( k2)
            coeffk3 = float(k3)
            coeffl0 = lambda0
            coeffxc0 = xc0
Monica Rainer's avatar
Monica Rainer committed
762
763
            coeffrms = round(rvrmse.value,2)

764
765
766
            if use_oliva:
                #coeffs = OrderedDict({'k1':coeffk1,'k2':coeffk2,'k3':coeffk3,'l0':coeffl0,'xc':coeffxc0,'rms':coeffrms})
                coeffs.update({'k1':coeffk1,'k2':coeffk2,'k3':coeffk3,'l0':coeffl0,'xc':coeffxc0,'rms':coeffrms})
767
                #calib_failed = False
768
                #calib = lambdafit(pixrange,lambda0,xc0)
Monica Rainer's avatar
Monica Rainer committed
769
770
771
772
773
774
775

            #coeffs = OrderedDict({'k1':k1,'k2':k2,'k3':k3,'l0':lambda0,'xc':xc0,'rms':rvrmse.value})

            #plt.plot(all_pixels,all_waves,'bo')
            #plt.plot(np.arange(len(pixrange)),lambdafit(np.arange(len(pixrange))),'r-')
            #plt.show()

776
        if use_poly:
Monica Rainer's avatar
Monica Rainer committed
777
            #print 'Poly3'
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
            fitpoly3 = poly.polyfit(all_pixels,all_waves,deg=3)
            #fitpoly3 = np.polyfit(all_pixels,all_waves,deg=3)
            #polycalib = np.polyval(fitpoly3,pixrange)

            #check_calib = np.mean(np.absolute(polycalib-calib))

            #if check_calib < CONFIG['CHECK_CALIB']:

            chisq=((poly.polyval(all_pixels,fitpoly3)-all_waves)**2).sum()
            rvchisq=(((poly.polyval(all_pixels,fitpoly3)-all_waves)/all_waves)**2).sum()
            #chisq=((np.polyval(fitpoly3,all_pixels)-all_waves)**2).sum()
            #rvchisq=(((np.polyval(fitpoly3,all_pixels)-all_waves)/all_waves)**2).sum()
            dof=max(len(all_pixels)-4,1)
            rmse=np.sqrt(chisq/dof)
            rvrmse=np.sqrt(rvchisq/dof)*const.c
            #print 'RMS of the calibration for order %s: %s' % (str(order),str(rvrmse),)

            #coeffc0 = round(fitpoly3[0],5)
            #coeffc1 = round(fitpoly3[1],5)
            #coeffc2 = round(fitpoly3[2],5)
            #coeffc3 = round(fitpoly3[3],5)
            #coeffrms = round(rvrmse.value,2)

            coeffc0 = fitpoly3[0]
            coeffc1 = fitpoly3[1]
            coeffc2 = fitpoly3[2]
            coeffc3 = fitpoly3[3]
            coeffrms = round(rvrmse.value,2)

807
808
            #calib_failed = False

809
810
            #coeffs = OrderedDict({'c0':coeffc0,'c1':coeffc1,'c2':coeffc2,'c3':coeffc3,'rms':coeffrms})
            coeffs.update({'c0':coeffc0,'c1':coeffc1,'c2':coeffc2,'c3':coeffc3,'rms_poly':coeffrms})
Monica Rainer's avatar
Monica Rainer committed
811

Monica Rainer's avatar
Monica Rainer committed
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        if use_poly4:
            #print 'Poly4'
            fitpoly4 = poly.polyfit(all_pixels,all_waves,deg=4)

            chisq=((poly.polyval(all_pixels,fitpoly4)-all_waves)**2).sum()
            rvchisq=(((poly.polyval(all_pixels,fitpoly4)-all_waves)/all_waves)**2).sum()

            dof=max(len(all_pixels)-5,1)
            rmse=np.sqrt(chisq/dof)
            rvrmse=np.sqrt(rvchisq/dof)*const.c


            coeffc0 = fitpoly4[0]
            coeffc1 = fitpoly4[1]
            coeffc2 = fitpoly4[2]
            coeffc3 = fitpoly4[3]
            coeffc4 = fitpoly4[4]
            coeffrms = round(rvrmse.value,2)
           
            coeffs.update({'c0':coeffc0, 'c1':coeffc1, 'c2':coeffc2, 'c3':coeffc3, 'c4':coeffc4, 'rms_poly':coeffrms})

Monica Rainer's avatar
Monica Rainer committed
833
834

    else:
835
        #print ' **** WARNING **** Order %s: not enough lines for the calibration!' % (str(order))
Monica Rainer's avatar
Monica Rainer committed
836
        #calib = np.zeros(len(lamp))
837
        messages.append(' **** WARNING **** Calibration failed for order %s, not enough lines.' % (str(order),))
838
839
        if use_oliva:
            #coeffs = OrderedDict({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
840
            coeffs.update({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
841
842
        if use_poly:
            #coeffs = OrderedDict({'c0':None,'c1':None,'c2':None,'c3':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
843
            coeffs.update({'c0':None,'c1':None,'c2':None,'c3':None,'rms_poly':None})
Monica Rainer's avatar
Monica Rainer committed
844
845
846
        if use_poly4:
            #coeffs = OrderedDict({'c0':None,'c1':None,'c2':None,'c3':None,'rms':None})
            coeffs.update({'c0':None,'c1':None,'c2':None,'c3':None,'c4':None,'rms_poly':None})
Monica Rainer's avatar
Monica Rainer committed
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
        calib_failed = True



    #plt.plot(all_pixels,all_waves,'bo')
    #plt.plot(np.arange(CONFIG['XCCD']),lambdafit(np.arange(CONFIG['XCCD'])),'r-')
    #plt.show()

    #print coeffs

    #fitpoly3 = np.polyval(np.polyfit(all_pixels,all_waves,deg=3),pixels)
    #chisq3=((fitpoly3-all_waves)**2).sum()
    # dof is degrees of freedom (number of data - number of parameters)
    #dof=len(all_pixels)-4
    #rmse3=np.sqrt(chisq3/dof)

    #print len(calib)
    #print len(lamp)

    warnings.simplefilter('default',RuntimeWarning)
    warnings.simplefilter("default", optimize.OptimizeWarning)

    #return calib, coeffs, messages
    return calib_failed, coeffs, messages


Monica Rainer's avatar
Monica Rainer committed
873
#--------------------- Apply wavelength calibration -------------------
Monica Rainer's avatar
Monica Rainer committed
874

Monica Rainer's avatar
Monica Rainer committed
875
def wcalib(heawave,o):
Monica Rainer's avatar
Monica Rainer committed
876

Monica Rainer's avatar
Monica Rainer committed
877
878
    #pixrange = -np.arange(CONFIG['YCCD'])+CONFIG['YCCD']
    pixrange = np.arange(CONFIG['YCCD'])+1
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896

    if CONFIG['CAL_FUNC']['Oliva']:
        def lambdafit(x,lambda0,xc0):
            return lambda0 + k1*(x-xc0) + k2*(x-xc0)**2 + k3*(x-xc0)**3

        keyk1 = ''.join((CONFIG['WLCOEFFS']['k1'][0],str(o+32)))
        k1 = float(heawave[keyk1])
        keyk2 = ''.join((CONFIG['WLCOEFFS']['k2'][0],str(o+32)))
        k2 = float(heawave[keyk2])
        keyk3 = ''.join((CONFIG['WLCOEFFS']['k3'][0],str(o+32)))
        k3 = float(heawave[keyk3])
        keyl0 = ''.join((CONFIG['WLCOEFFS']['l0'][0],str(o+32)))
        l0 = float(heawave[keyl0])
        keyxc = ''.join((CONFIG['WLCOEFFS']['xc'][0],str(o+32)))
        xc = float(heawave[keyxc])

        wave = lambdafit(pixrange,l0,xc)

Monica Rainer's avatar
Monica Rainer committed
897
    if CONFIG['CAL_FUNC']['Poly3']:
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915

        #def lambdafit(x):
        #    return c0 + c1*x + c2*(x**2) + c3*(x**3)

        keyc0 = ''.join((CONFIG['WLCOEFFS']['c0'][0],str(o+32)))
        c0 = float(heawave[keyc0])
        keyc1 = ''.join((CONFIG['WLCOEFFS']['c1'][0],str(o+32)))
        c1 = float(heawave[keyc1])
        keyc2 = ''.join((CONFIG['WLCOEFFS']['c2'][0],str(o+32)))
        c2 = float(heawave[keyc2])
        keyc3 = ''.join((CONFIG['WLCOEFFS']['c3'][0],str(o+32)))
        c3 = float(heawave[keyc3])

        fitpoly3 = np.array([c0,c1,c2,c3])
        wave = poly.polyval(pixrange,fitpoly3)
        #wave = np.polyval(fitpoly3,pixrange)

        #wave = lambdafit(pixrange)
Monica Rainer's avatar
Monica Rainer committed
916

Monica Rainer's avatar
Monica Rainer committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
    else:

        keyc0 = ''.join((CONFIG['WLCOEFFS']['c0'][0],str(o+32)))
        c0 = float(heawave[keyc0])
        keyc1 = ''.join((CONFIG['WLCOEFFS']['c1'][0],str(o+32)))
        c1 = float(heawave[keyc1])
        keyc2 = ''.join((CONFIG['WLCOEFFS']['c2'][0],str(o+32)))
        c2 = float(heawave[keyc2])
        keyc3 = ''.join((CONFIG['WLCOEFFS']['c3'][0],str(o+32)))
        c3 = float(heawave[keyc3])
        keyc4 = ''.join((CONFIG['WLCOEFFS']['c4'][0],str(o+32)))
        c4 = float(heawave[keyc4])

        fitpoly4 = np.array([c0,c1,c2,c3,c4])
        wave = poly.polyval(pixrange,fitpoly4)


Monica Rainer's avatar
Monica Rainer committed
934
    return wave
Monica Rainer's avatar
Monica Rainer committed
935
936


Monica Rainer's avatar
Monica Rainer committed
937
938
#--------------------- Linear interpolation and rebinning -------------------

939
940
#def rebin_linear(heawave,flux_old,heawave_old,o):
def rebin_linear(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
941
942
943
944
    """
    Rebin spectrum from wave_old to wave, interpolating linearly
    """

945
946
947
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
948
949
950

    #print wave
    #print wave_old
Monica Rainer's avatar
Monica Rainer committed
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

    #flux_new = np.interp(wave,wave_old,flux_old)

    flux_new = []

    for w in wave:
        iw = min(np.searchsorted(wave_old,w),len(wave_old)-1)
        if wave_old[iw] == w:
            flux_new.append(flux_old[iw])
        else:
            try:
                f1 = flux_old[iw-1]
                f2 = flux_old[iw]
                w1 = wave_old[iw-1]
                w2 = wave_old[iw]
                a = (f2-f1)/(w2-w1)
                b = f1 - a*w1
                flux = a*w + b
                flux_new.append(flux)
            except:
                flux_new.append(flux_old[iw])
    #plt.plot(flux_old)
    #plt.plot(flux_new)
    #plt.show()

Monica Rainer's avatar
Monica Rainer committed
976
977
978
979
980
981
    return np.asarray(flux_new)[::-1]
    #return np.asarray(flux_new)


#--------------------- Parabolic interpolation and rebinning -------------------

982
983
#def rebin2deg(heawave,flux_old,heawave_old,o):
def rebin2deg(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
984
985
986
987
    """
    Rebin spectrum from wave_old to wave, interpolating 2 degree
    """

988
989
990
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016

    #print wave
    #print wave_old

    #flux_new = np.interp(wave,wave_old,flux_old)

    flux_new = []

    for w in wave:
        iw = min(np.searchsorted(wave_old,w),len(wave_old)-1)
        if wave_old[iw] == w:
            flux_new.append(flux_old[iw])
        else:
            try:
                y0 = flux_old[iw-1]
                y1 = flux_old[iw]
                y2 = flux_old[iw+1]

                x0 = wave_old[iw-1]
                x1 = wave_old[iw]
                x2 = wave_old[iw+1]

                flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
                       y1*(w-x0)*(w-x2)/((x1-x0)*(x1-x2)) + \
                       y2*(w-x0)*(w-x1)/((x2-x0)*(x2-x1))

1017
                flux_new.append(flux) 
Monica Rainer's avatar
Monica Rainer committed
1018
1019

            except:
1020
                 try:
Monica Rainer's avatar
Monica Rainer committed
1021
1022
1023
                    y0 = flux_old[iw-2]
                    y1 = flux_old[iw-1]
                    y2 = flux_old[iw]
1024
 
Monica Rainer's avatar
Monica Rainer committed
1025
1026
1027
                    x0 = wave_old[iw-2]
                    x1 = wave_old[iw-1]
                    x2 = wave_old[iw]
1028
 
Monica Rainer's avatar
Monica Rainer committed
1029
                    flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
1030
1031
1032
                            y1*(w-x0)*(w-x2)/((x1-x0)*(x1-x2)) + \
                            y2*(w-x0)*(w-x1)/((x2-x0)*(x2-x1))
 
Monica Rainer's avatar
Monica Rainer committed
1033
1034
                    flux_new.append(flux)

1035
1036
                 except:
                     try:
Monica Rainer's avatar
Monica Rainer committed
1037
1038
1039
                        y0 = flux_old[iw]
                        y1 = flux_old[iw+1]
                        y2 = flux_old[iw+2]
1040
 
Monica Rainer's avatar
Monica Rainer committed
1041
1042
1043
                        x0 = wave_old[iw]
                        x1 = wave_old[iw+1]
                        x2 = wave_old[iw+2]
1044
 
Monica Rainer's avatar
Monica Rainer committed
1045
                        flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
1046
1047
1048
                                y1*(w-x0)*(w-x2)/((x1-x0)*(x1-x2)) + \
                                y2*(w-x0)*(w-x1)/((x2-x0)*(x2-x1))
 
Monica Rainer's avatar
Monica Rainer committed
1049
1050
                        flux_new.append(flux)

1051
                     except:
Monica Rainer's avatar
Monica Rainer committed
1052
                        flux_new.append(flux_old[iw])
1053

Monica Rainer's avatar
Monica Rainer committed
1054
1055
1056
1057
1058
1059
1060
    #plt.plot(flux_old)
    #plt.plot(flux_new)
    #plt.show()

    return np.asarray(flux_new)[::-1]
    #return np.asarray(flux_new)

1061
1062


Monica Rainer's avatar
Monica Rainer committed
1063
1064
1065
1066
#--------- Switch between linear and parabolic interpolation and rebinning --------

def rebin(heawave,flux_old,heawave_old,o):
    """
1067
    Decide which rebinning to use: linear, parabolic, np.interp or scipy UnivariateSpline
Monica Rainer's avatar
Monica Rainer committed
1068
    """
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107

    wave = wcalib(heawave,o)[::-1]
    wave_old = wcalib(heawave_old,o)[::-1]
    flux_old = flux_old[::-1]

    #t1 = time.time()
    flux_new = np.interp(wave,wave_old,flux_old)
    return np.asarray(flux_new)[::-1]
    #t2 = time.time()


    #spl = interpolate.UnivariateSpline(wave_old,flux_old,k=3,s=0)

    #try:
    #    flux_new = spl(wave)
    #except:
    #    select_wave = wave[wave_old[0]<wave<wave_old[-1]]
    #    flux_new = spl(select_wave)
    #    try:
    #        wave0 = wave[wave<wave_old[0]]
    #        wave0.fill(flux_old[0])
    #        flux_new = np.append(wave0,flux_new)
    #    except:
    #        pass
    #    try:
    #        wave1 = wave[wave>wave_old[-1]]
    #        wave1.fill(flux_old[-1])
    #        flux_new = np.append(flux_new,wave1)
    #    except:
    #        pass
        
    #t3 = time.time()
    #print 'Rebin scipy spline: %s s' % str(t3-t2)

    #return flux_new[::-1]
    #return rebin2deg(wave,wave_old,flux_old)
    #return rebin_linear(wave,wave_old,flux_old)


Monica Rainer's avatar
Monica Rainer committed
1108
1109

#--------------------- Check for keywords existence (interactive) -------------------
Monica Rainer's avatar
Monica Rainer committed
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126

def check_keyraw(header,filename):
    keys = [CONFIG['KEYS']['ID'] , CONFIG['KEYS']['PID'] , CONFIG['KEYS']['NODSTARE'] , CONFIG['KEYS']['EXTMODE'] , CONFIG['KEYS']['GROUPI'] , CONFIG['KEYS']['GROUPN']]
    #keys = [CONFIG['KEYS']['ID'] , CONFIG['KEYS']['PID'] , CONFIG['KEYS']['NODSTARE'] , CONFIG['KEYS']['EXTMODE'] , CONFIG['KEYS']['GROUPI'] , CONFIG['KEYS']['GROUPN'] , CONFIG['KEYS']['NREP']]

    ask = True
    for key in keys:
        try:
            header[key]
        except:
            if ask:
                skip = raw_input('Missing keywords in the header, do you want to skip the file? [y/n] ')
                if skip.lower() == 'y' or skip.lower() == 'yes':
                    return False
                else:
                    ask = False

1127
            #print 'Missing keyword %s in the header of %s' % (key,filename)
Monica Rainer's avatar
Monica Rainer committed
1128
1129
1130
1131
1132
1133
1134
1135
            #ask = 'Insert %s value: ' % (key)
            value = raw_input('Insert %s value: \n' % (key))
            if not value:
                value = None
            header[key] = value

    return header

Monica Rainer's avatar
Monica Rainer committed
1136
#--------------------- Check for keywords existence (not interactive) -------------------
Monica Rainer's avatar
Monica Rainer committed
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152

def check_keywords(header,filename):
    for key in CONFIG['KEYS']:
        try:
            header[CONFIG['KEYS'][key]]
        except:
            print 'Missing keyword %s in the header %s.' % (CONFIG['KEYS'][key],filename)
            ask = 'Insert %s value:\n' % (CONFIG['KEYS'][key])
            value = raw_input(ask)
            if not value:
                value = None
            header[CONFIG['KEYS'][key]] = value

    return header


Monica Rainer's avatar
Monica Rainer committed
1153
#--------------------- Compute barycentric correction -------------------
Monica Rainer's avatar
Monica Rainer committed
1154

Monica Rainer's avatar
Monica Rainer committed
1155
def berv_corr_old(hdr):
Monica Rainer's avatar
Monica Rainer committed
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
    # CORREZIONE BARICENTRICA + BJD
    # TNG coordinates
    latitude = 28.754
    longitude = -17.889056
    elevation = 2387.2
    try:
        ra = hdr[CONFIG['KEYS']['RA']]
        dec = hdr[CONFIG['KEYS']['DEC']]
    except:
        barycorr = 0.0
        hjd = hdr[CONFIG['DRS_MJD'][0]]
        return barycorr, hjd

Monica Rainer's avatar
Monica Rainer committed
1169
    # target coordinates
Monica Rainer's avatar
Monica Rainer committed
1170
1171
1172
1173
1174
    radec = coord.SkyCoord(ra,dec, unit=(u.hourangle, u.deg))
    ra = radec.ra.value
    dec = radec.dec.value
    equinox = float(hdr[CONFIG['KEYS']['EQUINOX']])

Monica Rainer's avatar
Monica Rainer committed
1175
    # proper motions
Monica Rainer's avatar
Monica Rainer committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
    try:
        pma = float(hdr[CONFIG['KEYS']['PMA']])
        pmd = float(hdr[CONFIG['KEYS']['PMD']])
    except:
        pma = 0.0
        pmd = 0.0

    if abs(pma) > 100:
        pma = 0.0
    if abs(pmd) > 100:
        pmd = 0.0

Monica Rainer's avatar
Monica Rainer committed
1188
    # JD (if MJD then convert to JD) + half exposure time
Monica Rainer's avatar
Monica Rainer committed
1189
1190
1191
1192
1193
    try:
        expt = float(hdr[CONFIG['KEYS']['EXPTIME']])/2.0
    except:
        expt = 0.0

Monica Rainer's avatar
Monica Rainer committed
1194
    try:
Monica Rainer's avatar
Monica Rainer committed
1195
        mjd = float(hdr[CONFIG['DRS_MJD'][0]])
Monica Rainer's avatar
Monica Rainer committed
1196
    except:
Monica Rainer's avatar
Monica Rainer committed
1197
        mjd = float(hdr[CONFIG['KEYS']['MJD']])
Monica Rainer's avatar
Monica Rainer committed
1198
        mjd = mjd + (expt/(86400.0))
Monica Rainer's avatar
Monica Rainer committed
1199
1200
1201
    if mjd < 100000:
        mjd = mjd + 2400000.5

Monica Rainer's avatar
Monica Rainer committed
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247

    barycorr, hjd, bjd, vbar, vdiurnal = baryvel.helcorr(longitude,latitude,elevation,ra,dec,mjd,equinox,pma,pmd)

    return barycorr, hjd, bjd


#--------------------- Compute barycentric correction NEW -------------------

def berv_corr(hdr):
    # CORREZIONE BARICENTRICA + BJD
    # TNG coordinates
    latitude = 28.754
    longitude = -17.889056
    elevation = 2387.2
    tng = coord.EarthLocation.from_geodetic(latitude,-longitude,elevation)

    try:
        ra = hdr[CONFIG['KEYS']['RA']]
        dec = hdr[CONFIG['KEYS']['DEC']]
    except:
        barycorr = 0.0
        hjd = hdr[CONFIG['DRS_MJD'][0]]
        return barycorr, hjd

    # proper motions
    try:
        pma = float(hdr[CONFIG['KEYS']['PMA']])
        pmd = float(hdr[CONFIG['KEYS']['PMD']])
    except:
        pma = 0.0
        pmd = 0.0

    if abs(pma) > 100:
        pma = 0.0
    if abs(pmd) > 100:
        pmd = 0.0

    # target coordinates
    radec = coord.SkyCoord(ra,dec, unit=(u.hourangle, u.deg))
    ra = radec.ra.value
    dec = radec.dec.value
    equinox = float(hdr[CONFIG['KEYS']['EQUINOX']])
    t = Time(equinox,format='jyear')
    epoch = t.jd

    # JD (if MJD then convert to JD) + half exposure time
Monica Rainer's avatar
Monica Rainer committed
1248
1249
1250
1251
1252
    try:
        expt = float(hdr[CONFIG['KEYS']['EXPTIME']])/2.0
    except:
        expt = 0.0

Monica Rainer's avatar
Monica Rainer committed
1253
1254
1255
1256
1257
1258
1259
    try:
        mjd = float(hdr[CONFIG['DRS_MJD'][0]])
    except:
        mjd = float(hdr[CONFIG['KEYS']['MJD']])
        mjd = mjd + (expt/(86400.0))
    if mjd < 100000:
        mjd = mjd + 2400000.5
Monica Rainer's avatar
Monica Rainer committed
1260

Monica Rainer's avatar
Monica Rainer committed
1261
    times = Time(mjd, format='jd', scale='utc', location=tng)
Monica Rainer's avatar
Monica Rainer committed
1262

Monica Rainer's avatar
Monica Rainer committed
1263
1264
1265
1266
1267
    #ltt_bary = times.light_travel_time(radec)
    #bjd = times.tdb + ltt_bary
    #bjd = bjd.value
    ltt_helio = times.light_travel_time(radec, 'heliocentric')
    hjd = times.utc + ltt_helio
Monica Rainer's avatar
Monica Rainer committed
1268
    hjd = hjd.value - 2400000.5
Monica Rainer's avatar
Monica Rainer committed
1269

Monica Rainer's avatar
Monica Rainer committed
1270
    #berv = bc.get_BC_vel(JDUTC=mjd, ra=ra, dec=dec, lat = latitude, longi = longitude, alt = elevation, pmra = pma, pmdec = pmd, epoch=epoch, ephemeris = 'de430', leap_update=True)
Monica Rainer's avatar
Monica Rainer committed
1271
    berv = bc.get_BC_vel(JDUTC=mjd, ra=ra, dec=dec, lat = latitude, longi = longitude, alt = elevation, pmra = pma, pmdec = pmd, epoch=epoch, leap_update=CONFIG['LEAP_UPDATE'])
Monica Rainer's avatar
Monica Rainer committed
1272
    berv = berv[0][0]/1000.0
Monica Rainer's avatar
Monica Rainer committed
1273

Monica Rainer's avatar
Monica Rainer committed
1274
    corr_time = bc.utc_tdb.JDUTC_to_BJDTDB(mjd, ra=ra, dec=dec, lat = latitude, longi = longitude, alt = elevation, pmra = pma, pmdec = pmd, epoch=epoch, leap_update=CONFIG['LEAP_UPDATE'])
Monica Rainer's avatar
Monica Rainer committed
1275

Monica Rainer's avatar
Monica Rainer committed
1276
    corr_time = corr_time[0][0] - 2400000.5
Monica Rainer's avatar
Monica Rainer committed
1277
1278

    return berv, hjd, corr_time
Monica Rainer's avatar
Monica Rainer committed
1279

Monica Rainer's avatar
Monica Rainer committed
1280
1281
1282
1283
1284
1285
1286
1287
#--------------------- Create s1d output -------------------

def create_s1d(spectrum, header):

    wave_old = {}
    wave_new = {}
    start = {}
    end = {}
1288
    s1d = np.asarray([])
Monica Rainer's avatar
Monica Rainer committed
1289
    wstep = CONFIG['S1D_STEP'] # step in nm of the final s1d file
1290
1291
1292
1293
1294
1295
    try:
        berv = float(header[CONFIG['BERV'][0]])
    except:
        berv = 0.0
    c = const.c.to('km/s')
    c = c.value
Monica Rainer's avatar
Monica Rainer committed
1296
1297
1298

    for o in reversed(xrange(CONFIG['N_ORD'])):
        #t1 = time.time()
1299
        #wfit = -99999
Monica Rainer's avatar
Monica Rainer committed
1300
1301
        flux_old = spectrum[o][::-1]

1302
1303
1304
1305
1306
1307
1308
1309
        if CONFIG['S1D_NORM']:
            # use the central part of the order to normalize it
            chunk = int(len(flux_old)/4)
            norm = flux_old[chunk:(chunk*3)]
            massimi = np.argsort(norm)
            massimi = massimi[-250:-50]+chunk
            valori = flux_old[massimi]
            norm_fit = np.polyval(np.polyfit(massimi,valori,1),np.arange(len(flux_old)))
Monica Rainer's avatar
Monica Rainer committed
1310
1311
            #flux_old = flux_old/norm_fit
            flux_old = np.true_divide(flux_old,norm_fit)
Monica Rainer's avatar
Monica Rainer committed
1312
1313
1314
1315
1316

        #t2 = time.time()
        #print 's1d spectrum order %s normalization: %s s' % (str(o),str(t2-t1))

        wave_old[o] = wcalib(header,o)[::-1]
1317
1318
        wave_old[o] = wave_old[o]*(1+(berv/c))

Monica Rainer's avatar
Monica Rainer committed
1319
        try:
1320
            shift = max(int(round((wave_old[o][0] - end[o+1])/wstep,0)),1)
1321
1322

            #shift = int(round((wave_old[o][0] - end[o+1])/wstep,0))
1323
            start[o] = round(end[o+1] + (shift*wstep),3)
Monica Rainer's avatar
Monica Rainer committed
1324
        except:
1325
            #shift = 1
Monica Rainer's avatar
Monica Rainer committed
1326
            start[o] = round(wave_old[o][0],3)
1327

1328
        nstep = int(round(((wave_old[o][-1]-start[o])/wstep),0))
Monica Rainer's avatar
Monica Rainer committed
1329
1330
        end[o] = round(start[o]+(nstep*wstep),3)

1331
        wave_new[o] = np.arange(start[o],end[o]+(wstep/10),wstep)
Monica Rainer's avatar
Monica Rainer committed
1332

1333
        spl = interpolate.UnivariateSpline(wave_old[o],flux_old,k=3,s=0)
Monica Rainer's avatar
Monica Rainer committed
1334

1335
1336
1337
        try:
            flux_new = spl(wave_new[o])
        except:
1338
            select_wave = wave_new[o][wave_old[o][0]<=wave_new[o]<=wave_old[o][-1]]
1339
1340
            flux_new = spl(select_wave)
            start[o] = select_wave[0]
1341
            #shift = int((start[o]-end[o+1])/wstep)+1
1342
            end[o] = select_wave[-1]
Monica Rainer's avatar
Monica Rainer committed
1343

1344
1345
        flux_new[abs(flux_new)<1e-04] = 0
        #print len(flux_new)
Monica Rainer's avatar
Monica Rainer committed
1346

1347
        if s1d.any():                
1348
1349
1350
            gap = start[o]- (end[o+1]+wstep)
            ngap = max(int(round(gap/wstep,0)),0)
            s1d = np.append(s1d,np.zeros(ngap))
Monica Rainer's avatar
Monica Rainer committed
1351

1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
            #print shift
            #if shift < 1:
            #    new = flux_new[0:-shift]
            #    old = s1d[shift:]
            #    if np.mean(new) > np.mean(old):
            #        s1d[shift:] = new
            #    shift = -shift+1
            #else:
            #    shift = 0

        #s1d = np.append(s1d,flux_new[shift:])
1363
        s1d = np.append(s1d,flux_new)
Monica Rainer's avatar
Monica Rainer committed
1364
1365
1366

        #t2 = time.time()
        #print 's1d spectrum order %s: %s s' % (str(o),str(t2-t1))
1367
    #print len(s1d)
Monica Rainer's avatar
Monica Rainer committed
1368

1369
    return s1d, start[CONFIG['N_ORD']-1]
Monica Rainer's avatar
Monica Rainer committed
1370

Monica Rainer's avatar
Monica Rainer committed
1371
1372
1373
1374
1375
1376

#--------------------- Create random string id -------------------

def random_id(length):
    return ''.join(random.SystemRandom().choice(string.lowercase+string.uppercase+string.digits) for i in range(length))