-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexample.py
2957 lines (2515 loc) · 161 KB
/
example.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
#
# This file is part of iSpec.
# Copyright Sergi Blanco-Cuaresma - http://www.blancocuaresma.com/s/
#
# iSpec is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# iSpec is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with iSpec. If not, see <http://www.gnu.org/licenses/>.
#
import os
import sys
import numpy as np
import logging
import multiprocessing
from multiprocessing import Pool
################################################################################
#--- iSpec directory -------------------------------------------------------------
ispec_dir = os.path.dirname(os.path.realpath(__file__)) + "/"
#ispec_dir = '/home/virtual/iSpec/'
sys.path.insert(0, os.path.abspath(ispec_dir))
import ispec
#--- Change LOG level ----------------------------------------------------------
#LOG_LEVEL = "warning"
LOG_LEVEL = "info"
logger = logging.getLogger() # root logger, common for all
logger.setLevel(logging.getLevelName(LOG_LEVEL.upper()))
################################################################################
def read_write_spectrum():
#--- Reading spectra -----------------------------------------------------------
logging.info("Reading spectra")
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
##--- Save spectrum ------------------------------------------------------------
logging.info("Saving spectrum...")
ispec.write_spectrum(star_spectrum, "example_sun.fits")
def convert_air_to_vacuum():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Converting wavelengths from air to vacuum and viceversa -------------------
star_spectrum_vacuum = ispec.air_to_vacuum(star_spectrum)
star_spectrum_air = ispec.vacuum_to_air(star_spectrum_vacuum)
def plot():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
mu_cas_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
#--- Plotting (requires graphical interface) -----------------------------------
logging.info("Plotting...")
ispec.plot_spectra([star_spectrum, mu_cas_spectrum])
ispec.show_histogram(star_spectrum['flux'])
def cut_spectrum_from_range():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Cut -----------------------------------------------------------------------
logging.info("Cutting...")
# - Keep points between two given wavelengths
wfilter = ispec.create_wavelength_filter(star_spectrum, wave_base=480.0, wave_top=680.0)
cutted_star_spectrum = star_spectrum[wfilter]
def cut_spectrum_from_segments():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Cut -----------------------------------------------------------------------
logging.info("Cutting...")
# Keep only points inside a list of segments
segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
wfilter = ispec.create_wavelength_filter(star_spectrum, regions=segments)
cutted_star_spectrum = star_spectrum[wfilter]
def determine_radial_velocity_with_mask():
mu_cas_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
#--- Radial Velocity determination with linelist mask --------------------------
logging.info("Radial velocity determination with linelist mask...")
# - Read atomic data
mask_file = ispec_dir + "input/linelists/CCF/Narval.Sun.370_1048nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/Atlas.Arcturus.372_926nm/mask.lst""
#mask_file = ispec_dir + "input/linelists/CCF/Atlas.Sun.372_926nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/HARPS_SOPHIE.A0.350_1095nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/HARPS_SOPHIE.F0.360_698nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/HARPS_SOPHIE.G2.375_679nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/HARPS_SOPHIE.K0.378_679nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/HARPS_SOPHIE.K5.378_680nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/HARPS_SOPHIE.M5.400_687nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/Synthetic.Sun.350_1100nm/mask.lst"
#mask_file = ispec_dir + "input/linelists/CCF/VALD.Sun.300_1100nm/mask.lst"
ccf_mask = ispec.read_cross_correlation_mask(mask_file)
models, ccf = ispec.cross_correlate_with_mask(mu_cas_spectrum, ccf_mask, \
lower_velocity_limit=-200, upper_velocity_limit=200, \
velocity_step=1.0, mask_depth=0.01, \
fourier=False)
# Number of models represent the number of components
components = len(models)
# First component:
rv = np.round(models[0].mu(), 2) # km/s
rv_err = np.round(models[0].emu(), 2) # km/s
def determine_radial_velocity_with_template():
mu_cas_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
#--- Radial Velocity determination with template -------------------------------
logging.info("Radial velocity determination with template...")
# - Read synthetic template
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")
models, ccf = ispec.cross_correlate_with_template(mu_cas_spectrum, template, \
lower_velocity_limit=-200, upper_velocity_limit=200, \
velocity_step=1.0, fourier=False)
# Number of models represent the number of components
components = len(models)
# First component:
rv = np.round(models[0].mu(), 2) # km/s
rv_err = np.round(models[0].emu(), 2) # km/s
def correct_radial_velocity():
mu_cas_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
#--- Radial Velocity correction ------------------------------------------------
logging.info("Radial velocity correction...")
rv = -96.40 # km/s
mu_cas_spectrum = ispec.correct_velocity(mu_cas_spectrum, rv)
def determine_tellurics_shift_with_mask():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Telluric velocity shift determination from spectrum --------------------------
logging.info("Telluric velocity shift determination...")
# - Telluric
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.0)
models, ccf = ispec.cross_correlate_with_mask(star_spectrum, telluric_linelist, \
lower_velocity_limit=-100, upper_velocity_limit=100, \
velocity_step=0.5, mask_depth=0.01, \
fourier = False,
only_one_peak = True)
bv = np.round(models[0].mu(), 2) # km/s
bv_err = np.round(models[0].emu(), 2) # km/s
def determine_tellurics_shift_with_template():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Telluric velocity shift determination from spectrum --------------------------
logging.info("Telluric velocity shift determination...")
# - Read synthetic template
template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Tellurics.350_1100nm/template.txt.gz")
models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
lower_velocity_limit=-100, upper_velocity_limit=100, \
velocity_step=0.5, fourier=False, \
only_one_peak = True)
bv = np.round(models[0].mu(), 2) # km/s
bv_err = np.round(models[0].emu(), 2) # km/s
def degrade_resolution():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Resolution degradation ----------------------------------------------------
logging.info("Resolution degradation...")
from_resolution = 80000
to_resolution = 47000
convolved_star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution, \
from_resolution=from_resolution)
def smooth_spectrum():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Smoothing spectrum (resolution will be affected) --------------------------
logging.info("Smoothing spectrum...")
resolution = 80000
smoothed_star_spectrum = ispec.convolve_spectrum(star_spectrum, resolution)
def resample_spectrum():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Resampling --------------------------------------------------------------
logging.info("Resampling...")
wavelengths = np.arange(480.0, 680.0, 0.001)
resampled_star_spectrum = ispec.resample_spectrum(star_spectrum, wavelengths, method="linear", zero_edges=True)
#resampled_star_spectrum = ispec.resample_spectrum(star_spectrum, wavelengths, method="bessel", zero_edges=True)
def coadd_spectra():
# WARNING: This example co-adds spectra from different stars, in a real life situation
# the logical thing is to co-add spectra from the same star/instrument
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
mu_cas_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
#--- Resampling and combining --------------------------------------------------
logging.info("Resampling and comibining...")
wavelengths = np.arange(480.0, 680.0, 0.001)
resampled_star_spectrum = ispec.resample_spectrum(star_spectrum, wavelengths, zero_edges=True)
resampled_mu_cas_spectrum = ispec.resample_spectrum(mu_cas_spectrum, wavelengths, zero_edges=True)
# Coadd previously resampled spectra
coadded_spectrum = ispec.create_spectrum_structure(resampled_star_spectrum['waveobs'])
coadded_spectrum['flux'] = resampled_star_spectrum['flux'] + resampled_mu_cas_spectrum['flux']
coadded_spectrum['err'] = np.sqrt(np.power(resampled_star_spectrum['err'],2) + \
np.power(resampled_mu_cas_spectrum['err'],2))
def merge_spectra():
# WARNING: This example merges spectra from different stars, in a real life situation
# the logical thing is to merge spectra from the same star/instrument
# and different wavelength ranges
#--- Mergin spectra ------------------------------------------------------------
logging.info("Mergin spectra...")
left_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
right_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
merged_spectrum = np.hstack((left_spectrum, right_spectrum))
def normalize_spectrum_using_continuum_regions():
"""
Consider only continuum regions for the fit, strategy 'median+max'
"""
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
continuum_regions = ispec.read_continuum_regions(ispec_dir + "/input/regions/fe_lines_continuum.txt")
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
continuum_regions=continuum_regions, nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Continuum normalization ---------------------------------------------------
logging.info("Continuum normalization...")
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
def normalize_spectrum_in_segments():
"""
Fit continuum in each segment independently, strategy 'median+max'
"""
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = 1
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
independent_regions=segments, nknots=nknots, degree=degree,\
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Continuum normalization ---------------------------------------------------
logging.info("Continuum normalization...")
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
def normalize_whole_spectrum_with_template():
"""
Use a template to normalize the whole spectrum
"""
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
synth_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Template"
nknots = None # Automatic: 1 spline every 5 nm (in this case, used to apply a gaussian filter)
from_resolution = 80000
median_wave_range=5.0
#strong_lines = ispec.read_line_regions(ispec_dir + "/input/regions/strong_lines/absorption_lines.txt")
strong_lines = ispec.read_line_regions(ispec_dir + "/input/regions/relevant/relevant_line_masks.txt")
#strong_lines = None
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
ignore=strong_lines, \
nknots=nknots, \
median_wave_range=median_wave_range, \
model=model, \
template=synth_spectrum)
#--- Continuum normalization ---------------------------------------------------
logging.info("Continuum normalization...")
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
def normalize_whole_spectrum():
"""
Use the whole spectrum, strategy 'median+max'
"""
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Continuum normalization ---------------------------------------------------
logging.info("Continuum normalization...")
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
def normalize_whole_spectrum_ignoring_prefixed_strong_lines():
"""
Use the whole spectrum but ignoring some strong lines, strategy 'median+max'
"""
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
strong_lines = ispec.read_line_regions(ispec_dir + "/input/regions/strong_lines/absorption_lines.txt")
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
ignore=strong_lines, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Continuum normalization ---------------------------------------------------
logging.info("Continuum normalization...")
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
def filter_cosmic_rays():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Filtering cosmic rays -----------------------------------------------------
# Spectrum should be already normalized
cosmics = ispec.create_filter_cosmic_rays(star_spectrum, star_continuum_model, \
resampling_wave_step=0.001, window_size=15, \
variation_limit=0.01)
clean_star_spectrum = star_spectrum[~cosmics]
def find_continuum_regions():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Find continuum regions ----------------------------------------------------
logging.info("Finding continuum regions...")
resolution = 80000
sigma = 0.001
max_continuum_diff = 1.0
fixed_wave_step = 0.05
star_continuum_regions = ispec.find_continuum(star_spectrum, resolution, \
max_std_continuum = sigma, \
continuum_model = star_continuum_model, \
max_continuum_diff=max_continuum_diff, \
fixed_wave_step=fixed_wave_step)
ispec.write_continuum_regions(star_continuum_regions, "example_star_fe_lines_continuum.txt")
def find_continuum_regions_in_segments():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Find continuum regions in segments ----------------------------------------
logging.info("Finding continuum regions...")
resolution = 80000
sigma = 0.001
max_continuum_diff = 1.0
fixed_wave_step = 0.05
# Limit the search to given segments
segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
limited_star_continuum_regions = ispec.find_continuum(star_spectrum, resolution, \
segments=segments, max_std_continuum = sigma, \
continuum_model = star_continuum_model, \
max_continuum_diff=max_continuum_diff, \
fixed_wave_step=fixed_wave_step)
ispec.write_continuum_regions(limited_star_continuum_regions, \
"example_limited_star_continuum_region.txt")
def find_linemasks(code = "spectrum"):
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Radial Velocity determination with template -------------------------------
logging.info("Radial velocity determination with template...")
# - Read synthetic template
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")
models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
lower_velocity_limit=-200, upper_velocity_limit=200, \
velocity_step=1.0, fourier=False)
# Number of models represent the number of components
components = len(models)
# First component:
rv = np.round(models[0].mu(), 2) # km/s
rv_err = np.round(models[0].emu(), 2) # km/s
#--- Radial Velocity correction ------------------------------------------------
logging.info("Radial velocity correction... %.2f +/- %.2f" % (rv, rv_err))
star_spectrum = ispec.correct_velocity(star_spectrum, rv)
#--- Telluric velocity shift determination from spectrum --------------------------
logging.info("Telluric velocity shift determination...")
# - Telluric
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.0)
models, ccf = ispec.cross_correlate_with_mask(star_spectrum, telluric_linelist, \
lower_velocity_limit=-100, upper_velocity_limit=100, \
velocity_step=0.5, mask_depth=0.01, \
fourier = False,
only_one_peak = True)
vel_telluric = np.round(models[0].mu(), 2) # km/s
vel_telluric_err = np.round(models[0].emu(), 2) # km/s
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Find linemasks ------------------------------------------------------------
logging.info("Finding line masks...")
#atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
#atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.1100_2400nm/atomic_lines.tsv"
atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_hfs_iso.420_920nm/atomic_lines.tsv"
#atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_nohfs_noiso.420_920nm/atomic_lines.tsv"
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
# Read
atomic_linelist = ispec.read_atomic_linelist(atomic_linelist_file, wave_base=np.min(star_spectrum['waveobs']), wave_top=np.max(star_spectrum['waveobs']))
atomic_linelist = atomic_linelist[atomic_linelist['theoretical_depth'] >= 0.01] # Select lines that have some minimal contribution in the sun
#telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.01)
#vel_telluric = 17.79 # km/s
#telluric_linelist = None
#vel_telluric = None
resolution = 80000
smoothed_star_spectrum = ispec.convolve_spectrum(star_spectrum, resolution)
min_depth = 0.05
max_depth = 1.00
star_linemasks = ispec.find_linemasks(star_spectrum, star_continuum_model, \
atomic_linelist=atomic_linelist, \
max_atomic_wave_diff = 0.005, \
telluric_linelist=telluric_linelist, \
vel_telluric=vel_telluric, \
minimum_depth=min_depth, maximum_depth=max_depth, \
smoothed_spectrum=smoothed_star_spectrum, \
check_derivatives=False, \
discard_gaussian=False, discard_voigt=True, \
closest_match=False)
# Exclude lines that have not been successfully cross matched with the atomic data
# because we cannot calculate the chemical abundance (it will crash the corresponding routines)
rejected_by_atomic_line_not_found = (star_linemasks['wave_nm'] == 0)
star_linemasks = star_linemasks[~rejected_by_atomic_line_not_found]
# Exclude lines with EW equal to zero
rejected_by_zero_ew = (star_linemasks['ew'] == 0)
star_linemasks = star_linemasks[~rejected_by_zero_ew]
# Select only iron lines
iron = star_linemasks['element'] == "Fe 1"
iron = np.logical_or(iron, star_linemasks['element'] == "Fe 2")
iron_star_linemasks = star_linemasks[iron]
# Write regions with only masks limits and note:
ispec.write_line_regions(star_linemasks, "example_star_linemasks.txt")
# Write iron regions with only masks limits and note:
ispec.write_line_regions(iron_star_linemasks, "example_star_fe_linemasks.txt")
# Write regions with masks limits, cross-matched atomic data and fit data
ispec.write_line_regions(star_linemasks, "example_star_fitted_linemasks.txt", extended=True)
recover_star_linemasks = ispec.read_line_regions("example_star_fitted_linemasks.txt")
# Write regions with masks limits and cross-matched atomic data (fit data fields are zeroed)
zeroed_star_linemasks = ispec.reset_fitted_data_fields(star_linemasks)
ispec.write_line_regions(zeroed_star_linemasks, "example_star_zeroed_fitted_linemasks.txt", extended=True)
# Write only atomic data for the selected regions:
ispec.write_atomic_linelist(star_linemasks, "example_star_atomic_linelist.txt")
def calculate_barycentric_velocity():
mu_cas_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
#--- Barycentric velocity correction from observation date/coordinates ---------
logging.info("Calculating barycentric velocity correction...")
day = 15
month = 2
year = 2012
hours = 0
minutes = 0
seconds = 0
ra_hours = 19
ra_minutes = 50
ra_seconds = 46.99
dec_degrees = 8
dec_minutes = 52
dec_seconds = 5.96
# Project velocity toward star
barycentric_vel = ispec.calculate_barycentric_velocity_correction((year, month, day, \
hours, minutes, seconds), (ra_hours, ra_minutes, \
ra_seconds, dec_degrees, dec_minutes, dec_seconds))
#--- Correcting barycentric velocity -------------------------------------------
corrected_spectrum = ispec.correct_velocity(mu_cas_spectrum, barycentric_vel)
def estimate_snr_from_flux():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
## WARNING: To compare SNR estimation between different spectra, they should
## be homogeneously sampled (consider a uniform re-sampling)
#--- Estimate SNR from flux ----------------------------------------------------
logging.info("Estimating SNR from fluxes...")
num_points = 10
estimated_snr = ispec.estimate_snr(star_spectrum['flux'], num_points=num_points)
def estimate_snr_from_err():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Estimate SNR from errors --------------------------------------------------
logging.info("Estimating SNR from errors...")
efilter = star_spectrum['err'] > 0
filtered_star_spectrum = star_spectrum[efilter]
if len(filtered_star_spectrum) > 1:
estimated_snr = np.median(filtered_star_spectrum['flux']/ filtered_star_spectrum['err'])
else:
# All the errors are set to zero and we cannot calculate SNR using them
estimated_snr = 0
def estimate_errors_from_snr():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Calculate errors based on SNR ---------------------------------------------
snr = 100
star_spectrum['err'] = star_spectrum['flux']/ snr
def clean_spectrum():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Clean fluxes and errors ---------------------------------------------------
logging.info("Cleaning fluxes and errors...")
flux_base = 0.0
flux_top = 1.0
err_base = 0.0
err_top = 1.0
ffilter = (star_spectrum['flux'] > flux_base) & (star_spectrum['flux'] <= flux_top)
efilter = (star_spectrum['err'] > err_base) & (star_spectrum['err'] <= err_top)
wfilter = np.logical_and(ffilter, efilter)
clean_star_spectrum = star_spectrum[wfilter]
def clean_telluric_regions():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Telluric velocity shift determination from spectrum --------------------------
logging.info("Telluric velocity shift determination...")
# - Telluric
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.0)
models, ccf = ispec.cross_correlate_with_mask(star_spectrum, telluric_linelist, \
lower_velocity_limit=-100, upper_velocity_limit=100, \
velocity_step=0.5, mask_depth=0.01, \
fourier = False,
only_one_peak = True)
bv = np.round(models[0].mu(), 2) # km/s
bv_err = np.round(models[0].emu(), 2) # km/s
#--- Clean regions that may be affected by tellurics ---------------------------
logging.info("Cleaning tellurics...")
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.0)
# - Filter regions that may be affected by telluric lines
#bv = 0.0
min_vel = -30.0
max_vel = +30.0
# Only the 25% of the deepest ones:
dfilter = telluric_linelist['depth'] > np.percentile(telluric_linelist['depth'], 75)
tfilter = ispec.create_filter_for_regions_affected_by_tellurics(star_spectrum['waveobs'], \
telluric_linelist[dfilter], min_velocity=-bv+min_vel, \
max_velocity=-bv+max_vel)
clean_star_spectrum = star_spectrum[~tfilter]
def adjust_line_masks():
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Adjust line masks ---------------------------------------------------------
resolution = 80000
smoothed_star_spectrum = ispec.convolve_spectrum(star_spectrum, resolution)
line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/fe_lines.txt")
linemasks = ispec.adjust_linemasks(smoothed_star_spectrum, line_regions, max_margin=0.5)
def create_segments_around_linemasks():
#---Create segments around linemasks -------------------------------------------
line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/fe_lines.txt")
segments = ispec.create_segments_around_lines(line_regions, margin=0.25)
def fit_lines_determine_ew_and_crossmatch_with_atomic_data(use_ares=False):
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Radial Velocity determination with template -------------------------------
logging.info("Radial velocity determination with template...")
# - Read synthetic template
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")
models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
lower_velocity_limit=-200, upper_velocity_limit=200, \
velocity_step=1.0, fourier=False)
# Number of models represent the number of components
components = len(models)
# First component:
rv = np.round(models[0].mu(), 2) # km/s
rv_err = np.round(models[0].emu(), 2) # km/s
#--- Radial Velocity correction ------------------------------------------------
logging.info("Radial velocity correction... %.2f +/- %.2f" % (rv, rv_err))
star_spectrum = ispec.correct_velocity(star_spectrum, rv)
#--- Telluric velocity shift determination from spectrum --------------------------
logging.info("Telluric velocity shift determination...")
# - Telluric
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.0)
models, ccf = ispec.cross_correlate_with_mask(star_spectrum, telluric_linelist, \
lower_velocity_limit=-100, upper_velocity_limit=100, \
velocity_step=0.5, mask_depth=0.01, \
fourier = False,
only_one_peak = True)
vel_telluric = np.round(models[0].mu(), 2) # km/s
vel_telluric_err = np.round(models[0].emu(), 2) # km/s
#--- Resolution degradation ----------------------------------------------------
# NOTE: The line selection was built based on a solar spectrum with R ~ 47,000 and GES/VALD atomic linelist.
from_resolution = 80000
to_resolution = 47000
star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution, from_resolution)
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = 80000
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Normalize -------------------------------------------------------------
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
#--- Fit lines -----------------------------------------------------------------
logging.info("Fitting lines...")
#atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
#atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.1100_2400nm/atomic_lines.tsv"
atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_hfs_iso.420_920nm/atomic_lines.tsv"
#atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_nohfs_noiso.420_920nm/atomic_lines.tsv"
# Read
atomic_linelist = ispec.read_atomic_linelist(atomic_linelist_file, wave_base=np.min(star_spectrum['waveobs']), wave_top=np.max(star_spectrum['waveobs']))
atomic_linelist = atomic_linelist[atomic_linelist['theoretical_depth'] >= 0.01] # Select lines that have some minimal contribution in the sun
#telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
#telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.01)
#vel_telluric = 17.79 # km/s
#telluric_linelist = None
#vel_telluric = None
line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/moog_synth_good_for_params_all.txt")
#line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/width_synth_good_for_params_all.txt")
#line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/moog_synth_good_for_params_all.txt")
#line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/width_synth_good_for_params_all.txt")
line_regions = ispec.adjust_linemasks(normalized_star_spectrum, line_regions, max_margin=0.5)
linemasks = ispec.fit_lines(line_regions, normalized_star_spectrum, star_continuum_model, \
atomic_linelist = atomic_linelist, \
#max_atomic_wave_diff = 0.005, \
max_atomic_wave_diff = 0.00, \
telluric_linelist = telluric_linelist, \
smoothed_spectrum = None, \
check_derivatives = False, \
vel_telluric = vel_telluric, discard_gaussian=False, \
discard_voigt=True, \
free_mu=True, crossmatch_with_mu=False, closest_match=False)
# Discard lines that are not cross matched with the same original element stored in the note
linemasks = linemasks[linemasks['element'] == line_regions['note']]
# Exclude lines that have not been successfully cross matched with the atomic data
# because we cannot calculate the chemical abundance (it will crash the corresponding routines)
rejected_by_atomic_line_not_found = (linemasks['wave_nm'] == 0)
linemasks = linemasks[~rejected_by_atomic_line_not_found]
# Exclude lines with EW equal to zero
rejected_by_zero_ew = (linemasks['ew'] == 0)
linemasks = linemasks[~rejected_by_zero_ew]
# Exclude lines that may be affected by tellurics
rejected_by_telluric_line = (linemasks['telluric_wave_peak'] != 0)
linemasks = linemasks[~rejected_by_telluric_line]
if use_ares:
# Replace the measured equivalent widths by the ones computed by ARES
old_linemasks = linemasks.copy()
### Different rejection parameters (check ARES papers):
## - http://adsabs.harvard.edu/abs/2007A%26A...469..783S
## - http://adsabs.harvard.edu/abs/2015A%26A...577A..67S
#linemasks = ispec.update_ew_with_ares(normalized_star_spectrum, linemasks, rejt="0.995", tmp_dir=None, verbose=0)
#linemasks = ispec.update_ew_with_ares(normalized_star_spectrum, linemasks, rejt="3;5764,5766,6047,6052,6068,6076", tmp_dir=None, verbose=0)
snr = 50
linemasks = ispec.update_ew_with_ares(normalized_star_spectrum, linemasks, rejt="%s" % (snr), tmp_dir=None, verbose=0)
ew = linemasks['ew']
ew_err = linemasks['ew_err']
# Save linemasks (line masks + atomic cross-matched information + fit information)
ispec.write_line_regions(linemasks, "example_fitted_atomic_linemask.txt", extended=True)
def fit_lines_already_crossmatched_with_atomic_data_and_determine_ew(use_ares=False):
star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
#--- Radial Velocity determination with template -------------------------------
logging.info("Radial velocity determination with template...")
# - Read synthetic template
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
#template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")
models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
lower_velocity_limit=-200, upper_velocity_limit=200, \
velocity_step=1.0, fourier=False)
# Number of models represent the number of components
components = len(models)
# First component:
rv = np.round(models[0].mu(), 2) # km/s
rv_err = np.round(models[0].emu(), 2) # km/s
#--- Radial Velocity correction ------------------------------------------------
logging.info("Radial velocity correction... %.2f +/- %.2f" % (rv, rv_err))
star_spectrum = ispec.correct_velocity(star_spectrum, rv)
#--- Telluric velocity shift determination from spectrum --------------------------
logging.info("Telluric velocity shift determination...")
# - Telluric
telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.0)
models, ccf = ispec.cross_correlate_with_mask(star_spectrum, telluric_linelist, \
lower_velocity_limit=-100, upper_velocity_limit=100, \
velocity_step=0.5, mask_depth=0.01, \
fourier = False,
only_one_peak = True)
vel_telluric = np.round(models[0].mu(), 2) # km/s
vel_telluric_err = np.round(models[0].emu(), 2) # km/s
#--- Resolution degradation ----------------------------------------------------
# NOTE: The line selection was built based on a solar spectrum with R ~ 47,000 and GES/VALD atomic linelist.
from_resolution = 80000
to_resolution = 47000
star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution, from_resolution)
#--- Continuum fit -------------------------------------------------------------
model = "Splines" # "Polynomy"
degree = 2
nknots = None # Automatic: 1 spline every 5 nm
from_resolution = to_resolution
# Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
order='median+max'
median_wave_range=0.05
max_wave_range=1.0
star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
nknots=nknots, degree=degree, \
median_wave_range=median_wave_range, \
max_wave_range=max_wave_range, \
model=model, order=order, \
automatic_strong_line_detection=True, \
strong_line_probability=0.5, \
use_errors_for_fitting=True)
#--- Normalize -------------------------------------------------------------
normalized_star_spectrum = ispec.normalize_spectrum(star_spectrum, star_continuum_model, consider_continuum_errors=False)
# Use a fixed value because the spectrum is already normalized
star_continuum_model = ispec.fit_continuum(star_spectrum, fixed_value=1.0, model="Fixed value")
#--- Read lines with atomic data ------------------------------------------------
line_regions_with_atomic_data = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/moog_synth_good_for_params_all_extended.txt")
#line_regions_with_atomic_data = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/width_synth_good_for_params_all_extended.txt")
#line_regions_with_atomic_data = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/moog_synth_good_for_params_all_extended.txt")
#line_regions_with_atomic_data = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/width_synth_good_for_params_all_extended.txt")
smoothed_star_spectrum = ispec.convolve_spectrum(star_spectrum, 2*to_resolution)
line_regions_with_atomic_data = ispec.adjust_linemasks(smoothed_star_spectrum, line_regions_with_atomic_data, max_margin=0.5)
#telluric_linelist_file = ispec_dir + "/input/linelists/CCF/Synth.Tellurics.500_1100nm/mask.lst"
#telluric_linelist = ispec.read_telluric_linelist(telluric_linelist_file, minimum_depth=0.01)
#vel_telluric = 17.79 # km/s
#telluric_linelist = None
#vel_telluric = None
#--- Fit the lines but do NOT cross-match with any atomic linelist since they already have that information
linemasks = ispec.fit_lines(line_regions_with_atomic_data, normalized_star_spectrum, star_continuum_model, \
atomic_linelist = None, \
max_atomic_wave_diff = 0.005, \
telluric_linelist = telluric_linelist, \
check_derivatives = False, \
vel_telluric = vel_telluric, discard_gaussian=False, \
smoothed_spectrum=None, \
discard_voigt=True, \
free_mu=True, crossmatch_with_mu=False, closest_match=False)
# Discard bad masks
flux_peak = normalized_star_spectrum['flux'][linemasks['peak']]
flux_base = normalized_star_spectrum['flux'][linemasks['base']]
flux_top = normalized_star_spectrum['flux'][linemasks['top']]
bad_mask = np.logical_or(linemasks['wave_peak'] <= linemasks['wave_base'], linemasks['wave_peak'] >= linemasks['wave_top'])
bad_mask = np.logical_or(bad_mask, flux_peak >= flux_base)
bad_mask = np.logical_or(bad_mask, flux_peak >= flux_top)
linemasks = linemasks[~bad_mask]
# Exclude lines with EW equal to zero
rejected_by_zero_ew = (linemasks['ew'] == 0)
linemasks = linemasks[~rejected_by_zero_ew]
# Exclude lines that may be affected by tellurics
rejected_by_telluric_line = (linemasks['telluric_wave_peak'] != 0)
linemasks = linemasks[~rejected_by_telluric_line]
if use_ares:
# Replace the measured equivalent widths by the ones computed by ARES
old_linemasks = linemasks.copy()
### Different rejection parameters (check ARES papers):
## - http://adsabs.harvard.edu/abs/2007A%26A...469..783S
## - http://adsabs.harvard.edu/abs/2015A%26A...577A..67S
#linemasks = ispec.update_ew_with_ares(normalized_star_spectrum, linemasks, rejt="0.995", tmp_dir=None, verbose=0)
#linemasks = ispec.update_ew_with_ares(normalized_star_spectrum, linemasks, rejt="3;5764,5766,6047,6052,6068,6076", tmp_dir=None, verbose=0)
snr = 50
linemasks = ispec.update_ew_with_ares(normalized_star_spectrum, linemasks, rejt="%s" % (snr), tmp_dir=None, verbose=0)
def synthesize_spectrum(code="spectrum"):
#--- Synthesizing spectrum -----------------------------------------------------
# Parameters
teff = 5771.0
logg = 4.44
MH = 0.00
alpha = ispec.determine_abundance_enchancements(MH)
microturbulence_vel = ispec.estimate_vmic(teff, logg, MH) # 1.07
macroturbulence = ispec.estimate_vmac(teff, logg, MH) # 4.21
vsini = 1.60 # Sun
limb_darkening_coeff = 0.6
resolution = 300000
wave_step = 0.001
# Wavelengths to synthesis
#regions = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
regions = None
wave_base = 515.0 # Magnesium triplet region
wave_top = 525.0
# Selected model amtosphere, linelist and solar abundances
#model = ispec_dir + "/input/atmospheres/MARCS/"
model = ispec_dir + "/input/atmospheres/MARCS.GES/"
#model = ispec_dir + "/input/atmospheres/MARCS.APOGEE/"
#model = ispec_dir + "/input/atmospheres/ATLAS9.APOGEE/"
#model = ispec_dir + "/input/atmospheres/ATLAS9.Castelli/"
#model = ispec_dir + "/input/atmospheres/ATLAS9.Kurucz/"