varie.py 37.6 KB
Newer Older
Monica Rainer's avatar
Monica Rainer committed
1
"""
Monica Rainer's avatar
Monica Rainer committed
2
Last modified: 2017-06-07
Monica Rainer's avatar
Monica Rainer committed
3
4
5
6
7
8
9

- 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
10
11
12
13
14
- 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
15
- berv: computation of barycentric velocity correction (to be updated)
Monica Rainer's avatar
Monica Rainer committed
16
- create_s1d: create s1d output
Monica Rainer's avatar
Monica Rainer committed
17
18
19
20
21
22
23
24
25
26
27
"""

from drslib.config import CONFIG
from drslib.berv import baryvel

from astropy import constants as const
from astropy import units as u
from astropy import coordinates as coord
from astropy.io import fits

import numpy as np
28
import numpy.polynomial.polynomial as poly
Monica Rainer's avatar
Monica Rainer committed
29
30
31
32
33
import math
import warnings

#import matplotlib.pyplot as plt
#from scipy import optimize, interpolate, signal
34
from scipy import optimize, interpolate
Monica Rainer's avatar
Monica Rainer committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

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
90
91
    #return np.ma.sqrt(np.ma.mean((np.ma.absolute(x- np.ma.mean(x)) /CONFIG['GAIN']) + ((CONFIG['RON']/CONFIG['GAIN']) ** 2)))
    return np.ma.sqrt(np.ma.mean((np.ma.absolute(x- np.ma.median(x)) /CONFIG['GAIN']) + ((CONFIG['RON']/CONFIG['GAIN']) ** 2)))
Monica Rainer's avatar
Monica Rainer committed
92
93
94
95
96
97
98


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

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

Monica Rainer's avatar
Monica Rainer committed
99
    for x in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
100
        # order limits
Monica Rainer's avatar
Monica Rainer committed
101
102
        start = x*CONFIG['W_ORD']
        end = min(start+CONFIG['W_ORD'],CONFIG['YCCD'])
Monica Rainer's avatar
Monica Rainer committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

        # 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):
        return p * np.exp(-((x-c)/sg)**2)

    # define variance function:
    def var(x):
        return (np.absolute(x)/gain) + (ron/gain) ** 2


    #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

    if abs(x0 - slit_pos) > 2:
        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)

    # update variance
    variance = var(StdFlux*profile)

    # optimize the profiles
    for row in xrange(rows):
        stop = 0 
        outlier = True
        while outlier:
243
244
            #fitprofile = np.polyval(np.polyfit(np.arange(columns),profile[row],deg=2,w=1./np.sqrt(variance[row])),np.arange(columns))
            fitprofile = poly.polyval(np.arange(columns),poly.polyfit(np.arange(columns),profile[row],deg=2,w=1./np.sqrt(variance[row])))
Monica Rainer's avatar
Monica Rainer committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

            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)

    #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'):
        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
    OptFlux[OptFlux==np.inf] = 0
    OptFlux[OptFlux==-np.inf] = 0
    OptFlux = np.nan_to_num(OptFlux)


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

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

            # update the model and its variance
            model = OptFlux*profile
            #model[rworst,cworst] = 0
            variance = var(model)

Monica Rainer's avatar
Monica Rainer committed
357
358
359
360
            stop += 1
            if stop > 20:
                cosmic = False

Monica Rainer's avatar
Monica Rainer committed
361
362
        else:
            cosmic = False               
Monica Rainer's avatar
Monica Rainer committed
363
364
365
366
367
        #stop += 1
        #if stop > 20:
        #    cosmic = False

    #print stop
Monica Rainer's avatar
Monica Rainer committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

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


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

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

Monica Rainer's avatar
Monica Rainer committed
391
    return OptFlux, varOptFlux, profile, x1, x2, stop
Monica Rainer's avatar
Monica Rainer committed
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418


#--------------------- 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):
        return (np.absolute(x)/gain) + (ron/gain) ** 2

    variance = var(optflux*profile)

    # optimal extraction
    with np.errstate(divide='ignore', invalid='ignore'):
        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

    # 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
419
    #plt.axis([0,CONFIG['YCCD'],-20,2000])
Monica Rainer's avatar
Monica Rainer committed
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    #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 -------------------

468
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655

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

    messages = []
    #print order

    # 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])
        #cont = min(wline) # fare mediana dei tre punti piu' bassi
        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

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

656
657
    coeffs = OrderedDict()

Monica Rainer's avatar
Monica Rainer committed
658
    if used > 1:
659

Monica Rainer's avatar
Monica Rainer committed
660
661
662
663
664
665
666
667
        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]))
668

Monica Rainer's avatar
Monica Rainer committed
669
670
671
672
673
        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),))

674
675
676
677
678
679
            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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
            #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),)
694
695
696
697
698
699
700
701
702
703
704
705
            #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
706
707
            coeffrms = round(rvrmse.value,2)

708
709
710
711
712
            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})
                calib_failed = False
                #calib = lambdafit(pixrange,lambda0,xc0)
Monica Rainer's avatar
Monica Rainer committed
713
714
715
716
717
718
719

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

720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
        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)

            calib_failed = False
            #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
754
755
756
757
758
759


    else:
        print ' **** WARNING **** Order %s: not enough lines for the calibration!' % (str(order))
        #calib = np.zeros(len(lamp))
        messages.append('Calibration failed for order %s, not enough lines.' % (str(order),))
760
761
        if use_oliva:
            #coeffs = OrderedDict({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
762
            coeffs.update({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
763
764
        if use_poly:
            #coeffs = OrderedDict({'c0':None,'c1':None,'c2':None,'c3':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
765
            coeffs.update({'c0':None,'c1':None,'c2':None,'c3':None,'rms_poly':None})
Monica Rainer's avatar
Monica Rainer committed
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
        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
792
#--------------------- Apply wavelength calibration -------------------
Monica Rainer's avatar
Monica Rainer committed
793

Monica Rainer's avatar
Monica Rainer committed
794
def wcalib(heawave,o):
Monica Rainer's avatar
Monica Rainer committed
795

Monica Rainer's avatar
Monica Rainer committed
796
797
    #pixrange = -np.arange(CONFIG['YCCD'])+CONFIG['YCCD']
    pixrange = np.arange(CONFIG['YCCD'])+1
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834

    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
835

Monica Rainer's avatar
Monica Rainer committed
836
    return wave
Monica Rainer's avatar
Monica Rainer committed
837
838


Monica Rainer's avatar
Monica Rainer committed
839
840
#--------------------- Linear interpolation and rebinning -------------------

841
842
#def rebin_linear(heawave,flux_old,heawave_old,o):
def rebin_linear(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
843
844
845
846
    """
    Rebin spectrum from wave_old to wave, interpolating linearly
    """

847
848
849
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
850
851
852

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

    #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
878
879
880
881
882
883
    return np.asarray(flux_new)[::-1]
    #return np.asarray(flux_new)


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

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

890
891
892
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918

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

919
                flux_new.append(flux) 
Monica Rainer's avatar
Monica Rainer committed
920
921

            except:
922
                 try:
Monica Rainer's avatar
Monica Rainer committed
923
924
925
                    y0 = flux_old[iw-2]
                    y1 = flux_old[iw-1]
                    y2 = flux_old[iw]
926
 
Monica Rainer's avatar
Monica Rainer committed
927
928
929
                    x0 = wave_old[iw-2]
                    x1 = wave_old[iw-1]
                    x2 = wave_old[iw]
930
 
Monica Rainer's avatar
Monica Rainer committed
931
                    flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
932
933
934
                            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
935
936
                    flux_new.append(flux)

937
938
                 except:
                     try:
Monica Rainer's avatar
Monica Rainer committed
939
940
941
                        y0 = flux_old[iw]
                        y1 = flux_old[iw+1]
                        y2 = flux_old[iw+2]
942
 
Monica Rainer's avatar
Monica Rainer committed
943
944
945
                        x0 = wave_old[iw]
                        x1 = wave_old[iw+1]
                        x2 = wave_old[iw+2]
946
 
Monica Rainer's avatar
Monica Rainer committed
947
                        flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
948
949
950
                                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
951
952
                        flux_new.append(flux)

953
                     except:
Monica Rainer's avatar
Monica Rainer committed
954
                        flux_new.append(flux_old[iw])
955

Monica Rainer's avatar
Monica Rainer committed
956
957
958
959
960
961
962
    #plt.plot(flux_old)
    #plt.plot(flux_new)
    #plt.show()

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

963
964


Monica Rainer's avatar
Monica Rainer committed
965
966
967
968
#--------- Switch between linear and parabolic interpolation and rebinning --------

def rebin(heawave,flux_old,heawave_old,o):
    """
969
    Decide which rebinning to use: linear, parabolic, np.interp or scipy UnivariateSpline
Monica Rainer's avatar
Monica Rainer committed
970
    """
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009

    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
1010
1011

#--------------------- Check for keywords existence (interactive) -------------------
Monica Rainer's avatar
Monica Rainer committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028

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

1029
            #print 'Missing keyword %s in the header of %s' % (key,filename)
Monica Rainer's avatar
Monica Rainer committed
1030
1031
1032
1033
1034
1035
1036
1037
            #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
1038
#--------------------- Check for keywords existence (not interactive) -------------------
Monica Rainer's avatar
Monica Rainer committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054

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
1055
#--------------------- Compute barycentric correction -------------------
Monica Rainer's avatar
Monica Rainer committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070

def berv_corr(hdr):
    # 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
1071
    # target coordinates
Monica Rainer's avatar
Monica Rainer committed
1072
1073
1074
1075
1076
    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
1077
    # proper motions
Monica Rainer's avatar
Monica Rainer committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
    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
1090
    # JD (if MJD then convert to JD) + half exposure time
Monica Rainer's avatar
Monica Rainer committed
1091
    try:
Monica Rainer's avatar
Monica Rainer committed
1092
        mjd = float(hdr[CONFIG['DRS_MJD'][0]])
Monica Rainer's avatar
Monica Rainer committed
1093
    except:
Monica Rainer's avatar
Monica Rainer committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
        mjd = float(hdr[CONFIG['KEYS']['MJD']])
    if mjd < 100000:
        mjd = mjd + 2400000.5

    try:
        expt = float(hdr[CONFIG['KEYS']['EXPTIME']])/2.0
    except:
        expt = 0.0

    mjd = mjd + (expt/(86400.0))

Monica Rainer's avatar
Monica Rainer committed
1105
1106
    barycorr, hjd, vbar, vdiurnal = baryvel.helcorr(longitude,latitude,elevation,ra,dec,mjd,equinox,pma,pmd)

Monica Rainer's avatar
Monica Rainer committed
1107
1108
    return barycorr, hjd

Monica Rainer's avatar
Monica Rainer committed
1109
1110
1111
1112
1113
1114
1115
1116
#--------------------- Create s1d output -------------------

def create_s1d(spectrum, header):

    wave_old = {}
    wave_new = {}
    start = {}
    end = {}
1117
    s1d = np.asarray([])
Monica Rainer's avatar
Monica Rainer committed
1118
    wstep = CONFIG['S1D_STEP'] # step in nm of the final s1d file
1119
1120
1121
1122
1123
1124
    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
1125
1126
1127

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

1131
1132
1133
1134
1135
1136
1137
1138
1139
        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)))
            flux_old = flux_old/norm_fit
Monica Rainer's avatar
Monica Rainer committed
1140
1141
1142
1143
1144

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

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

Monica Rainer's avatar
Monica Rainer committed
1147
        try:
1148
1149
1150
1151
            #shift = int((wave_old[o][0] - end[o+1])/wstep) -1
            shift = max(int(round((wave_old[o][0] - end[o+1])/wstep,0)),1)
            #start[o] = max(end[o+1] + (shift*wstep), end[o+1]+wstep)
            start[o] = round(end[o+1] + (shift*wstep),3)
Monica Rainer's avatar
Monica Rainer committed
1152
1153
        except:
            start[o] = round(wave_old[o][0],3)
1154
1155
        #nstep = int(round(((wave_old[o][-1]-start[o])/wstep),0))+1
        nstep = int(round(((wave_old[o][-1]-start[o])/wstep),0))
Monica Rainer's avatar
Monica Rainer committed
1156
1157
        end[o] = round(start[o]+(nstep*wstep),3)

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

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

1162
1163
1164
        try:
            flux_new = spl(wave_new[o])
        except:
1165
            select_wave = wave_new[o][wave_old[o][0]<=wave_new[o]<=wave_old[o][-1]]
1166
1167
1168
            flux_new = spl(select_wave)
            start[o] = select_wave[0]
            end[o] = select_wave[-1]
Monica Rainer's avatar
Monica Rainer committed
1169

1170
1171
        flux_new[abs(flux_new)<1e-04] = 0
        #print len(flux_new)
Monica Rainer's avatar
Monica Rainer committed
1172

1173
1174
1175
1176
        if s1d.any():
            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
1177

1178
        s1d = np.append(s1d,flux_new)
Monica Rainer's avatar
Monica Rainer committed
1179
1180
1181

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

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