-
Notifications
You must be signed in to change notification settings - Fork 7
/
fitter.py
1500 lines (1324 loc) · 57 KB
/
fitter.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
"""Main driver of the fitting routine."""
__all__ = ['Fitter', 'dynesty_log_like', 'dynesty_loglike_bma', 'pt_dynesty',
'pt_multinest']
import pickle
import time
import warnings
from multiprocessing import (Pool, set_start_method)
from tqdm import tqdm
import extinction
import astropy.units as u
import pandas as pd
import numpy as np
import scipy.stats as st
from numpy.random import choice
from astropy.constants import sigma_sb
from isochrones.interp import DFInterpolator
from termcolor import colored
from .config import (filesdir, gridsdir, priorsdir, filter_names, colors,
iso_mask, iso_bands)
from .error import *
from .isochrone import estimate
from .phot_utils import *
from .sed_library import *
from .utils import *
try:
import dynesty
from dynesty.utils import resample_equal
bma_flag = True
except ModuleNotFoundError:
wrn = 'Dynesty package not found.\n'
wrn += 'Install dynesty with `pip install dynesty`'
warnings.warn(wrn)
bma_flag = False
try:
import pymultinest
except ModuleNotFoundError:
warnings.warn(
'(py)MultiNest installation (or libmultinest.dylib) not detected.'
)
set_start_method('fork')
class Fitter:
"""The Fitter class handles the fitting routines and parameter estimation.
Examples
--------
The fitter isn't instantiaded with any arguments, rather you instantiate a
Fitter object, then you set up the configurations and finally you
initialize the object by running the initialize method.
>>> f = Fitter()
>>> f.star = s # s must be a valid Star object.
>>> f.initialize()
Attributes
----------
out_folder : type
Description of attribute `out_folder`.
verbose : type
Description of attribute `verbose`.
star : type
Description of attribute `star`.
setup : type
Description of attribute `setup`.
norm : type
Description of attribute `norm`.
grid : type
Description of attribute `grid`.
estimate_logg : type
Description of attribute `estimate_logg`.
priorfile : type
Description of attribute `priorfile`.
av_law : type
Description of attribute `av_law`.
n_samples : type
Description of attribute `n_samples`.
bma : type
Description of attribute `bma`.
prior_setup : type
Description of attribute `prior_setup`.
sequential : type
Description of attribute `sequential`.
"""
colors = colors
def __init__(self):
# Default values for attributes
self._interpolators = []
self._grids = []
self.out_folder = None
self.verbose = True
self.star = None
self.setup = ['dynesty']
self.norm = False
self.grid = 'phoenix'
self.estimate_logg = False
self.av_law = 'fitzpatrick'
self.n_samples = None
self.bma = False
self.prior_setup = None
self.sequential = True
self.experimental = False
@property
def star(self):
"""Star to fit for."""
return self._star
@star.setter
def star(self, star):
self._star = star
@property
def setup(self):
"""Set up options."""
return self._setup
@setup.setter
def setup(self, setup):
err_msg = 'The setup has to contain at least the fitting engine'
err_msg += f', multinest or dynesty.\nThe setup was {setup}'
if len(setup) < 1:
InputError(err_msg).__raise__()
self._setup = setup
self._engine = setup[0]
defaults = False
if len(setup) == 1:
defaults = True
if self._engine == 'multinest':
if defaults:
self._nlive = 500
self._dlogz = 0.5
else:
self._nlive = setup[1]
self._dlogz = setup[2]
if self._engine == 'dynesty':
if defaults:
self._nlive = 500
self._dlogz = 0.5
self._bound = 'multi'
self._sample = 'rwalk'
self._threads = 1
self._dynamic = False
else:
self._nlive = setup[1]
self._dlogz = setup[2]
self._bound = setup[3]
self._sample = setup[4]
self._threads = setup[5]
self._dynamic = setup[6]
@property
def norm(self):
"""Bool to decide if a normalization constant will be fitted.
Set as True to not fit for radius and distance and fit for a
normalization constant. After the fit a radius is calculated using
the Gaia parallax.
"""
return self._norm
@norm.setter
def norm(self, norm):
if type(norm) is not bool:
InputError('norm must be True or False.').__raise__()
self._norm = norm
@property
def grid(self):
"""Model grid selected."""
return self._grid
@grid.setter
def grid(self, grid):
assert type(grid) == str
self._grid = grid
if grid.lower() == 'phoenix':
with open(gridsdir + '/Phoenixv2_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
if grid.lower() == 'btsettl':
with open(gridsdir + '/BTSettl_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
if grid.lower() == 'btnextgen':
with open(gridsdir + '/BTNextGen_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
if grid.lower() == 'btcond':
with open(gridsdir + '/BTCond_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
if grid.lower() == 'ck04':
with open(gridsdir + '/CK04_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
if grid.lower() == 'kurucz':
with open(gridsdir + '/Kurucz_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
if grid.lower() == 'coelho':
with open(gridsdir + '/Coelho_DF.pkl', 'rb') as intp:
self._interpolator = DFInterpolator(pd.read_pickle(intp))
@property
def bma(self):
"""Bayesian Model Averaging (BMA).
Set to True if BMA is wanted. This loads every model grid interpolator
and fits an SED to all of them, so the runtime will be slower!
"""
return self._bma
@bma.setter
def bma(self, bma):
self._bma = bma if bma_flag else False
@property
def models(self):
"""Models to be used in BMA."""
return self._bma_models
@models.setter
def models(self, mods):
self._bma_models = mods
@property
def sequential(self):
"""Set to True to make BMA sequentially instead of parallel."""
return self._sequential
@sequential.setter
def sequential(self, sequential):
self._sequential = sequential
@property
def n_samples(self):
"""Set number of samples for BMA."""
return self._nsamp
@n_samples.setter
def n_samples(self, nsamp):
self._nsamp = nsamp
@property
def verbose(self):
"""Program verbosity. Default is True."""
return self._verbose
@verbose.setter
def verbose(self, verbose):
if type(verbose) is not bool:
InputError('Verbose must be True or False.').__raise__()
self._verbose = verbose
@property
def out_folder(self):
"""Output folder.
If none is provided the default will be the starname.
"""
return self._out_folder
@out_folder.setter
def out_folder(self, out_folder):
if type(out_folder) is not str and out_folder is not None:
err_msg = 'Output folder must be an address or None.'
InputError(err_msg).__raise__()
self._out_folder = out_folder
@property
def av_law(self):
"""Select extinction law."""
return self._av_law
@av_law.setter
def av_law(self, law):
laws = [
'cardelli',
'odonnell',
'calzetti',
'fitzpatrick'
]
law = law.lower()
if law not in laws:
err_msg = f'Extinction law {law} not recognized.'
err_msg += 'Available extinction laws are: `cardelli`, `odonnell`'
err_msg += ', `calzetti`, and `fitzpatrick`'
InputError(err_msg).__raise__()
law_f = None
if law == laws[0]:
law_f = extinction.ccm89
if law == laws[1]:
law_f = extinction.odonnell94
if law == laws[2]:
law_f = extinction.calzetti00
if law == laws[3]:
law_f = extinction.fitzpatrick99
self._av_law = law_f
def initialize(self):
"""Initialize the fitter.
To be run only after every input is added.
This function calculates the number of dimensions, runs the prior
creation, creates output directory, initializes coordinators and sets
up global variables.
"""
global prior_dict, coordinator, fixed, order, star, use_norm, av_law
self.start = time.time()
err_msg = 'No star is detected. Please create an instance of Star.'
if self.star is None:
er = InputError(err_msg)
er.log(self.out + '/output.log')
er.__raise__()
star = self.star
if not self._bma:
global interpolator
interpolator = self._interpolator
use_norm = self.norm
# Extinction law
av_law = self._av_law
# Declare order of parameters.
if not self.norm:
order = np.array(
[
'teff', 'logg', 'z',
'dist', 'rad', 'Av'
]
)
else:
order = np.array(['teff', 'logg', 'z', 'norm', 'Av'])
# Create output directory
if self.out_folder is None:
self.out_folder = self.star.starname + '/'
create_dir(self.out_folder)
self.star.save_mags(self.out_folder + '/')
# Parameter coordination.
# Order for the parameters are:
# teff, logg, z, dist, rad, Av, noise
# or
# teff, logg, z, norm, Av, noise
npars = 6 if not self.norm else 5
npars += self.star.used_filters.sum()
npars = int(npars)
self.coordinator = np.zeros(npars) # 1 for fixed params
self.fixed = np.zeros(npars)
coordinator = self.coordinator
fixed = self.fixed
# Setup priors.
self.default_priors = self._default_priors()
self.create_priors_from_setup()
prior_dict = self.priors
# Get dimensions.
self.ndim = self.get_ndim()
# warnings
if len(self._setup) == 1:
print('USING DEFAULT SETUP VALUES.')
# BMA settings
# if BMA is used, load all interpolators requested.
if self._bma:
if self.n_samples is None:
self.n_samples = 'max'
if self.star.offline:
if self.star.temp is None:
self.star.temp = 4001
off_msg = 'Offline mode assumes that the stellar'
off_msg += ' temperature is greater than 4000 K'
off_msg += '. If you believe this is not the case then please '
off_msg += 'add a temperature to the Star constructor. '
off_msg += f'The input temperature is {self.star.temp}'
print(colored(off_msg, 'yellow'))
for mod in self._bma_models:
# We'll assume that if ARIADNE is running in offline mode
# Then the star will have > 4000 K
if (mod.lower() in ['btcond', 'btnextgen'] and
self.star.temp > 4000) or \
(mod.lower() in ['ck04', 'kurucz'] and
self.star.temp < 4000) or \
(mod.lower() == 'coelho' and self.star.temp < 3500):
continue
df = self.load_interpolator(mod.lower())
self._interpolators.append(df)
self._grids.append(mod)
thr = self._threads if self._sequential else len(
self._interpolators)
else:
thr = self._threads
en = 'Bayesian Model Averaging' if self._bma else self._engine
display_routine(en, self._nlive, self._dlogz, self.ndim, self._bound,
self._sample, thr, self._dynamic)
def get_ndim(self):
"""Calculate number of dimensions."""
ndim = 6 if not self.norm else 5
ndim += self.star.used_filters.sum()
ndim -= self.coordinator.sum()
return int(ndim)
def _default_priors(self):
global order
defaults = dict()
# Logg prior setup.
if self.star.get_logg:
defaults['logg'] = st.norm(
loc=self.star.logg, scale=self.star.logg_e)
else:
# with open(priorsdir + '/logg_ppf.pkl', 'rb') as jar:
# defaults['logg'] = pickle.load(jar)
defaults['logg'] = st.uniform(loc=3.5, scale=2.5)
# Teff prior from RAVE
with open(priorsdir + '/teff_ppf.pkl', 'rb') as jar:
defaults['teff'] = pickle.load(jar)
# [Fe/H] prior setup.
defaults['z'] = st.norm(loc=-0.125, scale=0.234)
# Distance prior setup.
if not self._norm:
if self.star.dist != -1:
defaults['dist'] = st.truncnorm(
a=0, b=1e100, loc=self.star.dist, scale=3 * self.star.dist_e
)
else:
defaults['dist'] = st.uniform(loc=1, scale=3000)
# Radius prior setup.
defaults['rad'] = st.uniform(loc=0.05, scale=100)
# Normalization prior setup.
else:
# up = 1 / 1e-30
# defaults['norm'] = st.truncnorm(a=0, b=up, loc=1e-20, scale=1e-10)
defaults['norm'] = st.uniform(loc=0, scale=1e-20)
# Extinction prior setup.
if self.star.Av == 0.:
av_idx = 4 if self._norm else 5
self.coordinator[av_idx] = 1
self.fixed[av_idx] = 0
defaults['Av'] = None
else:
if self.star.Av_e is None:
defaults['Av'] = st.uniform(loc=0, scale=self.star.Av)
else:
mu = self.star.Av
sig = self.star.Av_e
low = 0
up = 100
b, a = (up - mu) / sig, (low - mu) / sig
defaults['Av'] = st.truncnorm(loc=mu, scale=sig, a=a, b=b)
# Noise model prior setup.
mask = self.star.filter_mask
flxs = self.star.flux[mask]
errs = self.star.flux_er[mask]
for filt, flx, flx_e in zip(self.star.filter_names[mask], flxs, errs):
p_ = get_noise_name(filt) + '_noise'
mu = 0
sigma = flx_e * 10
b = (1 - flx) / flx_e
defaults[p_] = st.truncnorm(loc=mu, scale=sigma, a=0, b=b)
# defaults[p_] = st.uniform(loc=0, scale=5)
order = np.append(order, p_)
return defaults
def create_priors_from_setup(self):
"""Create priors from the manual setup."""
prior_dict = dict()
keys = self.prior_setup.keys()
noise = []
mask = self.star.filter_mask
flxs = self.star.flux[mask]
errs = self.star.flux_er[mask]
for filt, flx, flx_e in zip(self.star.filter_names[mask], flxs, errs):
p_ = get_noise_name(filt) + '_noise'
noise.append(p_)
prior_out = 'Parameter\tPrior\tValues\n'
if 'norm' in keys and ('rad' in keys or 'dist' in keys):
er = PriorError('rad or dist', 1)
er.log(self.out_folder + '/output.log')
er.__raise__()
for k in keys:
if type(self.prior_setup[k]) == str:
if self.prior_setup[k] == 'default':
prior_dict[k] = self.default_priors[k]
prior_out += k + '\tdefault\n'
if self.prior_setup[k].lower() == 'rave':
# RAVE prior only available for teff and logg. It's already
# the default for [Fe/H]
if k == 'logg' or k == 'teff':
if k == 'teff':
PriorError('teff', 2).warn()
with open(priorsdir + '/teff_ppf.pkl', 'rb') as jar:
prior_dict[k] = pickle.load(jar)
prior_out += k + '\tRAVE\n'
else:
prior = self.prior_setup[k][0]
if prior == 'fixed':
value = self.prior_setup[k][1]
idx = np.where(k == order)[0]
self.coordinator[idx] = 1
self.fixed[idx] = value
prior_out += k + '\tfixed\t{}\n'.format(value)
if prior == 'normal':
mu = self.prior_setup[k][1]
sig = self.prior_setup[k][2]
prior_dict[k] = st.norm(loc=mu, scale=sig)
prior_out += k + '\tnormal\t{}\t{}\n'.format(mu, sig)
if prior == 'truncnorm':
mu = self.prior_setup[k][1]
sig = self.prior_setup[k][2]
low = self.prior_setup[k][3]
up = self.prior_setup[k][4]
b, a = (up - mu) / sig, (low - mu) / sig
prior_dict[k] = st.truncnorm(a=a, b=b, loc=mu, scale=sig)
prior_out += k
prior_out += '\ttruncatednormal\t{}\t{}\t{}\t{}\n'.format(
mu, sig, low, up)
if prior == 'uniform':
low = self.prior_setup[k][1]
up = self.prior_setup[k][2]
prior_dict[k] = st.uniform(loc=low, scale=up - low)
prior_out += k + '\tuniform\t{}\t{}\n'.format(low, up)
for par in noise:
prior_dict[par] = self.default_priors[par]
ff = open(self.out_folder + '/prior.dat', 'w')
ff.write(prior_out)
ff.close()
del ff
self.priors = prior_dict
pass
def fit(self):
"""Run fitting routine."""
if self._engine == 'multinest':
self.fit_multinest()
else:
self.fit_dynesty()
elapsed_time = execution_time(self.start)
end(self.coordinator, elapsed_time,
self.out_folder, self._engine, self.norm, )
pass
def fit_bma(self):
"""Perform the fit with different models and the average the output.
Only works with dynesty.
"""
if len(self.star.filter_names[self.star.filter_mask]) <= 5:
print(colored('\t\t\tNOT ENOUGH POINTS TO MAKE THE FIT! !', 'red'))
return
global interpolator
for intp, gr in zip(self._interpolators, self._grids):
interpolator = intp
self.grid = gr
out_file = self.out_folder + '/' + gr + '_out.pkl'
print('\t\t\tFITTING MODEL : ' + gr)
try:
self.fit_dynesty(out_file=out_file)
except ValueError as e:
dump_out = self.out_folder + '/' + gr + '_DUMP.pkl'
pickle.dump(self.sampler.results, open(dump_out, 'wb'))
DynestyError(dump_out, gr, e).__raise__()
continue
# Now that the fitting finished, read the outputs and average
# the posteriors
outs = []
for g in self._grids:
in_folder = f'{self.out_folder}/{g}_out.pkl'
outs.append(in_folder)
# with open(in_folder, 'rb') as out:
# outs.append(pickle.load(out))
c = np.random.choice(self.colors)
avgd = self.bayesian_model_average(outs, self._grids, self._norm,
self.n_samples, c)
self.save_bma(avgd)
elapsed_time = execution_time(self.start)
end(self.coordinator, elapsed_time, self.out_folder,
'Bayesian Model Averaging', self.norm)
pass
def _bma_dynesty(self, intp, grid):
global interpolator
interpolator = intp
# Parallel parallelized routine experiment
if self.experimental:
if self._dynamic:
with Pool(self._threads) as executor:
sampler = dynesty.DynamicNestedSampler(
dynesty_loglike_bma, pt_dynesty, self.ndim,
bound=self._bound, sample=self._sample, pool=executor,
queue_size=self._threads, logl_args=([intp])
)
sampler.run_nested(dlogz_init=self._dlogz,
nlive_batch=self._nlive,
wt_kwargs={'pfrac': .95})
else:
with Pool(self._threads) as executor:
sampler = dynesty.NestedSampler(
dynesty_loglike_bma, pt_dynesty, self.ndim,
nlive=self._nlive, bound=self._bound,
sample=self._sample, pool=executor,
queue_size=self._threads, logl_args=([intp])
)
sampler.run_nested(dlogz=self._dlogz)
elif self._dynamic:
sampler = dynesty.DynamicNestedSampler(
dynesty_loglike_bma, pt_dynesty, self.ndim,
bound=self._bound, sample=self._sample, logl_args=([intp])
)
sampler.run_nested(dlogz_init=self._dlogz,
nlive_init=self._nlive,
wt_kwargs={'pfrac': .95})
else:
try:
self.sampler = dynesty.NestedSampler(
dynesty_loglike_bma, pt_dynesty, self.ndim,
nlive=self._nlive, bound=self._bound,
sample=self._sample,
logl_args=([intp])
)
self.sampler.run_nested(dlogz=self._dlogz)
except Error:
dump_out = self.out_folder + '/' + grid + '_DUMP.pkl'
pickle.dump(self.sampler.results, open(dump_out, 'wb'))
er = DynestyError(dump_out, grid)
er.log(self.out + '/output.log')
er.__raise__()
results = self.sampler.results
out_file = self.out_folder + '/' + grid + '_out.pkl'
self.save(out_file, results=results)
pass
def fit_multinest(self, out_file=None):
"""Run MultiNest."""
# Set up some globals
global mask, flux, flux_er, filts, wave
mask = star.filter_mask
flux = star.flux[mask]
flux_er = star.flux_er[mask]
filts = star.filter_names[mask]
wave = star.wave[mask]
path = self.out_folder + '/mnest/'
create_dir(path) # Create multinest path.
pymultinest.run(
multinest_log_like, pt_multinest, self.ndim,
n_params=self.ndim,
sampling_efficiency=0.8,
evidence_tolerance=self._dlogz,
n_live_points=self._nlive,
outputfiles_basename=path + 'chains',
max_modes=100,
verbose=self.verbose,
resume=False
)
if out_file is None:
out_file = f'{self.out_folder}/{self._grid}_out.pkl'
self.save(out_file=out_file)
pass
def fit_dynesty(self, out_file=None):
"""Run dynesty."""
# Set up some globals
global mask, flux, flux_er, filts, wave
mask = star.filter_mask
flux = star.flux[mask]
flux_er = star.flux_er[mask]
filts = star.filter_names[mask]
wave = star.wave[mask]
if self._dynamic:
if self._threads > 1:
with Pool(self._threads) as executor:
self.sampler = dynesty.DynamicNestedSampler(
dynesty_log_like, pt_dynesty, self.ndim,
bound=self._bound, sample=self._sample,
pool=executor, walks=25,
queue_size=self._threads - 1
)
self.sampler.run_nested(dlogz_init=self._dlogz,
nlive_init=self._nlive,
wt_kwargs={'pfrac': 1})
else:
self.sampler = dynesty.DynamicNestedSampler(
dynesty_log_like, pt_dynesty, self.ndim, walks=25,
bound=self._bound, sample=self._sample
)
self.sampler.run_nested(dlogz_init=self._dlogz,
nlive_init=self._nlive,
wt_kwargs={'pfrac': 1})
else:
if self._threads > 1:
with Pool(self._threads) as executor:
self.sampler = dynesty.NestedSampler(
dynesty_log_like, pt_dynesty, self.ndim,
nlive=self._nlive, bound=self._bound,
sample=self._sample,
pool=executor, walks=25,
queue_size=self._threads - 1,
)
self.sampler.run_nested(dlogz=self._dlogz)
else:
self.sampler = dynesty.NestedSampler(
dynesty_log_like, pt_dynesty, self.ndim, walks=25,
nlive=self._nlive, bound=self._bound,
sample=self._sample
)
self.sampler.run_nested(dlogz=self._dlogz)
results = self.sampler.results
if out_file is None:
out_file = f'{self.out_folder}/{self._grid}_out.pkl'
self.save(out_file, results=results)
pass
def save(self, out_file, results=None):
"""Save multinest/dynesty output and relevant information.
Saves a dictionary as a pickle file. The dictionary contains the
following:
lnZ: The global evidence.
lnZerr: The global evidence error.
posterior_samples: A dictionary containing the samples of each
parameter (even if it's fixed), the evidence,
log likelihood, the prior, and the posterior
for each set of sampled parameters.
fixed: An array with the fixed parameter values.
coordinator : An array with the status of each parameter (1 for fixed
0 for free)
best_fit: The best fit is chosen to be the median of each sample.
It also includes the log likelihood of the best fit.
star: The Star object containing the information of the star (name,
magnitudes, fluxes, coordinates, etc)
engine: The fitting engine used (i.e. MultiNest or Dynesty)
Also creates a log file with the best fit parameters and 1 sigma
error bars.
"""
out = dict()
logdat = '#Parameter\tmedian\tupper\tlower\t3sig_CI\n'
log_out = self.out_folder + '/' + 'best_fit.dat'
if self._engine == 'multinest':
lnz, lnzer, posterior_samples = self.multinest_results(
self.out_folder,
self.ndim
)
else:
lnz, lnzer, posterior_samples = self.dynesty_results(results)
mask = self.star.filter_mask
# Save global evidence
if self._engine == 'dynesty':
out['dynesty'] = results
out['global_lnZ'] = lnz
out['global_lnZerr'] = lnzer
# Create raw samples holder
out['posterior_samples'] = dict()
j = 0
k = 0 # filter counter
for i, param in enumerate(order):
if not self.coordinator[i]:
samples = posterior_samples[:, j]
if 'noise' in param:
filt = self.star.filter_names[mask][k]
flx = self.star.flux[mask][k]
_, samples = flux_to_mag(flx, samples, filt)
k += 1
out['posterior_samples'][param] = samples
j += 1
else:
out['posterior_samples'][param] = self.fixed[i]
# Save loglike, priors and posteriors.
out['posterior_samples']['loglike'] = np.zeros(
posterior_samples.shape[0]
)
# If normalization constant was fitted, create a distribution of radii
# only if there's a distance available.
if use_norm and star.dist != -1:
rad = self._get_rad(
out['posterior_samples']['norm'], star.dist, star.dist_e
)
out['posterior_samples']['rad'] = rad
# Create a distribution of masses.
logg_samp = out['posterior_samples']['logg']
rad_samp = out['posterior_samples']['rad']
mass_samp = self._get_mass(logg_samp, rad_samp)
out['posterior_samples']['grav_mass'] = mass_samp
# Create a distribution of luminosities.
teff_samp = out['posterior_samples']['teff']
lum_samp = self._get_lum(teff_samp, rad_samp)
out['posterior_samples']['lum'] = lum_samp
# Create a distribution of angular diameters.
if not use_norm:
dist_samp = out['posterior_samples']['dist']
ad_samp = self._get_angular_diameter(rad_samp, dist_samp)
out['posterior_samples']['AD'] = ad_samp
for i in range(posterior_samples.shape[0]):
theta = build_params(
posterior_samples[i, :], flux, flux_er, filts, coordinator,
fixed, self.norm)
out['posterior_samples']['loglike'][i] = log_likelihood(
theta, flux, flux_er, wave, filts, interpolator, self.norm,
av_law)
# Best fit
# The logic is as follows:
# Calculate KDE for each marginalized posterior distributions
# Find peak
# peak is best fit.
# do only if not bma
if not self.bma:
out['best_fit'] = dict()
out['uncertainties'] = dict()
out['confidence_interval'] = dict()
best_theta = np.zeros(order.shape[0])
for i, param in enumerate(order):
if not self.coordinator[i]:
if 'noise' in param:
continue
samp = out['posterior_samples'][param]
if param == 'z':
logdat = out_filler(samp, logdat, param, '[Fe/H]', out)
elif param == 'norm':
logdat = out_filler(samp, logdat, param, '(R/D)^2',
out, fmt='e')
if star.dist != 1:
logdat = out_filler(
out['posterior_samples']['rad'], logdat, 'rad',
'R', out
)
else:
logdat = out_filler(samp, logdat, param, param, out)
else:
logdat = out_filler(
0, logdat, param, out, fixed=self.fixed[i]
)
best_theta[i] = out['best_fit'][param]
# Add derived mass to best fit dictionary.
samp = out['posterior_samples']['grav_mass']
logdat = out_filler(
samp, logdat, 'grav_mass', 'grav_mass', out
)
# Add derived luminosity to best fit dictionary.
samp = out['posterior_samples']['lum']
logdat = out_filler(samp, logdat, 'lum', 'lum', out)
# Add derived angular diameter to best fit dictionary.
if not use_norm:
samp = out['posterior_samples']['AD']
logdat = out_filler(samp, logdat, 'AD', 'AD', out)
for i, param in enumerate(order):
if not self.coordinator[i]:
if 'noise' not in param:
continue
samp = out['posterior_samples'][param]
logdat = out_filler(samp, logdat, param,
param, out, fmt='f')
# Fill in best loglike, prior and posterior.
out['best_fit']['loglike'] = log_likelihood(
best_theta, flux, flux_er, wave,
filts, interpolator, self.norm, av_law
)
# Spectral type
# Load Mamajek spt table
mamajek_spt = np.loadtxt(
filesdir + '/mamajek_spt.dat', dtype=str, usecols=[0])
mamajek_temp = np.loadtxt(
filesdir + '/mamajek_spt.dat', usecols=[1])
# Find spt
spt_idx = np.argmin(abs(mamajek_temp - out['best_fit']['teff']))
spt = mamajek_spt[spt_idx]
out['spectral_type'] = spt
# Utilities for plotting.
out['fixed'] = self.fixed
out['coordinator'] = self.coordinator
out['star'] = self.star
out['engine'] = self._engine
out['norm'] = self.norm
out['model_grid'] = self.grid
out['av_law'] = av_law
if not self.bma:
with open(log_out, 'w') as logfile:
logfile.write(logdat)
pickle.dump(out, open(out_file, 'wb'))
pass
def save_bma(self, avgd):
"""Save BMA output and relevant information.
Saves a dictionary as a pickle file. The dictionary contains the
following:
lnZ : The global evidences.
posterior_samples : A dictionary containing the samples of each
parameter (even if it's fixed), the evidence,
log likelihood, the prior, and the posterior
for each set of sampled parameters.
fixed : An array with the fixed parameter values.
coordinator : An array with the status of each parameter (1 for fixed
0 for free)
best_fit : The best fit is chosen to be the median of each sample.
It also includes the log likelihood of the best fit.
star : The Star object containing the information of the star (name,
magnitudes, fluxes, coordinates, etc)
Also creates a log file with the best fit parameters, 1 sigma
error bars and 3 sigma CIs.
"""
out = dict()
logdat_samples = '#Parameter\tmedian\tupper\tlower\t3sig_low\t3sig_up\n'
logdat_average = '#Parameter\tmedian\tupper\tlower\t3sig_low\t3sig_up\n'
log_out_samples = f'{self.out_folder}/best_fit_sample.dat'
log_out_average = f'{self.out_folder}/best_fit_average.dat'
prob_out = f'{self.out_folder}/model_probabilities.dat'
synth_out = f'{self.out_folder}/synthetic_fluxes.dat'
# Save global evidence of each model.
out['lnZ'] = avgd['evidences']
# Save original samples.
out['originals'] = avgd['originals']
# Save weights.
out['weights'] = avgd['weights']
# Create raw samples holder
out['weighted_samples'] = dict()
out['weighted_average'] = dict()
j = 0
for i, par in enumerate(order):
if not self.coordinator[i]:
out['weighted_samples'][par] = avgd['weighted_samples'][par]
out['weighted_average'][par] = avgd['weighted_average'][par]
j += 1
else:
out['weighted_samples'][par] = self.fixed[i]
out['weighted_average'][par] = self.fixed[i]
# If normalization constant was fitted, create a distribution of radii.
if use_norm and star.dist != -1:
rad_sampled = self._get_rad(
out['weighted_samples']['norm'], star.dist, star.dist_e
)
rad_averageed = self._get_rad(
out['weighted_average']['norm'], star.dist, star.dist_e
)
out['weighted_samples']['rad'] = rad_sampled
out['weighted_average']['rad'] = rad_averageed