forked from ashleychontos/pySYD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSYD.py
1451 lines (1311 loc) · 68.9 KB
/
SYD.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
import argparse
import glob
import multiprocessing as mp
import os
import pdb
import subprocess
import time as clock
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from astropy.convolution import (
Box1DKernel, Gaussian1DKernel, convolve, convolve_fft
)
from astropy.io import ascii
from astropy.stats import mad_std
from matplotlib.colors import LogNorm, Normalize, PowerNorm
from matplotlib.ticker import (
FormatStrFormatter, MaxNLocator, MultipleLocator, ScalarFormatter
)
from scipy import interpolate
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.optimize import curve_fit
from scipy.stats import chisquare
from functions import *
def main(args, parallel=False, nthreads=None):
"""Runs the SYD-PYpline.
Parameters
----------
args : argparse.Namespace
the command line arguments
parallel : bool
if true will run the pipeline on multiple threads. Default value is `False`. TODO: Currently not supported!
nthreads : Optional[int]
the number of threads to run the pipeline on if parallel processing is enabled. Default value is `None`.
"""
args = get_info(args)
set_plot_params()
for target in args.params['todo']:
args.target = target
Target(args)
if args.verbose:
print('Combining results into single csv file.')
print()
# Concatenates output into a two files
subprocess.call(['python', 'scrape_output.py'], shell=True)
class Target:
"""A pipeline target. Initialisation will cause the pipeline to process the target.
Attributes
----------
target : int
the target ID
params : dict
the pipeline parameters
findex : dict
the parameters of the find excess routine
fitbg : dict
the parameters of the fit background routine
verbose : bool
if true, verbosity will increase
show_plots : bool
if true, plots will be shown
ignore : bool
if true, multiple targets will not automatically turn set `verbose` and `show_plots` to `False`
keplercorr : bool
if true will correct Kepler artefacts in the power spectrum
filter : float
the box filter width [muHz] for the power spectrum
Parameters
----------
args : argparse.Namespace
the parsed and updated command line arguments
Methods
-------
TODO: Add methods
"""
def __init__(self, args):
self.target = args.target
self.params = args.params
self.findex = args.findex
self.fitbg = args.fitbg
self.verbose = args.verbose
self.show_plots = args.show
self.ignore = args.ignore
self.keplercorr = args.keplercorr
self.filter = args.filter
# Turn off verbosity and plot displays if there are multiple targets and ignore is `False`
if len(self.params['todo']) > 1 and not self.ignore:
self.verbose = False
self.show_plots = False
# Run the pipeline
self.run_syd()
def run_syd(self):
"""Load target data and run the pipeline routines."""
# Load target data
if self.load_data():
# Run the find excess routine
if self.findex['do']:
self.find_excess()
# Run the fit background routine
if self.fitbg['do']:
self.fit_background()
##########################################################################################
# #
# READING/WRITING TO/FROM FILES #
# #
##########################################################################################
def load_data(self):
"""Loads light curve and power spectrum data for the current target.
Returns
-------
success : bool
will return `True` if both the light curve and power spectrum data files exist otherwise `False`
"""
# Now done at beginning to make sure it only does this one per target
if glob.glob(self.params['path']+'%d_*' % self.target) != []:
# Load light curve
if not os.path.exists(self.params['path']+'%d_LC.txt' % self.target):
if self.verbose:
print('Error: %s%d_LC.txt not found' % (self.params['path'], self.target))
return False
else:
self.get_file(self.params['path'] + '%d_LC.txt' % self.target)
self.time = np.copy(self.x)
self.flux = np.copy(self.y)
self.cadence = int(np.nanmedian(np.diff(self.time)*24.0*60.0*60.0))
if self.cadence/60.0 < 10.0:
self.short_cadence = True
else:
self.short_cadence = False
self.nyquist = 10**6/(2.0*self.cadence)
if self.verbose:
print('# LIGHT CURVE: %d lines of data read' % len(self.time))
if self.short_cadence:
self.fitbg['smooth_ps'] = 2.5
# Load power spectrum
if not os.path.exists(self.params['path'] + '%d_PS.txt' % self.target):
if self.verbose:
print('Error: %s%d_PS.txt not found' % (self.params['path'], self.target))
return False
else:
self.get_file(self.params['path'] + '%d_PS.txt' % self.target)
self.frequency = np.copy(self.x)
self.power = np.copy(self.y)
if self.keplercorr:
self.remove_artefact(self.frequency, self.power)
self.power = np.copy(self.y)
if self.verbose:
print('## Removing Kepler artefacts ##')
if self.verbose:
print('# POWER SPECTRUM: %d lines of data read' % len(self.frequency))
self.oversample = int(round((1./((max(self.time)-min(self.time))*0.0864))/(self.frequency[1]-self.frequency[0])))
self.resolution = (self.frequency[1]-self.frequency[0])*self.oversample
if self.verbose:
print('-------------------------------------------------')
print('Target: %d' % self.target)
if self.oversample == 1:
print('critically sampled')
else:
print('oversampled by a factor of %d' % self.oversample)
print('time series cadence: %d seconds' % self.cadence)
print('power spectrum resolution: %.6f muHz' % self.resolution)
print('-------------------------------------------------')
# Create critically sampled PS
if self.oversample != 1:
self.freq = np.copy(self.frequency)
self.pow = np.copy(self.power)
self.frequency = np.array(self.frequency[self.oversample-1::self.oversample])
self.power = np.array(self.power[self.oversample-1::self.oversample])
else:
self.freq = np.copy(self.frequency)
self.pow = np.copy(self.power)
self.frequency = np.copy(self.frequency)
self.power = np.copy(self.power)
if hasattr(self, 'findex'):
if self.findex['do']:
# Make a mask using the given frequency bounds for the find excess routine
mask = np.ones_like(self.freq, dtype=bool)
if self.params[self.target]['lowerx'] is not None:
mask *= np.ma.getmask(np.ma.masked_greater_equal(self.freq, self.params[self.target]['lowerx']))
else:
mask *= np.ma.getmask(np.ma.masked_greater_equal(self.freq, self.findex['lower']))
if self.params[self.target]['upperx'] is not None:
mask *= np.ma.getmask(np.ma.masked_less_equal(self.freq, self.params[self.target]['upperx']))
else:
mask *= np.ma.getmask(np.ma.masked_less_equal(self.freq, self.findex['upper']))
self.freq = self.freq[mask]
self.pow = self.pow[mask]
return True
else:
print('Error: data not found for target %d' % self.target)
return False
def get_file(self, path):
"""Load either a light curve or a power spectrum data file and saves the data into `self.x` and `self.y`.
Parameters
----------
path : str
the file path of the data file
"""
f = open(path, "r")
lines = f.readlines()
f.close()
# Set values
self.x = np.array([float(line.strip().split()[0]) for line in lines])
self.y = np.array([float(line.strip().split()[1]) for line in lines])
def set_seed(self):
seed = list(np.random.randint(1,high=10000000,size=1))
df = pd.read_csv('Files/star_info.csv')
targets = df.targets.values.tolist()
idx = targets.index(self.target)
df.loc[idx,'seed'] = int(seed[0])
self.params[self.target]['seed'] = seed[0]
df.to_csv('Files/star_info.csv',index=False)
def save(self):
"""Save results of fit background routine"""
df = pd.DataFrame(self.final_pars)
self.df = df.copy()
if self.fitbg['num_mc_iter'] > 1:
for column in self.df.columns.values.tolist():
self.df['%s_err' % column] = np.array([mad_std(self.df[column].values)]*len(self.df))
new_df = pd.DataFrame(columns=['parameter', 'value', 'uncertainty'])
for c, col in enumerate(df.columns.values.tolist()):
new_df.loc[c, 'parameter'] = col
new_df.loc[c, 'value'] = self.final_pars[col][0]
if self.fitbg['num_mc_iter'] > 1:
new_df.loc[c, 'uncertainty'] = mad_std(self.final_pars[col])
else:
new_df.loc[c, 'uncertainty'] = '--'
new_df.to_csv(self.params[self.target]['path']+'%d_globalpars.csv' % self.target, index=False)
if self.fitbg['samples']:
self.df.to_csv(self.params[self.target]['path']+'%d_globalpars_all.csv' % self.target, index=False)
def check(self):
"""Check if there is prior knowledge about numax as SYD needs this information to work well
(either from findex module or from star info csv).
Returns
-------
result : bool
will return `True` if there is prior value for numax otherwise `False`.
"""
if 'numax' not in self.params[self.target].keys():
print(
"""WARNING: Suggested use of this pipeline requires either
stellar properties to estimate a numax or running the entire
pipeline from scratch (i.e. find_excess) first to
statistically determine a starting point for nuMax."""
)
return False
else:
return True
def get_initial_guesses(self):
"""Get initial guesses for the granulation background."""
# Check whether output from findex module exists; if yes, let that override star info guesses
if glob.glob(self.params[self.target]['path'] + '%d_findex.csv' % self.target) != []:
df = pd.read_csv(self.params[self.target]['path']+'%d_findex.csv' % self.target)
for col in ['numax', 'dnu', 'snr']:
self.params[self.target][col] = df.loc[0, col]
# If no output from findex module exists, assume SNR is high enough to run the fit background routine
else:
self.params[self.target]['snr'] = 10.0
# Mask power spectrum for fitbg module based on estimated/fitted numax
mask = np.ones_like(self.frequency, dtype=bool)
if self.params[self.target]['lowerb'] is not None:
mask *= np.ma.getmask(np.ma.masked_greater_equal(self.frequency, self.params[self.target]['lowerb']))
if self.params[self.target]['upperb'] is not None:
mask *= np.ma.getmask(np.ma.masked_less_equal(self.frequency, self.params[self.target]['upperb']))
else:
mask *= np.ma.getmask(np.ma.masked_less_equal(self.frequency, self.nyquist))
else:
if self.params[self.target]['numax'] > 300.0:
mask = np.ma.getmask(np.ma.masked_inside(self.frequency, 100.0, self.nyquist))
else:
mask = np.ma.getmask(np.ma.masked_inside(self.frequency, 1.0, 500.0))
# if lower numax and short cadence data, adjust default smoothing filter from 2.5->1.0muHz
if self.params[self.target]['numax'] <= 500. and self.short_cadence:
self.fitbg['smooth_ps'] = 1.0
self.frequency = self.frequency[mask]
self.power = self.power[mask]
self.width = self.params['width_sun']*(self.params[self.target]['numax']/self.params['numax_sun'])
self.times = self.width/self.params[self.target]['dnu']
# Arbitrary snr cut for leaving region out of background fit, ***statistically validate later?
if self.fitbg['lower_numax'] is not None:
self.maxpower = [self.fitbg['lower_numax'], self.fitbg['upper_numax']]
else:
if self.params[self.target]['snr'] < 2.0:
self.maxpower = [
self.params[self.target]['numax'] - self.width/2.0,
self.params[self.target]['numax']+self.width/2.0
]
else:
self.maxpower = [
self.params[self.target]['numax'] - self.times*self.params[self.target]['dnu'],
self.params[self.target]['numax']+self.times*self.params[self.target]['dnu']
]
# Adjust the lower frequency limit given numax
if self.params[self.target]['numax'] > 300.0:
self.frequency = self.frequency[self.frequency > 100.0]
self.power = self.power[self.frequency > 100.0]
self.fitbg['lower'] = 100.0
# Use scaling relation from sun to get starting points
scale = self.params['numax_sun']/((self.maxpower[1] + self.maxpower[0])/2.0)
taus = np.array(self.params['tau_sun'])*scale
b = 2.0*np.pi*(taus*1e-6)
mnu = (1.0/taus)*1e5
self.b = b[mnu >= min(self.frequency)]
self.mnu = mnu[mnu >= min(self.frequency)]
self.nlaws = len(self.mnu)
self.mnu_orig = np.copy(self.mnu)
self.b_orig = np.copy(self.b)
def write_excess(self, results):
"""Save the results of the find excess routine into the save folder of the current target.
Parameters
----------
results : list
the results of the find excess routine
"""
variables = ['target', 'numax', 'dnu', 'snr']
save_path = self.params[self.target]['path'] + '%d_findex.csv' % self.target
ascii.write(np.array(results), save_path, names=variables, delimiter=',', overwrite=True)
##########################################################################################
# #
# [CRUDE] FIND POWER EXCESS ROUTINE #
# #
##########################################################################################
# TODOS
# 1) add in process to check the binning/crude bg fit and retry if desired
# 2) allow user to pick model instead of it picking the highest SNR
# 3) check if the gaussian is fully resolved
# 4) maybe change the part that guesses the offset (mean of entire frequency range - not just the beginning)
# ADDED
# 1) Ability to add more trials for numax determination
def find_excess(self):
"""
Automatically finds power excess due to solar-like oscillations using a
frequency resolved collapsed autocorrelation function.
"""
N = int(self.findex['n_trials'] + 3)
if N % 3 == 0:
self.nrows = (N-1)//3
else:
self.nrows = N//3
if self.findex['binning'] is not None:
bin_freq, bin_pow = bin_data(self.freq, self.pow, self.findex)
self.bin_freq = bin_freq
self.bin_pow = bin_pow
if self.verbose:
print('binned to %d datapoints' % len(self.bin_freq))
boxsize = int(np.ceil(float(self.findex['smooth_width'])/(bin_freq[1]-bin_freq[0])))
sp = convolve(bin_pow, Box1DKernel(boxsize))
smooth_freq = bin_freq[int(boxsize/2):-int(boxsize/2)]
smooth_pow = sp[int(boxsize/2):-int(boxsize/2)]
s = InterpolatedUnivariateSpline(smooth_freq, smooth_pow, k=1)
self.interp_pow = s(self.freq)
self.bgcorr_pow = self.pow/self.interp_pow
if not self.short_cadence:
boxes = np.logspace(np.log10(0.5), np.log10(25.), self.findex['n_trials'])*1.
else:
boxes = np.logspace(np.log10(50.), np.log10(500.), self.findex['n_trials'])*1.
results = []
self.md = []
self.cumsum = []
self.fit_numax = []
self.fit_gauss = []
self.fit_snr = []
self.fx = []
self.fy = []
for i, box in enumerate(boxes):
subset = np.ceil(box/self.resolution)
steps = np.ceil((box*self.findex['step'])/self.resolution)
cumsum = np.zeros_like(self.freq)
md = np.zeros_like(self.freq)
j = 0
start = 0
while True:
if (start+subset) > len(self.freq):
break
f = self.freq[int(start):int(start+subset)]
p = self.bgcorr_pow[int(start):int(start+subset)]
lag = np.arange(0.0, len(p))*self.resolution
auto = np.real(np.fft.fft(np.fft.ifft(p)*np.conj(np.fft.ifft(p))))
corr = np.absolute(auto-np.mean(auto))
cumsum[j] = np.sum(corr)
md[j] = np.mean(f)
start += steps
j += 1
self.md.append(md[~np.ma.getmask(np.ma.masked_values(cumsum, 0.0))])
cumsum = cumsum[~np.ma.getmask(np.ma.masked_values(cumsum, 0.0))] - min(cumsum[~np.ma.getmask(np.ma.masked_values(cumsum, 0.0))])
cumsum = list(cumsum/max(cumsum))
idx = cumsum.index(max(cumsum))
self.cumsum.append(np.array(cumsum))
self.fit_numax.append(self.md[i][idx])
try:
best_vars, _ = curve_fit(gaussian, self.md[i], self.cumsum[i], p0=[np.mean(self.cumsum[i]), 1.0-np.mean(self.cumsum[i]), self.md[i][idx], self.params['width_sun']*(self.md[i][idx]/self.params['numax_sun'])])
except Exception as _:
results.append([self.target, np.nan, np.nan, -np.inf])
else:
self.fx.append(np.linspace(min(md), max(md), 10000))
# self.fy.append(gaussian(self.fx[i], best_vars[0], best_vars[1], best_vars[2], best_vars[3]))
self.fy.append(gaussian(self.fx[i], *best_vars))
snr = max(self.fy[i])/best_vars[0]
if snr > 100.:
snr = 100.
self.fit_snr.append(snr)
self.fit_gauss.append(best_vars[2])
results.append([self.target, best_vars[2], delta_nu(best_vars[2]), snr])
if self.verbose:
print('power excess trial %d: numax = %.2f +/- %.2f' % (i+1, best_vars[2], np.absolute(best_vars[3])/2.0))
print('S/N: %.2f' % snr)
compare = [each[-1] for each in results]
best = compare.index(max(compare))
if self.verbose:
print('picking model %d' % (best+1))
self.write_excess(results[best])
self.plot_findex()
##########################################################################################
# #
# FIT BACKGROUND ROUTINE #
# #
##########################################################################################
def fit_background(self, result=''):
"""Perform a fit to the granulation background and measures the frequency of maximum power (numax),
the large frequency separation (dnu) and oscillation amplitude.
Parameters
----------
result : str
TODO: Currently unused
"""
# Will only run routine if there is a prior numax estimate
if self.check():
self.get_initial_guesses()
self.final_pars = {
'numax_smooth': [],
'amp_smooth': [],
'numax_gaussian': [],
'amp_gaussian': [],
'fwhm_gaussian': [],
'dnu': [],
'wn': []
}
# Sampling process
i = 0
while i < self.fitbg['num_mc_iter']:
self.i = i
if self.i == 0:
# Record original PS information for plotting
self.random_pow = np.copy(self.power)
bin_freq, bin_pow, bin_err = mean_smooth_ind(self.frequency, self.random_pow, self.fitbg['ind_width'])
if self.verbose:
print('-------------------------------------------------')
print('binned to %d data points' % len(bin_freq))
else:
# Randomize power spectrum to get uncertainty on measured values
self.random_pow = (np.random.chisquare(2, len(self.frequency))*self.power)/2.
bin_freq, bin_pow, bin_err = mean_smooth_ind(self.frequency, self.random_pow, self.fitbg['ind_width'])
self.bin_freq = bin_freq[~((bin_freq > self.maxpower[0]) & (bin_freq < self.maxpower[1]))]
self.bin_pow = bin_pow[~((bin_freq > self.maxpower[0]) & (bin_freq < self.maxpower[1]))]
self.bin_err = bin_err[~((bin_freq > self.maxpower[0]) & (bin_freq < self.maxpower[1]))]
# Estimate white noise level
self.get_white_noise()
# Exclude region with power excess and smooth to estimate red/white noise components
boxkernel = Box1DKernel(int(np.ceil(self.fitbg['box_filter']/self.resolution)))
self.params[self.target]['mask'] = (self.frequency >= self.maxpower[0]) & (self.frequency <= self.maxpower[1])
self.smooth_pow = convolve(self.random_pow[~self.params[self.target]['mask']], boxkernel)
# Temporary array for inputs into model optimization (changes with each iteration)
pars = np.zeros((self.nlaws*2 + 1))
# Estimate amplitude for each harvey component
for n, nu in enumerate(self.mnu):
diff = list(np.absolute(self.frequency - nu))
idx = diff.index(min(diff))
if idx < self.fitbg['n_rms']:
pars[2*n] = np.mean(self.smooth_pow[:self.fitbg['n_rms']])
elif (len(self.smooth_pow)-idx) < self.fitbg['n_rms']:
pars[2*n] = np.mean(self.smooth_pow[-self.fitbg['n_rms']:])
else:
pars[2*n] = np.mean(self.smooth_pow[idx-int(self.fitbg['n_rms']/2):idx+int(self.fitbg['n_rms']/2)])
pars[2*n+1] = self.b[n]
pars[-1] = self.noise
self.pars = pars
# Smooth power spectrum - ONLY for plotting purposes, not used in subsequent analyses
self.smooth_power = convolve(self.power, Box1DKernel(int(np.ceil(self.fitbg['box_filter']/self.resolution))))
# If optimization does not converge, the rest of the code will not run
if self.get_red_noise():
continue
# save final values for Harvey laws from model fit
for n in range(self.nlaws):
self.final_pars['a_%d' % (n+1)].append(self.pars[2*n])
self.final_pars['b_%d' % (n+1)].append(self.pars[2*n+1])
self.final_pars['wn'].append(self.pars[2*self.nlaws])
# Estimate numax by 1) smoothing power and 2) fitting Gaussian
self.get_numax_smooth()
if list(self.region_freq) != []:
self.get_numax_gaussian()
self.bg_corr = self.random_pow/harvey(self.frequency, self.pars, total=True)
# Optional smoothing of PS to remove fine structure before computing ACF
if self.fitbg['smooth_ps'] is not None:
boxkernel = Box1DKernel(int(np.ceil(self.fitbg['smooth_ps']/self.resolution)))
self.bg_corr_smooth = convolve(self.bg_corr, boxkernel)
else:
self.bg_corr_smooth = np.copy(self.bg_corr)
# Calculate ACF using ffts (default) and estimate large frequency separation
dnu = self.get_frequency_spacing()
self.final_pars['dnu'].append(dnu)
if self.i == 0:
self.get_ridges()
self.plot_fitbg()
i += 1
# Save results
self.save()
# Multiple iterations
if self.fitbg['num_mc_iter'] > 1:
# Plot results of Monte-Carlo sampling
self.plot_mc()
if self.verbose:
print('numax (smoothed): %.2f +/- %.2f muHz' % (self.final_pars['numax_smooth'][0], mad_std(self.final_pars['numax_smooth'])))
print('maxamp (smoothed): %.2f +/- %.2f ppm^2/muHz' % (self.final_pars['amp_smooth'][0], mad_std(self.final_pars['amp_smooth'])))
print('numax (gaussian): %.2f +/- %.2f muHz' % (self.final_pars['numax_gaussian'][0], mad_std(self.final_pars['numax_gaussian'])))
print('maxamp (gaussian): %.2f +/- %.2f ppm^2/muHz' % (self.final_pars['amp_gaussian'][0], mad_std(self.final_pars['amp_gaussian'])))
print('fwhm (gaussian): %.2f +/- %.2f muHz' % (self.final_pars['fwhm_gaussian'][0], mad_std(self.final_pars['fwhm_gaussian'])))
print('dnu: %.2f +/- %.2f muHz' % (self.final_pars['dnu'][0], mad_std(self.final_pars['dnu'])))
print('-------------------------------------------------')
print()
# Single iteration
else:
if self.verbose:
print('numax (smoothed): %.2f muHz' % (self.final_pars['numax_smooth'][0]))
print('maxamp (smoothed): %.2f ppm^2/muHz' % (self.final_pars['amp_smooth'][0]))
print('numax (gaussian): %.2f muHz' % (self.final_pars['numax_gaussian'][0]))
print('maxamp (gaussian): %.2f ppm^2/muHz' % (self.final_pars['amp_gaussian'][0]))
print('fwhm (gaussian): %.2f muHz' % (self.final_pars['fwhm_gaussian'][0]))
print('dnu: %.2f' % (self.final_pars['dnu'][0]))
print('-------------------------------------------------')
print()
##########################################################################################
# #
# SYD-RELATED FUNCTIONS #
# #
##########################################################################################
def remove_artefact(self, frequency, power, lc=29.4244*60*1e-6):
"""Removes SC artefacts in Kepler power spectra by replacing them with noise (using linear interpolation)
following an exponential distribution; known artefacts are:
1) 1./LC harmonics
2) unknown artefacts at high frequencies (>5000 muHz)
3) excess power between 250-400 muHz (in Q0 and Q3 data only??)
Parameters
----------
frequency : np.ndarray
the frequency of the power spectrum
power : np.ndarray
the power of the power spectrum
lc : float
TODO: Write description. Default value is `29.4244*60*1e-6`.
"""
if self.params[self.target]['seed'] is None:
self.set_seed()
f, a = self.frequency, self.power
oversample = int(round((1.0/((max(self.time)-min(self.time))*0.0864))/(self.frequency[1]-self.frequency[0])))
resolution = (self.frequency[1]-self.frequency[0])*oversample
# LC period in Msec -> 1/LC ~muHz
lcp = 1.0/lc
art = (1.0 + np.arange(14))*lcp
# Lower limit of the artefacts
un1 = [4530.0, 5011.0, 5097.0, 5575.0, 7020.0, 7440.0, 7864.0]
# Upper limit of the artefacts
un2 = [4534.0, 5020.0, 5099.0, 5585.0, 7030.0, 7450.0, 7867.0]
# Estimate white noise
noisefl = np.mean(a[(f >= max(f)-100.0) & (f <= max(f)-50.0)])
np.random.seed(int(self.params[self.target]['seed']))
# Routine 1: remove 1/LC artefacts by subtracting +/- 5 muHz given each artefact
for i in range(len(art)):
if art[i] < np.max(f):
use = np.where((f > art[i]-5.0*resolution) & (f < art[i]+5.0*resolution))[0]
if use[0] != -1:
a[use] = noisefl*np.random.chisquare(2, len(use))/2.0
np.random.seed(int(self.params[self.target]['seed']))
# Routine 2: remove artefacts as identified in un1 & un2
for i in range(0, len(un1)):
if un1[i] < np.max(f):
use = np.where((f > un1[i]) & (f < un2[i]))[0]
if use[0] != -1:
a[use] = noisefl*np.random.chisquare(2, len(use))/2.0
# Routine 3: remove two wider artefacts as identified in un1 & un2
un1 = [240.0, 500.0]
un2 = [380.0, 530.0]
np.random.seed(int(self.params[self.target]['seed']))
for i in range(0,len(un1)):
# un1[i] : freq where artefact starts
# un2[i] : freq where artefact ends
# un_lower : initial freq to start fitting routine (aka un1[i]-20)
# un_upper : final freq to end fitting routine (aka un2[i]+20)
flower, fupper = un1[i] - 20, un2[i] + 20
usenoise = np.where(((f >= flower) & (f <= un1[i])) |
((f >= un2[i]) & (f <= fupper)))[0]
# Coeffs for linear fit
m, b = np.polyfit(f[usenoise], a[usenoise], 1)
# Index of artefact frequencies (ie. 240-380 muHz)
use = np.where((f >= un1[i]) & (f <= un2[i]))[0]
# Fill artefact frequencies with noise
a[use] = (f[use]*m+b)*np.random.chisquare(2, len(use))/2.0
# Power spectrum with artefact frequencies filled in with noise
self.y = a
def get_white_noise(self):
"""Estimate white level by taking a mean over a section of the power spectrum."""
if self.nyquist < 400.0:
mask = (self.frequency > 200.0) & (self.frequency < 270.0)
self.noise = np.mean(self.random_pow[mask])
elif self.nyquist > 400.0 and self.nyquist < 5000.0:
mask = (self.frequency > 4000.0) & (self.frequency < 4167.)
self.noise = np.mean(self.random_pow[mask])
elif self.nyquist > 5000.0 and self.nyquist < 9000.0:
mask = (self.frequency > 8000.0) & (self.frequency < 8200.0)
self.noise = np.mean(self.random_pow[mask])
else:
mask = (self.frequency > (max(self.frequency) - 0.1*max(self.frequency))) & (self.frequency < max(self.frequency))
self.noise = np.mean(self.random_pow[mask])
def get_red_noise(
self,
names=['one', 'one', 'two', 'two', 'three', 'three', 'four', 'four', 'five', 'five', 'six', 'six'],
bounds=[],
reduced_chi2=[],
paras=[],
a=[]
):
"""Fits a Harvey model for the stellar granulation background for the power spectrum.
Parameters
----------
names : list
the Harvey components to use in the background model
bounds : list
the bounds on the Harvey parameters
reduced_chi2 : list
the reduced chi-squared statistic
paras : list
the Harvey model parameters
a : list
the amplitude of the individual Harvey components
Returns
-------
again : bool
will return `True` if fitting failed and the iteration must be repeated otherwise `False`.
"""
# Get best fit model
if self.i == 0:
reduced_chi2 = []
bounds = []
a = []
paras = []
for n in range(self.nlaws):
a.append(self.pars[2*n])
self.a_orig = np.array(a)
if self.verbose:
print('Comparing %d different models:' % (self.nlaws*2))
for law in range(self.nlaws):
bb = np.zeros((2, 2*(law+1)+1)).tolist()
for z in range(2*(law+1)):
bb[0][z] = -np.inf
bb[1][z] = np.inf
bb[0][-1] = 0.
bb[1][-1] = np.inf
bounds.append(tuple(bb))
dict1 = dict(zip(np.arange(2*self.nlaws), names[:2*self.nlaws]))
for t in range(2*self.nlaws):
if t % 2 == 0:
if self.verbose:
print('%d: %s harvey model w/ white noise free parameter' % (t+1, dict1[t]))
delta = 2*(self.nlaws-(t//2+1))
pams = list(self.pars[:(-delta-1)])
pams.append(self.pars[-1])
try:
pp, _ = curve_fit(
self.fitbg['functions'][t//2+1],
self.bin_freq,
self.bin_pow,
p0=pams,
sigma=self.bin_err
)
except RuntimeError as _:
paras.append([])
reduced_chi2.append(np.inf)
else:
paras.append(pp)
chi, _ = chisquare(
f_obs=self.random_pow[~self.params[self.target]['mask']],
f_exp=harvey(
self.frequency[~self.params[self.target]['mask']],
pp,
total=True
)
)
reduced_chi2.append(chi/(len(self.frequency[~self.params[self.target]['mask']])-len(pams)))
else:
if self.verbose:
print('%d: %s harvey model w/ white noise fixed' % (t+1, dict1[t]))
delta = 2*(self.nlaws-(t//2+1))
pams = list(self.pars[:(-delta-1)])
pams.append(self.pars[-1])
try:
pp, _ = curve_fit(
self.fitbg['functions'][t//2+1],
self.bin_freq,
self.bin_pow,
p0=pams,
sigma=self.bin_err,
bounds=bounds[t//2]
)
except RuntimeError as _:
paras.append([])
reduced_chi2.append(np.inf)
else:
paras.append(pp)
chi, p = chisquare(
f_obs=self.random_pow[~self.params[self.target]['mask']],
f_exp=harvey(
self.frequency[~self.params[self.target]['mask']],
pp,
total=True
)
)
reduced_chi2.append(chi/(len(self.frequency[~self.params[self.target]['mask']])-len(pams)+1))
# Fitting succeeded
if np.isfinite(min(reduced_chi2)):
model = reduced_chi2.index(min(reduced_chi2)) + 1
if self.nlaws != (((model-1)//2)+1):
self.nlaws = ((model-1)//2)+1
self.mnu = self.mnu[:(self.nlaws)]
self.b = self.b[:(self.nlaws)]
if self.verbose:
print('Based on reduced chi-squared statistic: model %d' % model)
self.bounds = bounds[self.nlaws-1]
self.pars = paras[model-1]
self.exp_numax = self.params[self.target]['numax']
self.exp_dnu = self.params[self.target]['dnu']
self.sm_par = 4.*(self.exp_numax/self.params['numax_sun'])**0.2
if self.sm_par < 1.:
self.sm_par = 1.
for n in range(self.nlaws):
self.final_pars['a_%d' % (n+1)] = []
self.final_pars['b_%d' % (n+1)] = []
again = False
else:
again = True
else:
try:
pars, _ = curve_fit(
self.fitbg['functions'][self.nlaws],
self.bin_freq,
self.bin_pow,
p0=self.pars,
sigma=self.bin_err,
bounds=self.bounds
)
except RuntimeError as _:
again = True
else:
self.pars = pars
self.sm_par = 4.0*(self.exp_numax/self.params['numax_sun'])**0.2
if self.sm_par < 1.0:
self.sm_par = 1.0
again = False
return again
def get_numax_smooth(self):
"""Estimate numax by smoothing the power spectrum and taking the peak."""
sig = (self.sm_par*(self.exp_dnu/self.resolution))/np.sqrt(8.0*np.log(2.0))
pssm = convolve_fft(np.copy(self.random_pow), Gaussian1DKernel(int(sig)))
model = harvey(self.frequency, self.pars, total=True)
inner_freq = list(self.frequency[self.params[self.target]['mask']])
inner_obs = list(pssm[self.params[self.target]['mask']])
outer_freq = list(self.frequency[~self.params[self.target]['mask']])
outer_mod = list(model[~self.params[self.target]['mask']])
if self.fitbg['slope']:
# Correct for edge effects and residual slope in Gaussian fit
inner_mod = model[self.params[self.target]['mask']]
delta_y = inner_obs[-1]-inner_obs[0]
delta_x = inner_freq[-1]-inner_freq[0]
slope = delta_y/delta_x
b = slope*(-1.0*inner_freq[0]) + inner_obs[0]
corrected = np.array([inner_freq[z]*slope + b for z in range(len(inner_freq))])
corr_pssm = [inner_obs[z] - corrected[z] + inner_mod[z] for z in range(len(inner_obs))]
final_y = np.array(corr_pssm + outer_mod)
else:
outer_freq = list(self.frequency[~self.params[self.target]['mask']])
outer_mod = list(model[~self.params[self.target]['mask']])
final_y = np.array(inner_obs + outer_mod)
final_x = np.array(inner_freq + outer_freq)
ss = np.argsort(final_x)
final_x = final_x[ss]
final_y = final_y[ss]
self.pssm = np.copy(final_y)
self.pssm_bgcorr = self.pssm-harvey(final_x, self.pars, total=True)
self.region_freq = self.frequency[self.params[self.target]['mask']]
self.region_pow = self.pssm_bgcorr[self.params[self.target]['mask']]
idx = return_max(self.region_pow, index=True)
self.final_pars['numax_smooth'].append(self.region_freq[idx])
self.final_pars['amp_smooth'].append(self.region_pow[idx])
# Initial guesses for the parameters of the Gaussian fit to the power envelope
self.guesses = [
0.0,
max(self.region_pow),
self.region_freq[idx],
(max(self.region_freq) - min(self.region_freq))/np.sqrt(8.0*np.log(2.0))
]
def get_numax_gaussian(self):
"""Estimate numax by fitting a Gaussian to the power envelope of the smoothed power spectrum."""
bb = gaussian_bounds(self.region_freq, self.region_pow)
p_gauss1, _ = curve_fit(gaussian, self.region_freq, self.region_pow, p0=self.guesses, bounds=bb[0])
# create array with finer resolution for purposes of quantifying uncertainty
new_freq = np.linspace(min(self.region_freq), max(self.region_freq), 10000)
# numax_fit = list(gaussian(new_freq, p_gauss1[0], p_gauss1[1], p_gauss1[2], p_gauss1[3]))
numax_fit = list(gaussian(new_freq, *p_gauss1))
d = numax_fit.index(max(numax_fit))
self.final_pars['numax_gaussian'].append(new_freq[d])
self.final_pars['amp_gaussian'].append(p_gauss1[1])
self.final_pars['fwhm_gaussian'].append(p_gauss1[3])
if self.i == 0:
self.exp_numax = new_freq[d]
self.exp_dnu = 0.22*(self.exp_numax**0.797)
self.width = self.params['width_sun']*(self.exp_numax/self.params['numax_sun'])/2.
self.new_freq = np.copy(new_freq)
self.numax_fit = np.array(numax_fit)
def get_frequency_spacing(self):
"""Estimate the large frequency spacing or dnu.
Parameters
----------
dnu : float
the estimated value of dnu
"""
# Compute the ACF
self.compute_acf()
dnu = self.estimate_dnu()
return dnu
def compute_acf(self, fft=True):
"""Compute the ACF of the smooth background corrected power spectrum.
Parameters
----------
fft : bool
if true will use FFT to compute the ACF
"""
power = self.bg_corr_smooth[(self.frequency >= self.exp_numax-self.width) & (self.frequency <= self.exp_numax+self.width)]
lag = np.arange(0.0, len(power))*self.resolution
if fft:
auto = np.real(np.fft.fft(np.fft.ifft(power)*np.conj(np.fft.ifft(power))))
else:
auto = np.correlate(power-np.mean(power), power-np.mean(power), "full")
auto = auto[int(auto.size/2):]
mask = np.ma.getmask(np.ma.masked_inside(lag, self.exp_dnu/4., 2.*self.exp_dnu+self.exp_dnu/4.))
lag = lag[mask]
auto = auto[mask]
auto -= min(auto)
auto /= max(auto)
self.lag = np.copy(lag)
self.auto = np.copy(auto)
if self.i == 0:
self.freq = self.frequency[self.params[self.target]['mask']]
self.psd = self.bg_corr_smooth[self.params[self.target]['mask']]
def estimate_dnu(self):
"""Estimate a value for dnu."""
if self.i == 0:
# Get peaks from ACF
peaks_l, peaks_a = self.max_elements(self.lag, self.auto)
# Pick the peak closest to the modeled numax
idx = return_max(peaks_l, index=True, dnu=True, exp_dnu=self.exp_dnu)
bb = gaussian_bounds(self.lag, self.auto, best_x=peaks_l[idx], sigma=10**-2)
guesses = [np.mean(self.auto), peaks_a[idx], peaks_l[idx], peaks_l[idx]*0.01*2.0]
p_gauss2, _ = curve_fit(gaussian, self.lag, self.auto, p0=guesses, bounds=bb[0])
self.fitbg['acf_mask'] = [peaks_l[idx]-5.0*p_gauss2[3], peaks_l[idx]+5.0*p_gauss2[3]]
# Do the same only with the single peak
zoom_lag = self.lag[(self.lag >= self.fitbg['acf_mask'][0]) & (self.lag <= self.fitbg['acf_mask'][1])]
zoom_auto = self.auto[(self.lag >= self.fitbg['acf_mask'][0]) & (self.lag <= self.fitbg['acf_mask'][1])]
# Get peaks from ACF
peaks_l, peaks_a = self.max_elements(zoom_lag, zoom_auto)
# Pick the peak closest to the modeled numax
# idx = return_max(peaks_l, index=True, dnu=True, exp_dnu=self.exp_dnu)
best_lag = peaks_l[0]
best_auto = peaks_a[0]
bb = gaussian_bounds(zoom_lag, zoom_auto, best_x=best_lag, sigma=10**-2)
guesses = [np.mean(zoom_auto), best_auto, best_lag, best_lag*0.01*2.0]
p_gauss3, _ = curve_fit(gaussian, zoom_lag, zoom_auto, p0=guesses, bounds=bb[0])
# Create array with finer resolution for purposes of quantifying dnu uncertainty
new_lag = np.linspace(min(zoom_lag), max(zoom_lag), 2000)
dnu_fit = list(gaussian(new_lag, *p_gauss3))
d = dnu_fit.index(max(dnu_fit))
# Force `dnu` to be `guess`
if self.fitbg['force']:
dnu = self.fitbg['guess']
# Otherwise use fitted dnu
else:
dnu = new_lag[d]
if self.i == 0:
peaks_l[idx] = np.nan
peaks_a[idx] = np.nan
self.peaks_l = peaks_l
self.peaks_a = peaks_a
self.best_lag = best_lag
self.best_auto = best_auto
self.zoom_lag = zoom_lag
self.zoom_auto = zoom_auto
self.obs_dnu = dnu
self.new_lag = new_lag
self.dnu_fit = dnu_fit
return dnu
def get_ridges(self, start=0.0):
"""Create echelle diagram.
Parameters
----------