-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserval.py
executable file
·2319 lines (2037 loc) · 108 KB
/
serval.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
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
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
445
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
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
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
754
755
756
757
758
759
760
761
762
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
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
820
821
822
823
824
825
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
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
#! /usr/bin/env python
__author__ = 'Mathias Zechmeister'
__version__ = '2019-02-17'
description = '''
SERVAL - SpEctrum Radial Velocity AnaLyser (%s)
by %s
''' % (__version__, __author__)
import argparse
import copy
import ctypes
from ctypes import c_void_p, c_double, c_int
import csv
# from datetime import datetime imported with read_spec!
import glob
import os
import resource
import stat as os_stat
import sys
import time
import numpy as np
from numpy import std,arange,zeros,where, polynomial,setdiff1d,polyfit,array, newaxis,average
from scipy import interpolate, optimize
from scipy.optimize import curve_fit
from gplot import *
from pause import pause, stop
from wstat import wstd, wmean, wrms, rms, mlrms, iqr, wsem, nanwsem, nanwstd, naniqr, quantile
from read_spec import * # flag, sflag, def_wlog
from calcspec import *
from targ import Targ
import cubicSpline
import cspline as spl
import masktools
import phoenix_as_RVmodel
from chi2map import Chi2Map
gplot2 = Gplot() # for a second plot window
gplot.bar(0).colors('classic')
if 'gplot_set' in locals():
raise ImportError('Please update new gplot.py.')
if tuple(map(int,np.__version__.split('.'))) > (1,6,1):
np.seterr(invalid='ignore', divide='ignore') # suppression warnings when comparing with nan.
def lam2wave(l, wlog=def_wlog):
return np.log(l) if wlog else l
def wave2lam(w, wlog=def_wlog):
return np.exp(w) if wlog else w
servalsrc = os.path.dirname(os.path.realpath(__file__)) + os.sep
servaldir = os.path.dirname(os.path.realpath(servalsrc)) + os.sep
servallib = servaldir + 'lib' + os.sep
os.environ['ASTRO_DATA'] = servalsrc
ptr = np.ctypeslib.ndpointer
_pKolynomial0 = ctypes.CDLL(servalsrc+'polyregression.so')
_pKolynomial0.polyfit.restype = c_double
_pKolynomial = np.ctypeslib.load_library(servalsrc+'polyregression', '.')
_pKolynomial.polyfit.restype = c_double
_pKolynomial.polyfit.argtypes = [
ptr(dtype=np.float), # x2
ptr(dtype=np.float), # y2
ptr(dtype=np.float), # e_y2
ptr(dtype=np.float), # fmod
#ptr(dtype=np.bool), # ind
c_double, # ind
c_int, c_double, c_int, # n, wcen, deg
ptr(dtype=np.float), # p
ptr(dtype=np.float), # lhs
ptr(dtype=np.float) # pstat
]
_pKolynomial.interpol1D.argtypes = [
ptr(dtype=np.float), # xn
ptr(dtype=np.float), # yn
ptr(dtype=np.float), # x
ptr(dtype=np.float), # y
c_int, c_int # nn, n
]
c = 299792.4580 # [km/s] speed of light
def nans(*args, **kwargs):
return np.nan * np.empty(*args, **kwargs)
# default values
postiter = 3 # number of iterations for post rvs (postclip=3)
debug = 0
sp, fmod = None, None # @getHalpha
apar = zeros(3) # parabola parameters
astat = zeros(3*2-1)
alhs = zeros((3, 3))
def Using(point, verb=False):
usage = resource.getrusage(resource.RUSAGE_SELF)
if verb: print '%s: usertime=%s systime=%s mem=%s mb' % (point,usage[0],usage[1],
(usage[2]*resource.getpagesize())/1000000.0 )
return (usage[2]*resource.getpagesize())/1000000.0
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.logfile = None # open(logfilename, "a")
self.logbuf = ''
def flush(self):
# dummy for function astropy iers download; progress bar will not be shown
pass
def write(self, message): # fork the output to stdout and file
self.terminal.write(message)
if self.logfile:
self.logfile.write(message)
else:
self.logbuf += message
def logname(self, logfilename):
self.logfile = open(logfilename, 'a')
self.logfile.write(self.logbuf)
print 'logging to', logfilename
def minsec(t): return '%um%.3fs' % divmod(t, 60) # format time
class interp:
"""interpolation similar to interpolate.interp1d but faster
array must be sorted; 1D arrays only !!!
"""
def __init__(self, x, y) :
self.x = 1 * x # we like real arrays
self.y = 1 * y
def __call__(self, xx):
yy = 0 * xx
_pKolynomial.interpol1D(self.x, self.y, xx, yy, self.x.size, xx.size)
return yy
class Tpl:
def __init__(self, wk, fk, initfunc, evalfunc, mask=False, berv=None):
'''
wk : barycentric corrected wavelength
'''
ii = slice(None)
if mask:
ii = np.isfinite(fk)
self.wk = wk[ii]
self.fk = fk[ii]
self.berv = berv
self.funcarg = initfunc(self.wk, self.fk)
self.evalfunc = evalfunc
def __call__(self, w, der=0):
return self.evalfunc(w, self.funcarg, der=der)
def mskatm(self, w, msk):
# mask regions (atm, stellar) in template
# need target velocity and velocity range
if msk and self.berv:
# bb[o][tellmask(barshift(ww[o],-spt.berv))>0.01] |= flag.atm # mask as before berv correction
# bb[o][skymsk(barshift(ww[o],-spt.berv))>0.01] |= flag.sky # mask as before berv correction
# mask as before berv correction
return msk(barshift(w,-self.berv)) > 0.01
else:
return slice(0,0) # empty
def analyse_rv(obj, postiter=1, fibsuf='', oidx=None, safemode=False, pdf=False):
"""
"""
print obj+'/'+obj+'.rvc'+fibsuf+'.dat'
allrv = np.genfromtxt(obj+'/'+obj+'.rvo'+fibsuf+'.dat')
allerr = np.genfromtxt(obj+'/'+obj+'.rvo'+fibsuf+'.daterr')
sbjd = np.genfromtxt(obj+'/'+obj+'.rvo'+fibsuf+'.dat', dtype=('|S33'), usecols=[0]) # as string
snr = np.genfromtxt(obj+'/'+obj+'.snr'+fibsuf+'.dat')
if np.size(allrv) == 1:
return # just one line, e.g. drift
bjd, RVc_old, e_RVc_old, RVd, e_RVd, RV_old, e_RV_old, BRV, RVsa = np.genfromtxt(obj+'/'+obj+'.rvc'+fibsuf+'.dat', dtype=None).T
orders, = np.where(np.sum(allerr[:,5:]>0, 0)) # orders with all zero error values
if oidx is not None:
omiss = set(oidx) - set(orders)
if omiss: pause('WARNING: orders', omiss,'missing')
else: orders = np.array(sorted(set(orders) & set(oidx)))
omap = orders[:,newaxis]
rv, e_rv = allrv[:,5+orders], allerr[:,5+orders]
# ind, = where(np.isfinite(e_rv[i])) # do not use the failed and last order
RV, e_RV = nanwsem(rv, e=e_rv, axis=1)
RVc = RV - np.nan_to_num(RVd) - np.nan_to_num(RVsa)
e_RVc = np.sqrt(e_RV**2 + np.nan_to_num(e_RVd)**2)
# post RVs (re-weightening)
ok = e_rv > 0
ordmean = average(rv*0, axis=0)
gplot.key('tit "'+obj+'"')
for i in range(1+postiter): # centering, first loop to init, other to clip
RVp, e_RVp = nanwsem(rv-ordmean, e=e_rv*ok, axis=1)
orddisp = rv - ordmean - RVp[:,newaxis]
ordstd, d_ordmean = wstd(orddisp, e_rv*ok, axis=0)
ordmean += d_ordmean # update ordmean
ok &= np.abs(orddisp-d_ordmean) <= 3*ordstd # clip and update mask
if np.isnan(RVp.sum()) or np.isnan(e_RVp.sum()):
print 'WARNING: nan in post RVs. Maybe to few measurements. Re-setting to originals.\n'
RVp, e_RVp = RV, e_RV
break
else:
gplot(orddisp.T, ' matrix us (%s-1):3 t ""' % "".join(['$1==%s?%s:' % io for io in enumerate(orders)]))
ogplot(orders, ordstd, ' w lp lt 3 t "", "" us 1:(-$2) w lp t ""')
if 0: pause(i)
rvp = rv - ordmean
pdf=0
if pdf:
gplot.term('pdfcairo; set out "%s.pdf"'% obj)
if 1: # chromatic slope
gplot.xlabel('"BJD - 2 450 000"').ylabel('"chromatic index [m/s/Np]"')
gplot('"'+obj+'/'+obj+'.srv'+fibsuf+'.dat" us ($1-2450000):4:5 w e pt 7')
if not safemode: pause('chromatic index')
gplot.xlabel('"RV [m/s]"').ylabel('"chromatic index [m/s/Np]"')
gplot('"" us 2:4:3:5:($1-2450000) w xyerr pt 7 palette')
if not safemode: pause('correlation RV - chromatic index')
snro = snr[:,2+orders]
print "total SNR:", np.sum(snro**2)**0.5
if 1: # plot SNR
gplot.reset().xlabel('"Order"; set ylabel "SNR"; set ytics nomirr; set y2label "total SNR"; set y2tics; set yrange[0:]; set y2range[0:]')
gplot(snro, 'matrix us ($2+%i):3' % np.min(orders), flush='')
ogplot(np.sum(snro**2,axis=1)**0.5,' us (%i):1 axis x1y2 t "total SNR"'% (np.min(orders)+len(orders)))
if not safemode: pause()
gplot.reset()
# store post processed rvs
RVpc = RVp - np.nan_to_num(RVd) - np.nan_to_num(RVsa)
e_RVpc = np.sqrt(e_RVp**2 + np.nan_to_num(e_RVd)**2)
#unit_rvp = [open(obj+'/'+obj+'.post'+fibsuf+'.dat', 'w'), open(obj+'/'+obj+'.post.badrv'+fibsuf+'.dat', 'w')]
np.savetxt(obj+'/'+obj+'.post'+fibsuf+'.dat', zip(sbjd, RVpc, e_RVpc, RVp, e_RVp, RVd, e_RVd, BRV, RVsa), fmt='%s')
print 'Statistic on dispersion in RV time series for', obj
print ' %10s %10s %10s %10s %10s'% ('mlrms [m/s]', 'std [m/s]', 'wstd [m/s]', 'iqr [m/s]', 'wiqr [m/s]')
print 'RVmed: %10.4f' % std(allrv[:,3])
print 'RV: '+' %10.4f'*5 % (mlrms(RV,e_RV)[0], std(RV), wstd(RV,e_RV)[0], iqr(RV,sigma=True), iqr(RV, w=1/e_RV**2, sigma=True))
print 'RVp: '+' %10.4f'*5 % (mlrms(RVp,e_RVp)[0], std(RVp), wstd(RVp,e_RVp)[0], iqr(RVp,sigma=True), iqr(RVp, w=1/e_RVp**2, sigma=True))
print 'RVc: '+' %10.4f'*5 % (mlrms(RVc,e_RVc)[0], std(RVc), wstd(RVc,e_RVc)[0], iqr(RVc,sigma=True), iqr(RVc, w=1/e_RVc**2, sigma=True))
print 'RVpc: '+' %10.4f'*5 % (mlrms(RVpc,e_RVpc)[0], nanwstd(RVpc), nanwstd(RVpc,e=e_RVpc), naniqr(RVpc,sigma=True), iqr(RVpc, w=1/e_RVpc**2, sigma=True))
print 'median internal precision', np.median(e_RV)
print 'Time span [d]: ', bjd.max()-bjd.min()
gplot.reset().xlabel('"BJD - 2 450 000"; set ylabel "RV [m/s]"')
gplot('"'+obj+'/'+obj+'.rvc'+fibsuf+'.dat" us ($1-2450000):2:3 w e pt 7 t "rvc %s"'%obj)
if not safemode: pause('rvc')
gplot(bjd, allrv[:,3],' us ($1-2450000):2 t "RVmedian" lt 4', flush='')
ogplot(bjd, RV, e_RV, ' us ($1-2450000):2:3 w e t "RV"', flush='')
ogplot(bjd, RVp, e_RVp, ' us ($1-2450000):2:3 w e t "RVp"', flush='')
ogplot(bjd, RVc, e_RVc, ' us ($1-2450000):2:3 w e pt 7 lt 1 t "RVc"', flush='')
ogplot(bjd, RVpc, e_RVpc,' us ($1-2450000):2:3 w e pt 6 lt 7 t "RVpc"')
if not safemode: pause('rv')
if 0: # error comparison
gplot_set('set xlabel "Order"')
gplot(orders, ordstd, ' t "external error"')
ogplot(orders, np.mean(e_rv, axis=0), ' t "internal error"')
if not safemode: pause('ord disp')
if 1: # Order dispersion
gplot.reset().xlabel('"Order"')
#gplot('"'+filename,'" matrix every ::%i::%i us ($1-5):3' % (omin+5,omax+5))
#ogplot(allrv[:,5:71],' matrix every ::%i us 1:3' %omin)
# create ord, rv,e_rv, bb
#ore = [(o+omin,orddisp[n,o],e_rv[n,o],~ok[n,o]) for n,x in enumerate(orddisp[:,0]) for o,x in enumerate(orddisp[0,:])]
#ore = [(o,)+x for row in zip(orddisp,e_rv,~ok) for o,x in enumerate(zip(*row),omin)]
ore = [np.tile(orders,orddisp.shape).ravel(), orddisp.ravel(), e_rv.ravel(), ~ok.ravel()]
gplot(*ore + ['us 1:2:($3/30) w xe'], flush='')
if not ok.all(): ogplot('"" us 1:2:($3/30/$4) w xe', flush='') # mark 3-sigma outliners
#gplot(orddisp,' matrix us ($1+%i):3' % omin, flush='')
#gplot('"'+filename,'" matrix every ::'+str(omin+5)+' us ($1-5):3')
#ogplot(ordmean,' us ($0+%i):1 w lp lt 3 pt 3 t "ord mean"' %omin, flush='')
ogplot(orders, ordstd,' w lp lt 3 pt 3 t "1 sigma"', flush='')
ogplot('"" us 1:(-$2) w lp lt 3 pt 3 t ""', flush='')
ogplot('"" us 1:($2*3) w lp lt 4 pt 3 t "3 sigma"', flush='')
ogplot('"" us 1:(-$2*3) w lp lt 4 pt 3 t ""', flush='')
ogplot('"" us ($1+0.25):(0):(sprintf("%.2f",$2)) w labels rotate t""', flush='')
ogplot(*ore+[ 'us 1:2:($3) w point pal pt 6'])
if not safemode: pause('ord scatter')
print 'mean ord std:',np.mean(ordstd), ', median ord std:',np.median(ordstd)
if pdf:
gplot.out()
return allrv
def nomask(x): # dummy function, tellurics are not masked
return 0. * x
def lineindex(l, r1, r2):
if np.isnan(r1[0]) or np.isnan(r2[0]):
return np.nan, np.nan
s = l[0] / (r1[0]+r2[0]) * 2
# error propagation
e = s * np.sqrt((l[1]/l[0])**2 + (r1[1]**2+r2[1]**2)/(r1[0]+r2[0])**2)
return s, e
def getHalpha(v, typ='Halpha', inst='HARPS', rel=False, plot=False):
"""
v [km/s]
sp,fmod as global variables !
deblazed sp should be used !
"""
wcen, dv1, dv2 = {
'Halpha': (6562.808, -15.5, 15.5), # Kuerster et al. (2003, A&A, 403, 1077)
'Halpha': (6562.808, -40., 40.),
'Haleft': (6562.808, -300., -100.),
'Harigh': (6562.808, 100, 300),
'Haleft': (6562.808, -500., -300.),
'Harigh': (6562.808, 300, 500),
'CaI': (6572.795, -15.5, 15.5), # Kuerster et al. (2003, A&A, 403, 1077)
'CaH': (3968.470, -1.09/2./3968.470*c, 1.09/2./3968.470*c), # Lovis et al. (2011, arXiv1107.5325)
'CaK': (3933.664, -1.09/2./3933.664*c, 1.09/2./3933.664*c), # Lovis et al.
'CaIRT1': (8498.02, -15., 15.), # NIST + my definition
'CaIRT1a': (8492, -40, 40), # My definition
'CaIRT1b': (8504, -40, 40), # My definition
'CaIRT2': (8542.09, -15., 15.), # NIST + my definition
'CaIRT2a': (8542.09, -300, -200), # My definition
'CaIRT2b': (8542.09, 250, 350), # My definition, +50 due telluric
'CaIRT3': (8662.14, -15., 15.), # NIST + my definition
'CaIRT3a': (8662.14, -300, -200), # NIST + my definition
'CaIRT3b': (8662.14, 200, 300), # NIST + my definition
'NaD1': (5889.950943, -15., 15.), # NIST + my definition
'NaD2': (5895.924237, -15., 15.), # NIST + my definition
'NaDref1': (5885, -40, 40), # My definition
'NaDref2': ((5889.950+5895.924)/2, -40, 40), # My definition
'NaDref3': (5905, -40, 40) # My definition
}[typ]
wcen = lam2wave(airtovac(wcen))
o = None
if inst == 'HARPS':
if typ in ['Halpha', 'Haleft', 'Harigh', 'CaI']: o = 67
if typ in ['CaK']: o = 5
if typ in ['CaH']: o = 7
elif inst == 'CARM_VIS':
if typ in ['Halpha', 'Haleft', 'Harigh', 'CaI']: o = 25
if 'CaIRT1' in typ: o = 46
if 'CaIRT2' in typ: o = 46
if 'CaIRT3' in typ: o = 47
if 'NaD' in typ: o = 14
if o is None: return np.nan, np.nan
ind = o, (wcen+(v-sp.berv+dv1)/c < sp.w[o]) & (sp.w[o] < wcen+(v-sp.berv+dv2)/c)
if rel: # index relative to template
# relative index is not a good idea for variable lines
if np.isnan(fmod[ind]).all(): return np.nan, np.nan
if np.isnan(fmod[ind]).any(): pause()
mod = fmod[ind]
res = sp.f[ind] - mod
I = np.mean(res/fmod[ind])
e_I = rms(np.sqrt(sp.f[ind])/fmod[ind]) / np.sqrt(np.sum(ind[1])) # only for photon noise
else: # mean absolute flux ("box fitting" .... & ref reg => absolute index EW width)
I = np.mean(sp.f[ind])
e_I = 1. / ind[1].sum() * np.sqrt(np.sum(sp.e[ind]**2))
mod = I + 0*sp.f[ind]
if plot==True or typ in plot:
print typ, I, e_I
gplot(sp.w[o], fmod[o], sp.f[o], 'us 1:2 w l lt 3 t "template", "" us 1:3 lt 1 t "obs"')
ogplot(sp.w[ind], sp.f[ind], mod, 'lt 1 pt 7 t "'+typ+'", "" us 1:3 w l t "model", "" us 1:($2-$3) t "residuals"')
pause()
return I, e_I
def polyreg(x2, y2, e_y2, v, deg=1, retmod=True): # polynomial regression
"""Returns polynomial coefficients and goodness of fit."""
fmod = calcspec(x2, v, 1.) # get the shifted template
if 0: # python version
ind = fmod>0.01 # avoid zero flux, negative flux and overflow
p,stat = polynomial.polyfit(x2[ind]-calcspec.wcen, y2[ind]/fmod[ind], deg-1, w=fmod[ind]/e_y2[ind], full=True)
SSR = stat[0][0]
else: # pure c version
pstat = np.empty(deg*2-1)
p = np.empty(deg)
lhs = np.empty((deg, deg))
# _pKolynomial.polyfit(x2, y2, e_y2, fmod, ind, ind.size,globvar.wcen, rhs.size, rhs, lhs, pstat, chi)
ind = 0.0001
# no check for zero division inside _pKolynomial.polyfit!
#pause()
SSR = _pKolynomial.polyfit(x2, y2, e_y2, fmod, ind, x2.size, calcspec.wcen, deg, p, lhs, pstat)
if SSR < 0:
ii, = np.where((e_y2<=0) & (fmod>0.01))
print 'WARNING: Matrix is not positive definite.', 'Zero or negative yerr values for ', ii.size, 'at', ii
p = 0*p
pause(0)
if 0: #abs(v)>200./1000.:
gplot(x2,y2,calcspec(x2, v, *p), ' w lp,"" us 1:3 w l, "" us 1:($2-$3) t "res [v=%f,SSR=%f]"'%(v, SSR))
pause('v, SSR: ',v,SSR)
if retmod: # return the model
return p, SSR, calcspec(x2, v, *p, fmod=fmod)
return p, SSR
def gauss(x, a0, a1, a2, a3):
z = (x-a0) / a2
y = a1 * np.exp(-z**2 / 2) + a3 #+ a4 * x + a5 * x**2
return y
def optidrift(ft, df, f2, e2=None):
"""
Scale derivative to the residuals.
Model:
f(v) = A*f - A*df/dv * v/c
"""
# pre-normalise
#A = np.dot(ft, f2) / np.dot(ft, ft) # unweighted (more robust against bad error estimate)
A = np.dot(1/e2**2*ft, f2) / np.dot(1/e2**2*ft, ft)
fmod = A * ft
v = -c * np.dot(1/e2**2*df, f2-fmod) / np.dot(1/e2**2*df, df) / A #**2
if 0:
# show RV contribution of each pixel!
print 'median', np.median(-(f2-fmod)/df*c/A*1000), ' v', v*1000
gplot(-(f2-fmod)/df*c/A*1000, e2/df*c/A*1000, 'us 0:1:2 w e, %s' % (v*1000))
pause()
e_v = c / np.sqrt(np.dot(1/e2**2*df, df)) / A
fmod = fmod - A*df*v/c
#gplot(f2, ',', ft*A, ',', f2-fmod,e2, 'us 0:1:2 w e')
#gplot(f2, ',', ft*A, ',', f2-A*ft,e2, 'us 0:1:2 w e')
#gplot(f2, ft*A, A*ft-A*df/c*v, A*ft-A*df/c*0.1,' us 0:1, "" us 0:2, "" us 0:3, "" us 0:4, "" us 0:($1-$3) w lp, "" us 0:($1-$4) w lp lt 7')
return type('par',(),{'params': np.append(v,A), 'perror': np.array([e_v,1.0])}), fmod
def CCF(wt, ft, x2, y2, va, vb, e_y2=None, keep=None, plot=False, ccfmode='trapeze'):
# CCF is on the same level as the least square routine fit_spec
if keep is None: keep = np.arange(len(x2))
if e_y2 is None: e_y2 = np.sqrt(y2)
vgrid = np.arange(va, vb, v_step)
# CCF is a data compression/smoothing/binning
SSR = np.arange(vgrid.size, dtype=np.float64)
def model_box(x, v):
idx = np.searchsorted(wt+v/c, x)
return ft[idx] > 0
for i in SSR:
if ccfmode == 'box':
# real boxes (zero order interpolation)
#idx = np.searchsorted(wt+vgrid[i]/c, x2[keep])
#SSR[i] = np.dot(y2[keep], ft[idx]>0) / np.sum(ft[idx]>0)
y2mod = model_box(x2[keep], vgrid[i])
SSR[i] = np.dot(y2[keep], y2mod) / np.sum(y2mod)
# gplot(np.exp(x2), y2, ft[idx]*y2.max(),'w lp, "" us 1:3 w l lt 3')
if ccfmode == 'trapeze':
stop()
# gplot(np.exp(x2), y2,'w lp,', np.exp(x2[keep]),ft[idx]*5010, 'w l lt 3')
# Peak analysis with gaussian fit
# The Gaussian is a template for the second level product CCF
try:
params, covariance = curve_fit(gauss, vgrid, SSR, p0=(0., SSR.max()-SSR.min(), 2.5, SSR.min()))
perror = np.diag(covariance) if np.isfinite(covariance).min() else 0*params
SSRmod = gauss(vgrid, *params)
SSRmin = gauss(params[0], *params)
except:
params = [0,0,0,0]
perror = [0,0,0,0]
SSRmod = 0
SSRmin = 0
if 0:
# old CCF_binless version
# uses just the mask which has a fixed window size
idx = np.searchsorted(wt, x2[keep]) #v=0
ind = (ft[idx]>0) & (ft[idx-1]>0)
iidx = idx[ind] - 1 # previous/lower index
xv2 = (x2[keep[ind]]-0.5*(wt[iidx+1,0]+wt[iidx])) * c
yv2 = y2[keep[ind]] / ft[iidx]
ev2 = e_y2[keep[ind]] / ft[iidx]
elif ccfmode == 'binless':
# get the line center from the mask
# grab the data around the line center with the window size
# phase fold all windows to velocity space by subtracting the line center
# assume windows do not overlap
wsz = 6.0 # [km/s] 3.0 for HARPS, 6.0 for FEROS
linecen = 0.5 * (wt[1::4]+wt[2::4]) # get the linecenter form the mask
lineflux = 0.5 * (ft[1::4]+ft[2::4])
idx = np.searchsorted(linecen, x2[keep]) # find index of nearest largest line
idx = idx - ((linecen[idx]-x2[keep]) > (x2[keep]-linecen[idx-1])) # index of the nearest (smaller or larger) line
ind = np.abs(x2[keep]-linecen[idx]) < wsz/c # index for values with the window
xv2 = (x2[keep[ind]]-linecen[idx[ind]]) * c # phase fold
yv2 = y2[keep[ind]] / lineflux[idx[ind]]
ev2 = e_y2[keep[ind]] / lineflux[idx[ind]]
# normalise window flux with the flux mean in each window
iidx = idx[ind] - 1
lidx = iidx - iidx.min()
nlines = lidx.max() + 1
linenorm = np.zeros((nlines,2))
for i,y in zip(lidx, yv2): linenorm[i] += np.array([y,1])
linenorm = (linenorm[:,0] / linenorm[:,1])[lidx] # mean = sum / n
yv2norm = yv2 / linenorm
#yv2 = yv2norm
fmod = 0
if 0 or plot and ccfmode=='binless':
# try a robust gaussfit via iterative clipping
iidx = idx[ind] - 1
fmod = 0 * y2
try:
#par2, cov2 = curve_fit(gauss, xv2, yv2, p0=(0,1,2.5,0))
nclip = 1
good = np.arange(len(xv2))
for it in range(nclip+1):
par2, cov2 = curve_fit(gauss, xv2[good], yv2norm[good], p0=(0,1,2.5,0))
perr2 = np.diag(cov2)
SSR2mod = gauss(vgrid, *par2)
yv2mod = gauss(xv2, *par2)
normfac = params[1] / par2[1]
fmod[keep[ind]] = gauss(xv2, *par2)
# clip
kap = 3 * np.std(yv2norm[good]-yv2mod[good])
out = np.abs(yv2norm - yv2mod) > kap
rml = np.unique(lidx[out])
good = np.sum(lidx == rml[:,newaxis],0)==0 # ind for lines not reject (good windows)
if plot:
gplot(xv2, yv2norm, yv2mod,good, ', "" us 1:3, "" us 1:($2/($4==0)),', vgrid,SSR2mod,SSR2mod-kap,SSR2mod+kap, 'w l lt 7, "" us 1:3 w l lt 1, "" us 1:4 w l lt 1')
#pause()
except:
par2 = [0]
perr2 = [0,0,0]
normfac = 0
SSR2mod = vgrid*0
if plot&1:
gplot(vgrid, SSR, SSRmod, 'w lp pt 7 t "CCF", "" us 1:3 w l lt 3 lw 3 t"CCF fit %.2f +/- %.2f m/s"'%(params[0]*1000,perror[0]*1000))
if plot&1 and ccfmode=='binless':
# insert a -1 row for broken lines in plot
gg = []
for g,diff in zip(np.dstack((xv2, normfac*yv2norm, normfac*ev2, iidx-iidx.min()))[0], np.ediff1d(iidx, to_begin=0)): gg += [g*0-1,g] if diff else [g]
gg = np.array(gg)
gplot.palette('model HSV rgbformulae 3,2,2; set bar 0')
gplot(gg, 'us 1:($2/($4>-1)):4 w lp palette pt 7, "" us 1:($2/($4>-1)):3 w e pt 1 lt 1,', vgrid, normfac*SSR2mod, 'w l lc 3 lw 3 t"%.2f +/- %.2f m/s"'%(par2[0]*1000,perr2[2]*1000))
#gplot(xv2, normfac*yv2norm, normfac*ev2, iidx-iidx.min(), np.ediff1d(iidx, to_begin=0), 'us 1:2:4 w lp palette pt 7, "" us 1:2:3 w e pt 1 lt 1,', vgrid, normfac*SSR2mod, 'w l lc 0 lw 3 t"%.2f +/- %.2f m/s"'%(par2[0]*1000,perr2[2]*1000))
ogplot(vgrid, SSR, SSRmod, 'w lp lt 7 pt 7 t "CCF", "" us 1:3 w l lt 7 lw 3 t"CCF fit %.2f +/- %.2f m/s"'%(params[0]*1000,perror[0]*1000))
pause(params[0]*1000, perror[0]*1000)
print params[0]*1000, perror[0]*1000
if plot&1: pause()
if plot&2:
idx = np.searchsorted(wt, x2)
idx0 = np.searchsorted(wt-vgrid[0]/c, x2)
gplot(np.exp(x2), y2, ft[idx]/10, y2*(ft[idx]>0), y2*(ft[idx0]>0), 'w lp t "x2,y2 input spectrum", "" us 1:3 w l lt 3 t "mask (v=0)", "" us 1:4 lt 3 t "x2,y2*mask", "" us 1:5 lt 4 pt 1 t "x2,y2*mask(v=va)')
pause()
stat = {'std': 1, 'snr': 0}
params[0] *= -1
return type('par',(),{'params': params, 'perror':perror, 'ssr':SSRmin, 'niter':0}), fmod, (vgrid, SSR, SSRmod), stat
def SSRstat(vgrid, SSR, dk=1, plot='maybe'):
# analyse peak
k = SSR[dk:-dk].argmin() + dk # best point (exclude borders)
vpeak = vgrid[k-dk:k+dk+1]
SSRpeak = SSR[k-dk:k+dk+1] - SSR[k]
# interpolating parabola a0+a1*x+a2*x**2 (direct solution) through the three pixels in the minimum
a = np.array([0, (SSR[k+dk]-SSR[k-dk])/(2*v_step), (SSR[k+dk]-2*SSR[k]+SSR[k-dk])/(2*v_step**2)]) # interpolating parabola for even grid
v = (SSR[k+dk]-SSR[k-dk]) / (SSR[k+dk]-2*SSR[k]+SSR[k-dk]) * 0.5 * v_step
v = vgrid[k] - a[1]/2./a[2] # position of parabola minimum
e_v = np.nan
if -1 in SSR:
print 'opti warning: bad ccf.'
elif a[2] <= 0:
print 'opti warning: a[2]=%f<=0.' % a[2]
elif not vgrid[0] <= v <= vgrid[-1]:
print 'opti warning: v not in [va,vb].'
else:
e_v = 1. / a[2]**0.5
if (plot==1 and np.isnan(e_v)) or plot==2:
gplot.yrange('[*:%f]' % SSR.max())
gplot(vgrid, SSR-SSR[k], " w lp, v1="+str(vgrid[k])+", %f+(x-v1)*%f+(x-v1)**2*%f," % tuple(a), [v,v], [0,SSR[1]], 'w l t "%f km/s"'%v)
ogplot(vpeak, SSRpeak, ' lt 1 pt 6; set yrange [*:*]')
pause(v)
return v, e_v, a
def opti(va, vb, x2, y2, e_y2, p=None, vfix=False, plot=False):
""" vfix to fix v for RV constant stars?
performs a mini CCF; the grid stepping
returns best v and errors from parabola curvature
"""
vgrid = np.arange(va, vb, v_step)
nk = len(vgrid)
SSR = np.empty(nk)
for k in range(nk):
p, SSR[k] = polyreg(x2, y2, e_y2, vgrid[k], len(p), retmod=False)
# analyse the CCF peak fitting
v, e_v, a = SSRstat(vgrid, SSR, plot=(not safemode)*(1+plot))
if np.isnan(e_v):
v = vgrid[nk/2] # actually it should be nan, but may the next clipping loop or plot use vcen
print " Setting v=" % v
if vfix: v = 0.
p, SSRmin, fmod = polyreg(x2, y2, e_y2, v, len(p)) # final call with v
if 1 and (np.isnan(e_v) or plot) and not safemode:
gplot(x2, y2, fmod, ' w lp, "" us 1:3 w lp lt 3')
pause(v)
return type('par', (), {'params': np.append(v,p), 'perror': np.array([e_v,1.0]), 'ssr': (vgrid,SSR)}), fmod
def fitspec(tpl, w2, f2, e_y=None, v=0, vfix=False, clip=None, nclip=1, keep=None, indmod=np.s_[:], v_step=True, df=None, plot=False, deg=3, chi2map=False):
"""
Performs the robust least square fit via iterative clipping.
vfix : boolean, optional
v is fixed. For RV constant stars or in coadding when only the background polynomial is computed.
indmod : Index range to be finally calculated-
clip : Kappa sigma clipping value.
nclip : Number of clipping iterations (default: 0 if clip else 1).
df : Derivative for drift measurement.
v_step : Number of v steps (only background polynomial => v_step = false).
"""
if keep is None: keep = np.arange(len(w2))
if e_y is None: e_y = np.mean(f2)**0.5 + 0*f2 # mean photon noise
if clip is None: nclip = 0 # number of clip iterations; default 1
calcspec.wcen = np.mean(w2[keep])
calcspec.tpl = tpl
p = np.array([v, 1.] + [0]*deg) # => [v,1,0,0,0]
fMod = np.nan * w2
#fres = 0.*w2 # same size
for n in range(nclip+1):
if df is not None:
'''drift mode: scale derivative to residuals'''
par, fModkeep = optidrift(ft.take(keep,mode='clip'), df.take(keep,mode='clip'), f2.take(keep,mode='clip'),
e_y.take(keep,mode='clip'))
elif v_step:
'''least square mode'''
par, fModkeep = opti(v+v_lo, v+v_hi, w2.take(keep,mode='clip'), f2.take(keep,mode='clip'),
e_y.take(keep,mode='clip'), p[1:], vfix=vfix, plot=plot)
ssr = par.ssr
else:
'''only background polynomial'''
p, SSR, fModkeep = polyreg(w2.take(keep,mode='clip'), f2.take(keep,mode='clip'), e_y.take(keep,mode='clip'), v, len(p)-1)
par = type('par',(),{'params': np.append(v,p), 'ssr': SSR})
p = par.params
par.niter = n
if 1:
# exclude model regions with negative flux
# can occur e.g. in background in ThAr, or due to tellurics
ind = fModkeep > 0
keep = keep[ind] # ignore the pixels modelled with negative flux
fModkeep = fModkeep[ind]
# all might be negative (for low/zero S/N data)
#fres[keep] = (f2[keep] - fMod[keep]) / fMod[keep]**0.5
#res_std = rms(fres[keep]) # residual noise / photon noise
# use error predicted by model
#fres = (f2.take(keep,mode='clip')-fModkeep) / fModkeep**0.5
# use external errors
fres = (f2.take(keep,mode='clip')-fModkeep) / e_y.take(keep,mode='clip')
res_std = rms(fres) # residual noise / photon noise
if n < nclip:
ind = np.abs(fres) <= clip*res_std
nreject = len(keep) - np.sum(ind)
if nreject: keep = keep[ind] # prepare next clip loop
# else: break
if len(keep)<10: # too much rejected? too many negative values?
print "too much rejected, skipping"
break
if 0 and np.abs(par.params[0]*1000)>20:
if df:
fMod = ft * p[1] # compute also at bad pixels
else:
fMod = calcspec(w2, *p) # compute also at bad pixels
gplot.y2tics().ytics('nomir; set y2range [-5:35];')
gplot(w2,fMod,' w lp pt 7 ps 0.5 t "fmod"')
gplot+(w2[keep],fMod[keep],' w lp pt 7 ps 0.5 t "fmod[keep]"')
gplot+(w2,f2,' w lp pt 7 ps 0.5 t "f2"')
#ogplot(w2[keep],fres[keep],' w lp pt 7 ps 0.5 lc rgb "red" axis x1y2 t "residuals"',flush='')
ogplot(w2[keep],fres,' w lp pt 7 ps 0.5 lc rgb "black" axis x1y2, 0 w l lt 2 axis x1y2 t"", '+str(res_std)+' w l lt 1 axis x1y2, '+str(-res_std)+ ' w l lt 1 t "" axis x1y2')
pause('large RV', par.params[0]*1000)
stat = {"std": res_std, 'ssrmin': fres.sum(), "snr": np.mean(fModkeep)/np.mean(np.abs(f2.take(keep,mode='clip')-fModkeep))}
#pause(stat["snr"], wmean(fModkeep)/wrms(f2.take(keep,mode='clip')-fModkeep), np.median(fModkeep)/np.median(np.abs(f2.take(keep,mode='clip')-fModkeep)) )
if df is not None:
fMod[indmod] = ft[indmod]*p[1] - df[indmod]*p[1]*p[0]/c # compute also at bad pixels
else:
fMod[indmod] = calcspec(w2[indmod], *p) # compute also at bad pixels
if chi2map:
return par, fMod, keep, stat, ssr
else:
return par, fMod, keep, stat
def serval(*argv):
sys.stdout = Logger()
global obj, targ, oset, coadd, coset, last, tpl, sa, tplrv, debug, sp, fmod, reana, inst, fib, look, looki, lookt, lookp, lookssr, pmin, pmax, debug, pspllam, kapsig, nclip, atmfile, skyfile, atmwgt, omin, omax, ptmin, ptmax, driftref, deg, targrv
if not argv: argv = sys.argv # python shell start
else: argv = ['module '] + list(argv)
if len(argv)>1:
outdir = obj + '/'
fibsuf = '_B' if inst=='FEROS' and fib=='B' else ''
else:
print "object missing"
print "Example: "+sys.argv[0]+" gj699 dir_or_inputlist=/home/zechmeister/data/harps/gj699/path/ -restore omin=20 nset='1::2'"
return 1
print description
### SELECT INSTRUMENTAL FORMAT ###
# general default values
pat = '*tar' # default search pattern
maskfile = servallib + 'telluric_mask_atlas_short.dat'
# instrument specific default values
if inst == 'CARM_VIS':
if fib == '': fib = 'A'
iomax = 61 # NAXIS2
# pat = '*pho*_x2d_'+fib+'.fits'
pat = '*-vis_' + fib + '.fits'
maskfile = servallib + 'telluric_mask_carm_short.dat'
elif inst == 'CARM_NIR':
if fib == '': fib = 'A'
iomax = 28
iomax *= 2 # reshaping
pat = '*-nir_' + fib + '.fits'
maskfile = servallib + 'telluric_mask_carm_short.dat'
elif 'HARP' in inst:
if fib == '': fib = 'A'
if fib == 'A': iomax = 72
if fib == 'B': iomax = 71
if inst=='HARPN': iomax = 68
elif inst == 'FEROS':
iomax = 38
if fib == '': fib = 'A'
if fib == 'B': maskfile = servallib + 'feros_mask_short.dat'
ptomin = np.array([1800, 2000, 1800, 2000, 2000, 1600, 1500, 1400, 1100, 1000,
1000, 1000, 1000, 900, 800, 800, 800, 600, 500, 500,
400, 400, 300, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100])
ptomax = np.array([3100, 4000, 4000, 4000, 4000, 4500, 4600, 4600, 4800, 4800,
5000, 5200, 5200, 5300, 5600, 5700, 5800, 6000, 6100, 6300,
6500, 6600, 6700, 6800, 7100, 7200, 7400, 7700, 7900, 8100,
8400, 8600, 8900, 9200, 9500, 9800,10200,10600,11100])
pomin = ptomin + 300
pomax = ptomax - 300
pmin = pomin.min()
pmax = pomin.max()
elif inst == 'FTS':
iomax = 70
pmin = 300
pmax = 50000/5 - 500
ptmin = pmin - 100 # oversize the template
ptmax = pmax + 100
orders = np.arange(iomax)[oset]
corders = np.arange(iomax)[coset]
orders = sorted(set(orders) - set(o_excl))
corders = sorted(set(corders) - set(co_excl))
omin = min(orders)
omax = max(orders)
comin = min(corders)
comax = max(corders)
if reana:
x = analyse_rv(obj, postiter=postiter, fibsuf=fibsuf, oidx=orders)
exit()
os.system('mkdir -p '+obj)
t0 = time.time()
print "start time:", time.strftime("%Y-%m-%d %H:%M:%S %a", time.localtime())
use_drsberv = False
if fib == 'B' or (ccf is not None and 'th_mask' in ccf):
pass
### SELECT TARGET ###
targ = type('TARG', (), dict(name=targ, plx=targplx, rv=targrv, sa=float('nan')))
targ.ra, targ.de = targrade
targ.pmra, targ.pmde = targpm
if targ.name == 'cal':
print 'no barycentric correction (calibration)'
elif targ.ra and targ.de or targ.name:
targ = Targ(targ.name, targrade, targpm, plx=targplx, rv=targrv, cvs=obj+'/'+obj+'.targ.cvs')
print ' using sa=', targ.sa, 'm/s/yr', 'ra=', targ.ra, 'de=', targ.de, 'pmra=', targ.pmra, 'pmde=', targ.pmde
else:
print 'using barycentric correction from DRS'
# choose the interpolation type
spltype = 3 # 3=> fast version
spline_cv = {1: interpolate.splrep, 2: cubicSpline.spl_c, 3: cubicSpline.spl_cf }[spltype]
spline_ev = {1: interpolate.splev, 2: cubicSpline.spl_ev, 3: cubicSpline.spl_evf}[spltype]
print dir_or_inputlist
print 'tpl=%s pmin=%s nset=%s omin=%s omax=%s' % (tpl, pmin, nset, omin, omax)
''' SELECT FILES '''
files = sorted(glob.glob(dir_or_inputlist+os.sep+pat))
isfifo = os_stat.S_ISFIFO(os.stat(dir_or_inputlist).st_mode)
if os.path.isfile(dir_or_inputlist) or isfifo:
if dir_or_inputlist.endswith(('.txt', '.lis')) or isfifo:
files = []
with open(dir_or_inputlist) as f:
print 'getting filenames from file (',dir_or_inputlist,'):'
for line in f:
line = line.split() # remove comments
if line:
if os.path.isfile(line[0]):
files += [line[0]]
print len(files), files[-1]
else:
print 'skipping:', line[0]
if fib == 'B':
files = [f.replace('_A.fits','_B.fits') for f in files]
print 'renaming', files
else:
# case if dir_or_inputlist is one fits-file
files = [dir_or_inputlist]
# handle tar, e2ds, fox
if 'HARP' in inst and not files:
files = sorted(glob.glob(dir_or_inputlist+'/*e2ds_'+fib+'.fits'))
if not files:
files = sorted(glob.glob(dir_or_inputlist+'/*e2ds_'+fib+'.fits.gz'))
drs = bool(len(files))
if 'HARPS' in inst and not drs: # fox
files = sorted(glob.glob(dir_or_inputlist+'/*[0-9]_'+fib+'.fits'))
if 'CARM' in inst and not files:
files = sorted(glob.glob(dir_or_inputlist+'/*pho*_'+fib+'.fits'))
if 'FEROS' in inst:
files += sorted(glob.glob(dir_or_inputlist+'/f*'+('1' if fib=='A' else '2')+'0001.mt'))
if 'FTS' in inst:
files = sorted(glob.glob(dir_or_inputlist+'/*ap08.*_ScSm.txt'))
files = [s for s in files if '20_ap08.1_ScSm.txt' not in s and '20_ap08.2_ScSm.txt' not in s and '001_08_ap08.193_ScSm.txt' not in s ]
files = np.array(files)[nset]
nspec = len(files)
if not nspec:
print "no spectra found in", dir_or_inputlist, 'or using ', pat, inst
exit()
# expand slices to index arrays
if look: look = np.arange(iomax)[look]
if lookt: lookt = np.arange(iomax)[lookt]
if lookp: lookp = np.arange(iomax)[lookp]
if lookssr: lookssr = np.arange(iomax)[lookssr]
if outfmt or outchi: os.system('mkdir -p '+obj+'/res')
with open(outdir+'lastcmd.txt', 'w') as f:
print >>f, ' '.join(argv)
with open('cmdhistory.txt', 'a') as f:
print >>f, ' '.join(argv)
badfile = file(outdir + obj + '.flagdrs' + fibsuf + '.dat', 'w')
infofile = file(outdir + obj + '.info' + fibsuf + '.cvs', 'w')
bervfile = open(outdir + obj + '.brv' + fibsuf + '.dat', 'w')
prefile = outdir + obj + '.pre' + fibsuf + '.dat'
rvofile = outdir + obj + '.rvo' + fibsuf + '.dat'
snrfile = outdir + obj + '.snr' + fibsuf + '.dat'
chifile = outdir + obj + '.chi' + fibsuf + '.dat'
halfile = outdir + obj + '.halpha' + fibsuf + '.dat'
nadfile = outdir + obj + '.nad' + fibsuf + '.dat'
irtfile = outdir + obj + '.cairt' + fibsuf + '.dat'
dfwfile = outdir + obj + '.dlw' + fibsuf + '.dat'
# (echo 0 0 ; awk '{if($2!=x2){print x; print $0}; x=$0; x2=$2;}' telluric_mask_atlas.dat )> telluric_mask_atlas_short.dat
#################################
### Loading and prepare masks ###
#################################
mask = None
tellmask = nomask
skymsk = nomask
if fib == 'B':
if atmfile == 'auto':
atmfile = None
if skyfile == 'auto':
skyfile = None
if ccf and 'th_mask' not in ccf:
atmfile = None
if atmfile:
if atmfile != 'auto':
maskfile = atmfile
if 'mask_ne' in atmfile:
maskfile = servallib + atmfile
print 'maskfile', maskfile
mask = np.genfromtxt(maskfile, dtype=None)
if 'telluric_mask_atlas_short.dat' in maskfile:
lcorr = 0.000009 # Guillems mask needs this shift of 2.7 km/s
mask[:,0] = airtovac(mask[:,0]) * (1-lcorr)
if 'th_mask' in maskfile: # well, it is not atmosphere, but ...
mask[:,1] = mask[:,1] == 0 # invert mask; actually the telluric mask should be inverted (so that 1 means flagged and bad)
if skyfile:
if skyfile=='auto' and inst=='CARM_NIR':
skyfile = servallib + 'sky_carm_nir'
sky = np.genfromtxt(skyfile, dtype=None)
skymsk = interp(lam2wave(sky[:,0]), sky[:,1])
msksky = [0] * iomax
if 1 and inst=='CARM_VIS':
try:
import pyfits
except:
import astropy.io.fits as pyfits
msksky = flag.atm * pyfits.getdata(servallib + 'carm_vis_tel_sky.fits')
if msklist: # convert line list to mask
mask = masktools.list2mask(msklist, wd=mskwd)
mask[:,1] = mask[:,1] == 0 # invert mask; actually the telluric mask should be inverted (so that 1 means good)
if mask is None:
print 'using telluric mask: NONE'
else:
# make the discrete mask to a continuous mask via linear interpolation
tellmask = interp(lam2wave(mask[:,0]), mask[:,1])
print 'using telluric mask: ', maskfile
if 0:
mask2 = np.genfromtxt('telluric_add.dat', dtype=None)
# DO YOU NEED THIS: mask2[:,0] = airtovac(mask2[:,0]) ??
i0 = 0 #where(mask[:,0]<mask2[0][0])[0][-1]
for ran in mask2:
while (mask[i0,0]<ran[0]): i0 += 1
#if mask[i0-1,0]==0:
mask = np.insert(mask,i0,[ran[0]-0.0000001,0.0],axis=0) # insert
mask = np.insert(mask,i0+1,[ran[0],1.0],axis=0) # insert
#while (mask[i0,0]<ran[1]): np.delete(mask,i0,axis=0)
#if mask[i0-1,0]==0:
mask = np.insert(mask,i0+2,[ran[1],1.0],axis=0) # insert
mask = np.insert(mask,i0+3,[ran[1]+0.0000001,0.0],axis=0) # insert
################################
### READ FITS FILES ############
################################
splist = []
spi = None
SN55best = 0.
print " # %*s %*s OBJECT BJD SN DRSBERV DRSdrift flag calmode" % (-len(inst)-6, "inst_mode", -len(os.path.basename(files[0])), "timeid")
infowriter = csv.writer(infofile, delimiter=';', lineterminator="\n")
for n,filename in enumerate(files): # scanning fitsheader
print '%3i/%i' % (n+1, nspec),
sp = Spectrum(filename, inst=inst, pfits=2 if 'HARP' in inst else True, drs=drs, fib=fib, targ=targ, verb=True)
splist.append(sp)
if use_drsberv:
sp.bjd, sp.berv = sp.drsbjd, sp.drsberv
sp.sa = targ.sa / 365.25 * (sp.bjd-splist[0].bjd)
sp.header = None # saves memory(?), but needs re-read (?)
if inst == 'HARPS' and drs: sp.ccf = read_harps_ccf(filename)
if sp.sn55 < snmin: sp.flag |= sflag.lowSN
if sp.sn55 > snmax: sp.flag |= sflag.hiSN
if distmax and sp.ra and sp.de:
# check distance for mis-pointings
# yet no proper motion included
ra = (targ.ra[0] + (targ.ra[1]/60 + targ.ra[2]/3600)* np.sign(targ.ra[0]))*15 # [deg]
de = targ.de[0] + (targ.de[1]/60 + targ.de[2]/3600)* np.sign(targ.de[0]) # [deg]
dist = np.sqrt(((sp.ra-ra)*np.cos(np.deg2rad(sp.de)))**2 + (sp.de-de)**2) * 3600
if dist > distmax: sp.flag |= sflag.dist
if not sp.flag:
if SN55best < sp.sn55 < snmax:
SN55best = sp.sn55
spi = n
else:
print >>badfile, sp.bjd, sp.ccf.rvc, sp.ccf.err_rvc, sp.timeid, sp.flag
print >>bervfile, sp.bjd, sp.berv, sp.drsbjd, sp.drsberv, sp.drift, sp.timeid, sp.tmmean, sp.exptime, sp.berv_start, sp.berv_end
infowriter.writerow([sp.timeid, sp.bjd, sp.berv, sp.sn55, sp.obj, sp.exptime, sp.ccf.mask, sp.flag, sp.airmass, sp.ra, sp.de])
#print >>infofile, sp.timeid, sp.bjd, sp.berv, sp.sn55, sp.obj, sp.exptime, sp.ccf.mask, sp.flag
badfile.close()
bervfile.close()
infofile.close()
sys.stdout.logname(obj+'/log.'+obj)