/
targetdata.py
1629 lines (1286 loc) · 65.5 KB
/
targetdata.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 numpy as np
import matplotlib.pyplot as plt
from astropy.nddata import Cutout2D
from photutils import CircularAperture, RectangularAperture, aperture_photometry
from photutils import MMMBackground
from lightkurve import SFFCorrector, lightcurve
from scipy.optimize import minimize
from astropy import time, coordinates as coord, units as u
from astropy.coordinates import SkyCoord, Angle
from astropy.table import Table, Column
from astropy.wcs import WCS
from astropy.stats import SigmaClip, sigma_clip
from time import strftime
from astropy.io import fits
from scipy.stats import mode
from urllib.request import urlopen
import os, sys, copy
import os.path
import warnings
import pickle
import eleanor
from .ffi import use_pointing_model, load_pointing_model, centroid_quadratic
from .postcard import Postcard, Postcard_tesscut
__all__ = ['TargetData']
class TargetData(object):
"""
Object containing the light curve, target pixel file, and related information
for any given source.
Parameters
----------
source : eleanor.Source
The source object to use.
height : int, optional
Height in pixels of TPF to retrieve. Default value is 13 pixels. Must be an odd number,
or else will return an aperture one pixel taller than requested so target
falls on central pixel.
width : int, optional
Width in pixels of TPF to retrieve. Default value is 13 pixels. Must be an odd number,
or else will return an aperture one pixel wider than requested so target
falls on central pixel.
bkg_size : int, optional
Size of box to use for background estimation. If not set, will default to the width of the
target pixel file.
crowded_field : bool, optional
If true, will return a light curve built using a small aperture (not more than 8 pixels in size).
do_pca : bool, optional
If true, will return a PCA-corrected light curve.
do_psf : bool, optional
If true, will return a light curve made with a simple PSF model.
cal_cadences : tuple, optional
Start and end cadence numbers to use for optimal aperture selection.
try_load: bool, optional
If true, will search hidden ~/.eleanor directory to see if TPF has already
been created.
regressors : numpy.ndarray or str
Extra data to regress against in the correction. Should be shape (len(data.time), N) or `'corner'`.
If `'corner'` will use the four corner pixels of the TPF as extra information in the regression.
Attributes
----------
header : dict
FITS header for saving/loading data.
source_info : eleanor.Source
Pointer to input source.
aperture :
Aperture to use if overriding default. To use default, set to `None`.
tpf : np.ndarray
Target pixel file of fluxes; array with shape `dimensions`.
time : np.ndarray
Time series.
post_obj : eleanor.Postcard
Pointer to Postcard objects containing this TPF.
pointing_model : astropy.table.Table
Table of matrices describing the transformation matrix from FFI default
WCS and eleanor's corrected pointing.
tpf_err : np.ndarray
Errors on fluxes in `tpf`.
centroid_xs : np.ndarray
Position of the source in `x` inferred from pointing model; has same length as `time`.
Position is relative to the pixel coordinate system of the postcard.
centroid_ys : np.ndarray
Position of the source in `y` inferred from pointing model; has same length as `time`.
Position is relative to the pixel coordinate system of the postcard.
cen_x : int
Median `x` position of the source.
Position is relative to the pixel coordinate system of the postcard.
cen_y : int
Median `y` position of the source.
Position is relative to the pixel coordinate system of the postcard.
tpf_star_x : int
`x` position of the star on the TPF.
Position is relative to the size of the TPF.
tpf_star_y : int
`y` position of the star on the TPF.
Position is relative to the size of the TPF.
dimensions : tuple
Shape of `tpf`. Should be (`time`, `height`, `width`).
all_apertures : list
List of aperture objects.
aperture : array-like
Chosen aperture for producing `raw_flux` lightcurve. Format is array
with shape (`height`, `width`). All entries are floats in range [0,1].
all_flux_err : np.ndarray
Estimated uncertainties on `all_raw_flux`.
all_raw_flux : np.ndarray
All lightcurves extracted using `all_apertures`.
Has shape (N_apertures, N_time).
all_corr_flux : np.ndarray
All systematics-corrected lightcurves. See `all_raw_flux`.
best_ind : int
Index into `all_apertures` producing the best (least noisy) lightcurve.
corr_flux : np.ndarray
Systematics-corrected version of `raw_flux`.
flux_err : np.ndarray
Estimated uncertainty on `raw_flux`.
raw_flux : np.ndarray
Un-systematics-corrected lightcurve derived using `aperture` and `tpf`.
x_com : np.ndarray
Position of the source in `x` inferred from TPF; has same length as `time`.
Position is relative to the pixel coordinate system of the TPF.
y_com : np.ndarray
Position of the source in `y` inferred from TPF; has same length as `time`.
Position is relative to the pixel coordinate system of the TPF.
quality : int
Quality flag.
Notes
-----
`save()` and `load()` methods write/read these data to a FITS file with format:
Extension[0] = header
Extension[1] = (N_time, height, width) TPF, where n is the number of cadences in an observing run
Extension[2] = (3, N_time) time, raw flux, systematics corrected flux
"""
def __init__(self, source, height=13, width=13, save_postcard=True, do_pca=False, do_psf=False,
bkg_size=None, crowded_field=False, cal_cadences=None, try_load=True, regressors = None,
language='English'):
self.source_info = source
self.language = language
self.pca_flux = None
self.psf_flux = None
self.regressors = regressors
if self.source_info.premade is True:
self.load(directory=self.source_info.fn_dir)
else:
fnf = True
# Checks to see if file exists already
if try_load==True:
try:
default_fn = 'hlsp_eleanor_tess_ffi_tic{0}_s{1:02d}_tess_v{2}_lc.fits'.format(self.source_info.tic,
self.source_info.sector,
eleanor.__version__)
self.load(fn=default_fn)
print('Loading file {0} found on disk'.format(default_fn))
fnf = False
except:
pass
if fnf is True:
self.aperture = None
if source.tc == False:
self.post_obj = Postcard(source.postcard, source.postcard_bkg,
source.postcard_path)
else:
self.post_obj = Postcard_tesscut(source.cutout)
self.ffiindex = self.post_obj.ffiindex
self.flux_bkg = self.post_obj.bkg
self.get_time(source.coords)
if bkg_size is None:
bkg_size = width
# Uses the contamination ratio for crowded field if available and
# not already set by the user
if crowded_field is True:
self.crowded_field = 1
else:
if self.source_info.contratio is not None:
self.crowded_field = self.source_info.contratio
else:
self.crowded_field = 0
if cal_cadences is None:
self.cal_cadences = (0, len(self.post_obj.time)-0)
else:
self.cal_cadences = cal_cadences
try:
if source.pointing is not None:
self.pointing_model = source.pointing
else:
self.pointing_model = load_pointing_model(source.pm_dir, source.sector, source.camera, source.chip)
except:
self.pointing_model = None
self.get_tpf_from_postcard(source.coords, source.postcard, height, width, bkg_size, save_postcard, source)
self.set_quality()
self.get_cbvs()
self.create_apertures(self.tpf.shape[1], self.tpf.shape[2])
self.get_lightcurve()
if do_pca == True:
self.corrected_flux(pca=True)
else:
self.modes = None
self.pca_flux = None
if do_psf == True:
self.psf_lightcurve()
else:
self.psf_flux = None
self.center_of_mass()
self.set_header()
def get_time(self, coords):
"""Gets time, including light travel time correction to solar system barycenter for object given location"""
t0 = self.post_obj.time - self.post_obj.barycorr
ra = Angle(coords[0], u.deg)
dec = Angle(coords[1], u.deg)
greenwich = coord.EarthLocation.of_site('greenwich')
times = time.Time(t0+2457000, format='jd',
scale='utc', location=greenwich)
ltt_bary = times.light_travel_time(SkyCoord(ra, dec)).value
self.time = t0 + ltt_bary
self.barycorr = ltt_bary
def get_tpf_from_postcard(self, pos, postcard, height, width, bkg_size, save_postcard, source):
"""Gets TPF from postcard."""
self.tpf = None
self.centroid_xs = None
self.centroid_ys = None
xy = WCS(self.post_obj.header, naxis=2).all_world2pix(pos[0], pos[1], 1)
# Apply the pointing model to each cadence to find the centroids
if self.pointing_model is None:
self.centroid_xs = np.zeros_like(self.post_obj.time)
self.centroid_ys = np.zeros_like(self.post_obj.time)
else:
centroid_xs, centroid_ys = [], []
for i in range(len(self.pointing_model)):
new_coords = use_pointing_model(np.array(xy), self.pointing_model[i])
centroid_xs.append(new_coords[0][0])
centroid_ys.append(new_coords[0][1])
self.centroid_xs = np.array(centroid_xs)
self.centroid_ys = np.array(centroid_ys)
# Define tpf as region of postcard around target
med_x, med_y = np.nanmedian(self.centroid_xs), np.nanmedian(self.centroid_ys)
med_x, med_y = int(np.round(med_x,0)), int(np.round(med_y,0))
if source.tc == False:
post_flux = self.post_obj.flux
post_err = self.post_obj.flux_err
post_bkg2d = self.post_obj.background2d
post_bkg = self.post_obj.bkg
else:
post_flux = self.post_obj.flux + 0.0
post_err = self.post_obj.flux_err + 0.0
self.cen_x, self.cen_y = med_x, med_y
y_length, x_length = int(np.floor(height/2.)), int(np.floor(width/2.))
y_bkg_len, x_bkg_len = int(np.floor(bkg_size/2.)), int(np.floor(bkg_size/2.))
y_low_lim = med_y-y_length
y_upp_lim = med_y+y_length+1
x_low_lim = med_x-x_length
x_upp_lim = med_x+x_length+1
y_low_bkg = med_y-y_bkg_len
y_upp_bkg = med_y+y_bkg_len + 1
x_low_bkg = med_x-x_bkg_len
x_upp_bkg = med_x+x_bkg_len + 1
if height % 2 == 0 or width % 2 == 0:
warnings.warn('We force our TPFs to have an odd height and width so we can properly center our apertures.')
post_y_upp, post_x_upp = self.post_obj.dimensions[1], self.post_obj.dimensions[2]
# Fixes the postage stamp if the user requests a size that is too big for the postcard
if y_low_lim <= 0:
y_low_lim = 0
y_upp_lim = med_y + width + y_low_lim
if x_low_lim <= 0:
x_low_lim = 0
x_upp_lim = med_x + height + x_low_lim
if y_upp_lim > post_y_upp:
y_upp_lim = post_y_upp+1
y_low_lim = med_y - width + (post_y_upp-med_y)
if x_upp_lim > post_x_upp:
x_upp_lim = post_x_upp+1
x_low_lim = med_x - height + (post_x_upp-med_x)
self.tpf_star_y = width + (med_y - y_upp_lim)
self.tpf_star_x = height + (med_x - x_upp_lim)
if self.tpf_star_y == 0:
self.tpf_star_y = int(width/2)
if self.tpf_star_x == 0:
self.tpf_star_x = int(height/2)
if y_low_bkg <= 0:
y_low_bkg = 0
y_upp_bkg = med_y + width + y_low_bkg
if x_low_bkg <= 0:
x_low_bkg = 0
x_upp_bkg = med_x + height + x_low_bkg
if y_upp_bkg > post_y_upp:
y_upp_bkg = post_y_upp+1
y_low_bkg = med_y - width + (post_y_upp - med_y)
if x_upp_bkg > post_x_upp:
x_upp_bkg = post_x_upp+1
x_low_bkg = med_x - height + (post_x_upp - med_x)
if source.tc == False:
if (x_low_lim==0) or (y_low_lim==0) or (x_upp_lim==post_x_upp) or (y_upp_lim==post_y_upp):
warnings.warn("The size postage stamp you are requesting falls off the edge of the postcard.")
warnings.warn("WARNING: Your postage stamp may not be centered.")
self.tpf = post_flux[:, y_low_lim:y_upp_lim, x_low_lim:x_upp_lim]
h, w = self.tpf.shape[1], self.tpf.shape[2]
self.tpf_star_y = w + (med_y - y_upp_lim)
self.tpf_star_x = h + (med_x - x_upp_lim)
if med_x == int((x_upp_lim - x_low_lim)/2 + x_low_lim):
self.tpf_star_x = int(width/2)
if med_y == int((y_upp_lim - y_low_lim)/2 + y_low_lim):
self.tpf_star_y = int(height/2)
self.bkg_tpf = post_bkg2d[:, y_low_lim:y_upp_lim, x_low_lim:x_upp_lim]
self.tpf_flux_bkg = self.bkg_subtraction() + post_bkg
self.tpf_err = post_err[: , y_low_lim:y_upp_lim, x_low_lim:x_upp_lim]
self.tpf_err[np.isnan(self.tpf_err)] = np.inf
else:
if (height > 31) or (width > 31):
raise ValueError("Maximum allowed TPF size when using TessCut is 31 x 31 pixels.")
self.tpf = post_flux[:, 15-y_length:15+y_length+1, 15-x_length:15+x_length+1]
self.bkg_tpf = post_flux
self.tpf_err = post_err[:, 15-y_length:15+y_length+1, 15-x_length:15+x_length+1]
self.tpf_err[np.isnan(self.tpf_err)] = np.inf
self.bkg_subtraction()
self.dimensions = np.shape(self.tpf)
summed_tpf = np.nansum(self.tpf, axis=0)
mpix = np.unravel_index(summed_tpf.argmax(), summed_tpf.shape)
if np.abs(mpix[0] - x_length) > 1:
self.crowded_field = 1
if np.abs(mpix[1] - y_length) > 1:
self.crowded_field = 1
self.tpf = self.tpf
if save_postcard == False:
try:
if self.source_info.tc == False:
os.remove(self.post_obj.local_path)
os.remove(self.post_obj.local_path.replace('pc.fits', 'bkg.fits'))
else:
os.remove(self.source_info.postcard_path)
except OSError:
pass
return
def create_apertures(self, height, width):
"""Creates a range of sizes and shapes of apertures to test."""
default = 13
def circle_aperture(pos,r):
return CircularAperture(pos,r)
def square_aperture(pos, l, w, t):
return RectangularAperture(pos, l, w, t)
if self.source_info.tc == True:
center = (self.tpf_star_y, self.tpf_star_x)
else:
center = (self.tpf_star_x, self.tpf_star_y)
shape = (height, width)
clist = [1.25, 2.5, 3.5, 4]
rlist = [3, 3, 5, 4.1]
theta = [np.pi/4., 0, np.pi/4., 0]
# Creates 2 and 3 pixel apertures
lines = [ ((center[0], center[1]-0.5), 1, 2, 0),
((center[0]+0.5, center[1]), 2, 1, 0),
((center[0], center[1]+0.5), 1, 2, 0),
((center[0]-0.5, center[1]), 2, 1, 0) ]
delta = 0.48
t_w = 1.6; t_l = np.sqrt(2)
tris = [ ((center[0]+delta, center[1]-delta), t_w, t_l, np.pi/4),
((center[0]+delta, center[1]+delta), t_l, t_w, np.pi/4),
((center[0]-delta, center[1]+delta), t_w, t_l, np.pi/4),
((center[0]-delta, center[1]-delta), t_l, t_w, np.pi/4) ]
deg = 0
all_apertures = []
aperture_names = []
for i in range(len(tris)):
lap = square_aperture(lines[i][0], lines[i][1], lines[i][2], lines[i][3])
tap = square_aperture(tris[i][0] , tris[i][1] , tris[i][2] , tris[i][3])
lmask, lname = lap.to_mask(method='center').to_image(shape=shape), 'rectangle_{}'.format(int(deg))
tmask, tname = tap.to_mask(method='center').to_image(shape=shape), 'L_{}'.format(int(deg))
all_apertures.append(lmask)
aperture_names.append(lname)
all_apertures.append(tmask)
aperture_names.append(tname)
cap = circle_aperture(center, clist[i])
rap = square_aperture(center, rlist[i], rlist[i], theta[i])
for method in ['center', 'exact']:
cmask, cname = cap.to_mask(method=method).to_image(shape=shape), '{}_circle_{}'.format(clist[i], method)
rmask, rname = rap.to_mask(method=method).to_image(shape=shape), '{}_square_{}'.format(rlist[i], method)
all_apertures.append(cmask)
aperture_names.append(cname)
all_apertures.append(rmask)
aperture_names.append(rname)
deg += 90
if self.source_info.tc == True:
## Checks to see if there are empty rows/columns ##
## Sets those locations to 0 in the aperture mask ##
rows = np.unique(np.where(np.nanmedian(self.tpf, axis=0) == 0)[0])
cols = np.unique(np.where(np.nanmedian(self.tpf, axis=0) == 0)[1])
if len(rows) > 0 and len(cols) > 0:
if np.array_equal(cols, np.arange(0,height,1)):
for i in range(len(all_apertures)):
all_apertures[i][rows,:] = 0
if np.array_equal(rows, np.arange(0,width,1)):
for i in range(len(all_apertures)):
all_apertures[i][:,cols] = 0
self.all_apertures = np.array(all_apertures)
self.aperture_names = np.array(aperture_names)
if height < default or width < default:
warnings.warn('WARNING: Making a TPF smaller than (13,13) may provide inadequate results.')
def bkg_subtraction(self, scope="tpf", sigma=2.5):
"""Subtracts background flux from target pixel file.
Parameters
----------
scope : string, "tpf" or "postcard"
If `tpf`, will use data from the target pixel file only to estimate and remove the background.
If `postcard`, will use data from the entire postcard region to estimate and remove the background.
sigma : float
The standard deviation cut used to determine which pixels are representative of the background in each cadence.
"""
time = self.time
if self.source_info.tc == True:
flux = self.bkg_tpf
else:
flux = self.tpf
tpf_flux_bkg = []
sigma_clip = SigmaClip(sigma=sigma)
bkg = MMMBackground(sigma_clip=sigma_clip)
for i in range(len(time)):
bkg_value = bkg.calc_background(flux[i])
tpf_flux_bkg.append(bkg_value)
if self.source_info.tc == True:
self.tpf_flux_bkg = np.array(tpf_flux_bkg)
else:
return np.array(tpf_flux_bkg)
def get_lightcurve(self, aperture=None):
"""Extracts a light curve using the given aperture and TPF.
Can pass a user-defined aperture mask, otherwise determines which of a set of pre-determined apertures
provides the lowest scatter in the light curve.
Produces a mask, a numpy.ndarray object of the same shape as the target pixel file, which every pixel assigned
a weight in the range [0, 1].
Parameters
----------
aperture : numpy.ndarray
(`height`, `width`) array of floats in the range [0,1] with desired weights for each pixel to
create a light curve. If not set, ideal aperture is inferred automatically. If set, uses this
aperture at the expense of all other set apertures.
"""
def apply_mask(mask):
lc = np.zeros(len(self.tpf))
lc_err = np.zeros(len(self.tpf))
for cad in range(len(self.tpf)):
lc[cad] = np.nansum( self.tpf[cad] * mask)
lc_err[cad] = np.sqrt( np.nansum( self.tpf_err[cad]**2 * mask))
self.raw_flux = np.array(lc)
self.corr_flux = self.corrected_flux(flux=lc, skip=50)
self.flux_err = np.array(lc_err)
return
self.flux_err = None
if aperture is not None:
self.aperture = aperture
if self.language == 'Australian':
print("G'day Mate! ʕ •ᴥ•ʔ Your light curves are being translated ...")
if self.aperture is not None:
if np.shape(self.all_apertures[0]) != np.shape(self.aperture):
raise ValueError(
"Passed aperture does not match the size of the TPF. Please correct and try again. "
"Or, create a custom aperture using the function TargetData.custom_aperture(). See documentation for inputs.")
self.all_apertures = np.zeros((1, np.shape(self.tpf[0])[0], np.shape(self.tpf[0])[1]))
self.all_apertures[0] = self.aperture
self.all_flux_err = None
all_raw_lc_pc_sub = np.zeros((len(self.all_apertures), len(self.tpf)))
all_lc_err = np.zeros((len(self.all_apertures), len(self.tpf)))
all_corr_lc_pc_sub = np.copy(all_raw_lc_pc_sub)
# TPF background subtracted light curves
all_raw_lc_tpf_sub = np.zeros((len(self.all_apertures), len(self.tpf)))
all_corr_lc_tpf_sub = np.copy(all_raw_lc_tpf_sub)
# 2D background subtracted light curves
all_raw_lc_tpf_2d_sub = np.copy(all_raw_lc_tpf_sub)
all_corr_lc_tpf_2d_sub = np.copy(all_raw_lc_tpf_sub)
if self.source_info.tc == True:
for epoch in range(len(self.time)):
self.tpf[epoch] -= self.tpf_flux_bkg[epoch]
pc_stds = np.ones(len(self.all_apertures))
tpf_stds = np.ones(len(self.all_apertures))
stds_2d = np.ones(len(self.all_apertures))
ap_size = np.nansum(self.all_apertures, axis=(1,2))
for a in range(len(self.all_apertures)):
try:
all_lc_err[a] = np.sqrt( np.nansum(self.tpf_err**2 * self.all_apertures[a], axis=(1,2)))
all_raw_lc_pc_sub[a] = np.nansum( (self.tpf * self.all_apertures[a]), axis=(1,2) )
oned_bkg = np.zeros(self.tpf.shape)
for c in range(len(self.time)):
oned_bkg[c] = np.full((self.tpf.shape[1], self.tpf.shape[2]), self.tpf_flux_bkg[c])
post_bkg = np.zeros(self.tpf.shape)
for c in range(len(self.time)):
post_bkg[c] = np.full((self.tpf.shape[1], self.tpf.shape[2]), self.flux_bkg[c])
all_raw_lc_tpf_sub[a] = np.nansum( ((self.tpf + post_bkg - oned_bkg) * self.all_apertures[a]), axis=(1,2) )
if self.source_info.tc == False:
all_raw_lc_tpf_2d_sub[a] = np.nansum( ((self.tpf) - self.bkg_tpf) * self.all_apertures[a],
axis=(1,2))
except ValueError:
continue
## Remove something from all_raw_lc before passing into jitter_corr ##
try:
all_corr_lc_pc_sub[a] = self.corrected_flux(flux=all_raw_lc_pc_sub[a]/np.nanmedian(all_raw_lc_pc_sub[a]),
bkg=np.nansum(post_bkg*self.all_apertures[a], axis=(1,2)))
all_corr_lc_tpf_sub[a]= self.corrected_flux(flux=all_raw_lc_tpf_sub[a]/np.nanmedian(all_raw_lc_tpf_sub[a]),
bkg=np.nansum(oned_bkg*self.all_apertures[a], axis=(1,2)))
if self.source_info.tc == False:
all_corr_lc_tpf_2d_sub[a] = self.corrected_flux(flux=all_raw_lc_tpf_2d_sub[a]/np.nanmedian(all_raw_lc_tpf_2d_sub[a]),
bkg=np.nansum(self.bkg_tpf*self.all_apertures[a], axis=(1,2)))
except IndexError:
continue
q = self.quality == 0
lc_obj_tpf = lightcurve.LightCurve(time = self.time[q][self.cal_cadences[0]:self.cal_cadences[1]],
flux = all_corr_lc_tpf_sub[a][q][self.cal_cadences[0]:self.cal_cadences[1]])
flat_lc_tpf = lc_obj_tpf.flatten(polyorder=2, window_length=51).remove_outliers(sigma=4)
tpf_stds[a] = np.std(flat_lc_tpf.flux)
lc_obj_pc = lightcurve.LightCurve(time = self.time[q][self.cal_cadences[0]:self.cal_cadences[1]],
flux = all_corr_lc_pc_sub[a][q][self.cal_cadences[0]:self.cal_cadences[1]])
flat_lc_pc = lc_obj_pc.flatten(polyorder=2, window_length=51).remove_outliers(sigma=4)
pc_stds[a] = np.std(flat_lc_pc.flux)
if self.source_info.tc == False:
lc_2d_tpf = lightcurve.LightCurve(time = self.time[q][self.cal_cadences[0]:self.cal_cadences[1]],
flux = all_corr_lc_tpf_2d_sub[a][q][self.cal_cadences[0]:self.cal_cadences[1]])
flat_lc_2d = lc_2d_tpf.flatten(polyorder=2, window_length=51).remove_outliers(sigma=4)
stds_2d[a] = np.std(flat_lc_2d.flux)
all_corr_lc_tpf_2d_sub[a] = all_corr_lc_tpf_2d_sub[a] * np.nanmedian(all_raw_lc_tpf_2d_sub[a])
all_corr_lc_pc_sub[a] = all_corr_lc_pc_sub[a] * np.nanmedian(all_raw_lc_pc_sub[a])
all_corr_lc_tpf_sub[a] = all_corr_lc_tpf_sub[a] * np.nanmedian(all_raw_lc_tpf_sub[a])
if self.crowded_field > 0.15:
tpf_stds[ap_size > 8] = 1.0
pc_stds[ap_size > 8] = 1.0
if self.source_info.tc == False:
stds_2d[ap_size > 8] = 1.0
if self.source_info.tess_mag < 8.5:
tpf_stds[ap_size < 8] = 1.0
pc_stds[ap_size < 8] = 1.0
if self.source_info.tc == False:
stds_2d[ap_size < 8] = 1.0
best_ind_tpf = np.where(tpf_stds == np.nanmin(tpf_stds))[0][0]
best_ind_pc = np.where(pc_stds == np.nanmin(pc_stds))[0][0]
if self.source_info.tc == False:
best_ind_2d = np.where(stds_2d == np.nanmin(stds_2d))[0][0]
else:
best_ind_2d = None
if best_ind_2d is not None:
stds = np.array([pc_stds[best_ind_pc],
tpf_stds[best_ind_tpf],
stds_2d[best_ind_2d]])
std_inds = np.array([best_ind_pc, best_ind_tpf, best_ind_2d])
types = np.array(['PC_LEVEL', 'TPF_LEVEL', 'TPF_2D_LEVEL'])
else:
stds = np.array([pc_stds[best_ind_pc],
tpf_stds[best_ind_tpf]])
std_inds = np.array([best_ind_pc, best_ind_tpf])
types =np.array(['PC_LEVEL', 'TPF_LEVEL'])
best_ind = std_inds[np.argmin(stds)]
self.bkg_type = types[np.argmin(stds)]
## Checks if postcard or tpf level bkg subtraction is better ##
## Prints bkg_type to TPF header ##
# if pc_stds[best_ind_pc] <= tpf_stds[best_ind_tpf]:
# best_ind = best_ind_pc
if self.bkg_type == 'PC_LEVEL':
self.all_raw_flux = np.array(all_raw_lc_pc_sub)
self.all_corr_flux = np.array(all_corr_lc_pc_sub)
for epoch in range(len(self.time)):
self.tpf[epoch] += self.tpf_flux_bkg[epoch]
elif self.bkg_type == 'TPF_LEVEL':
self.all_raw_flux = np.array(all_raw_lc_tpf_sub)
self.all_corr_flux = np.array(all_corr_lc_tpf_sub)
elif self.bkg_type == 'TPF_2D_LEVEL':
self.all_raw_flux = np.array(all_raw_lc_tpf_2d_sub)
self.all_corr_flux = np.array(all_corr_lc_tpf_2d_sub)
if self.language == 'Australian':
for i in range(len(self.all_raw_flux)):
med = np.nanmedian(self.all_raw_flux[i])
self.all_raw_flux[i] = (med-self.all_raw_flux[i]) + med
med = np.nanmedian(self.all_corr_flux[i])
self.all_corr_flux[i] = (med-self.all_corr_flux[i]) + med
self.all_flux_err = np.array(all_lc_err)
self.corr_flux= self.all_corr_flux[best_ind]
self.raw_flux = self.all_raw_flux[best_ind]
self.aperture = self.all_apertures[best_ind]
self.flux_err = self.all_flux_err[best_ind]
self.aperture_size = np.nansum(self.aperture)
self.best_ind = best_ind
return
def get_cbvs(self):
""" Obtains the cotrending basis vectors (CBVs) as convolved down from the short-cadence targets.
Parameters
----------
"""
try:
matrix_file = np.loadtxt(self.source_info.eleanorpath + '/metadata/s{0:04d}/cbv_components_s{0:04d}_{1:04d}_{2:04d}.txt'.format(self.source_info.sector,
self.source_info.camera,
self.source_info.chip))
cbvs = np.asarray(matrix_file)
self.cbvs = np.reshape(cbvs, (len(self.time), 16))
except:
self.cbvs = np.zeros((len(self.time), 16))
return
def center_of_mass(self):
"""
Calculates the position of the source across all cadences using `muchbettermoments` and `self.best_aperture`.
Finds the brightest pixel in a (`height`, `width`) region summed up over all cadence.
Searches a smaller (3x3) region around this pixel at each cadence and uses `muchbettermoments` to find the maximum.
"""
self.x_com = []
self.y_com = []
summed_pixels = np.nansum(self.aperture * self.tpf, axis=0)
brightest = np.where(summed_pixels == np.max(summed_pixels))
cen = [brightest[0][0], brightest[1][0]]
if cen[0] < 3.0:
cen[0] = 3
if cen[1] < 3.0:
cen[1] = 3
if cen[0]+3 > np.shape(self.tpf[0])[0]:
cen[0] = np.shape(self.tpf[0])[0]-3
if cen[1]+3 > np.shape(self.tpf[0])[1]:
cen[1] = np.shape(self.tpf[0])[1]-3
for a in range(len(self.tpf)):
data = self.tpf[a, cen[0]-2:cen[0]+3, cen[1]-2:cen[1]+3]
c_0 = centroid_quadratic(data)
c_frame = [cen[0]+c_0[0]-2, cen[1]+c_0[1]-2]
self.x_com.append(c_frame[0])
self.y_com.append(c_frame[1])
self.x_com = np.array(self.x_com)
self.y_com = np.array(self.y_com)
return
def set_quality(self):
""" Reads in quality flags set in the postcard
"""
self.quality = np.array(self.post_obj.quality)
self.quality[np.nansum(self.tpf, axis=(1,2)) == 0] = 128
return
def psf_lightcurve(self, data_arr = None, err_arr = None, bkg_arr = None, nstars=1, model='gaussian', likelihood='gaussian',
xc=None, yc=None, verbose=True,
err_method=True, ignore_pixels=None):
"""
Performs PSF photometry for a selection of stars on a TPF.
Parameters
----------
data_arr: numpy.ndarray, optional
Data array to fit with the PSF model. If None, will default to `TargetData.tpf`.
err_arr: numpy.ndarray, optional
Uncertainty array to fit with the PSF model. If None, will default to `TargetData.tpf_flux_err`.
bkg_arr: numpy.ndarray, optional
List of background values to include as initial guesses for the background model. If None,
will default to `TargetData.flux_bkg`.
nstars: int, optional
Number of stars to be modeled on the TPF.
model: string, optional
PSF model to be applied. Presently must be `gaussian`, which models a single Gaussian.
Will be extended in the future once TESS PRF models are made publicly available.
likelihood: string, optinal
The data statistics given the parameters. Options are: 'gaussian' and 'poisson'.
xc: list, optional
The x-coordinates of stars in the zeroth cadence. Must have length `nstars`.
While the positions of stars will be fit in all cadences, the relative positions of
stars will be fixed following the delta values from this list.
yc: list, optional
The y-coordinates of stars in the zeroth cadence. Must have length `nstars`.
While the positions of stars will be fit in all cadences, the relative positions of
stars will be fixed following the delta values from this list.
verbose: bool, optional
If True, return information about the shape of the PSF at every cadence as well as the
PSF-inferred centroid shape.
err_method: bool, optional
If True, use the photometric uncertainties for each pixel in the TPF as delivered by the
TESS team. Otherwise, each pixel takes an equal uncertainty. If `err_arr` is passed
through instead, this setting is ignored.
ignore_pixels: int, optional
If not None, ignore a certain percentage of the brightest pixels away from the source
target, effectively masking other nearby, bright stars. This strategy appears to do a
reasonable job estimating the background more accurately in relatively crowded regions.
"""
import tensorflow as tf
from .models import Gaussian, Moffat
from tqdm import tqdm
tf.logging.set_verbosity(tf.logging.ERROR)
if data_arr is None:
data_arr = self.tpf + 0.0
data_arr[np.isnan(data_arr)] = 0.0
if err_arr is None:
if err_method == True:
err_arr = (self.tpf_err + 0.0) ** 2
else:
err_arr = np.ones_like(data_arr)
if bkg_arr is None:
bkg_arr = self.flux_bkg + 0.0
if yc is None:
yc = 0.5 * np.ones(nstars) * np.shape(data_arr[0])[1]
if xc is None:
xc = 0.5 * np.ones(nstars) * np.shape(data_arr[0])[0]
dsum = np.nansum(data_arr, axis=(0))
modepix = np.where(dsum == mode(dsum, axis=None)[0][0])
if len(modepix[0]) > 2.5:
for i in range(len(bkg_arr)):
err_arr[i][modepix] = np.inf
if ignore_pixels is not None:
tpfsum = np.nansum(data_arr, axis=(0))
percentile = 100-ignore_pixels
tpfsum[int(xc[0]-1.5):int(xc[0]+2.5),int(yc[0]-1.5):int(yc[0]+2.5)] = 0.0
err_arr[:, tpfsum > np.percentile(dsum, percentile)] = np.inf
if len(xc) != nstars:
raise ValueError('xc must have length nstars')
if len(yc) != nstars:
raise ValueError('yc must have length nstars')
flux = tf.Variable(np.ones(nstars)*np.max(data_arr[0]), dtype=tf.float64)
bkg = tf.Variable(bkg_arr[0], dtype=tf.float64)
xshift = tf.Variable(0.0, dtype=tf.float64)
yshift = tf.Variable(0.0, dtype=tf.float64)
if (model == 'gaussian'):
gaussian = Gaussian(shape=data_arr.shape[1:], col_ref=0, row_ref=0)
a = tf.Variable(initial_value=1., dtype=tf.float64)
b = tf.Variable(initial_value=0., dtype=tf.float64)
c = tf.Variable(initial_value=1., dtype=tf.float64)
if nstars == 1:
mean = gaussian(flux, xc[0]+xshift, yc[0]+yshift, a, b, c)
else:
mean = [gaussian(flux[j], xc[j]+xshift, yc[j]+yshift, a, b, c) for j in range(nstars)]
mean = np.sum(mean, axis=0)
var_list = [flux, xshift, yshift, a, b, c, bkg]
var_to_bounds = {flux: (0, np.infty),
xshift: (-1.0, 1.0),
yshift: (-1.0, 1.0),
a: (0, np.infty),
b: (-0.5, 0.5),
c: (0, np.infty)
}
elif model == 'moffat':
moffat = Moffat(shape=data_arr.shape[1:], col_ref=0, row_ref=0)
a = tf.Variable(initial_value=1., dtype=tf.float64)
b = tf.Variable(initial_value=0., dtype=tf.float64)
c = tf.Variable(initial_value=1., dtype=tf.float64)
beta = tf.Variable(initial_value=1, dtype=tf.float64)
if nstars == 1:
mean = moffat(flux, xc[0]+xshift, yc[0]+yshift, a, b, c, beta)
else:
mean = [moffat(flux[j], xc[j]+xshift, yc[j]+yshift, a, b, c, beta) for j in range(nstars)]
mean = np.sum(mean, axis=0)
var_list = [flux, xshift, yshift, a, b, c, beta, bkg]
var_to_bounds = {flux: (0, np.infty),
xshift: (-2.0, 2.0),
yshift: (-2.0, 2.0),
a: (0, 3.0),
b: (-0.5, 0.5),
c: (0, 3.0),
beta: (0, 10)
}
betaout = np.zeros(len(data_arr))
else:
raise ValueError('This model is not incorporated yet!') # we probably want this to be a warning actually,
# and a gentle return
aout = np.zeros(len(data_arr))
bout = np.zeros(len(data_arr))
cout = np.zeros(len(data_arr))
xout = np.zeros(len(data_arr))
yout = np.zeros(len(data_arr))
mean += bkg
data = tf.placeholder(dtype=tf.float64, shape=data_arr[0].shape)
derr = tf.placeholder(dtype=tf.float64, shape=data_arr[0].shape)
bkgval = tf.placeholder(dtype=tf.float64)
if likelihood == 'gaussian':
nll = tf.reduce_sum(tf.truediv(tf.squared_difference(mean, data), derr))
elif likelihood == 'poisson':
nll = tf.reduce_sum(tf.subtract(mean+bkgval, tf.multiply(data+bkgval, tf.log(mean+bkgval))))
else:
raise ValueError("likelihood argument {0} not supported".format(likelihood))
grad = tf.gradients(nll, var_list)
sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0}))
sess.run(tf.global_variables_initializer())
optimizer = tf.contrib.opt.ScipyOptimizerInterface(nll, var_list, method='TNC', tol=1e-4, var_to_bounds=var_to_bounds)
fout = np.zeros((len(data_arr), nstars))
bkgout = np.zeros(len(data_arr))
llout = np.zeros(len(data_arr))
for i in tqdm(range(len(data_arr))):
optim = optimizer.minimize(session=sess, feed_dict={data:data_arr[i], derr:err_arr[i], bkgval:bkg_arr[i]}) # we could also pass a pointing model here
# and just fit a single offset in all frames
fout[i] = sess.run(flux)
bkgout[i] = sess.run(bkg)
if model == 'gaussian':
aout[i] = sess.run(a)
bout[i] = sess.run(b)
cout[i] = sess.run(c)
xout[i] = sess.run(xshift)
yout[i] = sess.run(yshift)
llout[i] = sess.run(nll, feed_dict={data:data_arr[i], derr:err_arr[i], bkgval:bkg_arr[i]})
if model == 'moffat':
aout[i] = sess.run(a)
bout[i] = sess.run(b)
cout[i] = sess.run(c)
xout[i] = sess.run(xshift)
yout[i] = sess.run(yshift)
llout[i] = sess.run(nll, feed_dict={data:data_arr[i], derr:err_arr[i], bkgval:bkg_arr[i]})
betaout[i] = sess.run(beta)
sess.close()
self.psf_flux = fout[:,0]