-
Notifications
You must be signed in to change notification settings - Fork 0
/
CalcBroadening.py
executable file
·1672 lines (1383 loc) · 63.5 KB
/
CalcBroadening.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
from __future__ import division
from builtins import map
from builtins import str
from builtins import range
import os
import re
import pickle
import logging
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from past.utils import old_div
from scipy.optimize import curve_fit
from scipy.interpolate import UnivariateSpline
from PyAstronomy import pyasl
from astropy.io import fits, ascii
#from .interpol_function import interpol
from AtmosInterpol import interpol
from uncertainties import unumpy, ufloat, umath
plt.style.use(['seaborn-muted'])
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
#******************************************************************************
#******************************************************************************
class Vsini:
"""
spec_window is the spectral analysis window, a 1x2 numpy array
gauss is the instrumental broadening parameter
v_macro is the macroturbulence velocity
line_file is the name of the file containing the chosen lines
line is which of the lines on the previous file to work on
SN is the signal-to-noise ratio of the spectrum
# x_vel is the velocity shift to be applied to the x-axis
# x_wl is the wavelengths shift to be applied to the x-axis
# y_add is the additive shift to be applied to the spectrum
# y_mult is the multiplicative shift to be applied to the spectrum
# perf_radius is the number of points around the line center where
# to evaluate the performance of the synthetic spectrum
# bwing_w is the weight to be applied to the blue side of the line
# when evaluating the performance
# rwing_w is the weight to be applied to the red side of the line
# when evaluating the performance
# center_w is the weight to be applied to the line center when
# evaluating the performance
# Maximum number of points around the performance radius that are
# allowed to be a bad fit (1 S/N sigma lower than observed signal)
# If this limit is exceeded, the variable badfit_status will return
# True after running find()
# For high precision spectrum, set this to a very low number
"""
def __init__(self, spec_window, gauss, v_macro, line_file, line, SN,\
**kwargs):
self.name = kwargs.get('star_name', 'Unnamed star')
self.vshift = kwargs.get('x_vel', 0.0)
self.xshift = kwargs.get('x_wl', 0.0)
self.yadd = kwargs.get('y_add', 0.0)
self.ymult = kwargs.get('y_mult', 1.0)
self.radius = kwargs.get('perf_radius', 10)
self.bwing_w = kwargs.get('bwing_w', 3.0)
self.rwing_w = kwargs.get('rwing_w', 5.0)
self.center_w = kwargs.get('center_w', 25.0)
self.badfit_tol = kwargs.get('badfit_tol', 10)
self.c = 2.998E18
self.am = arr_manage()
self.spec = spec_window
self.gauss = gauss
self.v_m = v_macro
self.lines = np.loadtxt(line_file, skiprows=1, usecols=(0, 1))
try:
self.Z = self.lines[line, 1]
self.line_center = self.lines[line, 0]
except IndexError:
self.Z = self.lines[1]
self.line_center = self.lines[0]
self.spec_sigma = 1./SN
self.data = np.loadtxt('./Spectra/%s_%d.dat' % (self.name, line))
self.data_new = self.data
self.line_number = line
# Other attributes that will be properly assigned in other functions
self.data_target = []
self.center_index = 0
self.ci0 = 0
self.ci1 = 0
self.MOOG = None
self.check = None
self.pts = 15
self.pace = np.array([2.0, 2.0])
self.a_guess = np.array([-0.100, 0.100])
self.v_guess = np.array([0.5, 25.0])
self.min_i = 3
self.max_i = 21
self.limits = np.array([0.01, 0.001])
self.plot = True
self.v_low_limit = 0.5
self.save = None
self.silent = True
self.best_a = np.nan
self.best_v = np.nan
self.it = 0
self.finish = False
self.badfit_status = False
self.it2 = 0
self.best_v_antes = np.nan
self.best_a_antes = np.nan
self.v_grid = []
self.S = []
self.S_v = []
self.yfit_v = []
self.intern_u = 0
self.best_v_ind = 0
self.a_grid = []
self.S_a = []
self.yfit_a = []
self.best_a_ind = 0
self.go_v = 0
self.go_a = 0
self.v_change = None
self.a_change = None
self.v_width = np.nan
self.a_width = np.nan
def perf_new(self, v, a, mode='vsini'):
"""
The performance function: first it creates the params.txt file, then runs
moog in silent mode, interpolates the generated model to the points of
the observed spectrum, and then simply calculates the sum of squared
differences, weighted by the inverse of the observed spectrum to the power
of alpha.
"""
data_old = np.copy(self.data)
data_n = np.copy(self.data)
self.data_new[:, 0] = data_n[:, 0] + self.xshift - data_n[:, 0] * \
(old_div(self.c, (self.vshift*1E13 + self.c)) - 1.0)
self.data_new[:, 1] = data_n[:, 1] * self.ymult + self.yadd
self.data_target = self.am.x_set_limits(self.spec[0], self.spec[1],
self.data_new)
self.center_index = self.am.find_index(self.line_center, self.data_target[:, 0])
self.ci0 = self.center_index - self.radius
self.ci1 = self.center_index + self.radius+1
if 2.*self.radius > len(self.data_target[:, 1]):
self.radius = int(np.floor(old_div(len(self.data_target[:, 0]), 2)) - 1)
self.ci0 = self.center_index - self.radius
self.ci1 = self.center_index + self.radius+1
if self.ci1 > len(self.data_target[:, 0]):
resto = int(np.ceil((self.ci1 - len(self.data_target[:, 0]))))
self.radius -= resto
self.ci0 = self.center_index - self.radius
self.ci1 = self.center_index + self.radius+1
if self.ci0 < 0:
self.radius -= (self.radius - self.center_index)
self.ci0 = self.center_index - self.radius
self.ci1 = self.center_index + self.radius+1
if mode == 'vsini':
S = np.inf * np.ones(v.size)
self.MOOG.abunds = a
self.MOOG = self.MOOG.change_vsini(v)
for k, vsini in enumerate(v):
model_v = self.MOOG.model_vsini[str(vsini)]
if ~all(np.isnan(model_v.T[1])):
model_interp = np.interp(self.data_target[self.ci0:self.ci1, 0],\
model_v.T[0], model_v.T[1])
w = np.zeros(2 * self.radius + 1, float)
if self.ci1 > len(self.data_target[:, 0]):
w = np.zeros(2 * self.radius, float)
w[:self.radius-3] = self.bwing_w
w[self.radius+4:] = self.rwing_w
w[self.radius-3:self.radius+4] = self.center_w
S[k] = np.sum(w * (self.data_target[self.ci0:self.ci1, 1] - \
model_interp)**2.) / np.sum(w)
del model_interp, w
del model_v
else:
S = np.inf * np.ones(a.size)
self.MOOG.vsini = v
self.MOOG.model_ab = {}
for k, val in enumerate(a):
self.MOOG = self.MOOG.change_ab(val)
model_a = self.MOOG.model_ab[str(val)]
if ~all(np.isnan(model_a[:, 1])):
model_interp = np.interp(self.data_target[self.ci0:self.ci1, 0],\
model_a[:, 0], model_a[:, 1])
w = np.zeros(2 * self.radius + 1, float)
if self.ci1 > len(self.data_target[:, 0]):
w = np.zeros(2 * self.radius, float)
w[:self.radius-2] = self.bwing_w
w[self.radius+3:] = self.rwing_w
w[self.radius-2:self.radius+3] = self.center_w
S[k] = np.sum(w * (self.data_target[self.ci0:self.ci1, 1] - \
model_interp)**2) / np.sum(w)
del model_interp, w
del model_a
self.data = data_old
del data_old, data_n, self.data_target
return S
def perf(self, p):
data_old = np.copy(self.data)
data_n = np.copy(self.data)
self.data_new[:, 0] = data_n[:, 0] + self.xshift - data_n[:, 0] * \
(old_div(self.c, (self.vshift*1E13 + self.c)) - 1.0)
self.data_new[:, 1] = data_n[:, 1] * self.ymult + self.yadd
self.data_target = self.am.x_set_limits(self.spec[0], self.spec[1],
self.data_new)
# Running MOOGSILENT
self.MOOG.vsini = p[0]
self.MOOG.abunds = p[1]
self.MOOG = self.MOOG.run()
# Evaluating the performance in a radius around the center of the line
self.center_index = self.am.find_index(self.line_center,
self.data_target[:, 0])
self.ci0 = self.center_index - self.radius
self.ci1 = self.center_index + self.radius+1
if 2.*self.radius > len(self.data_target[:, 0]):
self.radius = int(np.floor(old_div(len(self.data_target[:, 0]), 2)) - 1)
self.ci0 = self.center_index - self.radius
self.ci1 = self.center_index + self.radius+1
model_interp = np.interp(self.data_target[self.ci0:self.ci1, 0],
self.MOOG.model[:, 0],
self.MOOG.model[:, 1])
# Checking the fit on line wings
self.check = self.data_target[self.ci0:self.ci1, 1] - model_interp
self.check = len(np.where(self.check > 1.*self.spec_sigma)[0])
# Creating the weights vector
w = np.zeros(2 * self.radius + 1, float)
if self.ci1 > len(self.data_target[:, 0]):
w = np.zeros(2 * self.radius, float)
w[:self.radius] = self.bwing_w
w[self.radius+1:] = self.rwing_w
w[self.radius] = self.center_w
S = old_div(np.sum(w * (self.data_target[self.ci0:self.ci1, 1] - \
model_interp)**2), np.sum(w))
self.data = data_old
del data_old, data_n, model_interp, w
return S
def find(self, **kwargs):
"""
-N: Number of points to try for each iteration
-pace: Narrowing factor when going to the next iteration
pace[0] = narrowing factor for vsini
pace[1] = narrowing factor for abundance
-a_guess: Initial guess range for abundance. It has to be a numpy array of
length = 2
-v_guess: Initial guess range for vsini. It has to be a numpy array of
length = 2
-min_i: Minimum number of iterations
-max_i: Maximum number of iterations
-limits: Convergence limits: a numpy array with length 2, corresponding to the
limits of vsini and abundance, respectively
-plot: Plot the spectral line fit at the end?
-v_low_limit: Lower limit of estimation of vsini
-save: Set 'save' to a filename with an extension (e.g. png, eps)
Overrides 'plot' to False
"""
self.pts = kwargs.get('N', 15)
self.pace = kwargs.get('pace', np.array([2.0, 2.0]))
self.a_guess = kwargs.get('a_guess', np.array([-0.100, 0.100]))
self.v_guess = kwargs.get('v_guess', np.array([0.5, 25.0]))
self.min_i = kwargs.get('min_i', 3)
self.max_i = kwargs.get('max_i', 21)
self.limits = kwargs.get('limits', np.array([0.01, 0.001]))
self.plot = kwargs.get('plot', True)
self.v_low_limit = kwargs.get('v_low_limit', 0.5)
self.save = kwargs.get('save', None)
if 'save' in kwargs:
self.plot = False
self.silent = False
self.best_a = np.mean(self.a_guess)
self.best_v = np.mean(self.v_guess)
self.it = 1
self.finish = False
self.badfit_status = False
MOOG = Driver(synth_interval=self.spec,\
abunds=np.array([[self.Z, self.best_a],]),\
obs_wl=self.data[:, 0], obs_flux=self.data[:, 1],\
gauss=self.gauss, macro_v=self.v_m,\
star_name=self.name, plot=self.plot,\
savefig=self.save,\
y_shift_add=self.yadd,\
y_shift_mult=self.ymult,\
wl_shift=self.xshift,\
line_number=self.line_number)
self.MOOG = MOOG
self.it2 = [0, 0]
while ~self.finish and self.it < self.max_i and self.v_guess[1] < 100.:
self.MOOG.it = self.it
self.best_v_antes = self.best_v
self.best_a_antes = self.best_a
# Evaluating vsini
self.v_grid = np.linspace(self.v_guess[0], self.v_guess[1], self.pts)
self.S = []
self.S = self.perf_new(self.v_grid, self.best_a, mode='vsini')
self.S_v = self.S
tck = UnivariateSpline(self.v_grid, self.S, k=4, s=0.0)#, s = 0.05)
yfit = tck.__call__(self.v_grid)
self.yfit_v = yfit
self.intern_u = [False, False]
try:
z = tck.derivative().roots()
tck2 = tck.derivative(n=2)
z2 = tck2.__call__(z)
i_s = np.where(z2 > 0.)[0]
if i_s.size == 1:
self.best_v = z[i_s[0]]
self.intern_u[0] = True
self.it2[0] += 1
best_l = np.searchsorted(self.v_grid, self.best_v)
best_u = best_l + 1
try:
dif_l = self.best_v - self.v_grid[best_l]
dif_u = self.v_grid[best_u] - self.best_v
if dif_l <= dif_u:
self.best_v_ind = best_l
else:
self.best_v_ind = best_u
except IndexError:
self.best_v_ind = best_l
else:
self.best_v_ind = np.where(self.S == min(self.S))[0][0]
self.best_v = self.v_grid[self.best_v_ind]
del z, tck2, z2
except ValueError:
self.best_v_ind = np.where(self.S == min(self.S))[0][0]
self.best_v = self.v_grid[self.best_v_ind]
del tck, yfit
# Evaluating abundance
self.a_grid = np.linspace(self.a_guess[0], self.a_guess[1], self.pts)
self.a_grid = self.a_grid[np.argsort(self.a_grid)]
self.S = []
self.S = self.perf_new(self.best_v, self.a_grid, mode='abundance')
self.S_a = self.S
tck = UnivariateSpline(self.a_grid, self.S, k=4, s=0.1)
yfit = tck.__call__(self.a_grid)
z = tck.derivative()
self.yfit_a = yfit
try:
z = tck.derivative().roots()
tck2 = tck.derivative(n=2)
z2 = tck2.__call__(z)
i_s = np.where(z2 > 0.)[0]
if i_s.size == 1:
self.best_a = z[i_s[0]]
self.intern_u[1] = True
self.it2[1] += 1
best_l = np.searchsorted(self.a_grid, self.best_a)
best_u = best_l + 1
try:
dif_l = self.best_a - self.a_grid[best_l]
dif_u = self.a_grid[best_u] - self.best_a
if dif_l <= dif_u:
self.best_a_ind = best_l
else:
self.best_a_ind = best_u
except IndexError:
self.best_a_ind = best_l
else:
self.best_a_ind = np.where(self.S == min(self.S))[0][0]
self.best_a = self.a_grid[self.best_a_ind]
del z, tck2, z2
except ValueError:
self.best_a_ind = np.where(self.S == min(self.S))[0][0]
self.best_a = self.a_grid[self.best_a_ind]
del tck, yfit
self.go_v = True
self.go_a = True
# Checking if the best values are too near the edges of the guess
if self.best_v_ind == 0 or self.best_v_ind == (self.pts-1) or \
self.best_v_ind == 1 or self.best_v_ind == (self.pts-2):
self.go_v = False
elif self.best_a_ind == 0 or self.best_a_ind == (self.pts-1) or \
self.best_a_ind == 1 or self.best_a_ind == (self.pts-2):
self.go_a = False
# Calculating changes
self.v_change = np.abs(self.best_v-np.mean(self.v_guess))
self.a_change = np.abs(self.best_a-np.mean(self.a_guess))
if ~self.silent:
if (self.it > self.min_i) and self.go_v and self.go_a\
and (min(self.S) <= self.spec_sigma)\
and(np.abs(self.best_a - self.best_a_antes) <= 0.01)\
and (np.abs(self.best_v - self.best_v_antes) <= 0.01):
self.finish = True
break
elif (self.it > self.min_i) and self.go_v and self.go_a and min(self.S) < 1e-4:
self.finish = True
break
elif self.it > self.min_i and self.intern_u[0]\
and self.intern_u[1] and self.go_v and \
self.go_a and self.it2[0] >= 2 and self.it2[1] >= 2:
self.finish = True
break
else:
if self.it > self.min_i and self.intern_u[0]\
and self.intern_u[1]:
self.finish = True
break
# Setting the new guess. If one of the best values are too near the
# edges of the previous guess, it will not narrow its new guess range.
self.v_width = self.v_guess[1]-self.v_guess[0]
self.a_width = self.a_guess[1]-self.a_guess[0]
if self.go_v:
self.v_guess = np.array([self.best_v-\
old_div(self.v_width, self.pace[0]), self.best_v+\
old_div(self.v_width, self.pace[0])])
else:
self.v_guess = np.array([self.best_v-old_div(self.v_width, 2),\
self.best_v+old_div(self.v_width, 2)])
if self.go_a:
self.a_guess = np.array([self.best_a-\
old_div(self.a_width, self.pace[1]), self.best_a+\
old_div(self.a_width, self.pace[1])])
if np.abs(self.a_guess[1] - self.a_guess[0]) < 0.05:
self.a_guess = np.array([self.best_a - 0.025,\
self.best_a + 0.025])
# Checking if the v_guess contains vsini lower than v_low_limit.
# If True, it will add a value to the array so that the lower limit
# is equal to the v_low_limit
if self.v_guess[0] < self.v_low_limit and ~self.silent:
self.v_guess[0] += self.v_low_limit-self.v_guess[0]
if self.a_guess[0] < -3.0 and ~self.silent:
self.a_guess[0] = -3.0#+ (-3.0 - self.a_guess[0])
self.it += 1
# Finalizing the routine
self.S = self.perf(np.array([self.best_v, self.best_a]))
# Trigger bad fit warning
if self.check > self.badfit_tol:
self.badfit_status = True
del MOOG
return self
#******************************************************************************
#******************************************************************************
class Driver:
"""
The MOOG driver object.
Parameters
----------
synth_interval : sequence
The synthesis wavelength interval lower and upper limits in angstrons.
Example: (6000, 6100).
abunds : ``numpy.array``
The atomic number (first column) and the abundance (second column) of
the elements to be synthetisized.
Example: numpy.array([[26, -0.05], [32, 0.01]])
step: float, optional
The wavelength step size of the synthesis. Default is 0.1.
opac: float, optional
Wavelength point to consider opacity contributions from neighboring
transitions. Default is 2.0.
wl_shift: float, optional
Wavelength shift to be applied to the observed spectrum. Default is 0.
v_shift: float, optional
Doppler velocity shift to be applied to the observed spectrum. Default
is 0.
y_shift_add: float, optional
Additive shift to be applied to the observed spectrum. Default is 0.
y_shift_mult: float, optional
Multiplicative factor to be applied to the observed spectrum. Default
is 1.0 (no modification).
gauss: float, optional
Value of the 1 sigma dispersion of the Gaussian smoothing to be applied
to the synthetic spectrum. Default is 0.
lorentz: float, optional
Default is 0.
eps: float, optional
Limb darkening coefficient. Default is 0.6.
macro_v: float, optional
Macroturbulence velocity of the star. Default is 0.
vsini: float, optional
The projected rotational velocity of the star. Default is 0.
linelist_in: str, optional
Name of the line list input file. Default is 'lines.dat'.
observed_in: str, optional
Name of the input file containing the observed spectrum. Default is
'spectrum.dat'.
atmosphere: int, optional
Default is 1.
molecules: int, optional
Default is 1.
trudamp: int, optional
Default is 1.
lines: int, optional
Default is 1.
flux: int, optional
Default is 0.
damping: int, optional
Default is 0.
star_name: str, optional
Self-explanatory. Default is 'Unnamed star'.
"""
def __init__(self, synth_interval, abunds, obs_wl, obs_flux, step=0.01, opac=2.0,
wl_shift=0.0, v_shift=0.0, y_shift_add=0.0, y_shift_mult=1.0,
gauss=0.0, lorentz=0.0, eps=0.6, macro_v=0.0, vsini=0.0,
observed_in='spectrum.dat',
atmosphere=1, molecules=1, trudamp=1, lines=1, flux=0,
damping=0, star_name='Unnamed star', plot=True, savefig=False,
line_number=0):
self.name = star_name
self.plot_switch = plot
self.savefig = savefig
# Output files
self.standard_out = './output/%s_l.out' % self.name
self.summary_out = './output/%s_li.out' % self.name
self.smoothed_out = './output/%s_s.out' % self.name
self.smoothed_out_new = './output/%s_sn.out' % self.name
# Input files
self.model_in = './atm_models/%s_v.atm' % self.name
self.lines_in = './MOOG_linelist/lines.%s_v.txt' % self.name
self.observed_in = './Spectra/%s_%d.dat' % (self.name, line_number)
# Output files
self.standard_out_moog = './output/%s_l.out' % self.name
self.summary_out_moog = './output/%s_li.out' % self.name
self.smoothed_out_moog = './output/%s_s.out' % self.name
self.smoothed_out_new_moog = './output/%s_sn.out' % self.name
# Input files
self.model_in_moog = './atm_models/%s_v.atm' % self.name
self.lines_in_moog = './MOOG_linelist/lines.%s_v.txt' % self.name
self.observed_in_moog = './Spectra/%s_%d.dat' % (self.name, line_number)
self.lines_ab = np.loadtxt(self.lines_in, usecols=(0,), skiprows=1)
# Synthesis parameters
self.syn_start = synth_interval[0]
self.syn_end = synth_interval[1]
self.wl_start = synth_interval[0]
self.wl_end = synth_interval[1]
self.step = step
self.opac = opac
self.wl_shift = wl_shift
if int(v_shift) != 0:
raise NotImplementedError('Doppler shift in the observed spectrum'
'is not implemented yet.')
self.v_shift = v_shift
self.y_shift_add = y_shift_add
self.y_shift_mult = y_shift_mult
self.gauss = gauss
self.lorentz = lorentz
self.dark = eps
self.macro_v = macro_v
self.vsini = vsini
self.N, self.n_cols = np.shape(abunds)
assert(self.n_cols == 2), 'Number of columns in `abunds` must be 2.'
if self.N == 1:
self.Z = abunds[0][0]
self.abunds = abunds[0][1]
elif self.N > 1:
self.Z = abunds[:, 0]
self.abunds = abunds[:, 1]
# MOOG synth options
self.atm = atmosphere
self.mol = molecules
self.tru = trudamp
self.lin = lines
self.flu = flux
self.dam = damping
# Reading the observed spectrum
if isinstance(observed_in, str):
self.obs_wl = obs_wl + wl_shift
self.obs_flux = obs_flux * y_shift_mult + y_shift_add
elif observed_in is None:
self.observed_in = observed_in
else:
raise TypeError('observed_in must be ``str`` or ``None``.')
self.data = np.array([self.obs_wl, self.obs_flux]).T
self.it = 0
self.c = 2.998E5 # km/s
self.model_ab = {}
self.model_vsini = {}
self.model = []
self.index = 0
self.start_index = 0
self.end_index = 0
def create_batch(self):
"""
Writes the MOOG driver file batch.par
"""
with open('./MOOGFEB2017/%s_synth.par' % self.name, 'w') as f:
f.truncate()
f.write("synth\n")
f.write("standard_out '%s'\n" % self.standard_out_moog)
f.write("summary_out '%s'\n" % self.summary_out_moog)
f.write("smoothed_out '%s'\n" % self.smoothed_out_moog)
f.write("model_in '%s'\n" % self.model_in_moog)
f.write("lines_in '%s'\n" % self.lines_in_moog)
f.write("observed_in '%s'\n" % self.observed_in_moog)
f.write("atmosphere %i\n" % self.atm)
f.write("molecules %i\n" % self.mol)
f.write("trudamp %i\n" % self.tru)
f.write("lines %i\n" % self.lin)
f.write("flux/int %i\n" % self.flu)
f.write("damping %i\n" % self.dam)
f.write("freeform 0\n")
f.write("plot 3\n")
f.write("abundances %i 1\n" % self.N)
if self.N > 1:
for k in range(self.N):
f.write(" %i %f\n" % (self.Z[k], self.abunds[k]))
else:
f.write(" %i %f\n" % (self.Z, self.abunds))
f.write("isotopes 0 1\n")
f.write("synlimits\n")
f.write(" %.2f %.2f %.2f %.1f\n" % (self.syn_start, self.syn_end,
self.step, self.opac))
f.write("obspectrum 5\n")
f.write("plotpars 1\n")
f.write(" %.2f %.2f 0.05 1.05\n" % (self.wl_start, self.wl_end))
f.write(" %.4f %.4f %.3f %.3f\n" % (self.v_shift, self.wl_shift,
self.y_shift_add,
self.y_shift_mult))
f.write(" gm %.3f 0.0 %.1f %.2f %.1f" % (self.gauss,
self.dark,
self.macro_v,
self.lorentz))
del f
def change_vsini(self, grid_v):
self.create_batch()
os.system('MOOGSILENT > temp.log 2>&1 << EOF\nMOOGFEB2017/%s_synth.par\n\nEOF' % self.name)
try:
model = np.loadtxt(self.smoothed_out, skiprows=2)
synth_wl = model[:, 0]
synth_flux = model[:, 1]
except:
model = []
synth_wl = np.arange(self.syn_start, self.syn_end, self.step)
synth_flux = np.zeros(synth_wl.size)
inonan = np.where(np.isfinite(synth_flux))[0]
if len(np.unique(synth_flux[inonan])) > 1:
synth_wl, synth_flux, self.obs_wl, self.obs_flux = \
self.smart_cut(synth_wl, synth_flux, self.obs_wl, self.obs_flux)
self.model_vsini = {}
for vsini in grid_v:
self.vsini = vsini
if self.vsini > 0.0:
conv_flux = pyasl.rotBroad(synth_wl, synth_flux, self.dark, self.vsini)
self.model_vsini[str(vsini)] = np.array([synth_wl, \
conv_flux/max(conv_flux)]).T
del conv_flux
else:
self.model_vsini[str(vsini)] = np.array([synth_wl,
np.nan*np.ones(synth_wl.size)]).T
del model, synth_wl, synth_flux
return self
def change_ab(self, a):
self.abunds = a
self.create_batch()
os.system('MOOGSILENT > temp.log 2>&1 << EOF\nMOOGFEB2017/%s_synth.par\n\nEOF' % self.name)
try:
model = np.loadtxt(self.smoothed_out, skiprows=2)
synth_wl = model[:, 0]
synth_flux = model[:, 1]
except:
model = []
synth_wl = np.arange(self.syn_start, self.syn_end, self.step)
synth_flux = np.zeros(synth_wl.size)
if self.vsini > 0.0:
inonan = np.where(np.isfinite(synth_flux))[0]
if len(np.unique(synth_flux[inonan])) > 1:
synth_wl, synth_flux, self.obs_wl, self.obs_flux = \
self.smart_cut(synth_wl, synth_flux, self.obs_wl, self.obs_flux)
conv_flux = pyasl.rotBroad(synth_wl, synth_flux, self.dark, self.vsini)
self.model_ab[str(a)] = np.array([synth_wl, old_div(conv_flux, max(conv_flux))]).T
del conv_flux
else:
self.model_ab[str(a)] = np.array([synth_wl, np.nan * np.ones(synth_wl.size)]).T
del synth_wl, synth_flux, model
return self
def run(self):
"""
Used to run MOOG silent.
"""
self.create_batch()
os.system('MOOGSILENT > temp.log 2>&1 << EOF\nMOOGFEB2017/%s_synth.par\n\nEOF' % self.name)
try:
self.model = np.loadtxt(self.smoothed_out, skiprows=2)
synth_wl = self.model[:, 0]
synth_flux = self.model[:, 1]
except:
self.model = []
synth_wl = np.arange(self.syn_start, self.syn_end, self.step)
synth_flux = np.zeros(synth_wl.size)
if self.vsini > 0.0:
inonan = np.where(np.isfinite(synth_flux))[0]
if len(np.unique(synth_flux[inonan])) > 1:
synth_wl, synth_flux, self.obs_wl, self.obs_flux = \
self.smart_cut(synth_wl, synth_flux, self.obs_wl, self.obs_flux)
conv_flux = pyasl.rotBroad(synth_wl, synth_flux, self.dark, self.vsini)
self.model = np.array([synth_wl, old_div(conv_flux, max(conv_flux))]).T
del conv_flux
del synth_wl, synth_flux
return self
def rot_prof(self, vz):
"""
This function creates a rotational profile based on Gray (2005).
Parameters
----------
vz : ``numpy.array``
The Doppler velocities from the spectral line center.
Returns
-------
profile : ``numpy.array``
The rotational profile.
"""
n = len(vz)
profile = np.zeros(n, float)
m = np.abs(vz) < self.vsini
profile[m] = old_div((2.*(1.-self.dark)*(1.-(old_div(vz[m], self.vsini)) ** 2.)
** 0.5 + 0.5 * np.pi * self.dark *
(1. - (old_div(vz[m], self.vsini)) ** 2.)), \
(np.pi * self.vsini * (1. - self.dark / 3.)))
del m
return profile
@staticmethod
def smart_cut(wl, flux, obs_wl, obs_flux):
"""
smart_cut() is used to prepare the synthetic spectrum for a convolution
with the rotational profile.
"""
ind0 = np.where(flux == min(flux))[0][0]
n = len(wl)
if ind0 < old_div((n - 1), 2):
if (ind0 + 1) % 2 == 0:
wl = wl[1:2 * ind0]
flux = flux[1:2 * ind0]
obs_flux = obs_flux[1:2 * ind0]
obs_wl = obs_wl[1:2 * ind0]
else:
wl = wl[0:2 * ind0 + 1]
flux = flux[0:2 * ind0 + 1]
obs_flux = obs_flux[0:2 * ind0 + 1]
obs_wl = obs_wl[0:2 * ind0 + 1]
elif ind0 > old_div((n - 1), 2):
if (ind0 + 1) % 2 == 0:
wl = wl[2*(ind0 - old_div((n - 1), 2)) + 1:-1]
flux = flux[2 * (ind0 - old_div((n - 1), 2)) + 1:-1]
obs_flux = obs_flux[2 * (ind0 - old_div((n - 1), 2)) + 1:-1]
obs_wl = obs_wl[2 * (ind0 - old_div((n - 1), 2)) + 1:-1]
else:
wl = wl[2 * (ind0 - old_div((n - 1), 2)):]
flux = flux[2 * (ind0 - old_div((n - 1), 2)):]
obs_flux = obs_flux[2 * (ind0 - old_div((n - 1), 2)):]
obs_wl = obs_wl[2 * (ind0 - old_div((n - 1), 2)):]
return wl, flux, obs_wl, obs_flux
#******************************************************************************
#******************************************************************************
#******************************************************************************
#******************************************************************************
class arr_manage:
"""
Used to perform a series of specific management routines to
numpy-arrays and data arrays and files.
"""
def __init__(self):
self.index = 0
self.start_index = 0
self.end_index = 0
def find_index(self, target, array):
"""
This routine finds the index of a value closest to the target in
a numpy-array.
"""
self.index = np.searchsorted(array, target, side='left')
return self.index
def x_set_limits(self, start, end, data2d):
"""
This routine returns a section of an array given the start and end
values. These values do not need to be the exact ones found in the
array.
"""
self.start_index = np.searchsorted(data2d[:, 0], start, side='left')
self.end_index = np.searchsorted(data2d[:, 0], end, side='left')
return data2d[self.start_index:self.end_index]
#******************************************************************************
#******************************************************************************
#******************************************************************************
#******************************************************************************
def calc_broadening(starname, Teff, met, logg, micro, ab_ni,\
err_T, err_logg, err_met, err_ni, snr, alias):
vmac, err_vmac = calc_vmac((Teff, err_T), (logg, err_logg))
#vmac, err_vmac = np.ones(len(vmac))*0.1, np.ones(len(vmac))*0.1
vsini, err_vsini, weight_vsini = calc_vsini(starname, Teff, met, logg, micro, vmac,\
ab_ni, err_met, err_ni, snr, alias)
if (vsini.size == 0) or np.all(vsini == 0.0) or np.all(err_vsini == 0.0):
i = np.where((vmac != 0.0) & (err_vmac != 0.0))[0]
vmac_final = np.median(vmac[i])
err_vmac_final = old_div(np.median(err_vmac[i]), np.sqrt(float(len(i))))
vsini_final = 0.0
err_vsini_final = 0.0
else:
i = np.where((vmac != 0.0) & (vsini != 0.0) & (err_vmac != 0.0) & (err_vsini != 0.0))[0]
#vmac_final = np.median(vmac[i])
#err_vmac_final = old_div(np.median(err_vmac[i]), np.sqrt(float(len(i))))
vm = np.median(unumpy.uarray(vmac[i], err_vmac[i]))
vmac_final = vm.n
err_vmac_final = vm.s
#vsini_final = np.average(vsini[i], weights=weight_vsini[i])
#err_vsini_final = np.sqrt(1./(1./(np.sum(err_vsini[i]**2.) + err_vmac_final**2.)))
v = np.median(unumpy.uarray(vsini[i], err_vsini[i])) + ufloat(0.0, err_vmac_final)
vsini_final = v.n
err_vsini_final = v.s
del i, vmac, err_vmac, vsini, err_vsini
if np.isnan(err_vsini_final):
err_vsini_final = 0.0
return vsini_final, err_vsini_final, vmac_final, err_vmac_final
#******************************************************************************
#******************************************************************************
#******************************************************************************
#******************************************************************************
def calc_vmac(Teff, logg):
"""
Computes vmac
"""
vmac_sun = np.array([3.0, 3.2, 3.1, 3.6, 2.9])
vmac = vmac_sun - 0.00707*Teff[0] + 9.2422*10**(-7.)*Teff[0]**2. + \
10.0 - 1.81*(logg[0] - 4.44) - 0.05
err_vmac = np.ones(5)*np.sqrt(0.1**2. + (9.2422*10**(-7.)*2*Teff[0]-0.00707)**2.*Teff[1]**2. +\
1.81**2.*logg[1]**2. + (logg[0] - 4.44)**2.*0.26**2. + 0.03**2.)
if np.mean(vmac) < 0.5:
#From Brewer et al. 2016:
teff = ufloat(Teff[0], Teff[1])
log_g = ufloat(logg[0], logg[1])
if log_g.n >= 4.0:
vmac = 2.202*umath.exp(0.0019*(teff - 5777.)) + 1.30
elif (4.0 > log_g.n >= 3.0):
vmac = 1.166*umath.exp(0.0028*(teff - 5777.)) + 3.30
else:
vmac = 4.0 + ufloat(0.0, 0.25)
logging.info(vmac.n + np.zeros(5))
logging.info(vmac.s + np.zeros(5))
return vmac.n + np.zeros(5), vmac.s + np.zeros(5)#, err_vmac
# E.1 from Melendez et al. 2012:
#vmac=np.zeros(5)+(13.499-0.00707*Teff[0]+9.2422*10**(-7)*Teff[0]**2.)
#err_vmac=np.zeros(5)+np.sqrt((2.*9.2422*10**(-7)*Teff[0]-0.00707)**2.*Teff[1]**2.)
# E.2 from Melendez et al. 2012
#vmac=np.zeros(5)+(3.50+(Teff[0]-5777.)/650.)
#err_vmac=np.zeros(5)+np.sqrt((1./650.)**2.*Teff[1]**2.)
#From Brewer et al. 2016:
#teff = ufloat(Teff[0], Teff[1])
#log_g = ufloat(logg[0], logg[1])
#if log_g.n >= 4.0:
# vmac = 2.202*umath.exp(0.0019*(teff - 5777.)) + 1.30
#elif (4.0 > log_g.n >= 3.0):
# vmac = 1.166*umath.exp(0.0028*(teff - 5777.)) + 3.30
#else:
# vmac = 4.0 + ufloat(0.0, 0.25)
#return vmac.n + np.zeros(5), vmac.s + np.zeros(5)#, err_vmac
return vmac, err_vmac