-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspamms.py
executable file
·2086 lines (1712 loc) · 95 KB
/
spamms.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
__version__ = '1.1.1'
import numpy as np
import glob
import os
import shutil
from schwimmbad import MultiPool
import sys
import itertools
import time
import functools
from scipy.interpolate import splrep, splev
from scipy import stats
import scipy.optimize as so
import phoebe
from phoebe import u,c
import math
from tqdm import tqdm, trange
import settings
from astropy.constants import R_sun, M_sun, G
import getopt
def read_input_file(input_file):
print('Reading input file...')
lines = tuple(open(input_file, 'r'))
object_type_ind = [i for i in range(len(lines)) if lines[i].startswith('object_type')][0]
object_type = lines[object_type_ind].split('=')[1].strip()
if object_type == 'single':
return read_s_input_file(input_file)
elif object_type == 'contact_binary':
return read_cb_input_file(input_file)
elif object_type == 'binary':
return read_b_input_file(input_file)
else:
raise ValueError('object_type must be one of the following [single, binary, contact_binary]')
def read_cb_input_file(input_file):
lines = tuple(open(input_file, 'r'))
object_type_ind = [i for i in range(len(lines)) if lines[i].startswith('object_type')][0]
object_type = lines[object_type_ind].split('=')[1].strip()
ntriangles = 5000
ntriangles_ind = [i for i in range(len(lines)) if lines[i].startswith('ntriangles')]
if len(ntriangles_ind) >= 1:
ntriangles = lines[ntriangles_ind[0]].split('=')[1].strip()
path_to_obs_spectra_ind = [i for i in range(len(lines)) if lines[i].startswith('path_to_obs_spectra')][0]
path_to_obs_spectra = lines[path_to_obs_spectra_ind].split('=')[1].strip()
if not path_to_obs_spectra.endswith('/'): path_to_obs_spectra += '/'
if path_to_obs_spectra == 'None/': path_to_obs_spectra = 'None'
output_directory_ind = [i for i in range(len(lines)) if lines[i].startswith('output_directory')][0]
output_directory = lines[output_directory_ind].split('=')[1].strip()
if not output_directory.endswith('/'): output_directory += '/'
path_to_grid_ind = [i for i in range(len(lines)) if lines[i].startswith('path_to_grid')][0]
path_to_grid = lines[path_to_grid_ind].split('=')[1].strip()
if not path_to_grid.endswith('/'): path_to_grid += '/'
fit_params = ['fillout_factor', 'teff_primary', 'teff_secondary', 'period', 'sma', 'inclination', 'q', 't0', 'async_primary', 'async_secondary', 'gamma']
abundance_params = ['he_abundances', 'cno_abundances']
fit_param_values = {'async_primary':1.0, 'async_secondary':1.0}
abund_param_values = {}
io_dict = {'object_type':object_type, 'ntriangles':ntriangles, 'path_to_obs_spectra':path_to_obs_spectra, 'output_directory':output_directory, 'path_to_grid':path_to_grid, 'input_file':input_file, 'rad_bound':False}
try:
times_ind = [i for i in range(len(lines)) if lines[i].startswith('times')][0]
times = lines[times_ind].split('=')[1].strip()
io_dict['times'] = arg_parse(times)
except:
pass
for param in fit_params:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
fit_param_values[param] = arg_parse(arg)
abund_param_values['he_abundances'] = [0.06, 0.1, 0.15, 0.2]
abund_param_values['cno_abundances'] = [6.5, 7.0, 7.5, 8.0, 8.5]
abund_param_values['lp_bins'] = 161
for param in abundance_params:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
abund_param_values[param] = arg_parse(arg)
if type(abund_param_values['lp_bins']) is list:
abund_param_values['lp_bins'] = int(abund_param_values['lp_bins'][0])
abund_param_values['interpolate_abundances'] = False
# interp_arg = lines[[i for i in range(len(lines)) if lines[i].startswith('interpolate_abundances')][0]].split('=')[1].strip()
# if interp_arg == 'False' or interp_arg == '0':
# abund_param_values['interpolate_abundances'] = False
# else:
# abund_param_values['interpolate_abundances'] = True
line_list_arg = lines[[i for i in range(len(lines)) if lines[i].startswith('selected_line_list =')][0]].split('=')[1].strip()
line_list = parse_line_list(line_list_arg)
return fit_param_values, abund_param_values, line_list, io_dict
def read_b_input_file(input_file):
lines = tuple(open(input_file, 'r'))
object_type_ind = [i for i in range(len(lines)) if lines[i].startswith('object_type')][0]
object_type = lines[object_type_ind].split('=')[1].strip()
ntriangles = 5000
ntriangles_ind = [i for i in range(len(lines)) if lines[i].startswith('ntriangles')]
if len(ntriangles_ind) >= 1:
ntriangles = lines[ntriangles_ind[0]].split('=')[1].strip()
path_to_obs_spectra_ind = [i for i in range(len(lines)) if lines[i].startswith('path_to_obs_spectra')][0]
path_to_obs_spectra = lines[path_to_obs_spectra_ind].split('=')[1].strip()
if not path_to_obs_spectra.endswith('/'): path_to_obs_spectra += '/'
if path_to_obs_spectra == 'None/': path_to_obs_spectra = 'None'
output_directory_ind = [i for i in range(len(lines)) if lines[i].startswith('output_directory')][0]
output_directory = lines[output_directory_ind].split('=')[1].strip()
if not output_directory.endswith('/'): output_directory += '/'
path_to_grid_ind = [i for i in range(len(lines)) if lines[i].startswith('path_to_grid')][0]
path_to_grid = lines[path_to_grid_ind].split('=')[1].strip()
if not path_to_grid.endswith('/'): path_to_grid += '/'
try:
dist_ind = [i for i in range(len(lines)) if lines[i].startswith('distortion')][0]
dist = lines[dist_ind].split('=')[1].strip()
if dist not in ['rotstar', 'roche', 'sphere']:
dist = 'roche'
except:
dist = 'roche'
fit_params = ['r_equiv_primary', 'r_equiv_secondary', 'teff_primary', 'teff_secondary', 'period', 'sma', 'inclination', 'q', 't0', 'async_primary', 'async_secondary', 'pitch_primary', 'pitch_secondary', 'yaw_primary', 'yaw_secondary', 'gamma']
abundance_params = ['he_abundances', 'cno_abundances']
fit_param_values = {'async_primary':1.0, 'async_secondary':1.0, 'pitch_primary':0.0, 'pitch_secondary':0.0, 'yaw_primary':0.0, 'yaw_secondary':0.0}
abund_param_values = {}
io_dict = {'object_type':object_type, 'ntriangles':ntriangles, 'path_to_obs_spectra':path_to_obs_spectra, 'output_directory':output_directory, 'path_to_grid':path_to_grid, 'input_file':input_file, 'distortion':dist, 'rad_bound':False}
try:
times_ind = [i for i in range(len(lines)) if lines[i].startswith('times')][0]
times = lines[times_ind].split('=')[1].strip()
io_dict['times'] = arg_parse(times)
except:
pass
for param in fit_params:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
fit_param_values[param] = arg_parse(arg)
abund_param_values['he_abundances'] = [0.06, 0.1, 0.15, 0.2]
abund_param_values['cno_abundances'] = [6.5, 7.0, 7.5, 8.0, 8.5]
abund_param_values['lp_bins'] = 161
for param in abundance_params:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
abund_param_values[param] = arg_parse(arg)
if type(abund_param_values['lp_bins']) is list:
abund_param_values['lp_bins'] = int(abund_param_values['lp_bins'][0])
abund_param_values['interpolate_abundances'] = False
# interp_arg = lines[[i for i in range(len(lines)) if lines[i].startswith('interpolate_abundances')][0]].split('=')[1].strip()
# if interp_arg == 'False' or interp_arg == '0':
# abund_param_values['interpolate_abundances'] = False
# else:
# abund_param_values['interpolate_abundances'] = True
line_list_arg = lines[[i for i in range(len(lines)) if lines[i].startswith('selected_line_list =')][0]].split('=')[1].strip()
line_list = parse_line_list(line_list_arg)
return fit_param_values, abund_param_values, line_list, io_dict
def read_s_input_file(input_file):
lines = tuple(open(input_file, 'r'))
object_type_ind = [i for i in range(len(lines)) if lines[i].startswith('object_type')][0]
object_type = lines[object_type_ind].split('=')[1].strip()
ntriangles = 5000
ntriangles_ind = [i for i in range(len(lines)) if lines[i].startswith('ntriangles')]
if len(ntriangles_ind) >= 1:
ntriangles = lines[ntriangles_ind[0]].split('=')[1].strip()
path_to_obs_spectra_ind = [i for i in range(len(lines)) if lines[i].startswith('path_to_obs_spectra')][0]
path_to_obs_spectra = lines[path_to_obs_spectra_ind].split('=')[1].strip()
if not path_to_obs_spectra.endswith('/'): path_to_obs_spectra += '/'
if path_to_obs_spectra == 'None/': path_to_obs_spectra = 'None'
output_directory_ind = [i for i in range(len(lines)) if lines[i].startswith('output_directory')][0]
output_directory = lines[output_directory_ind].split('=')[1].strip()
if not output_directory.endswith('/'): output_directory += '/'
path_to_grid_ind = [i for i in range(len(lines)) if lines[i].startswith('path_to_grid')][0]
path_to_grid = lines[path_to_grid_ind].split('=')[1].strip()
if not path_to_grid.endswith('/'): path_to_grid += '/'
try:
dist_ind = [i for i in range(len(lines)) if lines[i].startswith('distortion')][0]
dist = lines[dist_ind].split('=')[1].strip()
if dist not in ['rotstar', 'roche', 'sphere']:
dist = 'rotstar'
except:
dist = 'rotstar'
fit_params = ['teff', 'rotation_rate', 'requiv', 'inclination', 'mass', 't0', 'gamma']
fit_params_alt = ['teff', 'vsini', 'rotation_rate', 'v_crit_frac', 'requiv', 'r_pole', 'inclination', 'mass', 't0', 'gamma']
abundance_params = ['he_abundances', 'cno_abundances']
fit_param_values = {}
abund_param_values = {}
io_dict = {'object_type':object_type, 'ntriangles':ntriangles, 'path_to_obs_spectra':path_to_obs_spectra, 'output_directory':output_directory, 'path_to_grid':path_to_grid, 'input_file':input_file, 'distortion':dist, 'rad_bound':False}
try:
times_ind = [i for i in range(len(lines)) if lines[i].startswith('times')][0]
times = lines[times_ind].split('=')[1].strip()
io_dict['times'] = arg_parse(times)
except:
pass
for param in fit_params_alt:
try:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
fit_param_values[param] = arg_parse(arg)
except:
fit_param_values[param] = [-1.0]
for param in abundance_params:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
abund_param_values[param] = arg_parse(arg)
abund_param_values['he_abundances'] = [0.06, 0.1, 0.15, 0.2]
abund_param_values['cno_abundances'] = [6.5, 7.0, 7.5, 8.0, 8.5]
abund_param_values['lp_bins'] = 161
for param in abundance_params:
arg = lines[[i for i in range(len(lines)) if lines[i].startswith(param)][0]].split('=')[1].strip()
abund_param_values[param] = arg_parse(arg)
if type(abund_param_values['lp_bins']) is list:
abund_param_values['lp_bins'] = int(abund_param_values['lp_bins'][0])
abund_param_values['interpolate_abundances'] = False
# interp_arg = lines[[i for i in range(len(lines)) if lines[i].startswith('interpolate_abundances')][0]].split('=')[1].strip()
# if interp_arg == 'False' or interp_arg == '0':
# abund_param_values['interpolate_abundances'] = False
# else:
# abund_param_values['interpolate_abundances'] = True
line_list_arg = lines[[i for i in range(len(lines)) if lines[i].startswith('selected_line_list =')][0]].split('=')[1].strip()
line_list = parse_line_list(line_list_arg)
return fit_param_values, abund_param_values, line_list, io_dict
def arg_parse(arg):
if arg.startswith('('):
dstr = [float(i) for i in arg.strip('()').split(',')]
value = np.linspace(dstr[0], dstr[1], int(dstr[2]))
elif arg.startswith('['):
value = [float(i) for i in arg.strip('[]').split(',')]
else:
value = [float(arg)]
return list(value)
def parse_line_list(arg):
arg = arg.strip('[]').split(',')
line_list = [i.strip().strip("'") for i in arg]
return line_list
def setup_output_directory(io_dict):
'''
Sets up output directory
'''
print('Setting up output directory...')
output_directory = io_dict['output_directory']
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
os.mkdir(output_directory)
shutil.copy(io_dict['input_file'], output_directory + 'input.txt')
try:
shutil.copytree(io_dict['path_to_obs_spectra'], output_directory + 'input_spectra')
except:
pass
print('Output Directory: %s' %output_directory)
def check_input_spectra(io_dict):
spec_files = glob.glob(io_dict['path_to_obs_spectra'] + '*_spec.txt')
hjd_files = glob.glob(io_dict['path_to_obs_spectra'] + '*_hjd.txt')
for spec_file in spec_files:
spec = np.loadtxt(spec_file).T
n_spec = len(spec[1:])
expected_hjd_file = spec_file[:-9] + '_hjd.txt'
try:
hjd = np.loadtxt(expected_hjd_file, ndmin=1)
if len(hjd) != n_spec:
raise ValueError('Number of times in HJD file does not match number of Spectra in file: %s' %spec_file)
except:
raise IOError('Expected HJD file not found: %s' %expected_hjd_file)
spec_files_corenames = [i[:-9] for i in spec_files]
hjd_files_corenames = [i[:-8] for i in hjd_files]
dif_set = list(set(spec_files_corenames).symmetric_difference(set(hjd_files_corenames)))
if len(dif_set) !=0:
raise ValueError('Mismatch between Spectra and HJD core filenames %s' %dif_set)
print('Input spectra checks complete')
def check_grid(times, abund_param_values, io_dict, grid_entries, run_dictionary):
if io_dict['object_type'] == 'contact_binary':
cb = run_cb_phoebe_model(times, abund_param_values, io_dict, run_dictionary)
elif io_dict['object_type'] == 'binary':
cb = run_b_phoebe_model(times, abund_param_values, io_dict, run_dictionary)
else:
if io_dict['distortion'] == 'rotstar':
cb = run_s_phoebe_model(times, abund_param_values, io_dict, run_dictionary)
else:
cb = run_sb_phoebe_model(times, abund_param_values, io_dict, run_dictionary)
combs, mode_combs = determine_tgr_combinations(cb, io_dict)
missing_combs = [i for i in combs if i not in grid_entries]
return missing_combs
def get_obs_spec_and_times(io_dict):
if io_dict['path_to_obs_spectra'] == 'None':
times = io_dict['times']
obs_specs = None
return np.array(times), obs_specs
else:
spec_files = glob.glob(io_dict['path_to_obs_spectra'] + '*_spec.txt')
hjd_files = glob.glob(io_dict['path_to_obs_spectra'] + '*_hjd.txt')
spec_files.sort()
hjd_files.sort()
times = []
for hjd_file in hjd_files:
times.extend(np.loadtxt(hjd_file, ndmin=1))
obs_specs = {}
for spec_file in spec_files:
x = np.loadtxt(spec_file).T
w = x[0]
f = x[1:]
times_temp = np.loadtxt(spec_file[:-8] + 'hjd.txt', ndmin=1)
for i in range(len(f)):
dic = {'wavelength':w, 'flux':f[i]}
obs_specs[str(round(times_temp[i], 13)).ljust(13, '0')] = dic
return np.array(times), obs_specs
def create_runs_and_ids(fit_param_values):
keys = []
values = []
for key, value in fit_param_values.items():
keys.append(key)
values.append(value)
runs = list(itertools.product(*values))
run_dictionaries = [dict(zip(keys,i)) for i in runs]
for i, j in enumerate(run_dictionaries):
j['run_id'] = i
run_ids = range(len(run_dictionaries))
dictionary_of_run_dicts = dict(zip(run_ids, run_dictionaries))
return run_dictionaries
def rpole_to_requiv(r_pole, vrot, n=5000, return_r_equator=False):
'''
r_pole - is the polar radius in units of solar radius
vrot - is the rotational velocity as a percentage of the critical velocity (value between 0 and 1)
n - is the number of theta points that we will use to plot the surface
'''
r_pole*=1.0
vrot*=1.0
n+=1
# create an array of angles ranging from theta = 0 (upper pole) to theta = pi (lower pole)
theta = np.linspace(0,np.pi, n)
# to solve Eq. 6, we need to find the roots of the 3rd order polynomial. a, b, c and d are the coefficients of the polynomial
a = (vrot / r_pole - vrot**3/(3.*r_pole))**2 * np.sin(theta)**2
b = 0
c = -3.0
d = 3.*r_pole
# we'll collect our radii at each theta in the rs array
rs = []
# for each theta we find the roots and check to make sure it is positive and not complex and dump them into rs
for i in range(len(a)):
x = np.roots([a[i], b, c, d])
inds = np.iscomplex(x) == False
y = x.real[inds]
ind = np.argmin((r_pole*1.25 - y)**2)
if y[ind] > 0:
rs.append(y[ind])
else:
rs.append(y[ind]/2.*-1.0)
# convert rs and thetas to xs and ys
rs = np.array(rs)
xs = rs * np.sin(theta)
ys = rs * np.cos(theta)
# now we can calculate the volume of our system using the disk integration method
# we'll create a new equally spaced y array and a corresponding x array
new_ys = np.linspace(-1*r_pole, r_pole, n)
new_xs = np.interp(new_ys, ys[::-1], xs[::-1])
# calculate the volume
vol = 0
dy = (2*r_pole) / (n-1)
for i in range(1, n):
r = (new_xs[i] + new_xs[i-1])/2
vol += np.pi * r**2 *dy
# calculate r_equiv from the calculated total volume
r_equiv = (vol * 3./(4.*np.pi))**(1./3)
if return_r_equator:
return r_equiv, max(rs)
else:
return r_equiv
def func_requiv_to_rpole(rpole, vrot, requiv):
return np.sqrt((rpole_to_requiv(rpole, vrot) - requiv)**2)
def requiv_to_rpole(requiv, vrot):
'''
requiv - is the volumetric equivalent spherical radius in units of solar radius
vrot - is the rotational velocity as a percentage of the critical velocity (value between 0 and 1)
'''
res = so.minimize(func_requiv_to_rpole, np.array([requiv]), args = (vrot,requiv), bounds=[(requiv*0.5,requiv*1.1)])
return res.x[0]
def func_requiv_to_rpole_abs_units(rpole, vrot, requiv, mass):
v_crit = calc_critical_velocity(mass, rpole)
v_percent_crit = vrot/v_crit
return np.sqrt((rpole_to_requiv(rpole, v_percent_crit) - requiv)**2)
def requiv_to_rpole_abs_units(requiv, vrot, mass):
'''
requiv - is the volumetric equivalent spherical radius in units of solar radius
vrot - is the rotational velocity in km/s
mass - is the mass in solar masses
'''
res = so.minimize(func_requiv_to_rpole_abs_units, np.array([requiv]), args = (vrot,requiv,mass), bounds=[(requiv*0.5,requiv*1.1)])
return res.x[0]
def calc_critical_velocity(M, r_pole):
'''
M - mass in units of solar mass
r_pole - polar radius in units of solar radius
Calculates critival velocity given M and R
This is a simple rearangement of Eq. 5 above.
'''
# We convert all values to km, kg and s so that the final rotational velocity is in km/s
v_crit = np.sqrt(2./3. * G.to('km3/(kg s2)') * M*M_sun.to('kg') / (r_pole*R_sun.to('km')))
return v_crit.value
def rotation_rate_to_period(v, r):
if v == 0:
P = 9999999999999
else:
P = ((2 * np.pi * r * R_sun.to('km').value) / v)/(24*60*60)
return P
def run_cb_phoebe_model(times, abund_param_values, io_dict, run_dictionary):
start_time_prog_1 = time.time()
logger = phoebe.logger(clevel='ERROR')
cb = phoebe.default_binary(contact_binary = True)
cb.flip_constraint('pot@contact_envelope', 'requiv')
cb.flip_constraint('fillout_factor', 'pot@contact_envelope')
# cb['pot@contact_envelope@component'].set_value()
cb['fillout_factor@component'].set_value(value = run_dictionary['fillout_factor'])
cb['gravb_bol'].set_value_all(value=1.0)
cb['irrad_frac_refl_bol'].set_value_all(value=1.0)
cb['teff@primary'].set_value(value = run_dictionary['teff_primary'])
cb['teff@secondary'].set_value(value = run_dictionary['teff_secondary'])
cb['period@binary'].set_value(value = run_dictionary['period'])
cb['sma@binary'].set_value(value = run_dictionary['sma'])
cb['q@binary'].set_value(value = run_dictionary['q'])
if phoebe_ver < 2.2:
cb['ntriangles'].set_value_all(value = io_dict['ntriangles'])
else:
cb['ntriangles'].set_value(value = io_dict['ntriangles'])
cb['incl'].set_value(value = run_dictionary['inclination'])
t = list(times)
cb.add_dataset('lc', times=t, dataset='lc01')
cb.add_dataset('rv', times=t, dataset='rv01')
cb.add_dataset('mesh', times=t, dataset='mesh01')
cb.add_dataset('orb', times=t, dataset='orb01')
if phoebe_ver < 2.2:
cb['ld_func'].set_value_all(value = 'logarithmic')
else:
cb['ld_mode'].set_value_all(value = 'manual')
cb['ld_func'].set_value_all(value = 'logarithmic')
cb['ld_mode_bol'].set_value_all(value = 'manual')
cb['ld_func_bol'].set_value_all(value = 'logarithmic')
cb['atm'].set_value_all(value='blackbody')
cb['include_times'] = 't0_ref@binary'
cb.flip_constraint('t0_ref@binary', 't0_supconj')
cb['t0_ref@binary@component'].set_value(value = run_dictionary['t0'])
cb['columns'] = ['*@lc01', '*@rv01', 'us', 'vs', 'ws', 'vus', 'vvs', 'vws', 'loggs', 'teffs', 'mus', 'visibilities', 'rs', 'areas']
cb.run_compute()
execution_time = time.time() - start_time_prog_1
# print execution_time
return cb
def run_b_phoebe_model(times, abund_param_values, io_dict, run_dictionary):
start_time_prog_1 = time.time()
logger = phoebe.logger(clevel='ERROR')
b = phoebe.default_binary()
b['gravb_bol'].set_value_all(value=1.0)
b['irrad_frac_refl_bol'].set_value_all(value=1.0)
b['requiv@primary'].set_value(value = run_dictionary['r_equiv_primary'])
b['requiv@secondary'].set_value(value = run_dictionary['r_equiv_secondary'])
b['teff@primary'].set_value(value = run_dictionary['teff_primary'])
b['teff@secondary'].set_value(value = run_dictionary['teff_secondary'])
b['period@binary'].set_value(value = run_dictionary['period'])
b['sma@binary'].set_value(value = run_dictionary['sma'])
b['q@binary'].set_value(value = run_dictionary['q'])
b['distortion_method'].set_value_all(value = io_dict['distortion'])
b['ntriangles'].set_value_all(value = io_dict['ntriangles'])
b['incl@binary'].set_value(value = run_dictionary['inclination'])
b['syncpar@primary'].set_value(value = run_dictionary['async_primary'])
b['syncpar@secondary'].set_value(value = run_dictionary['async_secondary'])
b['pitch@primary'].set_value(value = run_dictionary['pitch_primary'])
b['pitch@secondary'].set_value(value = run_dictionary['pitch_secondary'])
b['yaw@primary'].set_value(value = run_dictionary['yaw_primary'])
b['yaw@secondary'].set_value(value = run_dictionary['yaw_secondary'])
t = list(times)
b.add_dataset('lc', times=t, dataset='lc01')
b.add_dataset('rv', times=t, dataset='rv01')
b.add_dataset('mesh', times=t, dataset='mesh01')
b.add_dataset('orb', times=t, dataset='orb01')
if phoebe_ver < 2.2:
b['ld_func'].set_value_all(value = 'logarithmic')
else:
b['ld_mode'].set_value_all(value = 'manual')
b['ld_func'].set_value_all(value = 'logarithmic')
b['ld_mode_bol'].set_value_all(value = 'manual')
b['ld_func_bol'].set_value_all(value = 'logarithmic')
b['atm'].set_value_all(value='blackbody')
b['include_times'] = 't0_ref@binary'
b.flip_constraint('t0_ref@binary', 't0_supconj')
b['t0_ref@binary@component'].set_value(value = run_dictionary['t0'])
b['columns'] = ['*@lc01', '*@rv01', 'us', 'vs', 'ws', 'vus', 'vvs', 'vws', 'loggs', 'teffs', 'mus', 'visibilities', 'rs', 'areas']
b.run_compute()
execution_time = time.time() - start_time_prog_1
# print execution_time
return b
def run_s_phoebe_model(times, abund_param_values, io_dict, run_dictionary):
start_time_prog_1 = time.time()
logger = phoebe.logger(clevel='ERROR')
s = phoebe.default_star()
s['teff@component'].set_value(value = run_dictionary['teff'])
s['gravb_bol'].set_value(value = 1.0)
s['irrad_frac_refl_bol'].set_value(value = 1.0)
s['mass@component'].set_value(value = run_dictionary['mass'])
if run_dictionary['r_pole'] != -1:
v_crit = calc_critical_velocity(run_dictionary['mass'], run_dictionary['r_pole'])
if run_dictionary['v_crit_frac'] != -1:
vrot = v_crit * run_dictionary['v_crit_frac']
v_percent_crit = run_dictionary['v_crit_frac']
elif run_dictionary['rotation_rate'] != -1:
vrot = run_dictionary['rotation_rate']
v_percent_crit = vrot / v_crit
else:
vrot = run_dictionary['vsini'] / (np.sin(run_dictionary['inclination'] * np.pi/180.))
v_percent_crit = vrot / v_crit
if vrot == 0:
s['distortion_method'].set_value(value='sphere')
s['requiv@component'].set_value(value = run_dictionary['r_pole'])
s['period@component'].set_value(value = 9999999999999)
else:
# calculate r_equiv given r_pole and v_percent_crit:
r_equiv, r_equator = rpole_to_requiv(run_dictionary['r_pole'], v_percent_crit, n=5000, return_r_equator=True)
s['requiv@component'].set_value(value = r_equiv)
# calculate period from v_rot and r_equator
period = rotation_rate_to_period(vrot, r_equator)
s['period@component'].set_value(value = period)
else:
s['requiv@component'].set_value(value = run_dictionary['requiv'])
if run_dictionary['rotation_rate'] == 0:
s['distortion_method'].set_value('sphere')
elif run_dictionary['rotation_rate'] == -1 and run_dictionary['v_crit_frac'] != -1:
# calculate r_pole given r_equiv and v_percent_crit; calc r_equator:
r_pole = requiv_to_rpole(run_dictionary['requiv'], run_dictionary['v_crit_frac'])
junk, r_equator = rpole_to_requiv(r_pole, run_dictionary['v_crit_frac'], n=5000, return_r_equator=True)
# calc v_crit from mass and r_pole and then v_rot from v_crit
v_crit = calc_critical_velocity(run_dictionary['mass'], r_pole)
vrot = v_crit * run_dictionary['v_crit_frac']
period = rotation_rate_to_period(vrot, r_equator)
else:
if run_dictionary['rotation_rate'] == -1:
vrot = run_dictionary['vsini'] / (np.sin(run_dictionary['inclination'] * np.pi/180.))
else:
vrot = run_dictionary['rotation_rate']
r_pole = requiv_to_rpole_abs_units(run_dictionary['requiv'], vrot, run_dictionary['mass'])
v_crit = calc_critical_velocity(run_dictionary['mass'], r_pole)
v_percent_crit = vrot / v_crit
junk, r_equator = rpole_to_requiv(r_pole, v_percent_crit, n=5000, return_r_equator=True)
period = rotation_rate_to_period(vrot, r_equator)
s['period@component'].set_value(value = period)
if run_dictionary['inclination'] == -1 and run_dictionary['rotation_rate'] == -1:
s['incl@binary'].set_value(value = np.arcsin(run_dictionary['vsini'] / vrot) * 180./np.pi)
elif run_dictionary['inclination'] == -1 and run_dictionary['rotation_rate'] != -1:
s['incl@component'].set_value(value = np.arcsin(run_dictionary['vsini'] / run_dictionary['rotation_rate']) * 180./np.pi)
else:
s['incl@component'].set_value(value = run_dictionary['inclination'])
s['ntriangles'].set_value(value = io_dict['ntriangles'])
t = list(times)
s.add_dataset('lc', times=t, dataset='lc01')
s.add_dataset('rv', times=t, dataset='rv01')
s.add_dataset('mesh', times=t, dataset='mesh01')
s.add_dataset('orb', times=t, dataset='orb01')
if phoebe_ver < 2.2:
s['ld_func'].set_value_all(value = 'logarithmic')
else:
s['ld_mode'].set_value_all(value = 'manual')
s['ld_func'].set_value_all(value = 'logarithmic')
s['ld_mode_bol'].set_value(value = 'manual')
s['ld_func_bol'].set_value(value = 'logarithmic')
s['atm'].set_value(value='blackbody')
s['include_times'] = 't0@system'
s['t0@system'].set_value(value = run_dictionary['t0'])
s['columns'] = ['*@lc01', '*@rv01', 'us', 'vs', 'ws', 'vus', 'vvs', 'vws', 'loggs', 'teffs', 'mus', 'visibilities', 'rs', 'areas']
s.run_compute()
execution_time = time.time() - start_time_prog_1
# print execution_time
return s
def run_sb_phoebe_model(times, abund_param_values, io_dict, run_dictionary):
start_time_prog_1 = time.time()
logger = phoebe.logger(clevel='ERROR')
b = phoebe.default_binary()
b['teff@primary'].set_value(value = run_dictionary['teff'])
b['gravb_bol'].set_value_all(value=1.0)
b['irrad_frac_refl_bol'].set_value_all(value=1.0)
b['distortion_method'].set_value_all(value = io_dict['distortion'])
b.flip_constraint('mass@primary', 'sma@binary')
b.flip_constraint('mass@secondary', 'q@binary')
b['mass@component@primary'].set_value(value = run_dictionary['mass'])
b['period@binary'].set_value(value = 99999999)
if run_dictionary['r_pole'] != -1:
# calculate v_{%c} from M, r_pole and v_rot:
v_crit = calc_critical_velocity(run_dictionary['mass'], run_dictionary['r_pole'])
if run_dictionary['v_crit_frac'] != -1:
vrot = v_crit * run_dictionary['v_crit_frac']
v_percent_crit = run_dictionary['v_crit_frac']
elif run_dictionary['rotation_rate'] != -1:
vrot = run_dictionary['rotation_rate']
v_percent_crit = vrot / v_crit
else:
vrot = run_dictionary['vsini'] / (np.sin(run_dictionary['inclination'] * np.pi/180.))
v_percent_crit = vrot / v_crit
if vrot == 0:
b['distortion_method'].set_value_all('sphere')
b['requiv@primary'].set_value(value = run_dictionary['r_pole'])
else:
# calculate r_equiv given r_pole and v_percent_crit:
r_equiv, r_equator = rpole_to_requiv(run_dictionary['r_pole'], v_percent_crit, n=5000, return_r_equator=True)
b['requiv@primary'].set_value(value = r_equiv)
# calculate period from v_rot and r_equator
period = rotation_rate_to_period(vrot, r_equator)
b.flip_constraint('period@primary', 'syncpar@primary')
b['period@primary'].set_value(value = period)
else:
b['requiv@primary'].set_value(value = run_dictionary['requiv'])
if run_dictionary['rotation_rate'] == 0:
b['distortion_method'].set_value_all('sphere')
elif run_dictionary['rotation_rate'] == -1 and run_dictionary['v_crit_frac'] != -1:
# calculate r_pole given r_equiv and v_percent_crit; calc r_equator:
r_pole = requiv_to_rpole(run_dictionary['requiv'], run_dictionary['v_crit_frac'])
junk, r_equator = rpole_to_requiv(r_pole, run_dictionary['v_crit_frac'], n=5000, return_r_equator=True)
# calc v_crit from mass and r_pole and then v_rot from v_crit
v_crit = calc_critical_velocity(run_dictionary['mass'], r_pole)
vrot = v_crit * run_dictionary['v_crit_frac']
period = rotation_rate_to_period(vrot, r_equator)
else:
if run_dictionary['rotation_rate'] == -1:
vrot = run_dictionary['vsini'] / (np.sin(run_dictionary['inclination'] * np.pi/180.))
else:
vrot = run_dictionary['rotation_rate']
r_pole = requiv_to_rpole_abs_units(run_dictionary['requiv'], vrot, run_dictionary['mass'])
v_crit = calc_critical_velocity(run_dictionary['mass'], r_pole)
v_percent_crit = vrot / v_crit
junk, r_equator = rpole_to_requiv(r_pole, v_percent_crit, n=5000, return_r_equator=True)
period = rotation_rate_to_period(vrot, r_equator)
b.flip_constraint('period@primary', 'syncpar@primary')
b['period@primary'].set_value(value = period)
if run_dictionary['inclination'] == -1 and run_dictionary['rotation_rate'] == -1:
b['incl@binary'].set_value(value = np.arcsin(run_dictionary['vsini'] / vrot) * 180./np.pi)
elif run_dictionary['inclination'] == -1 and run_dictionary['rotation_rate'] != -1:
b['incl@binary'].set_value(value = np.arcsin(run_dictionary['vsini'] / run_dictionary['rotation_rate']) * 180./np.pi)
else:
b['incl@binary'].set_value(value = run_dictionary['inclination'])
b['ntriangles'].set_value_all(value = io_dict['ntriangles'])
t = list(times)
b.add_dataset('lc', times=t, dataset='lc01')
b.add_dataset('rv', times=t, dataset='rv01')
b.add_dataset('mesh', times=t, dataset='mesh01')
b.add_dataset('orb', times=t, dataset='orb01')
if phoebe_ver < 2.2:
b['ld_func'].set_value_all(value = 'logarithmic')
else:
b['ld_mode'].set_value_all(value = 'manual')
b['ld_func'].set_value_all(value = 'logarithmic')
b['ld_mode_bol'].set_value_all(value = 'manual')
b['ld_func_bol'].set_value_all(value = 'logarithmic')
b['atm'].set_value_all(value='blackbody')
b['include_times'] = 't0_ref@binary'
b.flip_constraint('t0_ref@binary', 't0_supconj')
b['t0_ref@binary@component'].set_value(value = -24999999)
b['columns'] = ['*@lc01', '*@rv01', 'us', 'vs', 'ws', 'vus', 'vvs', 'vws', 'loggs', 'teffs', 'mus', 'visibilities', 'rs', 'areas']
b.run_compute()
execution_time = time.time() - start_time_prog_1
# print execution_time
return b
def update_output_directories(times, abund_param_values, io_dict, run_dictionary):
model_path = io_dict['output_directory'] + 'Model_' + str(run_dictionary['run_id']).zfill(4)
os.mkdir(model_path)
with open(model_path + '/model_info.txt', 'w') as file:
for key, value in io_dict.items():
file.write('%s:%s\n' % (key, value))
for key, value in run_dictionary.items():
file.write('%s:%s\n' % (key, value))
if abund_param_values['interpolate_abundances']:
print('abundance interpolation is not supported yet.')
he_abundances = [i for j in abund_param_values['cno_abundances'] for i in abund_param_values['he_abundances']]
cno_abundances = [j for j in abund_param_values['cno_abundances'] for i in abund_param_values['he_abundances']]
# he_abundances = [0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2]
# cno_abundances = [6.5, 6.5, 6.5, 6.5, 7.0, 7.0, 7.0, 7.0, 7.5, 7.5, 7.5, 7.5, 8.0, 8.0, 8.0, 8.0, 8.5, 8.5, 8.5, 8.5]
for i in range(len(he_abundances)):
os.mkdir(model_path + '/He' + str(he_abundances[i]) + '_CNO' + str(cno_abundances[i]))
return model_path
def calc_spec_by_phase(mesh_vals, hjd, model_path, lines, abund_param_values, lines_dic, io_dict):
nw = []
nf = []
# print 'assigning spectra'
for line in lines:
assign_and_calc_abundance(mesh_vals, hjd, model_path, abund_param_values, lines_dic, io_dict, line)
def assign_and_calc_abundance(mesh_vals, hjd, model_path, abund_param_values, lines_dic, io_dict, line):
start_time = time.time()
he_abundances = [i for j in abund_param_values['cno_abundances'] for i in abund_param_values['he_abundances']]
cno_abundances = [j for j in abund_param_values['cno_abundances'] for i in abund_param_values['he_abundances']]
# he_abundances = [0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2, 0.06, 0.1, 0.15, 0.2]
# cno_abundances = [6.5, 6.5, 6.5, 6.5, 7.0, 7.0, 7.0, 7.0, 7.5, 7.5, 7.5, 7.5, 8.0, 8.0, 8.0, 8.0, 8.5, 8.5, 8.5, 8.5]
ws, star_profs, wind_profs = assign_spectra_interp(mesh_vals, line, lines_dic, io_dict, abund_param_values)
# if 'upper' in lines_dic.keys():
# ws, star_profs, wind_profs = assign_spectra_interp(mesh_vals, line, lines_dic)
# else:
# ws, star_profs, wind_profs = assign_spectra(mesh_vals, line, lines_dic)
waves = []
phots = []
lp_bins = abund_param_values['lp_bins']
for i in range(int(len(ws[0])/lp_bins)):
wavg_single, phot_avg_single = calc_flux_optimize(ws[:,lp_bins*i:lp_bins*(i+1)], ws, star_profs[:,lp_bins*i:lp_bins*(i+1)], wind_profs[:,lp_bins*i:lp_bins*(i+1)], mesh_vals)
waves.append(wavg_single)
phots.append(phot_avg_single/phot_avg_single[-1])
np.savetxt(model_path + '/He' + str(he_abundances[i]) + '_CNO' + str(cno_abundances[i]) + '/hjd' + str(round(hjd, 13)).ljust(13, '0') + '_' + line + '.txt', np.array([wavg_single, phot_avg_single/phot_avg_single[-1]]).T)
# phot_avg = interp_abundances(phots, He_abundance, CNO_abundance)
# wavg = waves[0]
# return np.array(wavg), np.array(phot_avg)/phot_avg[0]
# wave, phots = calc_flux_bulk(ws, star_profs, wind_profs, mesh_vals)
# for i in range(20):
# np.savetxt(model_path + '/He' + str(he_abundances[i]) + '_CNO' + str(cno_abundances[i]) + '/hjd' + str(hjd).ljust(13, '0') + '_' + line + '.txt', np.array([wave, phots[i]/phots[i][0]]).T)
print(time.time() - start_time)
def assign_spectra(mesh_vals, line, lines_dic, io_dict):
ts = np.around(mesh_vals['teffs'] / 1000.0) * 1000.0
lgs = np.around(mesh_vals['loggs']*10.) / 10.
rads = np.around(mesh_vals['rs'] * 4.0) / 4.0
ws = []
star_profs = []
wind_profs = []
start_time = time.time()
for i in tqdm(range(len(ts))):
w, st, wi = lookup_line_profs_from_dic(ts[i], lgs[i], rads[i], mesh_vals['mus'][i], mesh_vals['viss'][i], line, lines_dic)
ws.append(w)
star_profs.append(st)
wind_profs.append(np.array(wi))
elapsed_time = time.time() - start_time
# print 'Average iterations per second: ' + str(len(ts) / elapsed_time)
ws = dopler_shift(np.array(ws), np.array([mesh_vals['rvs']]*len(ws[0])).T)
ws=np.array(ws, dtype='float')
return np.array(ws), np.array(star_profs), np.array(wind_profs)
def assign_spectra_interp(mesh_vals, line, lines_dic, io_dict, abund_param_values):
ts = mesh_vals['ts']
tls = mesh_vals['tls']
tus = mesh_vals['tus']
w1s = mesh_vals['w1s']
w2s = mesh_vals['w2s']
lgs = mesh_vals['lgs']
rads = mesh_vals['rads']
ws = []
star_low_profs = []
wind_low_profs = []
star_high_profs = []
wind_high_profs = []
start_time = time.time()
for i in tqdm(range(len(ts))):
w, stl, wil = lookup_line_profs_from_dic(tls[i], lgs[i], rads[i], mesh_vals['mus'][i], mesh_vals['viss'][i], line, lines_dic)
wu, stu, wiu = lookup_line_profs_from_dic(tus[i], lgs[i], rads[i], mesh_vals['mus'][i], mesh_vals['viss'][i], line, lines_dic)
ws.append(w)
star_low_profs.append(stl)
wind_low_profs.append(np.array(wil))
star_high_profs.append(stu)
wind_high_profs.append(wiu)
n_tot_bins = len(abund_param_values['he_abundances']) * len(abund_param_values['cno_abundances']) * abund_param_values['lp_bins']
w1s = np.array([w1s]* n_tot_bins).T
w2s = np.array([w2s]* n_tot_bins).T
#When you fall directly on a grid temperature, w1==w2==0. check for this with w3
w3s = w1s + w2s == 0
star_profs = np.array(star_low_profs) * w1s + np.array(star_high_profs) * w2s + np.array(star_high_profs) * w3s
wind_profs = np.array(wind_low_profs) * w1s + np.array(wind_high_profs) * w2s + np.array(wind_high_profs) * w3s
elapsed_time = time.time() - start_time
# print 'Average iterations per second: ' + str(len(ts) / elapsed_time)
# print mesh_vals['rvs']
ws = dopler_shift(np.array(ws), np.array([mesh_vals['rvs']]*len(ws[0])).T)
ws=np.array(ws, dtype='float')
return np.array(ws), np.array(star_profs), np.array(wind_profs)
def dopler_shift(w, rv):
c = 299792.458
return w*c/(c-rv)
def lookup_line_profs_from_dic(t, g, r, m, v, line, lines_dic):
combination = 'T' + str(int(t)) + '_G' + str(g) + '_R' + format(r, '.2f')
w = lines_dic[line]['wavelength'][combination]
if v == 0:
return w, np.zeros_like(w, dtype='float'), np.zeros_like(w, dtype='float')
wlfr = 121.585278
pray_phot = np.sqrt(1 - m**2)
pray_wind = np.sqrt(wlfr**2 - (np.sqrt(wlfr**2 - 1)/wlfr * m * wlfr)**2)
pray_phot_norm = pray_phot/wlfr
pray_wind_norm = pray_wind/wlfr
ind = int(pray_phot*100)
indw = int(pray_wind_norm*100)
# print filename, ind
upper = lines_dic[line]['phot'][combination][ind+1]
lower = lines_dic[line]['phot'][combination][ind]
upperw = lines_dic[line]['wind'][combination][indw+1]
lowerw = lines_dic[line]['wind'][combination][indw]
rise = upper - lower
risew = upperw - lowerw
run = (pray_phot*100)%1
runw = (pray_wind_norm*100)%1
star_prof = lower + rise*run
wind_prof = lowerw + risew*runw
return w, star_prof, wind_prof
def calc_flux_optimize(ws, ws_all, star_profs, wind_profs, mesh_vals):
viss = mesh_vals['viss']
areas = mesh_vals['areas']
mus = mesh_vals['mus']
rs_sol = mesh_vals['rs_sol']
Ro = 695700000
factor_phot = viss * mus * areas / Ro**2
factor_wind = (mus > 0) * mus * areas / (Ro)**2 * 112**2
star_profs *= np.array([factor_phot]*len(star_profs[0])).T
wind_profs *= np.array([factor_wind]*len(wind_profs[0])).T
star_profs += wind_profs
w_min = min(ws_all[:,0])
w_min = math.floor(w_min*10)/10
w_max = max(ws_all[:,-1])
w_max = math.ceil(w_max*10)/10
w = ws.T
w = np.insert(w, 0, [w_min] * len(w[0]), axis=0)
w = np.insert(w, len(w), [w_max] * len(w[0]), axis=0)
ws = w.T
f = np.array(star_profs).T
f = np.insert(f, 0, f[0], axis=0)
f = np.insert(f, len(f), f[-1], axis=0)
star_profs = f.T
wave = np.arange(w_min, w_max, 0.1)
I_star = []
for i in range(len(ws)):
I_star.append(np.interp(wave, ws[i], star_profs[i]))
I_star = np.array(I_star)
indi = np.argsort(I_star[:,0])
indi = indi[::-1]
flux = np.sum(I_star, axis=0)
i = 0
while max(I_star[:,0][indi][i:]/flux[0]) > 0.05:
i += 1
flux = np.sum(I_star[indi][i:], axis=0)