tglc 0.5.7__tar.gz → 0.5.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: tglc
3
- Version: 0.5.7
3
+ Version: 0.5.8
4
4
  Summary: TESS-Gaia Light Curve
5
5
  Home-page: https://github.com/TeHanHunter/TESS_Gaia_Light_Curve
6
6
  Author: Te Han
@@ -24,9 +24,9 @@ Usage
24
24
  There are four fluxes in each FITS file: aperture flux, PSF flux, calibrated aperture flux, and calibrated PSF flux.
25
25
  If you are uncertain which to use:
26
26
 
27
- * Calibrated aperture flux is the most robust in transit depth. Use this if you are doing transit science.
28
- * Calibrated psf flux is better in deblending targets. Use this if you need to deblend a target near a variable source. The best deblending can be achieved with tglc package by setting a non-zero prior.
29
- * The aperture flux and PSF flux are not detrended or normalized. Use this if you are doing stellar variability science. Or, if the detrending is not optimal (default detrending has a window length of 1 day), start with the aperture flux or PSF flux and detrend carefully!
27
+ * Calibrated psf flux is better in **deblending** targets. Use this if you need to deblend a target near a variable source. The best deblending can be achieved with tglc package by setting a non-zero prior. It also gives the more accurate **transit depth** in most cases, especially when fitting with an optimized prior.
28
+ * Calibrated aperture flux usually has slightly **higher SNR**. The transit depth (or variation amplitude), however, can be imperfect since the normalization depends on the PSF fitting which is imperfect. This imperfection can be minimized by using a bigger aperture than the default aperture (3*3). One need to use the tglc package and set tglc_lc(save_aper=True) to access the 5*5 aperture. In the presence of a bright but "constant" contamination (several magnitudes brighter), the calibrated aperture flux is better in removing the constant contamination.
29
+ * The aperture flux and PSF flux are not detrended or normalized. Use this if you are doing stellar variability science with long baseline. Or, if the detrending is not optimal (default detrending has a window length of 1 day; see Known Problems below), start with the aperture flux or PSF flux and detrend carefully!
30
30
  * **If you are uncertain, start with calibrated aperture flux!**
31
31
 
32
32
  The `tutorial <tutorial/TGLC_tutorial.ipynb>`_ shows the syntaxes and differences among these light curves in several examples.
@@ -60,7 +60,8 @@ for the latest tglc release. After installation, follow the `tutorial <tutorial/
60
60
  Known Problems
61
61
  ==================================
62
62
  There are several imperfections we noticed in the MAST TGLC light curves and tglc package:
63
- * If the star is very dim (~< 15 Tmag) near a variable source, it can make the aperture and/or PSF light curve negative for some cadences. This is a very rare scenario, but could be important. The detrending algorithm could malfunction and result in bad cal_aper_flux and/or cal_psf_flux. This is now fixed for tglc package, but this problem remains for the primary mission light curves published on MAST. Please detrend again if necessary. We will also correct for the extended mission light curves on MAST.
63
+
64
+ * If the star is very dim (~< 15 Tmag) near a variable source, it can make the aperture and/or PSF light curve negative for some cadences. The detrending algorithm could malfunction and result in bad cal_aper_flux and/or cal_psf_flux. This is now fixed for tglc package, but this problem remains for the primary mission light curves published on MAST. Please detrend again if necessary.The extended mission light curves on MAST will not be affected. This is a very rare scenario, but could be important.
64
65
 
65
66
  ==================================
66
67
  Reference
@@ -10,9 +10,9 @@ Usage
10
10
  There are four fluxes in each FITS file: aperture flux, PSF flux, calibrated aperture flux, and calibrated PSF flux.
11
11
  If you are uncertain which to use:
12
12
 
13
- * Calibrated aperture flux is the most robust in transit depth. Use this if you are doing transit science.
14
- * Calibrated psf flux is better in deblending targets. Use this if you need to deblend a target near a variable source. The best deblending can be achieved with tglc package by setting a non-zero prior.
15
- * The aperture flux and PSF flux are not detrended or normalized. Use this if you are doing stellar variability science. Or, if the detrending is not optimal (default detrending has a window length of 1 day), start with the aperture flux or PSF flux and detrend carefully!
13
+ * Calibrated psf flux is better in **deblending** targets. Use this if you need to deblend a target near a variable source. The best deblending can be achieved with tglc package by setting a non-zero prior. It also gives the more accurate **transit depth** in most cases, especially when fitting with an optimized prior.
14
+ * Calibrated aperture flux usually has slightly **higher SNR**. The transit depth (or variation amplitude), however, can be imperfect since the normalization depends on the PSF fitting which is imperfect. This imperfection can be minimized by using a bigger aperture than the default aperture (3*3). One need to use the tglc package and set tglc_lc(save_aper=True) to access the 5*5 aperture. In the presence of a bright but "constant" contamination (several magnitudes brighter), the calibrated aperture flux is better in removing the constant contamination.
15
+ * The aperture flux and PSF flux are not detrended or normalized. Use this if you are doing stellar variability science with long baseline. Or, if the detrending is not optimal (default detrending has a window length of 1 day; see Known Problems below), start with the aperture flux or PSF flux and detrend carefully!
16
16
  * **If you are uncertain, start with calibrated aperture flux!**
17
17
 
18
18
  The `tutorial <tutorial/TGLC_tutorial.ipynb>`_ shows the syntaxes and differences among these light curves in several examples.
@@ -46,7 +46,8 @@ for the latest tglc release. After installation, follow the `tutorial <tutorial/
46
46
  Known Problems
47
47
  ==================================
48
48
  There are several imperfections we noticed in the MAST TGLC light curves and tglc package:
49
- * If the star is very dim (~< 15 Tmag) near a variable source, it can make the aperture and/or PSF light curve negative for some cadences. This is a very rare scenario, but could be important. The detrending algorithm could malfunction and result in bad cal_aper_flux and/or cal_psf_flux. This is now fixed for tglc package, but this problem remains for the primary mission light curves published on MAST. Please detrend again if necessary. We will also correct for the extended mission light curves on MAST.
49
+
50
+ * If the star is very dim (~< 15 Tmag) near a variable source, it can make the aperture and/or PSF light curve negative for some cadences. The detrending algorithm could malfunction and result in bad cal_aper_flux and/or cal_psf_flux. This is now fixed for tglc package, but this problem remains for the primary mission light curves published on MAST. Please detrend again if necessary.The extended mission light curves on MAST will not be affected. This is a very rare scenario, but could be important.
50
51
 
51
52
  ==================================
52
53
  Reference
@@ -6,7 +6,7 @@ with open("README.rst", "r", encoding="utf-8") as fh:
6
6
  long_description = fh.read()
7
7
  setuptools.setup(
8
8
  name="tglc",
9
- version='0.5.7',
9
+ version='0.5.8',
10
10
  author="Te Han",
11
11
  author_email="tehanhunter@gmail.com",
12
12
  description="TESS-Gaia Light Curve",
@@ -0,0 +1,3 @@
1
+ __version__ = "0.5.8"
2
+ __author__ = 'Te Han, Timothy Brandt'
3
+ __credits__ = 'University of California, Santa Barbara'
@@ -200,6 +200,7 @@ def fit_lc(A, source, star_info=None, x=0., y=0., star_num=0, factor=2, psf_size
200
200
  for j in range(len(source.time)):
201
201
  aperture[j] = np.array(source.flux[j][down:up, left:right]).flatten() - np.dot(A_cut, e_psf[j])
202
202
  aperture = aperture.reshape((len(source.time), up - down, right - left))
203
+ # np.save(f'_residual_{source.sector}.npy', aperture)
203
204
 
204
205
  # psf_lc
205
206
  over_size = psf_size * factor + 1
@@ -259,6 +260,8 @@ def fit_lc(A, source, star_info=None, x=0., y=0., star_num=0, factor=2, psf_size
259
260
  aper_flat = np.delete(aper_flat, edge_pixel[outliers])
260
261
  psf_lc[j] = np.linalg.lstsq(a, aper_flat)[0][0]
261
262
  portion = np.nansum(psf_shape[:, 4:7, 4:7]) / np.nansum(psf_shape)
263
+ # print(np.nansum(psf_shape[:, 5, 5]) / np.nansum(psf_shape))
264
+ # np.save(f'toi-5344_psf_{source.sector}.npy', psf_shape)
262
265
  return aperture, psf_lc, y - down, x - left, portion
263
266
 
264
267
 
@@ -427,12 +430,14 @@ def bg_mod(source, q=None, aper_lc=None, psf_lc=None, portion=None, star_num=0,
427
430
  :return: local background, modified aperture light curve, modified PSF light curve
428
431
  '''
429
432
  bar = 15000 * 10 ** ((source.gaia['tess_mag'][star_num] - 10) / -2.5)
433
+ # print(bar)
430
434
  # med_epsf = np.nanmedian(e_psf[:, :23 ** 2].reshape(len(source.time), 23, 23), axis=0)
431
435
  # centroid_to_aper_ratio = 4/9 * np.sum(med_epsf[10:13, 10:13]) / np.sum(med_epsf)
432
436
  # centroid_to_aper_ratio = np.nanmedian(ratio)
433
437
  # flux_bar = aperture_bar * centroid_to_aper_ratio
434
438
  # lightcurve = lightcurve + (flux_bar - np.nanmedian(lightcurve[q]))
435
439
  aperture_bar = bar * portion
440
+ # print(bar)
436
441
  local_bg = np.nanmedian(aper_lc[q]) - aperture_bar
437
442
  if np.isnan(local_bg):
438
443
  local_bg = 0
@@ -62,14 +62,14 @@ def mast_json2table(json_obj):
62
62
  return data_table
63
63
 
64
64
 
65
- def tic_advanced_search_position_rows(ra=1., dec=1., radius=0.5):
65
+ def tic_advanced_search_position_rows(ra=1., dec=1., radius=0.5, limit_mag=16):
66
66
  request = {"service": "Mast.Catalogs.Filtered.Tic.Position.Rows",
67
67
  "format": "json",
68
68
  "params": {
69
69
  "columns": 'ID, GAIA',
70
70
  "filters": [
71
71
  {"paramName": "Tmag",
72
- "values": [{"min": -10., "max": 16.5}]}],
72
+ "values": [{"min": -10., "max": (limit_mag + 0.5)}]}],
73
73
  "ra": ra,
74
74
  "dec": dec,
75
75
  "radius": radius
@@ -89,7 +89,7 @@ def convert_gaia_id(catalogdata_tic):
89
89
  gaia_array = np.array(catalogdata_tic['GAIA'])
90
90
  gaia_array = gaia_array[gaia_array != 'None']
91
91
  # np.save('gaia_array.npy', gaia_array)
92
- segment = len(gaia_array) // 10000
92
+ segment = (len(gaia_array) - 1) // 10000
93
93
  gaia_tuple = tuple(gaia_array[:10000])
94
94
  results = Gaia.launch_job_async(query.format(gaia_ids=gaia_tuple)).get_results()
95
95
  # np.save('result.npy', np.array(results))
@@ -23,7 +23,7 @@ Gaia.MAIN_GAIA_TABLE = "gaiadr3.gaia_source"
23
23
 
24
24
 
25
25
  class Source_cut(object):
26
- def __init__(self, name, size=50, sector=None, cadence=None):
26
+ def __init__(self, name, size=50, sector=None, cadence=None, limit_mag=None):
27
27
  """
28
28
  Source_cut object that includes all data from TESS and Gaia DR3
29
29
  :param name: str, required
@@ -62,7 +62,7 @@ class Source_cut(object):
62
62
  columns=['DESIGNATION', 'phot_g_mean_mag', 'phot_bp_mean_mag',
63
63
  'phot_rp_mean_mag', 'ra', 'dec', 'pmra', 'pmdec']).get_results()
64
64
  print(f'Found {len(catalogdata)} Gaia DR3 objects.')
65
- catalogdata_tic = tic_advanced_search_position_rows(ra=ra, dec=dec, radius=(self.size + 2) * 21 * 0.707 / 3600)
65
+ catalogdata_tic = tic_advanced_search_position_rows(ra=ra, dec=dec, radius=(self.size + 2) * 21 * 0.707 / 3600, limit_mag=limit_mag)
66
66
  print(f'Found {len(catalogdata_tic)} TIC objects.')
67
67
  self.tic = convert_gaia_id(catalogdata_tic)
68
68
  sector_table = Tesscut.get_sectors(coordinates=coord)
@@ -71,9 +71,12 @@ class Source_cut(object):
71
71
  print(sector_table)
72
72
  if sector is None:
73
73
  hdulist = Tesscut.get_cutouts(coordinates=coord, size=self.size)
74
- elif sector is True:
74
+ elif sector == 'first':
75
75
  hdulist = Tesscut.get_cutouts(coordinates=coord, size=self.size, sector=sector_table['sector'][0])
76
76
  sector = sector_table['sector'][0]
77
+ elif sector == 'last':
78
+ hdulist = Tesscut.get_cutouts(coordinates=coord, size=self.size, sector=sector_table['sector'][-1])
79
+ sector = sector_table['sector'][-1]
77
80
  else:
78
81
  hdulist = Tesscut.get_cutouts(coordinates=coord, size=self.size, sector=sector)
79
82
  self.catalogdata = catalogdata
@@ -234,7 +237,7 @@ class Source_cut_pseudo(object):
234
237
  self.gaia = gaia_targets
235
238
 
236
239
 
237
- def ffi_cut(target='', local_directory='', size=90, sector=None):
240
+ def ffi_cut(target='', local_directory='', size=90, sector=None, limit_mag=None):
238
241
  """
239
242
  Function to generate Source_cut objects
240
243
  :param target: string, required
@@ -249,8 +252,10 @@ def ffi_cut(target='', local_directory='', size=90, sector=None):
249
252
  """
250
253
  if sector is None:
251
254
  source_name = f'source_{target}'
252
- elif sector is True:
255
+ elif sector == 'first':
253
256
  source_name = f'source_{target}_earliest_sector'
257
+ elif sector == 'last':
258
+ source_name = f'source_{target}_last_sector'
254
259
  else:
255
260
  source_name = f'source_{target}_sector_{sector}'
256
261
  source_exists = exists(f'{local_directory}source/{source_name}.pkl')
@@ -261,6 +266,6 @@ def ffi_cut(target='', local_directory='', size=90, sector=None):
261
266
  print('Loaded ffi_cut from directory. ')
262
267
  else:
263
268
  with open(f'{local_directory}source/{source_name}.pkl', 'wb') as output:
264
- source = Source_cut(target, size=size, sector=sector)
269
+ source = Source_cut(target, size=size, sector=sector, limit_mag=limit_mag)
265
270
  pickle.dump(source, output, pickle.HIGHEST_PROTOCOL)
266
271
  return source
@@ -38,12 +38,12 @@ def zip_folder(i, sector=1, do_zip=True, lc_num_per_zip=1e6):
38
38
  original_file = f'/home/tehan/data/sector{sector:04d}/lc/{cam}-{ccd}/'
39
39
  files = glob(f'{original_file}*.fits')
40
40
  if do_zip:
41
- num_zips = int(len(files) // lc_num_per_zip + 1)
42
- for i in range(num_zips):
43
- with zipfile.ZipFile(f'{zip_file}_{i:02d}.zip', 'w') as zipMe:
44
- for file in files[int(i * lc_num_per_zip):int((i + 1) * lc_num_per_zip)]:
45
- zipMe.write(file, compress_type=zipfile.ZIP_DEFLATED)
46
- # shutil.make_archive(zip_file, 'zip', original_file)
41
+ # num_zips = int(len(files) // lc_num_per_zip + 1)
42
+ # for i in range(num_zips):
43
+ # with zipfile.ZipFile(f'{zip_file}_{i:02d}.zip', 'w') as zipMe:
44
+ # for file in files[int(i * lc_num_per_zip):int((i + 1) * lc_num_per_zip)]:
45
+ # zipMe.write(file, compress_type=zipfile.ZIP_DEFLATED)
46
+ shutil.make_archive(zip_file, 'zip', original_file)
47
47
  return
48
48
  else:
49
49
  ftps = ftplib.FTP_TLS('archive.stsci.edu')
@@ -108,8 +108,9 @@ def star_spliter(server=1, # or 2
108
108
 
109
109
 
110
110
  if __name__ == '__main__':
111
- # sector = 1
112
- # filter_no_tic(sector=sector)
113
- # hlsp_transfer(sector=sector, do_zip=True)
111
+ sector = 1
112
+ filter_no_tic(sector=sector)
113
+ hlsp_transfer(sector=sector, do_zip=True)
114
114
  # hlsp_transfer(sector=sector, do_zip=False)
115
- star_spliter(server=1) # star_list='/home/tehan/Documents/tglc/dominic_EB/eb_cat.txt'
115
+ # star_spliter(server=1)
116
+ # star_list='/home/tehan/Documents/tglc/dominic_EB/eb_cat.txt'
@@ -21,7 +21,7 @@ controller = ThreadpoolController()
21
21
 
22
22
  @controller.wrap(limits=1, user_api='blas')
23
23
  def tglc_lc(target='TIC 264468702', local_directory='', size=90, save_aper=True, limit_mag=16, get_all_lc=False,
24
- first_sector_only=False, sector=None, prior=None):
24
+ first_sector_only=False, last_sector_only=False, sector=None, prior=None):
25
25
  '''
26
26
  Generate light curve for a single target.
27
27
 
@@ -37,8 +37,11 @@ def tglc_lc(target='TIC 264468702', local_directory='', size=90, save_aper=True,
37
37
  os.makedirs(local_directory + f'epsf/', exist_ok=True)
38
38
  os.makedirs(local_directory + f'source/', exist_ok=True)
39
39
  if first_sector_only:
40
- sector = True
41
- source = ffi_cut(target=target, size=size, local_directory=local_directory, sector=sector) # sector
40
+ sector = 'first'
41
+ elif last_sector_only:
42
+ sector = 'last'
43
+ source = ffi_cut(target=target, size=size, local_directory=local_directory, sector=sector,
44
+ limit_mag=limit_mag) # sector
42
45
  if get_all_lc:
43
46
  name = None
44
47
  else:
@@ -54,14 +57,20 @@ def tglc_lc(target='TIC 264468702', local_directory='', size=90, save_aper=True,
54
57
  source.select_sector(sector=sector)
55
58
  epsf(source, factor=2, sector=source.sector, target=target, local_directory=local_directory,
56
59
  name=name, limit_mag=limit_mag, save_aper=save_aper, prior=prior)
60
+ elif first_sector_only:
61
+ source.select_sector(sector=source.sector_table['sector'][0])
62
+ epsf(source, factor=2, sector=source.sector, target=target, local_directory=local_directory,
63
+ name=name, limit_mag=limit_mag, save_aper=save_aper, prior=prior)
64
+ elif last_sector_only:
65
+ source.select_sector(sector=source.sector_table['sector'][-1])
66
+ epsf(source, factor=2, sector=source.sector, target=target, local_directory=local_directory,
67
+ name=name, limit_mag=limit_mag, save_aper=save_aper, prior=prior)
57
68
  else:
58
69
  for j in range(len(source.sector_table)):
59
70
  # try:
60
71
  source.select_sector(sector=source.sector_table['sector'][j])
61
72
  epsf(source, factor=2, sector=source.sector, target=target, local_directory=local_directory,
62
73
  name=name, limit_mag=limit_mag, save_aper=save_aper, prior=prior)
63
- if first_sector_only:
64
- break
65
74
 
66
75
 
67
76
  def search_stars(i, sector=1, tics=None, local_directory=None):
@@ -86,25 +95,72 @@ def star_spliter(server=1, # or 2
86
95
  return
87
96
 
88
97
 
89
- def plot_lc(local_directory=None):
98
+ def plot_lc(local_directory=None, type='cal_aper_flux'):
90
99
  files = glob(f'{local_directory}*.fits')
91
100
  os.makedirs(f'{local_directory}plots/', exist_ok=True)
92
101
  for i in range(len(files)):
93
102
  with fits.open(files[i], mode='denywrite') as hdul:
94
103
  q = [a and b for a, b in zip(list(hdul[1].data['TESS_flags'] == 0), list(hdul[1].data['TGLC_flags'] == 0))]
95
104
  plt.figure(constrained_layout=False, figsize=(8, 4))
96
- plt.plot(hdul[1].data['time'], hdul[1].data['cal_aper_flux'], '.', c='silver', label='cal_aper')
97
- plt.plot(hdul[1].data['time'][q], hdul[1].data['cal_aper_flux'][q], '.k', label='cal_aper_flagged')
105
+ plt.plot(hdul[1].data['time'], hdul[1].data[type], '.', c='silver', label=type)
106
+ plt.plot(hdul[1].data['time'][q], hdul[1].data[type][q], '.k', label=f'{type}_flagged')
98
107
  # plt.xlim(2845, 2855)
108
+ plt.ylim(0.5, 1.5)
109
+ plt.title(f'TIC_{hdul[0].header["TICID"]}_sector_{hdul[0].header["SECTOR"]:04d}_{type}')
110
+ plt.legend()
111
+ # plt.show()
112
+ plt.savefig(
113
+ f'{local_directory}plots/TIC_{hdul[0].header["TICID"]}_sector_{hdul[0].header["SECTOR"]:04d}.png',
114
+ dpi=300)
115
+ plt.close()
116
+
117
+
118
+ def plot_aperture(local_directory=None, type='cal_aper_flux'):
119
+ files = glob(f'{local_directory}*.fits')
120
+ os.makedirs(f'{local_directory}plots/', exist_ok=True)
121
+ portion = [0.9361215204370542, 0.9320709087810205]
122
+ data = np.empty((3, 0))
123
+
124
+ for i in range(len(files)):
125
+ with fits.open(files[i], mode='denywrite') as hdul:
126
+ print(files[i], portion[i])
127
+ q = [a and b for a, b in zip(list(hdul[1].data['TESS_flags'] == 0), list(hdul[1].data['TGLC_flags'] == 0))]
128
+ plt.figure(constrained_layout=False, figsize=(8, 4))
129
+ plt.plot(hdul[1].data['time'] % 3.79262026, hdul[1].data[type], '.', c='silver', label=type)
130
+ plt.plot(hdul[1].data['time'][q] % 3.79262026, hdul[1].data[type][q], '.k', label=f'{type}_flagged')
131
+ aperture_bar = 709.5512462444653 * portion[i]
132
+ aper_lc = np.nansum(hdul[0].data, axis=(1, 2))
133
+ local_bg = np.nanmedian(aper_lc) - aperture_bar
134
+ aper_lc = (aper_lc - local_bg) / portion[i]
135
+ cal_aper_lc = aper_lc / np.nanmedian(aper_lc)
136
+ cal_aper_lc[np.where(cal_aper_lc > 100)] = np.nan
137
+ _, trend = flatten(hdul[1].data['time'], cal_aper_lc - np.nanmin(cal_aper_lc) + 1000,
138
+ window_length=1, method='biweight', return_trend=True)
139
+ cal_aper_lc = (cal_aper_lc - np.nanmin(cal_aper_lc) + 1000 - trend) / np.nanmedian(cal_aper_lc) + 1
140
+ non_outliers = np.where(cal_aper_lc[q] > 0.6)[0]
141
+ plt.plot(hdul[1].data['time'][q][non_outliers] % 3.79262026, cal_aper_lc[q][non_outliers], '.r',
142
+ label=f'5_5_pixel_flagged')
143
+ plt.xlim(0.5, 1.0)
144
+ plt.ylim(0.95, 1.1)
99
145
  plt.title(f'TIC_{hdul[0].header["TICID"]}_sector_{hdul[0].header["SECTOR"]:04d}')
100
146
  plt.legend()
101
147
  # plt.show()
102
148
  plt.savefig(
103
149
  f'{local_directory}plots/TIC_{hdul[0].header["TICID"]}_sector_{hdul[0].header["SECTOR"]:04d}.png',
104
150
  dpi=300)
151
+ time = hdul[1].data['time'][q][non_outliers]
152
+ flux = cal_aper_lc[q][non_outliers]
153
+ f_err = 1.4826 * np.nanmedian(np.abs(flux - np.nanmedian(flux)))
154
+ not_nan = np.invert(np.isnan(flux))
155
+ data_ = np.array([time[not_nan],
156
+ flux[not_nan],
157
+ np.array([f_err] * len(time[not_nan]))
158
+ ])
159
+ data = np.append(data, data_, axis=1)
160
+ np.savetxt(f'{local_directory}TESS_TOI-5344_5_5_aper.csv', data, delimiter=',')
105
161
 
106
162
 
107
- def plot_pf_lc(local_directory=None, period=None):
163
+ def plot_pf_lc(local_directory=None, period=None, type='cal_aper_flux'):
108
164
  files = glob(f'{local_directory}*.fits')
109
165
  os.makedirs(f'{local_directory}plots/', exist_ok=True)
110
166
  fig = plt.figure(figsize=(13, 5))
@@ -116,20 +172,21 @@ def plot_pf_lc(local_directory=None, period=None):
116
172
  if len(hdul[1].data['cal_aper_flux']) == len(hdul[1].data['time']):
117
173
  if hdul[0].header["SECTOR"] <= 26:
118
174
  t = hdul[1].data['time'][q]
119
- f = hdul[1].data['cal_psf_flux'][q]
120
- else:
175
+ f = hdul[1].data[type][q]
176
+ elif hdul[0].header["SECTOR"] <= 55:
121
177
  t = np.mean(hdul[1].data['time'][q][:len(hdul[1].data['time'][q]) // 3 * 3].reshape(-1, 3), axis=1)
122
178
  f = np.mean(
123
- hdul[1].data['cal_aper_flux'][q][:len(hdul[1].data['cal_aper_flux'][q]) // 3 * 3].reshape(-1,
124
- 3),
125
- axis=1)
126
- plt.plot(hdul[1].data['time'] % period / period, hdul[1].data['cal_aper_flux'], '.', c=f'C{j}', ms=2)
127
- plt.errorbar(t % period / period, f, hdul[1].header['CAPE_ERR'], c=f'C{j}', ls='', elinewidth=0,
179
+ hdul[1].data[type][q][:len(hdul[1].data[type][q]) // 3 * 3].reshape(-1, 3), axis=1)
180
+ else:
181
+ t = np.mean(hdul[1].data['time'][q][:len(hdul[1].data['time'][q]) // 9 * 9].reshape(-1, 9), axis=1)
182
+ f = np.mean(
183
+ hdul[1].data[type][q][:len(hdul[1].data[type][q]) // 9 * 9].reshape(-1, 9), axis=1)
184
+ plt.plot(hdul[1].data['time'] % period / period, hdul[1].data[type], '.', c='silver', ms=2)
185
+ plt.errorbar(t % period / period, f, hdul[1].header['CAPE_ERR'], c=f'C{j}', ls='', elinewidth=1,
128
186
  marker='.', ms=2, zorder=2, label=f'Sector {hdul[0].header["sector"]}')
129
- #
130
187
  else:
131
188
  not_plotted_num += 1
132
- title = f'TIC_{hdul[0].header["TICID"]} with {len(files) - not_plotted_num} sector(s) of data'
189
+ title = f'TIC_{hdul[0].header["TICID"]} with {len(files) - not_plotted_num} sector(s) of data, {type}'
133
190
  # PDCSAP_files = glob('/home/tehan/Documents/GEMS/TIC 172370679/PDCSAP/*.txt')
134
191
  # for i in range(len(files)):
135
192
  # PDCSAP = ascii.read(PDCSAP_files[i])
@@ -141,7 +198,9 @@ def plot_pf_lc(local_directory=None, period=None):
141
198
  # plt.xlim(0.84, 0.86)
142
199
  plt.legend()
143
200
  plt.title(title)
144
- plt.xlabel('Phase (days)')
201
+ plt.xlim(0.16, 0.26)
202
+ plt.ylim(0.9, 1.1)
203
+ plt.xlabel('Phase')
145
204
  plt.ylabel('Normalized flux')
146
205
  plt.savefig(f'{local_directory}/plots/{title}.png', dpi=300)
147
206
  plt.close(fig)
@@ -149,6 +208,7 @@ def plot_pf_lc(local_directory=None, period=None):
149
208
 
150
209
  def plot_contamination(local_directory=None, gaia_dr3=None):
151
210
  files = glob(f'{local_directory}lc/*.fits')
211
+ os.makedirs(f'{local_directory}lc/plots/', exist_ok=True)
152
212
  for i in range(len(files)):
153
213
  with open(glob(f'{local_directory}source/*.pkl')[0], 'rb') as input_:
154
214
  with fits.open(files[i], mode='denywrite') as hdul:
@@ -159,8 +219,8 @@ def plot_contamination(local_directory=None, gaia_dr3=None):
159
219
  # print(source.gaia[891])
160
220
  # print(source.gaia[140])
161
221
  nearby_stars = np.argsort(
162
- (source.gaia[f'sector_{sector}_x'][:1000] - source.gaia[star_num][f'sector_{sector}_x']) ** 2 +
163
- (source.gaia[f'sector_{sector}_y'][:1000] - source.gaia[star_num][f'sector_{sector}_y']) ** 2)[1:10]
222
+ (source.gaia[f'sector_{sector}_x'][:500] - source.gaia[star_num][f'sector_{sector}_x']) ** 2 +
223
+ (source.gaia[f'sector_{sector}_y'][:500] - source.gaia[star_num][f'sector_{sector}_y']) ** 2)[0:5]
164
224
  # print(f'sector = {source.sector}')
165
225
  star_x = source.gaia[star_num][f'sector_{sector}_x'][0]
166
226
  star_y = source.gaia[star_num][f'sector_{sector}_y'][0]
@@ -173,7 +233,7 @@ def plot_contamination(local_directory=None, gaia_dr3=None):
173
233
  ax0 = fig.add_subplot(gs[:5, :5])
174
234
  ax0.imshow(source.flux[0], cmap='RdBu', vmin=-max_flux, vmax=max_flux, origin='lower')
175
235
 
176
- ax0.scatter(source.gaia[f'sector_{sector}_x'][:1000], source.gaia[f'sector_{sector}_y'][:1000], s=50,
236
+ ax0.scatter(source.gaia[f'sector_{sector}_x'][:500], source.gaia[f'sector_{sector}_y'][:500], s=50,
177
237
  c='r', label='background stars')
178
238
  ax0.scatter(source.gaia[f'sector_{sector}_x'][nearby_stars],
179
239
  source.gaia[f'sector_{sector}_y'][nearby_stars], s=50,
@@ -181,12 +241,31 @@ def plot_contamination(local_directory=None, gaia_dr3=None):
181
241
  for l in range(len(nearby_stars)):
182
242
  index = np.where(
183
243
  source.tic['dr3_source_id'] == int(source.gaia['DESIGNATION'][nearby_stars[l]].split(' ')[-1]))
244
+ gaia_targets = source.gaia
245
+ median_time = np.median(source.time)
246
+ interval = (median_time - 388.5) / 365.25 + 3000
247
+ ra = gaia_targets['ra'][nearby_stars[l]]
248
+ dec = gaia_targets['dec'][nearby_stars[l]]
249
+ if not np.isnan(gaia_targets['pmra'][nearby_stars[l]]):
250
+ ra += gaia_targets['pmra'][nearby_stars[l]] * np.cos(np.deg2rad(dec)) * interval / 1000 / 3600
251
+ if not np.isnan(gaia_targets['pmdec'][nearby_stars[l]]):
252
+ dec += gaia_targets['pmdec'][nearby_stars[l]] * interval / 1000 / 3600
253
+ pixel = source.wcs.all_world2pix(np.array([ra, dec]).reshape((1, 2)), 0)
254
+ x_gaia = pixel[0][0]
255
+ y_gaia = pixel[0][1]
256
+ ax0.arrow(source.gaia[f'sector_{sector}_x'][nearby_stars[l]],
257
+ source.gaia[f'sector_{sector}_y'][nearby_stars[l]],
258
+ x_gaia - source.gaia[f'sector_{sector}_x'][nearby_stars[l]],
259
+ y_gaia - source.gaia[f'sector_{sector}_y'][nearby_stars[l]],
260
+ width=0.02, color='r', edgecolor=None, head_width=0.1)
184
261
  try:
185
262
  ax0.text(source.gaia[f'sector_{sector}_x'][nearby_stars[l]] - 0.1,
186
- source.gaia[f'sector_{sector}_y'][nearby_stars[l]] + 0.2,
187
- f'TIC {int(source.tic["TIC"][index])}', rotation=90)
263
+ source.gaia[f'sector_{sector}_y'][nearby_stars[l]] + 0.3,
264
+ f'TIC {int(source.tic["TIC"][index])}', rotation=90)
188
265
  except TypeError:
189
- pass
266
+ ax0.text(source.gaia[f'sector_{sector}_x'][nearby_stars[l]] - 0.1,
267
+ source.gaia[f'sector_{sector}_y'][nearby_stars[l]] + 0.2,
268
+ f'{source.gaia[f"DESIGNATION"][nearby_stars[l]]}', rotation=90)
190
269
  ax0.scatter(star_x, star_y, s=300, c='r', marker='*', label='target star')
191
270
 
192
271
  # ax0.legend()
@@ -214,47 +293,38 @@ def plot_contamination(local_directory=None, gaia_dr3=None):
214
293
  for k in range(x_):
215
294
  ax_ = fig.add_subplot(gs[(4 - j), (5 + k)])
216
295
  ax_.patch.set_facecolor('C0')
217
- ax_.patch.set_alpha(min(1, max(0, 3 * np.median(hdul[0].data[:, j, k]) / max_flux)))
296
+ ax_.patch.set_alpha(min(1, max(0, 5 * np.nanmedian(hdul[0].data[:, j, k]) / max_flux)))
218
297
  q = [a and b for a, b in
219
298
  zip(list(hdul[1].data['TESS_flags'] == 0), list(hdul[1].data['TGLC_flags'] == 0))]
220
299
 
221
300
  _, trend = flatten(hdul[1].data['time'][q],
222
- hdul[0].data[:, j, k][q] - np.min(hdul[0].data[:, j, k][q]) + 1000,
301
+ hdul[0].data[:, j, k][q] - np.nanmin(hdul[0].data[:, j, k][q]) + 1000,
223
302
  window_length=1, method='biweight', return_trend=True)
224
- cal_aper = (hdul[0].data[:, j, k][q] - np.min(
225
- hdul[0].data[:, j, k][q]) + 1000 - trend) / np.median(
303
+ cal_aper = (hdul[0].data[:, j, k][q] - np.nanmin(
304
+ hdul[0].data[:, j, k][q]) + 1000 - trend) / np.nanmedian(
226
305
  hdul[0].data[:, j, k][q]) + 1
227
306
  ax_.plot(hdul[1].data['time'][q], cal_aper, '.k', ms=1, label='center pixel')
307
+ ax_.set_ylim(0.95, 1.05)
228
308
  plt.savefig(f'{local_directory}lc/plots/contamination_sector_{hdul[0].header["SECTOR"]:04d}.pdf',
229
309
  dpi=300)
230
310
  plt.show()
231
311
 
232
312
 
233
- def choose_prior(local_directory=None, priors=np.logspace(-5, 0, 100)):
234
- mad = np.zeros((5, 100))
313
+ def choose_prior(tics, local_directory=None, priors=np.logspace(-5, 0, 100)):
314
+ mad = np.zeros((2, 100))
235
315
  for i in trange(len(priors)):
236
- get_tglc_lc(tics=tics, method='query', server=1, directory=local_directory, prior=priors[i])
237
- with fits.open(
238
- '/home/tehan/data/cosmos/GEMS/TIC 172370679/lc/hlsp_tglc_tess_ffi_gaiaid-2073530190996615424-s0014-cam1-ccd1_tess_v1_llc.fits',
239
- mode='denywrite') as hdul:
240
- mad[0, i] = np.median(abs(hdul[1].data['cal_psf_flux'] - np.median(hdul[1].data['cal_psf_flux'])))
241
- with fits.open(
242
- '/home/tehan/data/cosmos/GEMS/TIC 172370679/lc/hlsp_tglc_tess_ffi_gaiaid-2073530190996615424-s0015-cam1-ccd2_tess_v1_llc.fits',
243
- mode='denywrite') as hdul:
244
- mad[1, i] = np.median(abs(hdul[1].data['cal_psf_flux'] - np.median(hdul[1].data['cal_psf_flux'])))
245
- with fits.open(
246
- '/home/tehan/data/cosmos/GEMS/TIC 172370679/lc/hlsp_tglc_tess_ffi_gaiaid-2073530190996615424-s0041-cam1-ccd1_tess_v1_llc.fits',
247
- mode='denywrite') as hdul:
248
- mad[2, i] = np.median(abs(hdul[1].data['cal_psf_flux'] - np.median(hdul[1].data['cal_psf_flux'])))
249
- with fits.open(
250
- '/home/tehan/data/cosmos/GEMS/TIC 172370679/lc/hlsp_tglc_tess_ffi_gaiaid-2073530190996615424-s0054-cam3-ccd2_tess_v1_llc.fits',
251
- mode='denywrite') as hdul:
252
- mad[3, i] = np.median(abs(hdul[1].data['cal_psf_flux'] - np.median(hdul[1].data['cal_psf_flux'])))
253
- with fits.open(
254
- '/home/tehan/data/cosmos/GEMS/TIC 172370679/lc/hlsp_tglc_tess_ffi_gaiaid-2073530190996615424-s0055-cam3-ccd1_tess_v1_llc.fits',
255
- mode='denywrite') as hdul:
256
- mad[4, i] = np.median(abs(hdul[1].data['cal_psf_flux'] - np.median(hdul[1].data['cal_psf_flux'])))
257
- np.save('/home/tehan/data/cosmos/GEMS/TIC 172370679/mad.npy', mad)
316
+ resid = get_tglc_lc(tics=tics, method='query', server=1, directory=local_directory, prior=priors[i])
317
+ print(resid)
318
+ mad[:, i] = resid
319
+ # with fits.open(
320
+ # '/home/tehan/data/cosmos/GEMS/TIC 16005254/lc/hlsp_tglc_tess_ffi_gaiaid-52359538285081728-s0043-cam3-ccd3_tess_v1_llc.fits',
321
+ # mode='denywrite') as hdul:
322
+ # mad[0, i] = np.nanmedian(abs(hdul[1].data['cal_psf_flux'] - np.nanmedian(hdul[1].data['cal_psf_flux'])))
323
+ # with fits.open(
324
+ # '/home/tehan/data/cosmos/GEMS/TIC 16005254/lc/hlsp_tglc_tess_ffi_gaiaid-52359538285081728-s0044-cam1-ccd1_tess_v1_llc.fits',
325
+ # mode='denywrite') as hdul:
326
+ # mad[1, i] = np.nanmedian(abs(hdul[1].data['cal_psf_flux'] - np.nanmedian(hdul[1].data['cal_psf_flux'])))
327
+ np.save('/home/tehan/Documents/GEMS/TIC 16005254/mad.npy', mad)
258
328
  # plt.plot(priors, mad)
259
329
  # plt.xscale('log')
260
330
  # plt.title(f'best prior = {priors[np.argmin(mad)]:04d}')
@@ -267,19 +337,19 @@ def get_tglc_lc(tics=None, method='query', server=1, directory=None, prior=None)
267
337
  target = f'TIC {tics[i]}'
268
338
  local_directory = f'{directory}{target}/'
269
339
  os.makedirs(local_directory, exist_ok=True)
270
- tglc_lc(target=target, local_directory=local_directory, size=90, save_aper=True, limit_mag=16,
271
- get_all_lc=False, first_sector_only=False, sector=None, prior=prior)
340
+ tglc_lc(target=target, local_directory=local_directory, size=90, save_aper=False, limit_mag=16,
341
+ get_all_lc=False, first_sector_only=False, last_sector_only=True, sector=None, prior=prior)
272
342
  if method == 'search':
273
343
  star_spliter(server=server, tics=tics, local_directory=directory)
274
344
 
275
345
 
276
346
  if __name__ == '__main__':
277
- tics = [119585136]
347
+ tics = [11893637]
278
348
  directory = f'/home/tehan/data/cosmos/GEMS/'
279
349
  os.makedirs(directory, exist_ok=True)
280
350
  get_tglc_lc(tics=tics, method='query', server=1, directory=directory)
281
- # plot_contamination(local_directory=f'{directory}TIC 27858644/', gaia_dr3=2091177593123254016)
282
- # plot_contamination(local_directory=f'{directory}TIC 172370679/', gaia_dr3=2073530190996615424)
283
- # plot_lc(local_directory=f'{directory}TIC 135272255/lc/')
284
- # plot_pf_lc(local_directory=f'{directory}TIC 27858644/lc/', period=384)
285
- # choose_prior(local_directory=directory)
351
+ plot_lc(local_directory=f'{directory}TIC {tics[0]}/lc/', type='cal_aper_flux')
352
+ # plot_aperture(local_directory=f'{directory}TIC {tics[0]}/lc/', type='cal_aper_flux')
353
+ # plot_contamination(local_directory=f'{directory}TIC {tics[0]}/', gaia_dr3=52359538285081728)
354
+ # plot_pf_lc(local_directory=f'{directory}TIC {tics[0]}/lc/', period=3.7926244)
355
+ # choose_prior(tics, local_directory=directory)
@@ -278,9 +278,11 @@ def epsf(source, psf_size=11, factor=2, local_directory='', target=None, cut_x=0
278
278
  str(source.tic['dr3_source_id'][np.where(source.tic['TIC'] == name)][0]))[0][0])
279
279
  end = start + 1
280
280
  except IndexError:
281
- print(f'Target not found in the requested sector (Sector {sector}). It is possible that this target does '
282
- f'not have a Gaia ID. ')
283
- return
281
+ print(f'Target not found in the requested sector (Sector {sector}). This can be caused by a lack of Gaia '
282
+ f'ID or an incomplete TESS to Gaia crossmatch table. Please check whether the output light curve Gaia'
283
+ f' DR3 ID agrees with your target.')
284
+ start = 0
285
+ end = 1
284
286
  for i in trange(start, end, desc='Fitting lc', disable=no_progress_bar):
285
287
  if x_left <= x_round[i] < source.size - x_right and y_left <= y_round[i] < source.size - y_right:
286
288
  if type(source) == Source:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: tglc
3
- Version: 0.5.7
3
+ Version: 0.5.8
4
4
  Summary: TESS-Gaia Light Curve
5
5
  Home-page: https://github.com/TeHanHunter/TESS_Gaia_Light_Curve
6
6
  Author: Te Han
@@ -24,9 +24,9 @@ Usage
24
24
  There are four fluxes in each FITS file: aperture flux, PSF flux, calibrated aperture flux, and calibrated PSF flux.
25
25
  If you are uncertain which to use:
26
26
 
27
- * Calibrated aperture flux is the most robust in transit depth. Use this if you are doing transit science.
28
- * Calibrated psf flux is better in deblending targets. Use this if you need to deblend a target near a variable source. The best deblending can be achieved with tglc package by setting a non-zero prior.
29
- * The aperture flux and PSF flux are not detrended or normalized. Use this if you are doing stellar variability science. Or, if the detrending is not optimal (default detrending has a window length of 1 day), start with the aperture flux or PSF flux and detrend carefully!
27
+ * Calibrated psf flux is better in **deblending** targets. Use this if you need to deblend a target near a variable source. The best deblending can be achieved with tglc package by setting a non-zero prior. It also gives the more accurate **transit depth** in most cases, especially when fitting with an optimized prior.
28
+ * Calibrated aperture flux usually has slightly **higher SNR**. The transit depth (or variation amplitude), however, can be imperfect since the normalization depends on the PSF fitting which is imperfect. This imperfection can be minimized by using a bigger aperture than the default aperture (3*3). One need to use the tglc package and set tglc_lc(save_aper=True) to access the 5*5 aperture. In the presence of a bright but "constant" contamination (several magnitudes brighter), the calibrated aperture flux is better in removing the constant contamination.
29
+ * The aperture flux and PSF flux are not detrended or normalized. Use this if you are doing stellar variability science with long baseline. Or, if the detrending is not optimal (default detrending has a window length of 1 day; see Known Problems below), start with the aperture flux or PSF flux and detrend carefully!
30
30
  * **If you are uncertain, start with calibrated aperture flux!**
31
31
 
32
32
  The `tutorial <tutorial/TGLC_tutorial.ipynb>`_ shows the syntaxes and differences among these light curves in several examples.
@@ -60,7 +60,8 @@ for the latest tglc release. After installation, follow the `tutorial <tutorial/
60
60
  Known Problems
61
61
  ==================================
62
62
  There are several imperfections we noticed in the MAST TGLC light curves and tglc package:
63
- * If the star is very dim (~< 15 Tmag) near a variable source, it can make the aperture and/or PSF light curve negative for some cadences. This is a very rare scenario, but could be important. The detrending algorithm could malfunction and result in bad cal_aper_flux and/or cal_psf_flux. This is now fixed for tglc package, but this problem remains for the primary mission light curves published on MAST. Please detrend again if necessary. We will also correct for the extended mission light curves on MAST.
63
+
64
+ * If the star is very dim (~< 15 Tmag) near a variable source, it can make the aperture and/or PSF light curve negative for some cadences. The detrending algorithm could malfunction and result in bad cal_aper_flux and/or cal_psf_flux. This is now fixed for tglc package, but this problem remains for the primary mission light curves published on MAST. Please detrend again if necessary.The extended mission light curves on MAST will not be affected. This is a very rare scenario, but could be important.
64
65
 
65
66
  ==================================
66
67
  Reference
@@ -1,3 +0,0 @@
1
- __version__ = "0.5.7"
2
- __author__ = 'Te Han, Timothy Brandt'
3
- __credits__ = 'University of California, Santa Barbara'
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes