varie.py 42.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
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

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))

    #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
93
    #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
94
95
    #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
96

97
98
#-------------- Define straighten option vertical shift -------------------
def shiftY(fdata):
99
100
101
102
103
104
105
106
107
108
    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']
109

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

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

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

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

        # 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
155
        return p * np.exp(-((x-c)/float(sg))**2)
Monica Rainer's avatar
Monica Rainer committed
156
157
158

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


    #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
204
    if abs(x0 - slit_pos) > CONFIG['Y_POS']:
Monica Rainer's avatar
Monica Rainer committed
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
        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
252
253
254
    #plt.plot(profile[x1:x2])
    #plt.show()

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

    # optimize the profiles
    for row in xrange(rows):
        stop = 0 
        outlier = True
        while outlier:
263
            #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
264
            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
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

            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)
    #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
315
316
317
    #plt.plot(profile[x1:x2])
    #plt.show()

Monica Rainer's avatar
Monica Rainer committed
318
319
320
321
322
323
324
325
326
327
328
329
    #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
330
331
332
333
        #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
334
335
336
337
    OptFlux[OptFlux==np.inf] = 0
    OptFlux[OptFlux==-np.inf] = 0
    OptFlux = np.nan_to_num(OptFlux)

338
    OptFlux[OptFlux<0] = 0
Monica Rainer's avatar
Monica Rainer committed
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

    #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)

    stop = 0 
    cosmic = True
    while cosmic:
        with np.errstate(divide='ignore', invalid='ignore', over='ignore'):
            outliers = np.true_divide((data-model)**2,np.abs(variance))
        #outliers[outliers==np.inf] = 50
        outliers[np.isnan(outliers)] = 50
        #if outliers[np.isnan(outliers)]:
        #    print len(outliers[np.isnan(outliers)])
        #outliers = np.nan_to_num(outliers)

        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]

            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
369
370
371
372
                #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
373
374
375
376
377

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

378
379
            OptFlux[OptFlux<0] = 0

Monica Rainer's avatar
Monica Rainer committed
380
381
382
383
384
            # update the model and its variance
            model = OptFlux*profile
            #model[rworst,cworst] = 0
            variance = var(model)

Monica Rainer's avatar
Monica Rainer committed
385
386
387
388
            stop += 1
            if stop > 20:
                cosmic = False

Monica Rainer's avatar
Monica Rainer committed
389
390
        else:
            cosmic = False               
Monica Rainer's avatar
Monica Rainer committed
391
392
393
394
395
        #stop += 1
        #if stop > 20:
        #    cosmic = False

    #print stop
Monica Rainer's avatar
Monica Rainer committed
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

    # 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
411
412
    #plt.plot(profile[x1:x2])
    #plt.show()
Monica Rainer's avatar
Monica Rainer committed
413
414
415
416
417
418
419
420

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

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

Monica Rainer's avatar
Monica Rainer committed
421
    return OptFlux, varOptFlux, profile, x1, x2, stop
Monica Rainer's avatar
Monica Rainer committed
422
423
424
425
426
427
428
429
430
431
432


#--------------------- 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
433
        return (np.absolute(x)/float(gain)) + (ron/float(gain)) ** 2
Monica Rainer's avatar
Monica Rainer committed
434
435
436
437
438

    variance = var(optflux*profile)

    # optimal extraction
    with np.errstate(divide='ignore', invalid='ignore'):
Monica Rainer's avatar
Monica Rainer committed
439
440
441
442
        #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
443
444
445
446
447
448
449
450

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

500
def UNe_calibrate(lamp,order,select_lines,all_lines,use_oliva=CONFIG['CAL_FUNC']['Oliva'],use_poly=CONFIG['CAL_FUNC']['Poly3']):
Monica Rainer's avatar
Monica Rainer committed
501
502
503
504
505
506

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

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

    # 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])
550
551
552
553
        #if cont < 0:
        #    wline = wline - cont
        #    cont = 0

Monica Rainer's avatar
Monica Rainer committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        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:
569
570
            #print 'gauss 1 failed'
            #print select_lines[pixel]['wave']
Monica Rainer's avatar
Monica Rainer committed
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
            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])
653
654
655
656
657

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

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

699
700
    coeffs = OrderedDict()

Monica Rainer's avatar
Monica Rainer committed
701
    if used > 1:
702

Monica Rainer's avatar
Monica Rainer committed
703
704
705
706
707
708
709
710
        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]))
711

Monica Rainer's avatar
Monica Rainer committed
712
713
714
715
716
        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),))

717
718
719
720
721
722
            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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
            #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),)
737
738
739
740
741
742
743
744
745
746
747
748
            #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
749
750
            coeffrms = round(rvrmse.value,2)

751
752
753
            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})
754
                #calib_failed = False
755
                #calib = lambdafit(pixrange,lambda0,xc0)
Monica Rainer's avatar
Monica Rainer committed
756
757
758
759
760
761
762

            #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()

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
        if use_poly:

            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)

794
795
            #calib_failed = False

796
797
            #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
798
799
800


    else:
801
        #print ' **** WARNING **** Order %s: not enough lines for the calibration!' % (str(order))
Monica Rainer's avatar
Monica Rainer committed
802
        #calib = np.zeros(len(lamp))
803
        messages.append(' **** WARNING **** Calibration failed for order %s, not enough lines.' % (str(order),))
804
805
        if use_oliva:
            #coeffs = OrderedDict({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
806
            coeffs.update({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
807
808
        if use_poly:
            #coeffs = OrderedDict({'c0':None,'c1':None,'c2':None,'c3':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
809
            coeffs.update({'c0':None,'c1':None,'c2':None,'c3':None,'rms_poly':None})
Monica Rainer's avatar
Monica Rainer committed
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
        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
836
#--------------------- Apply wavelength calibration -------------------
Monica Rainer's avatar
Monica Rainer committed
837

Monica Rainer's avatar
Monica Rainer committed
838
def wcalib(heawave,o):
Monica Rainer's avatar
Monica Rainer committed
839

Monica Rainer's avatar
Monica Rainer committed
840
841
    #pixrange = -np.arange(CONFIG['YCCD'])+CONFIG['YCCD']
    pixrange = np.arange(CONFIG['YCCD'])+1
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

    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)

    else:

        #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
879

Monica Rainer's avatar
Monica Rainer committed
880
    return wave
Monica Rainer's avatar
Monica Rainer committed
881
882


Monica Rainer's avatar
Monica Rainer committed
883
884
#--------------------- Linear interpolation and rebinning -------------------

885
886
#def rebin_linear(heawave,flux_old,heawave_old,o):
def rebin_linear(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
887
888
889
890
    """
    Rebin spectrum from wave_old to wave, interpolating linearly
    """

891
892
893
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
894
895
896

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

    #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
922
923
924
925
926
927
    return np.asarray(flux_new)[::-1]
    #return np.asarray(flux_new)


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

928
929
#def rebin2deg(heawave,flux_old,heawave_old,o):
def rebin2deg(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
930
931
932
933
    """
    Rebin spectrum from wave_old to wave, interpolating 2 degree
    """

934
935
936
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
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

    #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))

963
                flux_new.append(flux) 
Monica Rainer's avatar
Monica Rainer committed
964
965

            except:
966
                 try:
Monica Rainer's avatar
Monica Rainer committed
967
968
969
                    y0 = flux_old[iw-2]
                    y1 = flux_old[iw-1]
                    y2 = flux_old[iw]
970
 
Monica Rainer's avatar
Monica Rainer committed
971
972
973
                    x0 = wave_old[iw-2]
                    x1 = wave_old[iw-1]
                    x2 = wave_old[iw]
974
 
Monica Rainer's avatar
Monica Rainer committed
975
                    flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
976
977
978
                            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
979
980
                    flux_new.append(flux)

981
982
                 except:
                     try:
Monica Rainer's avatar
Monica Rainer committed
983
984
985
                        y0 = flux_old[iw]
                        y1 = flux_old[iw+1]
                        y2 = flux_old[iw+2]
986
 
Monica Rainer's avatar
Monica Rainer committed
987
988
989
                        x0 = wave_old[iw]
                        x1 = wave_old[iw+1]
                        x2 = wave_old[iw+2]
990
 
Monica Rainer's avatar
Monica Rainer committed
991
                        flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
992
993
994
                                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
995
996
                        flux_new.append(flux)

997
                     except:
Monica Rainer's avatar
Monica Rainer committed
998
                        flux_new.append(flux_old[iw])
999

Monica Rainer's avatar
Monica Rainer committed
1000
1001
1002
1003
1004
1005
1006
    #plt.plot(flux_old)
    #plt.plot(flux_new)
    #plt.show()

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

1007
1008


Monica Rainer's avatar
Monica Rainer committed
1009
1010
1011
1012
#--------- Switch between linear and parabolic interpolation and rebinning --------

def rebin(heawave,flux_old,heawave_old,o):
    """
1013
    Decide which rebinning to use: linear, parabolic, np.interp or scipy UnivariateSpline
Monica Rainer's avatar
Monica Rainer committed
1014
    """
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053

    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
1054
1055

#--------------------- Check for keywords existence (interactive) -------------------
Monica Rainer's avatar
Monica Rainer committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072

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

1073
            #print 'Missing keyword %s in the header of %s' % (key,filename)
Monica Rainer's avatar
Monica Rainer committed
1074
1075
1076
1077
1078
1079
1080
1081
            #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
1082
#--------------------- Check for keywords existence (not interactive) -------------------
Monica Rainer's avatar
Monica Rainer committed
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098

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
1099
#--------------------- Compute barycentric correction -------------------
Monica Rainer's avatar
Monica Rainer committed
1100

Monica Rainer's avatar
Monica Rainer committed
1101
def berv_corr_old(hdr):
Monica Rainer's avatar
Monica Rainer committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
    # 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
1115
    # target coordinates
Monica Rainer's avatar
Monica Rainer committed
1116
1117
1118
1119
1120
    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
1121
    # proper motions
Monica Rainer's avatar
Monica Rainer committed
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
    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
1134
    # JD (if MJD then convert to JD) + half exposure time
Monica Rainer's avatar
Monica Rainer committed
1135
1136
1137
1138
1139
    try:
        expt = float(hdr[CONFIG['KEYS']['EXPTIME']])/2.0
    except:
        expt = 0.0

Monica Rainer's avatar
Monica Rainer committed
1140
    try:
Monica Rainer's avatar
Monica Rainer committed
1141
        mjd = float(hdr[CONFIG['DRS_MJD'][0]])
Monica Rainer's avatar
Monica Rainer committed
1142
    except:
Monica Rainer's avatar
Monica Rainer committed
1143
        mjd = float(hdr[CONFIG['KEYS']['MJD']])
Monica Rainer's avatar
Monica Rainer committed
1144
        mjd = mjd + (expt/(86400.0))
Monica Rainer's avatar
Monica Rainer committed
1145
1146
1147
    if mjd < 100000:
        mjd = mjd + 2400000.5

Monica Rainer's avatar
Monica Rainer committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193

    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
1194
1195
1196
1197
1198
    try:
        expt = float(hdr[CONFIG['KEYS']['EXPTIME']])/2.0
    except:
        expt = 0.0

Monica Rainer's avatar
Monica Rainer committed
1199
1200
1201
1202
1203
1204
1205
    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
1206

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

Monica Rainer's avatar
Monica Rainer committed
1209
1210
1211
1212
1213
    #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
1214
    hjd = hjd.value - 2400000.5
Monica Rainer's avatar
Monica Rainer committed
1215

Monica Rainer's avatar
Monica Rainer committed
1216
1217
    #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)
    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=True)
Monica Rainer's avatar
Monica Rainer committed
1218
    berv = berv[0][0]/1000.0
Monica Rainer's avatar
Monica Rainer committed
1219
1220
1221

    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=True)

Monica Rainer's avatar
Monica Rainer committed
1222
    corr_time = corr_time[0][0] - 2400000.5
Monica Rainer's avatar
Monica Rainer committed
1223
1224

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

Monica Rainer's avatar
Monica Rainer committed
1226
1227
1228
1229
1230
1231
1232
1233
#--------------------- Create s1d output -------------------

def create_s1d(spectrum, header):

    wave_old = {}
    wave_new = {}
    start = {}
    end = {}
1234
    s1d = np.asarray([])
Monica Rainer's avatar
Monica Rainer committed
1235
    wstep = CONFIG['S1D_STEP'] # step in nm of the final s1d file
1236
1237
1238
1239
1240
1241
    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
1242
1243
1244

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

1248
1249
1250
1251
1252
1253
1254
1255
        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
1256
1257
            #flux_old = flux_old/norm_fit
            flux_old = np.true_divide(flux_old,norm_fit)
Monica Rainer's avatar
Monica Rainer committed
1258
1259
1260
1261
1262

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

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

Monica Rainer's avatar
Monica Rainer committed
1265
        try:
1266
            shift = max(int(round((wave_old[o][0] - end[o+1])/wstep,0)),1)
1267
1268

            #shift = int(round((wave_old[o][0] - end[o+1])/wstep,0))
1269
            start[o] = round(end[o+1] + (shift*wstep),3)
Monica Rainer's avatar
Monica Rainer committed
1270
        except:
1271
            #shift = 1
Monica Rainer's avatar
Monica Rainer committed
1272
            start[o] = round(wave_old[o][0],3)
1273

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

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

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

1281
1282
1283
        try:
            flux_new = spl(wave_new[o])
        except:
1284
            select_wave = wave_new[o][wave_old[o][0]<=wave_new[o]<=wave_old[o][-1]]
1285
1286
            flux_new = spl(select_wave)
            start[o] = select_wave[0]
1287
            #shift = int((start[o]-end[o+1])/wstep)+1
1288
            end[o] = select_wave[-1]
Monica Rainer's avatar
Monica Rainer committed
1289

1290
1291
        flux_new[abs(flux_new)<1e-04] = 0
        #print len(flux_new)
Monica Rainer's avatar
Monica Rainer committed
1292

1293
        if s1d.any():                
1294
1295
1296
            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
1297

1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
            #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:])
1309
        s1d = np.append(s1d,flux_new)
Monica Rainer's avatar
Monica Rainer committed
1310
1311
1312

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

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

Monica Rainer's avatar
Monica Rainer committed
1317
1318
1319
1320
1321
1322

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

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