varie.py 39.2 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
19
20
21
22
23
24
25
26
"""

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
27
import numpy.polynomial.polynomial as poly
Monica Rainer's avatar
Monica Rainer committed
28
29
import math
import warnings
Monica Rainer's avatar
Monica Rainer committed
30
import string, random
Monica Rainer's avatar
Monica Rainer committed
31
32
33

#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
#-------------- Define straighten option vertical shift -------------------
def shiftY(fdata):
    # search for shift defined in the straighten options in config.py
96
97
98
99
100
101
102
103
    #for opt in CONFIG['STRAIGHT_OPT']:
    #    try:
    #        dy = opt.rindex('DY=')
    #        ypos = int(opt[dy-2:])
    #        shift = CONFIG['SHIFT_Y'] + ypos
    #        return shift
    #    except:
    #        pass
104
    # if the shift is not defined, compute it
105
106
107
108
109
110
111
112
113
114
    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']
115

Monica Rainer's avatar
Monica Rainer committed
116
117
118
119
120
121

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

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

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

        # 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

Monica Rainer's avatar
Monica Rainer committed
210
    if abs(x0 - slit_pos) > CONFIG['Y_POS']:
Monica Rainer's avatar
Monica Rainer committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        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:
266
267
            #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
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

            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)

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

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

376
377
            OptFlux[OptFlux<0] = 0

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

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

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

    #print stop
Monica Rainer's avatar
Monica Rainer committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416

    # 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
417
    return OptFlux, varOptFlux, profile, x1, x2, stop
Monica Rainer's avatar
Monica Rainer committed
418
419
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


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

494
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
495
496
497
498
499
500

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

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

    # 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

683
684
    coeffs = OrderedDict()

Monica Rainer's avatar
Monica Rainer committed
685
    if used > 1:
686

Monica Rainer's avatar
Monica Rainer committed
687
688
689
690
691
692
693
694
        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]))
695

Monica Rainer's avatar
Monica Rainer committed
696
697
698
699
700
        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),))

701
702
703
704
705
706
            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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
            #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),)
721
722
723
724
725
726
727
728
729
730
731
732
            #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
733
734
            coeffrms = round(rvrmse.value,2)

735
736
737
            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})
738
                #calib_failed = False
739
                #calib = lambdafit(pixrange,lambda0,xc0)
Monica Rainer's avatar
Monica Rainer committed
740
741
742
743
744
745
746

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

747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
        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)

778
779
            #calib_failed = False

780
781
            #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
782
783
784
785
786
787


    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),))
788
789
        if use_oliva:
            #coeffs = OrderedDict({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
790
            coeffs.update({'k1':None,'k2':None,'k3':None,'l0':None,'xc':None,'rms':None})
791
792
        if use_poly:
            #coeffs = OrderedDict({'c0':None,'c1':None,'c2':None,'c3':None,'rms':None})
Monica Rainer's avatar
Monica Rainer committed
793
            coeffs.update({'c0':None,'c1':None,'c2':None,'c3':None,'rms_poly':None})
Monica Rainer's avatar
Monica Rainer committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
        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
820
#--------------------- Apply wavelength calibration -------------------
Monica Rainer's avatar
Monica Rainer committed
821

Monica Rainer's avatar
Monica Rainer committed
822
def wcalib(heawave,o):
Monica Rainer's avatar
Monica Rainer committed
823

Monica Rainer's avatar
Monica Rainer committed
824
825
    #pixrange = -np.arange(CONFIG['YCCD'])+CONFIG['YCCD']
    pixrange = np.arange(CONFIG['YCCD'])+1
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862

    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
863

Monica Rainer's avatar
Monica Rainer committed
864
    return wave
Monica Rainer's avatar
Monica Rainer committed
865
866


Monica Rainer's avatar
Monica Rainer committed
867
868
#--------------------- Linear interpolation and rebinning -------------------

869
870
#def rebin_linear(heawave,flux_old,heawave_old,o):
def rebin_linear(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
871
872
873
874
    """
    Rebin spectrum from wave_old to wave, interpolating linearly
    """

875
876
877
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
878
879
880

    #print wave
    #print wave_old
Monica Rainer's avatar
Monica Rainer committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905

    #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
906
907
908
909
910
911
    return np.asarray(flux_new)[::-1]
    #return np.asarray(flux_new)


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

912
913
#def rebin2deg(heawave,flux_old,heawave_old,o):
def rebin2deg(wave,wave_old,flux_old):
Monica Rainer's avatar
Monica Rainer committed
914
915
916
917
    """
    Rebin spectrum from wave_old to wave, interpolating 2 degree
    """

918
919
920
    #wave = wcalib(heawave,o)[::-1]
    #wave_old = wcalib(heawave_old,o)[::-1]
    #flux_old = flux_old[::-1]
Monica Rainer's avatar
Monica Rainer committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946

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

947
                flux_new.append(flux) 
Monica Rainer's avatar
Monica Rainer committed
948
949

            except:
950
                 try:
Monica Rainer's avatar
Monica Rainer committed
951
952
953
                    y0 = flux_old[iw-2]
                    y1 = flux_old[iw-1]
                    y2 = flux_old[iw]
954
 
Monica Rainer's avatar
Monica Rainer committed
955
956
957
                    x0 = wave_old[iw-2]
                    x1 = wave_old[iw-1]
                    x2 = wave_old[iw]
958
 
Monica Rainer's avatar
Monica Rainer committed
959
                    flux = y0*(w-x1)*(w-x2)/((x0-x1)*(x0-x2)) + \
960
961
962
                            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
963
964
                    flux_new.append(flux)

965
966
                 except:
                     try:
Monica Rainer's avatar
Monica Rainer committed
967
968
969
                        y0 = flux_old[iw]
                        y1 = flux_old[iw+1]
                        y2 = flux_old[iw+2]
970
 
Monica Rainer's avatar
Monica Rainer committed
971
972
973
                        x0 = wave_old[iw]
                        x1 = wave_old[iw+1]
                        x2 = wave_old[iw+2]
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
                     except:
Monica Rainer's avatar
Monica Rainer committed
982
                        flux_new.append(flux_old[iw])
983

Monica Rainer's avatar
Monica Rainer committed
984
985
986
987
988
989
990
    #plt.plot(flux_old)
    #plt.plot(flux_new)
    #plt.show()

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

991
992


Monica Rainer's avatar
Monica Rainer committed
993
994
995
996
#--------- Switch between linear and parabolic interpolation and rebinning --------

def rebin(heawave,flux_old,heawave_old,o):
    """
997
    Decide which rebinning to use: linear, parabolic, np.interp or scipy UnivariateSpline
Monica Rainer's avatar
Monica Rainer committed
998
    """
999
1000

    wave = wcalib(heawave,o)[::-1]
For faster browsing, not all history is shown. View entire blame