-
Notifications
You must be signed in to change notification settings - Fork 158
/
cbvcorrector.py
1952 lines (1591 loc) · 76.3 KB
/
cbvcorrector.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
"""Defines Corrector classes that utilize Kepler/K2/TESS Cotrending Basis Vectors.
"""
import logging
import copy
import requests
import urllib.request
import glob
import os
from astropy.io import fits as pyfits
from astropy.table import Table
from astropy.time import Time
from astropy.timeseries import TimeSeries
from astropy.units import Quantity, Unit
from astropy.utils.decorators import deprecated
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import PchipInterpolator
from sklearn import linear_model
from scipy.optimize import minimize_scalar
from .designmatrix import DesignMatrix, DesignMatrixCollection
from .. import MPLSTYLE
from ..lightcurve import LightCurve
from ..utils import channel_to_module_output, validate_method, LightkurveDeprecationWarning
from ..search import search_lightcurve
from .regressioncorrector import RegressionCorrector
from ..collections import LightCurveCollection
from .metrics import overfit_metric_lombscargle, underfit_metric_neighbors, MinTargetsError
log = logging.getLogger(__name__)
__all__ = ['CBVCorrector', 'CotrendingBasisVectors', 'KeplerCotrendingBasisVectors',
'TessCotrendingBasisVectors', 'load_kepler_cbvs','load_tess_cbvs',
'download_kepler_cbvs', 'download_tess_cbvs']
#*******************************************************************************
# CBV Corrector Class
class CBVCorrector(RegressionCorrector):
"""Class for removing systematics using Cotrending Basis Vectors (CBVs)
from Kepler/K2/TESS.
On construction of this object, the relevant CBVs will be downloaded from
MAST appropriate for the lightcurve object passed to the constructor.
For TESS there are multiple CBV types. All are loaded and the user must
specify which to use in the correction.
Attributes
----------
lc : LightCurve
The light curve loaded into CBVCorrector in electrons / second
cbvs : CotrendingBasisVectors list
The retrieved CBVs, can contain multiple types of CBVs
interpolated_cbvs : bool
If true then the CBVs have been interpolated to the lightcurve
cbv_design_matrix : DesignMatrix
The retrieved CBVs ported into a DesignMatrix object
extra_design_matrix : DesignMatrix
An extra design matrix to include in the fit with the CBVs
design_matrix_collection : DesignMatrixCollection
The design matrix collection composed of cbv_design_matrix and extra_design_matrix
corrected_lc : LightCurve
The returned light curve from correct() in electrons / second
coefficients : float ndarray
The fit coefficients corresponding to the design_matrix_collection
coefficients_err : float ndarray
The error estimates for the coefficients, see regressioncorrector
model_lc : LightCurve
The model fit to the lightcurve 'lc'
diagnostic_lightcurves : dict
Model fits for each of the sub design matrices fit in model_lc
lc_neighborhood : LightCurveCollection
SPOC SAP light curves of all targets within the defined neighborhood of the
target under study for use with the under-fitting metric
lc_neighborhood_flux : list of arrays
Neighboring target flux aligned or interpolated to the target under
study cadence
cadence_mask : np.ndarray of bool
Mask, where True indicates a cadence that was used in
RegressionCorrector.correct.
Note: The saved cadence_mask is overwritten for each call to correct().
over_fitting_score : float
Over-fitting score from the most recent run of correct()
under_fitting_score : float
Under-fitting score from the most recent run of correct()
alpha : float
L2-norm regularization term used in most recent fit
Equivalent to: designmatrix prior sigma = np.median(self.lc.flux_err) / np.sqrt(alpha)
"""
def __init__(self, lc, interpolate_cbvs=False, extrapolate_cbvs=False, do_not_load_cbvs=False,
cbv_dir=None):
"""Constructor
This constructor will retrieve all relevant CBVs from MAST and then
align or interpolate them with the passed-in light curve.
Parameters
----------
lc : LightCurve
The light curve to correct
interpolate_cbvs : bool
By default, the cbvs will be 'aligned' to the lightcurve. If you
wish to interpolate the cbvs instead then set this to True.
Uses Piecewise Cubic Hermite Interpolating Polynomial (PCHIP).
extrapolate_cbvs : bool
Set to True if the CBVs also have to be extrapolated outside their time
stamp range. (If False then those cadences are filled with NaNs.)
do_not_load_cbvs : bool
If True then the CBVs will NOT be loaded from MAST.
Use this option if you wish to use the CBV corrector methods with only a
custom design matrix (via the ext_dm argument in the corrector methods)
cbv_dir : str
Path to specific directory holding TESS CBVs. If this is None, will query
MAST by default.
"""
if not isinstance(lc, LightCurve):
raise Exception('<lc> must be a LightCurve class')
assert lc.flux.unit==Unit('electron / second'), \
'cbvCorrector expects light curve to be passed in e-/s units.'
if extrapolate_cbvs and (extrapolate_cbvs != interpolate_cbvs):
raise Exception('interpolate_cbvs must be True if extrapolate_cbvs is True')
# We do not want any NaNs
lc = lc.remove_nans()
# Call the RegresssionCorrector Constructor
super(CBVCorrector, self).__init__(lc)
#***
# Retrieve all relevant CBVs from either MAST or a local directory
cbvs = []
if (not do_not_load_cbvs):
if self.lc.mission == 'Kepler':
cbvs.append(load_kepler_cbvs(cbv_dir=cbv_dir,mission=self.lc.mission, quarter=self.lc.quarter,
channel=self.lc.channel))
elif self.lc.mission == 'K2':
cbvs.append(load_kepler_cbvs(cbv_dir=cbv_dir,mission=self.lc.mission, campaign=self.lc.campaign,
channel=self.lc.channel))
elif self.lc.mission == 'TESS':
# For TESS we load multiple CBV types
# Single-Scale
cbvs.append(load_tess_cbvs(cbv_dir=cbv_dir,sector=self.lc.sector,
camera=self.lc.camera, ccd=self.lc.ccd, cbv_type='SingleScale'))
# Multi-Scale
# Although there has always been 3 bands, there could be more,
# continue to load more bands until no more are left to load
iBand = int(0)
moreData = True
while moreData:
iBand += 1
cbvObj = load_tess_cbvs(cbv_dir=cbv_dir,sector=self.lc.sector,
camera=self.lc.camera, ccd=self.lc.ccd, cbv_type='MultiScale',
band=iBand)
if (cbvObj.band == iBand):
cbvs.append(cbvObj)
else:
moreData = False
# Spike
cbvs.append(load_tess_cbvs(cbv_dir=cbv_dir,sector=self.lc.sector,
camera=self.lc.camera, ccd=self.lc.ccd, cbv_type='Spike'))
else:
raise ValueError('Unknown mission type')
for idx in np.arange(len(cbvs)):
if (not isinstance(cbvs[idx], CotrendingBasisVectors)):
raise Exception('CBVs could not be loaded. CBVCorrector must exit')
# Set the CBV time format units to the lightcurve time format units
for idx in np.arange(len(cbvs)):
# astropy.time.Time makes this easy!
cbvs[idx].time.format = lc.time.format
# Align or interpolate the CBVs with the lightcurve flux using the cadence numbers
for idx in np.arange(len(cbvs)):
if interpolate_cbvs:
cbvs[idx] = cbvs[idx].interpolate(self.lc, extrapolate=extrapolate_cbvs)
else:
cbvs[idx] = cbvs[idx].align(self.lc)
self.cbvs = cbvs
self.interpolated_cbvs = interpolate_cbvs
self.extrapolated_cbvs = extrapolate_cbvs
# Initialize all extra attributes to None
self.cbv_design_matrix = None
self.extra_design_matrix = None
self.design_matrix_collection = None
self.corrected_lc = None
self.coefficients = None
self.coefficients_err = None
self.model_lc = None
self.diagnostic_lightcurves = None
self.lc_neighborhood = None
self.lc_neighborhood_flux = None
self.cadence_mask = None
self.over_fitting_score = None
self.under_fitting_score = None
self.alpha = None
def correct_gaussian_prior(self, cbv_type=['SingleScale'],
cbv_indices=[np.arange(1,9)],
alpha=1e-20, ext_dm=None, cadence_mask=None, **kwargs):
""" Performs the correction using RegressionCorrector methods.
This method will assemble the full design matrix collection composed of
cbv_design_matrix and extra_design_matrix (ext_dm). It then uses the
alpha L2-Norm (Ridge Regression) penalty term to set the width on the
design matrix priors. Then uses the super-class
RegressionCorrector.correct to perform the correction.
The relation between the L2-Norm alpha term and the Gaussian prior sigma
is:
alpha = flux_sigma^2 / sigma^2
By default this method will use the first 8 "SingleScale" basis vectors.
Parameters
----------
cbv_type : str list
List of CBV types to use
cbv_indices : list of lists
List of CBV vectors to use in each passed cbv_type. {'ALL' => Use all}
NOTE: 1-Based indexing!
alpha : float
L2-norm regularization penatly term. Default = 1e-20
{0 => no regularization}
ext_dm : `.DesignMatrix` or `.DesignMatrixCollection`
Optionally pass an extra design matrix to also be used in the fit
cadence_mask : np.ndarray of bools (optional)
Mask, where True indicates a cadence that should be used.
**kwargs : dict
Additional keyword arguments passed to
`RegressionCorrector.correct`.
Returns
-------
`.LightCurve`
Corrected light curve, with noise removed. In units of electrons / second
Examples
--------
The following example will perform the correction using the
SingleScale and Spike basis vectors with a weak regularization alpha
term of 0.1. It also adds in an external design matrix to perfomr a
joint fit.
>>> cbv_type = ['SingleScale', 'Spike']
>>> cbv_indices = [np.arange(1,9), 'ALL']
>>> corrected_lc = cbvCorrector.correct_gaussian_prior(cbv_type=cbv_type, # doctest: +SKIP
>>> cbv_indices=cbv_indices, alpha=0.1, # doctest: +SKIP
>>> ext_dm=design_matrix ) # doctest: +SKIP
"""
# Perform all the preparatory stuff common to all correct methods
self._correct_initialization(cbv_type=cbv_type,
cbv_indices=cbv_indices, ext_dm=ext_dm)
# Add in a width to the Gaussian priors
# alpha = flux_sigma^2 / sigma^2
if (alpha == 0.0):
sigma = None
else:
sigma = np.median(self.lc.flux_err.value) / np.sqrt(np.abs(alpha))
self._set_prior_width(sigma)
# Use RegressionCorrector.correct for the actual fitting
self.correct_regressioncorrector(self.design_matrix_collection,
cadence_mask=cadence_mask, **kwargs)
self.alpha = alpha
return self.corrected_lc
def correct_elasticnet(self, cbv_type='SingleScale', cbv_indices=np.arange(1,9),
alpha=1e-20, l1_ratio=0.01, ext_dm=None, cadence_mask=None, **kwargs):
""" Performs the correction using scikit-learn's ElasticNet which
utilizes combined L1- and L2-Norm priors as a regularizer.
This method will assemble the full design matrix collection composed of
cbv_design_matrix and extra_design_matrix (ext_dm). Then uses
scikit-learn.linear_model.ElasticNet to perform the correction.
By default this method will use the first 8 "SingleScale" basis vectors.
This method will preserve the median value of the light curve flux.
Note that the alpha term in scikit-learn's ElasticNet does not have the
same scaling as when used in CBVCorrector.correct_gaussian_prior or
CBVCorrector.correct. Do not assume similar results with a
similar alpha value.
Parameters
----------
cbv_type : str list
List of CBV types to use
cbv_indices : list of lists
List of CBV vectors to use in each passed cbv_type. {'ALL' => Use all}
NOTE: 1-Based indexing!
alpha : float
L2-norm regularization pentaly term.
{0 => no regularization}
l1_ratio : float
Elastic-Net mixing parameter
l1_ratio = 0 => L2 penalty (Ridge). l1_ratio = 1 => L1 penalty (Lasso).
ext_dm : `.DesignMatrix` or `.DesignMatrixCollection`
Optionally pass an extra design matrix to also be used in the fit
cadence_mask : np.ndarray of bools (optional)
Mask, where True indicates a cadence that should be used.
**kwargs : dict
Additional keyword arguments passed to
`sklearn.linear_model.ElasticNet`.
Returns
-------
`.LightCurve`
Corrected light curve, with noise removed. In units of electrons / second
Examples
--------
The following example will perform the ElasticNet correction using the
SingleScale and Spike basis vectors with a strong regualrization alpha
term of 1.0 and an L1 ratio of 0.9 which means predominantly a Lasso
regularization but with a slight amount of Ridge Regression.
>>> cbv_type = ['SingleScale', 'Spike']
>>> cbv_indices = [np.arange(1,9), 'ALL']
>>> corrected_lc = cbvCorrector.correct_elasticnet(cbv_type=cbv_type, # doctest: +SKIP
>>> cbv_indices=cbv_indices, alpha=1.0, l1_ratio=0.9) # doctest: +SKIP
"""
# Perform all the preparatory stuff common to all correct methods
self._correct_initialization(cbv_type=cbv_type,
cbv_indices=cbv_indices, ext_dm=ext_dm)
# Default cadence mask
if cadence_mask is None:
cadence_mask = np.ones(len(self.lc.flux), bool)
# Use Scikit-learn ElasticNet
self.regressor = linear_model.ElasticNet(alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=False, **kwargs)
X = self.design_matrix_collection.values
y = self.lc.flux
# Set mask
# note: ElasticNet has no internal way to do this so we have to just
# remove the cadences from X and y
XMasked = X.copy()
yMasked = y.copy()
XMasked = XMasked[cadence_mask,:]
yMasked = yMasked[cadence_mask]
# Perform the ElasticNet fit
self.regressor.fit(XMasked, yMasked)
# Finishing work
# When creating the model do not include the constant
model_flux = np.dot(X[:,0:-1], self.regressor.coef_[0:-1])
model_flux -= np.median(model_flux)
# TODO: Propagation of uncertainties. They really do not change much.
model_err = np.zeros(len(model_flux))
self.coefficients = self.regressor.coef_
self.model_lc = LightCurve(time=self.lc.time,
flux=model_flux*self.lc.flux.unit,
flux_err=model_err*self.lc.flux_err.unit)
self.corrected_lc = self.lc.copy()
self.corrected_lc.flux = self.lc.flux - self.model_lc.flux
self.corrected_lc.flux_err = (self.lc.flux_err**2 + model_err**2)**0.5
self.diagnostic_lightcurves = self._create_diagnostic_lightcurves()
self.cadence_mask = cadence_mask
self.alpha = alpha
return self.corrected_lc
def correct(self, cbv_type=['SingleScale'],
cbv_indices=[np.arange(1,9)],
ext_dm=None, cadence_mask=None, alpha_bounds=[1e-4,1e4],
target_over_score=0.5, target_under_score=0.5, max_iter=100):
""" Optimizes the correction by adjusting the L2-Norm (Ridge Regression)
regularization penalty term, alpha, based on the introduced noise
(over-fitting) and residual correlation (under-fitting) goodness
metrics. The numercial optimization is performed using the
scipy.optimize.minimize_scalar Brent's method.
The optimizer attempts to maximize the over- and under-fitting goodness
metrics. However, once the target_over_score or target_under_score is
reached, a "Leaky ReLU" is used so that the optimization "pressure"
concentrates on the other metric until both metrics rise above their
respective target scores, instead of driving a single metric to near
1.0.
The optimization parameters used are stored in self.optimization_params
as a record of how the optimization was performed.
The optimized correction is performed using LightKurve's
RegressionCorrector methods. See correct_gaussian_prior for details.
Parameters
----------
cbv_type : str list
List of CBV types to use in correction {'ALL' => Use all}
cbv_indices : list of lists
List of CBV vectors to use in each of cbv_type passed. {'ALL' => Use all}
NOTE: 1-Based indexing!
ext_dm : `.DesignMatrix` or `.DesignMatrixCollection`
Optionally pass an extra design matrix to also be used in the fit
cadence_mask : np.ndarray of bools (optional)
Mask, where True indicates a cadence that should be used.
alpha_bounds : float list(len=2)
upper anbd lowe bounds for alpha
target_over_score : float
Target Over-fitting metric score
target_under_score : float
Target under-fitting metric score
max_iter : int
Maximum number of iterations to optimize goodness metrics
Returns
-------
`.LightCurve`
Corrected light curve, with noise removed. In units of electrons / second
Examples
--------
The following example will perform the correction using the
SingleScale and Spike basis vectors. It will use alpha bounds of
[1.0,1e3]. The target over-fitting score is 0.5 and the target
under-fitting score is 0.8.
>>> cbv_type = ['SingleScale', 'Spike']
>>> cbv_indices = [np.arange(1,9), 'ALL']
>>> cbvCorrector.correct(cbv_type=cbv_type, cbv_indices=cbv_indices, # doctest: +SKIP
>>> alpha_bounds=[1.0,1e3], # doctest: +SKIP
>>> target_over_score=0.5, target_under_score=0.8) # doctest: +SKIP
"""
# Perform all the preparatory stuff common to all correct methods
self._correct_initialization(cbv_type=cbv_type,
cbv_indices=cbv_indices, ext_dm=ext_dm)
# Create a dictionary for optimization parameters to easily pass to the
# objective function, and also to save for posterity
self.optimization_params = {'alpha_bounds': alpha_bounds,
'target_over_score': target_over_score,
'target_under_score': target_under_score,
'max_iter': max_iter,
'cadence_mask': cadence_mask,
'over_metric_nSamples': 1}
#***
# Use scipy.optimize.minimize_scalar
# Minimize the introduced metric
minimize_result = minimize_scalar(self._goodness_metric_obj_fun, method='Bounded',
bounds=alpha_bounds,
options={'maxiter':max_iter, 'disp': False})
# Re-fit with final alpha value
# (scipy.optimize.minimize_scalar does not exit with the final fit!)
self._goodness_metric_obj_fun(minimize_result.x)
# Only display over- or under-fitting scores if requested to optimize
# for each
if (self.optimization_params['target_over_score'] > 0):
self.over_fitting_score = self.over_fitting_metric(n_samples=10)
print('Optimized Over-fitting metric: {}'.format(self.over_fitting_score))
else:
self.over_fitting_score = -1.0
if (self.optimization_params['target_under_score'] > 0):
self.under_fitting_score = self.under_fitting_metric()
print('Optimized Under-fitting metric: {}'.format(self.under_fitting_score))
else:
self.under_fitting_score = -1.0
self.alpha = minimize_result.x
print('Optimized Alpha: {0:2.3e}'.format(self.alpha))
return self.corrected_lc
def correct_regressioncorrector(self, design_matrix_collection, **kwargs):
""" Pass-through method to gain access to the superclass
RegressionCorrector.correct() method.
"""
# All this does is call the superclass 'correct' method as pass the
# input arguments.
return super(CBVCorrector, self).correct(design_matrix_collection, **kwargs)
def over_fitting_metric(self,
n_samples: int = 10):
""" Computes the over-fitting metric using
metrics.overfit_metric_lombscargle
See that function for a description of the algorithm.
Parameters
----------
n_samples : int
The number of times to compute and average the metric
This can stabalize the value, defaut = 10
Returns
-------
over_fitting_metric : float
A float in the range [0,1] where 0 => Bad, 1 => Good
"""
# Check if corrected_lc is present
if (self.corrected_lc is None):
log.warning('A corrected light curve does not exist, please run '
'correct first')
return None
# Ignore masked cadences
orig_lc = self.lc.copy()
orig_lc = orig_lc[self.cadence_mask]
corrected_lc = self.corrected_lc.copy()
corrected_lc = corrected_lc[self.cadence_mask]
return overfit_metric_lombscargle (orig_lc, corrected_lc, n_samples=n_samples)
def under_fitting_metric(self,
radius: float = None,
min_targets: int = 30,
max_targets: int = 50):
""" Computes the under-fitting metric using
metrics.underfit_metric_neighbors
See that function for a description of the algorithm.
For TESS, the default radius is 5000 arcseconds.
For Kepler/K2, the default radius is 1000 arcseconds
This function will begin with the given radius in arcseconds and
finds all neighboring targets. If not enough were found (< min_targets)
the radius is increased until a minimum number are found.
The downloaded neighboring targets will be "aligned" to the
corrected_lc, meaning the cadence numbers are used to align the targets
to the corrected_lc. However, if the CBVCorrector object was
instantiated with interpolated_cbvs=True then the targets will be
interpolated to the corrected_lc cadence times.
Parameters
----------
radius : float
Search radius to find neighboring targets in arcseconds
min_targets : float
Minimum number of targets to use in correlation metric
Using too few can cause unreliable results. Default = 30
max_targets : float
Maximum number of targets to use in correlation metric
Using too many can slow down the metric due to large data
download. Default = 50
Returns
-------
under_fitting_metric : float
A float in the range [0,1] where 0 => Bad, 1 => Good
"""
# Check if corrected_lc is present
if (self.corrected_lc is None):
raise Exception('A corrected light curve does not exist, please run '
'correct first')
return None
# Set default radius if one is not provided.
if (radius is None):
if (self.lc.mission == 'TESS'):
radius = 5000
else:
radius = 1000
interpolate = self.interpolated_cbvs
extrapolate = self.extrapolated_cbvs
# Make a copy of radius because it changes locally
dynamic_search_radius = radius
# Max search radius is the diagonal distance along a CCD in arcseconds
# 1 pixel in TESS is 21.09 arcseconds
# 1 pixel in Kepler/K2 is 3.98 arcseconds
if (self.lc.mission == 'TESS'):
# 24 degrees of a TESS CCD array (2 CCD's wide) is 86,400 arcseconds
max_search_radius = np.sqrt(2) * (86400/2.0)
elif (self.lc.mission == 'Kepler' or self.lc.mission == 'K2'):
# One Kepler CCD spans 4,096 arcseconds
max_search_radius = np.sqrt(2) * 4096
else:
raise Exception('Unknown mission')
# Ignore masked cadences
corrected_lc = self.corrected_lc.copy()
corrected_lc = corrected_lc[self.cadence_mask]
# Dynamically increase radius until min_targets reached.
continue_searching = True
while (continue_searching):
try:
metric = underfit_metric_neighbors (corrected_lc,
dynamic_search_radius, min_targets, max_targets,
interpolate, extrapolate)
except MinTargetsError:
# Too few targets found, try increasing search radius
if (dynamic_search_radius > max_search_radius):
# Hit the edge of the CCD, we have to give up
raise Exception('Not enough neighboring targets were '
'found. under_fitting_metric failed')
# Too few found, increase search radius
dynamic_search_radius *= 1.5
else:
continue_searching = False
return metric
def _correct_initialization(self, cbv_type='SingleScale', cbv_indices='ALL',
ext_dm=None):
""" Performs all the preparatory work needed before applying a 'correct'
method.
This helper function is used so that multiple correct methods can be used
without the need to repeat preparatory code.
The main thing this method does is set up the design matrix, given the
requested CBVs and external design matrix.
Parameters
----------
cbv_type : str list
List of CBV types to use
Can be None if only ext_dm is used
cbv_indices : list of lists
List of CBV vectors to use in each passed cbv_type. {'ALL' => Use all}
Can be None if only ext_dm is used
ext_dm : `.DesignMatrix` or `.DesignMatrixCollection`
Optionally pass an extra design matrix to additionally be used in the fit
"""
assert not ((cbv_type is None) ^ (cbv_indices is None)), \
'Both cbv_type and cbv_indices must be None, or neither'
if (cbv_type is None and cbv_indices is None):
use_cbvs = False
else:
use_cbvs = True
# If any DesignMatrix was passed then store it
self.extra_design_matrix = ext_dm
# Check that extra design matrix is aligned with lc flux
if ext_dm is not None:
assert isinstance(ext_dm, DesignMatrix), \
'ext_dm must be a DesignMatrix'
if (ext_dm.df.shape[0] != len(self.lc.flux)):
raise ValueError(
'ext_dm must contain the same number of cadences as lc.flux')
# Create a CBV design matrix for each CBV set requested
self.cbv_design_matrix = []
if use_cbvs:
assert (not isinstance(cbv_type, str) and
not isinstance(cbv_indices[0], int)), \
'cbv_type and cbv_indices must be lists of strings'
if (self.lc.mission in ['Kepler', 'K2']):
assert len(cbv_type) == 1 , \
'cbv_type must be only Single-Scale for Kepler and K2 missions'
assert cbv_type == ['SingleScale'], \
'cbv_type must be Single-Scale for Kepler and K2 missions'
if (isinstance(cbv_type, list) and len(cbv_type) != 1):
assert (self.lc.mission == 'TESS'), \
'Multiple CBV types are only allowed for TESS'
assert (len(cbv_type) == len(cbv_indices)), \
'cbv_type and cbv_indices must be the same list length'
# Loop through all the stored CBVs and find the ones matching the
# requested cbv_type list
for idx in np.arange(len(cbv_type)):
for cbvs in self.cbvs:
# Temporarily copy the cbv_indices requested
cbv_idx_loop = cbv_indices[idx]
# If requesting 'ALL' CBVs then set to max default number
# Remember, cbv indices is 1-based!
if (isinstance(cbv_idx_loop, str) and (cbv_idx_loop == 'ALL')):
cbv_idx_loop = cbvs.cbv_indices
# Trim to nCBVs in cbvs
cbv_idx_loop = np.array([idx for idx in cbv_idx_loop if
bool(np.in1d(idx, cbvs.cbv_indices))])
if cbv_type[idx].find('MultiScale') >= 0:
# Find the correct band if this is a multi-scale CBV set
band = int(cbv_type[idx][-1])
if (cbvs.cbv_type in cbv_type[idx] and cbvs.band == band):
self.cbv_design_matrix.append(cbvs.to_designmatrix(
cbv_indices=cbv_idx_loop, name=cbv_type[idx]))
else:
if (cbvs.cbv_type in cbv_type[idx]):
self.cbv_design_matrix.append(cbvs.to_designmatrix(
cbv_indices=cbv_idx_loop, name=cbv_type[idx]))
#***
# Create the design matrix collection with CBVs, plus extra passed basis vectors
# Create the full design matrix collection from all the sub-design
# matrices (I.e 'flatten' the design matrix collection)
if self.extra_design_matrix is not None and \
self.cbv_design_matrix != []:
# Combine cbv_design_matrix and extra_design_matrix
dm_to_flatten = [[cbv_dm for cbv_dm in self.cbv_design_matrix],
[self.extra_design_matrix]]
flattened_dm_list = [item for sublist in dm_to_flatten for item in sublist]
elif self.cbv_design_matrix != []:
# Just use cbv_design_matrix
dm_to_flatten = [[cbv_dm for cbv_dm in self.cbv_design_matrix]]
flattened_dm_list = [item for sublist in dm_to_flatten for item in sublist]
else:
# Just use extra_design_matrix
flattened_dm_list = [self.extra_design_matrix]
# Add in a constant to the design matrix collection
# Note: correct_elasticnet ASSUMES the the last vector in the
# design_matrix_collection is the constant
flattened_dm_list.append(DesignMatrix(np.ones(flattened_dm_list[0].shape[0]),
columns=['Constant'], name='Constant'))
self.design_matrix_collection = DesignMatrixCollection(flattened_dm_list)
def _set_prior_width(self, sigma):
""" Sets the Gaussian prior in the design_matrix_collection widths to sigma
Parameters
----------
sigma : scalar float
all widths are set to the same value
If sigma = None then uniform sigma is set
"""
if (isinstance(sigma, list)):
raise Exception("separate widths is not yet implemented")
for dm in self.design_matrix_collection:
nCBVs = len(dm.prior_sigma)
if sigma is None:
dm.prior_sigma = np.ones(nCBVs) * np.inf
else:
dm.prior_sigma = np.ones(nCBVs) * sigma
def _goodness_metric_obj_fun(self, alpha):
""" The objective function to minimize with
scipy.optimize.minimize_scalar
First sets the alpha regularization penalty then runs
RegressionCorrector.correct and then computes the over- and
under-fitting goodness metrics to return a scalar penalty term to
minimize.
Uses the paramaters in self.optimization_params.
Parameters (in self.optimization_params)
----------
alpha : float
regularization penalty term value to set
cadence_mask : np.ndarray of bools (optional)
Mask, where True indicates a cadence that should be used.
target_over_score : float
Target Over-fitting metric score
If <=0 then ignore over-fitting metric
target_under_score : float
Target under-fitting metric score
If <=0 then ignore under-fitting metric
Returns
-------
penalty : float
Penalty term for minimizer, based on goodness metrics
"""
# Add in a width to the Gaussian priors
# alpha = flux_sigma^2 / sigma^2
sigma = np.median(self.lc.flux_err.value) / np.sqrt(np.abs(alpha))
self._set_prior_width(sigma)
# Use RegressionCorrector.correct for the actual fitting
self.correct_regressioncorrector(self.design_matrix_collection,
cadence_mask=self.optimization_params['cadence_mask'])
# Do not compute and ignore if target score < 0
if (self.optimization_params['target_over_score'] > 0):
overMetric = self.over_fitting_metric(
n_samples=self.optimization_params['over_metric_nSamples'])
else:
overMetric = 1.0
# Do not compute and ignore if target score < 0
if (self.optimization_params['target_under_score'] > 0):
underMetric = self.under_fitting_metric()
else:
underMetric = 1.0
# Once we hit the target we want to ease-back on increasing the metric
# However, we don't want to ease-back to zero pressure, that will
# unconstrain the penalty term and cause the optmizer to run wild.
# So, use a "Leaky ReLU"
# metric' = threshold + (metric - threshold) * leakFactor
leakFactor = 0.01
if (self.optimization_params['target_over_score'] > 0 and
overMetric >= self.optimization_params['target_over_score']):
overMetric = (self.optimization_params['target_over_score'] +
leakFactor *
(overMetric -
self.optimization_params['target_over_score']))
if (self.optimization_params['target_under_score'] > 0 and
underMetric >= self.optimization_params['target_under_score']):
underMetric = (self.optimization_params['target_under_score'] +
leakFactor *
(underMetric -
self.optimization_params['target_under_score']))
penalty = -(overMetric + underMetric)
return penalty
def diagnose(self):
""" Returns diagnostic plots to assess the most recent correction.
If a correction has not yet been fitted, a ``ValueError`` will be raised.
Returns
-------
`~matplotlib.axes.Axes`
The matplotlib axes object.
"""
axs = self._diagnostic_plot()
plt.title('Alpha = {0:2.3e}'.format(self.alpha))
return axs
def goodness_metric_scan_plot(self, cbv_type=['SingleScale'],
cbv_indices=[np.arange(1,9)], alpha_range_log10=[-4, 4],
ext_dm=None, cadence_mask=None):
""" Returns a diagnostic plot of the over and under goodness metrics as a
function of the L2-Norm regularization term, alpha.
alpha is scanned by default to the range 10^-4 : 10^4 in logspace
cbvCorrector.correct_gaussian_prior is used to make the correction for
each alpha. Then the over and under goodness metric are computed.
If a correction has already been performed (via one of the correct_*
methods) then the used alpha value is also plotted for reference.
Parameters
----------
cbv_type : str list
List of CBV types to use in correction {'ALL' => Use all}
cbv_indices : list of lists
List of CBV vectors to use in each of cbv_type passed. {'ALL' => Use all}
NOTE: 1-Based indexing!
alpha_range_log10 : [list of two] The start and end exponent for the logspace scan.
Default = [-4, 4]
ext_dm : `.DesignMatrix` or `.DesignMatrixCollection`
Optionally pass an extra design matrix to also be used in the fit
cadence_mask : np.ndarray of bools (optional)
Mask, where True indicates a cadence that should be used.
Returns
-------
`~matplotlib.axes.Axes`
The matplotlib axes object.
"""
alphaArray = np.logspace(alpha_range_log10[0], alpha_range_log10[1], num=100)
# We need to make a copy of self so that the scan's final fit parameters
# do not over-write any stored fit parameters
cbvCorrectorCopy = self.copy()
# Compute both metrics vs. alpha
overMetric = []
underMetric = []
for thisAlpha in alphaArray:
cbvCorrectorCopy.correct_gaussian_prior(cbv_type=cbv_type, cbv_indices=cbv_indices,
alpha=thisAlpha, ext_dm=ext_dm,
cadence_mask=cadence_mask)
overMetric.append(cbvCorrectorCopy.over_fitting_metric(n_samples=1))
underMetric.append(cbvCorrectorCopy.under_fitting_metric())
# plot both
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.semilogx(alphaArray, underMetric, 'b.', label='UnderFit')
ax.semilogx(alphaArray, overMetric, 'r.', label='OverFit')
if (isinstance(self.alpha, float)):
ax.semilogx([self.alpha, self.alpha], [0, 1.0], 'k-',
label='corrected_lc Alpha = {0:2.3e}'.format(self.alpha))
plt.title('Goodness Metrics vs. L2-Norm Penalty (alpha)')
plt.xlabel('Regularization Factor Alpha')
plt.ylabel('Goodness Metric')
ax.grid(':', alpha=0.3)
ax.legend()
return ax
def copy(self):
"""Returns a copy of this `cbvCorrector` object.
This method uses Python's `copy.deepcopy` function to ensure that all
objects stored within the cbvCorrector instance are fully copied.
Returns
-------
cbvCorrector_copy : `cbvCorrector`
A new object which is a copy of the original.
"""
return copy.deepcopy(self)
def __repr__(self):
""" This will print all attributes of the class kinda like in
self.__dict__
"""
dictionary = self.__dict__.copy()
dictionary['lc'] = '<{} targetid={} length={}>'.format(type(self.lc),
self.lc.targetid, len(self.lc))
if self.corrected_lc is not None:
dictionary['corrected_lc'] = '<{} targetid={} length={}>'.format(
type(self.corrected_lc), self.corrected_lc.targetid,
len(self.corrected_lc))
dict_string = '\n'
for key in dictionary.keys():
dict_string += '\t{} = {}\n'.format(key, dictionary[key])
return dict_string
#*******************************************************************************
#*******************************************************************************
#*******************************************************************************
# Cotrending Basis Vectors Classes and Functions
#*******************************************************************************
#*******************************************************************************
#*******************************************************************************
class CotrendingBasisVectors(TimeSeries):
"""
Defines a CotrendingBasisVectors class, which is the Superclass for
KeplerCotrendingBasisVectors and TessCotrendingBasisVectors.
Normally, one would use these latter classes instead of instantiating
CotrendingBasisVectors directly. However, for generating custom CBVs one can
use this super class.
Stores Cotrending Basis Vectors for the Kepler/K2/TESS missions.
Each CotrendingBasisVectors object contains only ONE set of CBVs.
Instantiate multiple objects to store multiple set of CBVS, for example, to
save each of the three multi-scale bands in TESS.
CotrendingBasisVectors calls the standard __init__ from
astropy.timeseries.TimeSeries
Parameters
----------
data : `~astropy.table.Table`
Data to initialize CotrendingBasisVectors. The
CBVs should be in columns called ``'CADENCENO'``, ``'GAP'``, ``'VECTOR_1'``,
``'VECTOR_2'``, ... ``'VECTOR_N'``
If 'GAP' is not given then it is filled with all False.
If 'CADENCENO' is not given then it is filled with np.arange(nCadences)
time : `~astropy.time.Time`
Time values.
**kwargs : dict