def get_ffilc(name=None, tic=None, coords=None, sectors='all'): """ """ if name is None and tic is None and coords is None: raise ValueError('Please specify a name, TIC ID, or coordinates!') if name is None and tic is not None: name = 'TIC ' + str(tic) if coords is not None: if isinstance(coords, tuple) or isinstance(coords, list): coords = SkyCoord(coords[0], coords[1], unit='deg') if sectors == 'all' and coords is not None: sector_table = Tesscut.get_sectors(coordinates=coord) sectors = list( map(int, [row[6:10] for row in sector_table['sectorName']])) #tesscut add more here to parse sectors? elif sectors == 'all' and name is not None: sector_table = Tesscut.get_sectors(objectname=name) sectors = list( map(int, [row[6:10] for row in sector_table['sectorName']])) if name is None and tic is not None: name = "TIC " + str(tic) search_result = lk.search_tesscut(name, sector=sectors) else: print('hi')
def showStar(self): plt.close('all') if (len(self.RA) == 0): self.changeCounter(0) self.errorWindow("ALL DONE.") self.clearValues() self.changeRADEC() coord = SkyCoord(self.RA[len(self.RA) - 1], self.DE[len(self.DE) - 1], unit="deg") self.tpf = search_tesscut(coord).download_all(cutout_size=(10, 10)) print(self.tpf) if (hasattr(self.tpf, "__len__")): self.target_mask0 = self.tpf[0].create_threshold_mask(threshold=3) n_target_pixels = self.target_mask0.sum() raw_lc = self.tpf[0].to_lightcurve(aperture_mask=self.target_mask0) time_mask = ( (raw_lc.time < 1856) | (raw_lc.time > 1858)) # sector 20 raw_lc = raw_lc[time_mask] self.bkgr_mask0 = ~self.tpf[0].create_threshold_mask( threshold=0.001, reference_pixel=None) n_background_pixels = self.bkgr_mask0.sum() bkgr_lc_per_pixel = self.tpf[0].to_lightcurve( aperture_mask=self.bkgr_mask0) / n_background_pixels bkgr_lc_per_pixel = bkgr_lc_per_pixel[time_mask] bkgr_estimate_lc = bkgr_lc_per_pixel * n_target_pixels self.star_lc = (raw_lc - bkgr_estimate_lc.flux).flatten() self.star_lc = self.star_lc.remove_nans().remove_outliers(sigma=6) for itpf in self.tpf[1:]: target_mask = itpf.create_threshold_mask(threshold=3) n_target_pixels = target_mask.sum() raw_lc = itpf.to_lightcurve(aperture_mask=target_mask) raw_lc = raw_lc[time_mask] bkgr_mask = ~itpf.create_threshold_mask(threshold=0.001, reference_pixel=None) n_background_pixels = bkgr_mask.sum() bkgr_lc_per_pixel = itpf.to_lightcurve( aperture_mask=bkgr_mask) / n_background_pixels bkgr_lc_per_pixel = bkgr_lc_per_pixel[time_mask] bkgr_estimate_lc = bkgr_lc_per_pixel * n_target_pixels temp_lc = (raw_lc - bkgr_estimate_lc.flux).flatten() temp_lc = temp_lc.remove_nans().remove_outliers(sigma=6) self.star_lc = self.star_lc.append(temp_lc) self.lspg = self.star_lc.to_periodogram(maximum_frequency=12.0, oversample_factor=10) else: self.errorWindow("NOT IN SECTOR") self.saveStar() return # Put TPF in window self.addTPF() # Make plots self.updatePlots()
def download_target_px_file(tic_id): """ """ sr = lk.search_tesscut("TIC {}".format(tic_id)) lcfs = sr.download_all() tpf = lcfs[0] aperture_mask = tpf.create_threshold_mask(threshold=7) lc = tpf.to_lightcurve(aperture_mask=aperture_mask) return lc
def Get_TESS(RA, DEC, Size, Sector=None): ''' Use the lightkurve mast query to get FFI cutouts of a given position ''' c = SkyCoord(ra=float(RA) * u.degree, dec=float(DEC) * u.degree, frame='icrs') tess = lk.search_tesscut(c, sector=Sector) tpf = tess.download(cutout_size=Size) return tpf
def plot_gaia_overlay(self, tic=None, tpf=None, magnitude_limit=18): """Check if the source is contaminated.""" if tic is None: tic = self.obj.source_info.tic if tpf is None: tpf = lk.search_tesscut(f'TIC {tic}')[0].download(cutout_size=(self.obj.tpf.shape[1], self.obj.tpf.shape[2])) fig = tpf.plot(show_colorbar=False, title='TIC {0}'.format(tic)) fig = self._add_gaia_figure_elements(tpf, fig, magnitude_limit=magnitude_limit) return fig
def xmkpy3_plot_add_compass_rose_v5(): import matplotlib.pyplot as plt import lightkurve as lk # obj = 3 # USER CUSTOMIZE # tpf = None if (obj == 1): north_arm_arcsec = 8 tpf = lk.search_targetpixelfile( target='Kepler-138b', mission='Kepler', quarter=10)\ .download(quality_bitmask=0) # ^--- Exoplanet Kelper-138b is "KIC 7603200" elif (obj == 2): north_arm_arcsec = 42 search_results = lk.search_tesscut(target='CD Ind', sector=1) tpf = search_results[0].download(cutout_size=(11, 11), quality_bitmask=0) elif (obj == 3): north_arm_arcsec = 42 tpf = lk.search_targetpixelfile(target='CD Ind', mission='TESS', sector=1).download(quality_bitmask=0) else: print('***ERROR*** BAD OBJECT NUMBER:', obj) # pass:if assert (tpf is not None) # # Plot the 2nd frame of the TPF ax = tpf.plot(frame=1, cmap='gray_r') # # add a compass rose using the WCS from the TargetPixelFile mkpy3_plot_add_compass_rose_v5(ax=ax, wcs=tpf.wcs, north_arm_arcsec=north_arm_arcsec, verbose=True) # print(tpf.path, '\n^--- tpf.path\n') print(tpf.ra, '=tpf.ra') print(tpf.dec, '=tpf.dec') print(obj, '=obj') # plot_file = 'mkpy3_plot1.png' plt.savefig(plot_file, bbox_inches="tight") plt.close() print('\n', plot_file, ' <--- new PNG file written')
def test_tpf_cutout(): """ """ t = FFI_cutout( ticid=TICID, sector=SECTOR, quality_bitmask="default", apply_data_quality_mask=False, cutout_size=CUTOUT_SIZE, ) tpf1 = t.get_tpf_tesscut() assert tpf1.targetid == TICID assert tpf1.sector == SECTOR assert tpf1.flux.shape[1:] == CUTOUT_SIZE res = lk.search_tesscut(f"TIC {t.ticid}", sector=SECTOR) # assert tpf2.flux.shape[1:] == CUTOUT_SIZE tpf2 = res.download() assert f"TIC {tpf1.targetid}" == tpf2.targetid assert tpf1.sector == tpf2.sector assert tpf1.quality_bitmask == tpf2.quality_bitmask
def extract_sectors(object_info, cache_dir): mission, mission_prefix, id_int = LcBuilder().parse_object_info( object_info.mission_id()) object_sectors = None if mission == "Kepler": lcf_search_results = lightkurve.search_targetpixelfile( object_info.mission_id(), mission=object_info.mission_id(), cadence="long") object_sectors = lcf_search_results.download_all( download_dir=cache_dir).quarter elif mission == "K2": lcf_search_results = lightkurve.search_targetpixelfile( object_info.mission_id(), mission=object_info.mission_id(), cadence="long") object_sectors = lcf_search_results.download_all( download_dir=cache_dir).campaign elif mission == "TESS": lcf_search_results = lightkurve.search_tesscut( object_info.mission_id()) object_sectors = lcf_search_results.download_all( download_dir=cache_dir).sector return object_sectors
if load_handpicked: # Get hand picked group key gmin = targets[handpicked_key].min() # Get original apertures group_apts = getOrigAps(targets) # Download each TESS cuts for each target for ticid, Ggroup in targets[[ticid_col, handpicked_key]]: # Get aperture and convert to Keppler/Tess format apt = group_apts[Ggroup - gmin] + 1 apt[apt == 2] += 1 print(f'Downloading TIC ID={ticid}') tpf = search_tesscut(ticid, sector=sector).download(cutout_size=cutout_size) # Write TIC ID and pipeline aperture to HDUs tpf.hdu[0].header['TIC ID'] = ticid tpf.hdu[0].header['TICID'] = ticid tpf.hdu[2].data = apt tpf_fn = template_fn.format(ticid=ticid, sec=sector, cutsize=cutout_size) print(f'Saving to {tpf_fn}') tpf.to_fits(output_fn=tpf_fn, overwrite=True) else: # Download each TESS cuts for each target for ticid in targets[ticid_col]:
print('\n\nDATA ==========================================================') obj = 6 # <--- USER CUSTOMIZE if (obj == 1): target = 'CD Ind' mission = 'TESS' sector = 1 width_height_arcmin = 6 # use with TESS <--- USER CUSTOMIZE north_arm_arcsec = 42 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.9 # USER CUSTOMIZE title_ = target + ' : TESS : Sector ' + str(sector) # USER CUSTOMIZE title2_ = title_ + " : Frame " + str(frame) print('DOWNLOAD START:', str(datetime.datetime.now())) search_results = lk.search_tesscut(target=target, sector=sector)[0] tpf = search_results[0].download(cutout_size=(11, 11), quality_bitmask=0) print('DOWNLOAD STOP:', str(datetime.datetime.now())) # pass:if if (obj == 2): target = 'XZ Cyg' mission = 'TESS' sector = 14 width_height_arcmin = 6 # use with TESS <--- USER CUSTOMIZE north_arm_arcsec = 42 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.9 # USER CUSTOMIZE title_ = target + ' : TESS : Sector ' + str(sector) # USER CUSTOMIZE title2_ = title_ + " : Frame " + str(frame) print('DOWNLOAD START:', str(datetime.datetime.now()))
def mkpy3_tess_tpf_overlay_v6( tpf=None, frame=0, survey='2MASS-J', rotationAngle_deg=None, # None or '123.456' (float) or 'tpf' width_height_arcmin=6.0, shrink=1.0, show_plot=True, plot_file='mkpy3_plot.png', overwrite=False, figsize_str='[9,9]', title=None, percentile=99.5, cmap='gray_r', colors_str="[None,'dodgerblue','red']", lws_str='[0,3,4]', zorders_str='[0,2,4]', marker_kwargs_str="{'edgecolor':'yellow', 's':600, 'facecolor':'None', " "'lw':3, 'zorder':10}", # or 'None' print_gaia_dr2=True, gaia_dr2_kwargs_str="{'edgecolor':'cyan', 's':150, 'facecolor':'None', " "'lw':3, 'zorder':20}", # or 'None' print_vsx=True, vsx_kwargs_str="{'s':900, 'color':'lawngreen', 'marker':'x', 'lw':5, " "'zorder':30}", # or 'None' sexagesimal=False, verbose=False ): """ Function: mkpy3_tess_tpf_overlay_v6() Purpose: Plot a TESS TargetPixelFile (TPF) overlay on a sky survey image. Parameters ---------- tpf : (lightkurve TargetPixelFile object) (optional) A lightkurve TargetPixelFile (TPF) object. [default: None] frame : (int) (optional) Frame number to use. [range: 0 to number of cadences in the TPF minus 1] [default: 0] survey : (str) (optional) A sky survey name. [default: '2MASS-J'] [verified: '2MASS-J', 'DSS2 Red'] rotationAngle_deg : None, (float), or 'tpf' (3-char str) (optional) Angle in degrees to rotate the sky survey image. [default: None ---> 'tpf'] [example values: 'None' or 12.345 (float) or 'tpf'] width_height_arcmin : (float) (optional) Width and height of the survey image [arcmin]. [default: 6.0] shrink : (float) (optional) Survey search radius shrink factor. [range: 0.0 to 1.0] [default: 1.0] show_plot : (bool) (optional) If True, show the plot. [default=True] plot_file : (str) (optional) Filename of the output plot. [default: 'mkpy3_plot.png'] overwrite : (bool) (optional) If True, overwrite ("clobber") an existing output file. If False, do *not* create output file when plot_file != 'mkpy3_plot.png'. [default: False] figsize_str : (str) (optional) A string of a 2-time list of figure widht and height [Matplotlib]. [default: '[9,9]'] title : (str) (optional) Title of the plot. If None, a title will be created. An empty string ('') will produce a blank title. [default: None] percentile : (float) (optional) Percentile [percentage of pixels to keep] used to set the colorbar. [range: 0.0 to 100.0] [default: 99.5] cmap : (str) (optional) Colormap name [Matplotlib]. [default: 'gray_r'] colors_str : (str) (optional) A string of a 3-item list of overlay color names [Matplotlib]. [default: "['None','dodgerblue','red']"] lws_str : (str) (optional) A string of a 3-item list of overlay line widths [Matplotlib]. [default: '[0,3,4]'] zorders_str : (str) (optional) A string of a 3-item list of overlay zorder values [Matplotlib]. [default: '[0,2,4]'] marker_kwargs_str : (str) (optional) A string of a dictionary of arguments for ax.scatter() [Matplotlib]. The target is marked according to the kwarg values. If set to None, the target is *not* marked. [default: "{'edgecolor':'yellow', 's':600, 'facecolor':'None', 'lw':3, 'zorder':10}"] print_gaia_dr2 : (bool) (optional) If True, print the GAIA DR2 catalog results. [default=True] gaia_dr2_kwargs_str : (str) (optional) A string of a dictionary of arguments for ax.scatter() [Matplotlib]. GAIA DR2 stars are marked accordinbg to the kwarg values. If set to None, no GAIA DR2 data are shown and plotted. [default: "{'edgecolor':'cyan', 's':150, 'facecolor':'None', 'lw':3, 'zorder':20}"] print_vsx : (bool) (optional) If True, print the VSX catalog results. [default=True] vsx_kwargs_str : (str) (optional) A string of a dictionary of arguments for ax.scatter() [Matplotlib]. VSX varaible stars are marked accordinbg to the kwarg values. If set to None, no VSX data are shown and plotted. [default: "{'s':900, 'color':'lawngreen', 'marker':'x', 'lw':5, 'zorder':30}"] sexagesimal : (bool) (optional) If True, print catalog positions as sexagesimal [hms dms]. [default=False] verbose : (bool) (optional) If True, print extra information. [default: False] Returns ------- ax : (matplotlib axes object) or (None) A matplotlib axes object *if* show_plot is False *else* None . # Kenneth Mighell # Kepler Support Scientist # NASA Ames Research Center / SETI Institute """ import ntpath import os import sys import lightkurve as lk import mkpy3 if (tpf is None): target = 'V1460 Her' sector = 24 # alternative: # target = 'XZ Cyg' # sector = 14 title = target + ' : TESS : Sector ' + str(sector) search_result = lk.search_tesscut(target=target, sector=sector)[0] tpf = search_result.download(cutout_size=(11, 13), quality_bitmask=0) # pass:if assert(tpf is not None) tpf_filename = ntpath.basename(tpf.path) tpf_dirname = os.path.dirname(tpf.path) try: print() print('TPF filename:', tpf_filename) print('TPF dirname: ', tpf_dirname) assert(tpf.mission == 'TESS') print() except Exception: print(tpf_filename, '=tpf_filename') print('^--- *** ERROR *** This file does not appear to be a TESS ' 'TargetPixelFile') print() print('Bye...\n', flush=True) sys.exit(1) # pass:try ax = mkpy3.mkpy3_tpf_overlay_v6( tpf=tpf, frame=frame, survey=survey, rotationAngle_deg=rotationAngle_deg, width_height_arcmin=width_height_arcmin, shrink=shrink, show_plot=show_plot, plot_file=plot_file, overwrite=overwrite, figsize_str=figsize_str, title=title, percentile=percentile, cmap=cmap, colors_str=colors_str, lws_str=lws_str, zorders_str=zorders_str, marker_kwargs_str=marker_kwargs_str, print_gaia_dr2=print_gaia_dr2, gaia_dr2_kwargs_str=gaia_dr2_kwargs_str, print_vsx=print_vsx, vsx_kwargs_str=vsx_kwargs_str, sexagesimal=sexagesimal, verbose=verbose) return ax
if args.gid != None: gaia_id, mag = args.gid, np.float(args.gmag) else: if args.COORD is not False: gaia_id, mag = get_gaia_data(ra, dec) else: gaia_id, mag = get_gaia_data_from_tic(tic) if np.isnan(mag): gaia_id, mag = get_gaia_data(ra, dec) # By coordinates ----------------------------------------------------------------- if args.COORD is not False: # if args.sector != None: tpf = search_tesscut(ra + " " + dec, sector=int(args.sector)).download( cutout_size=(12, 12)) # else: tpf = search_tesscut(ra + " " + dec).download( cutout_size=(12, 12)) # pipeline = "False" print(' --> Using TESScut to get the TPF') # By TIC name -------------------------------------------------------------------- else: # If the target is in the CTL (short-cadance targets)... try: if args.sector != None: tpf = search_targetpixelfile("TIC " + tic, sector=int(args.sector),
def xmkpy3_tpf_overlay_v6(): """ Unit test """ import matplotlib.pyplot as plt import os import ntpath import datetime import lightkurve as lk from astropy.visualization import ImageNormalize, PercentileInterval,\ SqrtStretch # import mkpy3 cmap = 'gray_r' verbose = False mission = None target = None quarter = None campaign = None sector = None print( '\n\nDATA ==========================================================') obj = 6 # <--- USER CUSTOMIZE if (obj == 1): target = 'CD Ind' mission = 'TESS' sector = 1 width_height_arcmin = 6 # use with TESS <--- USER CUSTOMIZE north_arm_arcsec = 42 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.9 # USER CUSTOMIZE title_ = target + ' : TESS : Sector ' + str(sector) # USER CUSTOMIZE print('DOWNLOAD START:', str(datetime.datetime.now())) search_results = lk.search_tesscut(target=target, sector=sector)[0] tpf = search_results[0].download(cutout_size=(11, 11), quality_bitmask=0) print('DOWNLOAD STOP:', str(datetime.datetime.now())) # pass:if if (obj == 2): target = 'XZ Cyg' mission = 'TESS' sector = 14 width_height_arcmin = 6 # use with TESS <--- USER CUSTOMIZE north_arm_arcsec = 42 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.9 # USER CUSTOMIZE title_ = target + ' : TESS : Sector ' + str(sector) # USER CUSTOMIZE print('DOWNLOAD START:', str(datetime.datetime.now())) search_results = lk.search_tesscut(target=target, sector=sector)[0] tpf = search_results[0].download(cutout_size=(11, 11), quality_bitmask=0) print('DOWNLOAD STOP:', str(datetime.datetime.now())) # pass:if if (obj == 3): target = 'V1460 Her' mission = 'TESS' sector = 24 width_height_arcmin = 6 # use with TESS <--- USER CUSTOMIZE north_arm_arcsec = 42 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.9 # USER CUSTOMIZE title_ = target + ' : TESS : Sector ' + str(sector) # USER CUSTOMIZE print('DOWNLOAD START:', str(datetime.datetime.now())) search_results = lk.search_tesscut(target=target, sector=sector)[0] tpf = search_results[0].download(cutout_size=(11, 11), quality_bitmask=0) print('DOWNLOAD STOP:', str(datetime.datetime.now())) # pass:if if (obj == 4): target = 'Kepler-138b' mission = 'Kepler' quarter = 10 width_height_arcmin = 1.8 # use with Kepler/K2 <--- USER CUSTOMIZE north_arm_arcsec = 6 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.0 # USER CUSTOMIZE title_ = target + ' : Kepler : Quarter ' + str( quarter) # USER CUSTOMIZE print('DOWNLOAD START:', str(datetime.datetime.now())) tpf = lk.search_targetpixelfile( target=target, mission=mission, quarter=quarter).download(quality_bitmask=0) # ^--- exoplanet Kelper-138b is "KIC 7603200" print('DOWNLOAD STOP:', str(datetime.datetime.now())) # pass:if if (obj == 5): target = 'K2-34b' mission = 'k2' campaign = 18 width_height_arcmin = 1.8 # use with Kepler/K2 <--- USER CUSTOMIZE north_arm_arcsec = 6 # USER CUSTOMIZE frame = 1 # USER CUSTOMIZE percentile = 99.0 # USER CUSTOMIZE title_ = target + ' : K2 : Campaign ' + str(campaign) # USER CUSTOMIZE print('DOWNLOAD START:', str(datetime.datetime.now())) tpf = lk.search_targetpixelfile( target=target, mission=mission, campaign=campaign).download(quality_bitmask=0) # ^--- exoplanet K2-34b is "EPIC 212110888" print('DOWNLOAD STOP:', str(datetime.datetime.now())) # pass:if if (obj == 6): target = 'CD Ind' sector = 1 mission = 'TESS' frame = 1 width_height_arcmin = 6 # USER CUSTOMIZE north_arm_arcsec = 42 # USER CUSTOMIZE percentile = 99.5 # USER CUSTOMIZE title_ = target + ' : TESS : Sector ' + str(sector) # USER CUSTOMIZE # radius = 120 # arcsec print('DOWNLOAD START:', str(datetime.datetime.now())) search_results = lk.search_targetpixelfile(target, radius=radius, mission=mission, sector=sector) tpf = search_results[0].download(quality_bitmask=0) print('DOWNLOAD STOP:', str(datetime.datetime.now())) print(search_results) print(tpf) print(tpf.wcs) print(':-)') # pass:if print() print(mission, '=mission') print(target, '=target') if (mission == 'kepler'): print(quarter, '=quarter') # pass:if if (mission == 'k2'): print(campaign, '=campaign') # pass:if if (mission == 'tess'): print(sector, '=sector') # pass:if tpf_dir = os.path.dirname(tpf.path) tpf_file = ntpath.basename(tpf.path) cwd = os.getcwd() print('\n CWD:', cwd) print(' TPF dirname:', tpf_dir) print('TPF filename:', tpf_file) print() print(tpf) print('^--- tpf') if (verbose): print() print(tpf.wcs) print('^--- tpf.wcs') # pass:if print('\n\nPLOT#1 =======================================================') ax = tpf.plot(frame=frame, cmap=cmap) ax.set_title(title_) mkpy3.mkpy3_plot_add_compass_rose_v5(ax=ax, north_arm_arcsec=north_arm_arcsec, wcs=tpf.wcs, verbose=verbose) # mark the target with a yellow circle: target_wx0, target_wy0 = tpf.wcs.wcs_world2pix(tpf.ra, tpf.dec, 0) marker_kwargs = \ {'edgecolor': 'yellow', 's': 600, 'facecolor': 'None', 'lw': 3, 'zorder': 10} ax.scatter(target_wx0 + tpf.column, target_wy0 + tpf.row, **marker_kwargs) oplot1 = 'mkpy3_plot1.png' plt.savefig(oplot1, bbox_inches="tight") print('\n', oplot1, ' <--- new PNG file written') plt.close() print('\n\nPLOT#2 =======================================================') fig = plt.figure(figsize=(7, 7)) ax = plt.subplot(projection=tpf.wcs) image_data = tpf.hdu[1].data['flux'][frame] norm = ImageNormalize(image_data, interval=PercentileInterval(percentile), stretch=SqrtStretch()) ax.imshow(image_data, norm=norm, cmap=cmap) ax.tick_params(axis='x', labelsize=16, length=5, width=2, labeltop=True, labelbottom=True) ax.tick_params(axis='y', labelsize=16, length=5, width=2, labelright=True, labelleft=True) ax.coords[0].set_major_formatter('d.dd') ax.coords[1].set_major_formatter('d.dd') ax.set_xlabel('Right Ascension (J2000)', size=24) ax.set_ylabel('Declination (J2000)', size=24) fig.suptitle(title_, size=24) ax.grid(True, color='palegreen', lw=2, zorder=1) mkpy3.mkpy3_plot_add_compass_rose_v5(ax=ax, north_arm_arcsec=north_arm_arcsec, wcs=tpf.wcs, verbose=verbose) marker_kwargs =\ {'edgecolor': 'yellow', 's': 600, 'facecolor': 'None', 'lw': 3, 'zorder': 10} ax.scatter(tpf.ra, tpf.dec, transform=ax.get_transform('icrs'), **marker_kwargs) oplot2 = 'mkpy3_plot2.png' plt.savefig(oplot2, dpi=150, bbox_inches="tight") print('\n', oplot2, ' <--- plot file written') plt.close() # ========================================================================= shrink = 0.75 print_gaia_dr2 = False print_vsx = False print('\n\nPLOT#4 =======================================================') rotationAngle_deg = 0.0 # no rotation ax = mkpy3_tpf_overlay_v6(tpf=tpf, rotationAngle_deg=rotationAngle_deg, width_height_arcmin=width_height_arcmin, percentile=percentile, shrink=shrink, show_plot=False, plot_file='', title=title_, print_gaia_dr2=print_gaia_dr2, print_vsx=print_vsx, verbose=verbose) ax.coords[0].set_major_formatter('d.dd') ax.coords[1].set_major_formatter('d.dd') ax.tick_params(axis='x', labelsize=16, length=5, width=2, labeltop=True, labelbottom=True) ax.tick_params(axis='y', labelsize=16, length=5, width=2, labelright=True, labelleft=True) ax.grid(True, color='palegreen', lw=2, zorder=1) mkpy3.mkpy3_plot_add_compass_rose_v5(ax=ax, north_arm_arcsec=2 * north_arm_arcsec) oplot4 = 'mkpy3_plot4.png' plt.savefig(oplot4, bbox_inches="tight") print('\n', oplot4, ' <--- new PNG file written') plt.close() print('\n\nPLOT#3 =======================================================') # # compute rotation based on the WCS of the TPF: rotationAngle_deg = 'tpf' # ax = mkpy3_tpf_overlay_v6(tpf=tpf, rotationAngle_deg=rotationAngle_deg, width_height_arcmin=width_height_arcmin, shrink=shrink, show_plot=False, plot_file='', title=title_, percentile=percentile, print_gaia_dr2=print_gaia_dr2, print_vsx=print_vsx, verbose=verbose) ax.coords[0].set_major_formatter('d.dd') ax.coords[1].set_major_formatter('d.dd') ax.tick_params(axis='x', labelsize=16, length=5, width=2, labeltop=True, labelbottom=True) ax.tick_params(axis='y', labelsize=16, length=5, width=2, labelright=True, labelleft=True) ax.grid(True, color='palegreen', lw=2, zorder=1) mkpy3.mkpy3_plot_add_compass_rose_v5(ax=ax, north_arm_arcsec=2 * north_arm_arcsec) oplot3 = 'mkpy3_plot3.png' plt.savefig(oplot3, bbox_inches="tight") print('\n', oplot3, ' <--- new PNG file written') plt.close() print() print('==================================================================') print() print('[*]', ax.tpf_positionAngle_deg, '=ax.tpf_positionAngle_deg') print('[*]', ax.tpf_n_pa_deg, '=ax.tpf_n_pa_deg') print('[*]', ax.tpf_mirrored, '=ax.tpf_mirrored') print('[*]', ax.tpf_north_top_half, '=ax.tpf_north_top_half') print('[*]', ax.tpf_east_left_half, '=ax.tpf_east_left_half') print('[*]') print('[*] <---', ax.survey_rotationAngle_deg, '=ax.survey_rotationAngle_deg') print('[*] --->', ax.survey_rotate_deg, '=ax.survey_rotate_deg') print('[*]') print('[*]', ax.survey_positionAngle_deg, '=ax.survey_positionAngle_deg') print('[*]', ax.survey_n_pa_deg, '=ax.survey_n_pa_deg') print('[*]', ax.survey_mirrored, '=ax.survey_mirrored') print('[*]', ax.survey_north_top_half, '=ax.survey_north_top_half') print('[*]', ax.survey_east_left_half, '=ax.survey_east_left_half') print('[*]') print('[*]', ax.xaxis_inverted, '=ax.xaxis_inverted') print('[*]', ax.yaxis_inverted, '=ax.yaxis_inverted') print() print('[-]', target, '=target') print('[-]', mission, '=mission') if (mission == 'TESS'): print('[-]', sector, '=sector') elif (mission == 'kepler'): print('[-]', quarter, '=quarter') else: print('[-]', campaign, '=campaign') # pass:if print('[-]', tpf.ra, '=tpf.ra [deg]') print('[-]', tpf.dec, '=tpf.dec [deg]') print('[-]', obj, '=obj') print() print() print('PLOTS DONE =======================================================') print() print('plot files written:\n') print(' ', oplot1, oplot2, oplot3, oplot4) print() print('FILE:', __file__) print('TIME:', str(datetime.datetime.now())) print('DONE:', __name__)
continue # Assuming we got at least one sample tpf, extract their aperture masks apertures = [] for sample in group_samples: print('Gathering aperture masks from sample TPF', sample) lcf = TessLightCurveFile(sample) current_aperture = lcf.hdu[2].data apertures.append(current_aperture) # Generate boolean master aperture mask # I want to keep the mask pixels that are shared between at least two images. # That means that if I sum the aperture masks, I will keep the mask pixels that are above 6. boolean_apt = np.sum(apertures, axis=0) > max(6, 3 * n_samples // 3) # Now use the boolean aperture mask to export light curves of current group for target in group_targets: # Skip lightcurves files that already exist if isfile(lc_filename.format(target, sector)): continue print('Exporting light curve file for TIC =', target) # Download cutouts to create light curve tpf = search_tesscut(target, sector=sector).download(cutout_size=cutoutsize) # Generate light curve using the aperture mask `new_apt` lc = tpf.to_lightcurve(aperture_mask=boolean_apt) # Export light curve into FITS file lc.to_fits(lc_filename.format(target, sector), overwrite=True) # scatter plot light curve # lc.scatter()
def get_cutout(ticid, cutout_size=9): """ """ tpf = lk.search_tesscut(ticid)[0].download(cutout_size=cutout_size) return tpf
Complete_Clusters=Table.read(data_dir+'Cluster_Catalog_Kharchenko_updated.fits') Complete_Clusters=Complete_Clusters.to_pandas() Complete_Clusters['CLUSTER_RADIUS']=Complete_Clusters['CLUSTER_RADIUS'] for i in range(len(Complete_Clusters)): Complete_Clusters['NAME'][i] = Complete_Clusters['NAME'][i].decode("utf-8").strip() ## Download target pixel file ## # input name of the interested cluster CLUSTERS = ["NGC 2422"] # initialize the target pixel file and cutout size tpfs = [0] cutout_size = 99 search = lk.search_tesscut(CLUSTERS[0])#search for the cluster in TESS using lightkurve char = "" if len(search) != 1: char = "s" print("{0} has {1} result{2}.".format(CLUSTERS, len(search), char)) tpfs = search.download_all(cutout_size=cutout_size)# download target pixel file for corresponding cluster sectors = [this_tpfs.sector for this_tpfs in tpfs] #sectors cluster was observed in orbit_times = pd.read_csv(data_dir+'orbit_times_20201013_1338.csv', comment = '#')# read the file containing epoch info of the sectors start_times = orbit_times[orbit_times['Sector'].isin(sectors)]['Start TJD'].values # start times for the sectors that this cluster was observed in end_times = orbit_times[orbit_times['Sector'].isin(sectors)]['End TJD'].values # end times for the sectors #get the frequency and Lomb-Scargle periodogram power for the ensemble photometry of the cluster omega, P_LS = get_LCs(CLUSTERS,'ensemble') plt.plot(omega,P_LS) plt.xscale('log') # quick plot of the periodogram
def make_ica_plot(tic, tpf=None): """ """ if tpf is None: tpf = lk.search_tesscut(f'TIC {tic}').download(cutout_size=11) raw_lc = tpf.to_lightcurve(aperture_mask='all') ##Perform ICA n_components = 20 X = np.ascontiguousarray(np.nan_to_num(tpf.flux), np.float64) X_flat = X.reshape(len(tpf.flux), -1) #turns three dimensional into two dimensional f1 = np.reshape(X_flat, (len(X), -1)) X_pix = f1 / np.nansum(X_flat, axis=-1)[:, None] ica = FastICA(n_components=n_components) #define n_components S_ = ica.fit_transform(X_pix) A_ = ica.mixing_ #combine x_flat to get x a = np.dot(S_.T, S_) a[np.diag_indices_from(a)] += 1e-5 b = np.dot(S_.T, raw_lc.flux) w = np.linalg.solve(a, b) comp_lcs = [] blss = [] max_powers = [] for i,s in enumerate(S_.T): component_lc = s * w[i] comp_lcs.append(component_lc) # plt.plot(component_lc + i*1e5) model = BoxLeastSquares(tpf.time, component_lc) results = model.autopower(0.16, minimum_period=.5, maximum_period=24.) # model = transitleastsquares(tpf.time, component_lc) # results = model.power() period, power = results.period, results.power blss.append([period, power]) # print(results.depth_snr[np.argmax(power)]) if (np.std(component_lc) > 1e4) or (np.abs(period[np.argmax(power)] - 14) < 2) or (results.depth[np.argmax(power)]/np.median(component_lc) < 0): power = [0] max_powers.append(np.max(power)) # plt.ylim(-1e5, 10e5) best_pers = blss[np.argmax(max_powers)][0] best_powers = blss[np.argmax(max_powers)][1] period = best_pers[np.argmax(best_powers)] transit_lc = lk.LightCurve(time=tpf.time, flux=comp_lcs[np.argmax(max_powers)]) fig, ax = plt.subplots(2, 3, figsize=(10, 7)) fig.suptitle(f'TIC {tic}') for i,c in enumerate(comp_lcs): ax[0,0].plot(tpf.time, c + i*1e5) ax[0,0].set_ylim(-1e5, n_components*1e5) ax[0,0].set_xlim(tpf.time[0], tpf.time[-1]) ax[0,0].set_xlabel('Time') ax[0,0].set_ylabel('Flux') ax[0,0].yaxis.set_major_formatter(mtick.FormatStrFormatter('%.e')) ax[0,0].set_title('ICA Components') transit_lc.plot(ax=ax[0,1]) ax[0,1].set_xlim(tpf.time[0], tpf.time[-1]) ax[0,1].yaxis.set_major_formatter(mtick.FormatStrFormatter('%.e')) ax[0,1].set_title('ICA comp with max BLS power') transit_lc.remove_outliers(9).fold(period).scatter(ax=ax[0,2], c='k', label=f'Period={period:.2f}') transit_lc.remove_outliers(9).fold(period).bin(7).plot(ax=ax[0,2], c='r', lw=2, C='C1', label='Binned') ax[0,2].set_ylim(-5*np.std(transit_lc.flux), 2*np.std(transit_lc.flux)) ax[0,2].set_xlim(-.5,.5) ax[0,2].set_title('Folded ICA Transit Component') A_useful = A_.reshape(11,11,n_components).T #reshape from 2d to 3d weighted_comp = A_useful[np.argmax(max_powers)].T * w[np.argmax(max_powers)] ax[1,0].imshow(weighted_comp, origin='lower') ax[1,1].imshow(tpf.flux[200], origin='lower') im = ax[1,2].imshow(weighted_comp / tpf.flux[200], origin='lower') ax[1,0].set_title('Weighted Transit Component') ax[1,1].set_title('TPF') ax[1,2].set_title('Model / Flux') plt.colorbar(im) fig.tight_layout(rect=[0, 0.03, 1, 0.95]) fig.patch.set_facecolor('white') fig.set_size_inches(10, 7) return fig
from lightkurve import search_tesscut from lightkurve import DesignMatrix from lightkurve import RegressionCorrector import numpy as np import astropy.units as u import matplotlib.pyplot as plt # ADD: # quality_bitmask='hard' # to download_all for harder cut on QUALITY flag tpf = search_tesscut("BV Aqr").download_all() print(tpf) if (hasattr(tpf, "__len__")): N = len(tpf) target_mask1 = tpf[0].create_threshold_mask(threshold=3) raw_lc = tpf[0].to_lightcurve(aperture_mask=target_mask1) comb_mask = ((raw_lc.time < 1347) | (raw_lc.time > 1350)) & (raw_lc.flux_err > 0) raw_lc = raw_lc[comb_mask] bkgr = tpf[0].flux[:, ~target_mask1] dm = DesignMatrix(bkgr[comb_mask], name='regressors').pca(5).append_constant() rc = RegressionCorrector(raw_lc) rc.correct(dm) corrected_lc = (raw_lc - rc.model_lc + np.percentile(rc.model_lc.flux, 5)).flatten() for itpf in tpf[1:]: target_mask = itpf.create_threshold_mask(threshold=3) raw_lc = itpf.to_lightcurve(aperture_mask=target_mask) raw_lc = raw_lc[raw_lc.flux_err > 0] bkgr = itpf.flux[:, ~target_mask]
def vetting_field_of_view(self, indir, tic, ra, dec, sectors): maglim = 6 sectors_search = None if sectors is not None and len( sectors) == 0 else sectors tpf_source = lightkurve.search_targetpixelfile("TIC " + str(tic), sector=sectors, mission='TESS') if tpf_source is None or len(tpf_source) == 0: ra_str = str(ra) dec_str = "+" + str(dec) if dec >= 0 else str(dec) tpf_source = lightkurve.search_tesscut(ra_str + " " + dec_str, sector=sectors_search) for i in range(0, len(tpf_source)): tpf = tpf_source[i].download(cutout_size=(12, 12)) pipeline = True fig = plt.figure(figsize=(6.93, 5.5)) gs = gridspec.GridSpec(1, 3, height_ratios=[1], width_ratios=[1, 0.05, 0.01]) gs.update(left=0.05, right=0.95, bottom=0.12, top=0.95, wspace=0.01, hspace=0.03) ax1 = plt.subplot(gs[0, 0]) # TPF plot mean_tpf = np.mean(tpf.flux.value, axis=0) nx, ny = np.shape(mean_tpf) norm = ImageNormalize(stretch=stretching.LogStretch()) division = np.int(np.log10(np.nanmax(tpf.flux.value))) splot = plt.imshow(np.nanmean(tpf.flux, axis=0) / 10 ** division, norm=norm, \ extent=[tpf.column, tpf.column + ny, tpf.row, tpf.row + nx], origin='lower', zorder=0) # Pipeline aperture if pipeline: # aperture_mask = tpf.pipeline_mask aperture = tpf._parse_aperture_mask(aperture_mask) maskcolor = 'lightgray' print(" --> Using pipeline aperture...") else: aperture_mask = tpf.create_threshold_mask( threshold=10, reference_pixel='center') aperture = tpf._parse_aperture_mask(aperture_mask) maskcolor = 'lightgray' print(" --> Using threshold aperture...") for i in range(aperture.shape[0]): for j in range(aperture.shape[1]): if aperture_mask[i, j]: ax1.add_patch( patches.Rectangle((j + tpf.column, i + tpf.row), 1, 1, color=maskcolor, fill=True, alpha=0.4)) ax1.add_patch( patches.Rectangle((j + tpf.column, i + tpf.row), 1, 1, color=maskcolor, fill=False, alpha=1, lw=2)) # Gaia sources gaia_id, mag = tpfplotter.get_gaia_data_from_tic(tic) r, res = tpfplotter.add_gaia_figure_elements(tpf, magnitude_limit=mag + np.float(maglim), targ_mag=mag) x, y, gaiamags = r x, y, gaiamags = np.array(x) + 0.5, np.array(y) + 0.5, np.array( gaiamags) size = 128.0 / 2**((gaiamags - mag)) plt.scatter(x, y, s=size, c='red', alpha=0.6, edgecolor=None, zorder=10) # Gaia source for the target this = np.where(np.array(res['Source']) == int(gaia_id))[0] plt.scatter(x[this], y[this], marker='x', c='white', s=32, zorder=11) # Legend add = 0 if np.int(maglim) % 2 != 0: add = 1 maxmag = np.int(maglim) + add legend_mags = np.linspace(-2, maxmag, np.int((maxmag + 2) / 2 + 1)) fake_sizes = mag + legend_mags # np.array([mag-2,mag,mag+2,mag+5, mag+8]) for f in fake_sizes: size = 128.0 / 2**((f - mag)) plt.scatter(0, 0, s=size, c='red', alpha=0.6, edgecolor=None, zorder=10, label=r'$\Delta m=$ ' + str(np.int(f - mag))) ax1.legend(fancybox=True, framealpha=0.7) # Source labels dist = np.sqrt((x - x[this])**2 + (y - y[this])**2) dsort = np.argsort(dist) for d, elem in enumerate(dsort): if dist[elem] < 6: plt.text(x[elem] + 0.1, y[elem] + 0.1, str(d + 1), color='white', zorder=100) # Orientation arrows tpfplotter.plot_orientation(tpf) # Labels and titles plt.xlim(tpf.column, tpf.column + ny) plt.ylim(tpf.row, tpf.row + nx) plt.xlabel('Pixel Column Number', fontsize=16) plt.ylabel('Pixel Row Number', fontsize=16) plt.title('Coordinates ' + tic + ' - Sector ' + str(tpf.sector), fontsize=16) # + ' - Camera '+str(tpf.camera)) # # Colorbar cbax = plt.subplot(gs[0, 1]) # Place it where it should be. pos1 = cbax.get_position() # get the original position pos2 = [pos1.x0 - 0.05, pos1.y0, pos1.width, pos1.height] cbax.set_position(pos2) # set a new position cb = Colorbar(ax=cbax, mappable=splot, orientation='vertical', ticklocation='right') plt.xticks(fontsize=14) exponent = r'$\times 10^' + str(division) + '$' cb.set_label(r'Flux ' + exponent + r' (e$^-$)', labelpad=10, fontsize=16) save_dir = indir + "/tpfplot" if not os.path.exists(save_dir): os.makedirs(save_dir) plt.savefig(save_dir + '/TPF_Gaia_TIC' + tic + '_S' + str(tpf.sector) + '.pdf') # Save Gaia sources info dist = np.sqrt((x - x[this])**2 + (y - y[this])**2) GaiaID = np.array(res['Source']) srt = np.argsort(dist) x, y, gaiamags, dist, GaiaID = x[srt], y[srt], gaiamags[srt], dist[ srt], GaiaID[srt] IDs = np.arange(len(x)) + 1 inside = np.zeros(len(x)) for i in range(aperture.shape[0]): for j in range(aperture.shape[1]): if aperture_mask[i, j]: xtpf, ytpf = j + tpf.column, i + tpf.row _inside = np.where((x > xtpf) & (x < xtpf + 1) & (y > ytpf) & (y < ytpf + 1))[0] inside[_inside] = 1 data = Table([ IDs, GaiaID, x, y, dist, dist * 21., gaiamags, inside.astype('int') ], names=[ '# ID', 'GaiaID', 'x', 'y', 'Dist_pix', 'Dist_arcsec', 'Gmag', 'InAper' ]) ascii.write(data, save_dir + '/Gaia_TIC' + tic + '_S' + str(tpf.sector) + '.dat', overwrite=True) return save_dir
if (__name__ == '__main__'): import matplotlib.pyplot as plt import lightkurve as lk # obj = 3 # USER CUSTOMIZE # tpf = None if (obj == 1): north_arm_arcsec = 8 tpf = lk.search_targetpixelfile( target='Kepler-138b', mission='Kepler', quarter=10)\ .download(quality_bitmask=0) # ^--- Exoplanet Kelper-138b is "KIC 7603200" elif (obj == 2): north_arm_arcsec = 42 search_results = lk.search_tesscut(target='CD Ind', sector=1) tpf = search_results[0].download(cutout_size=(11, 11), quality_bitmask=0) elif (obj == 3): north_arm_arcsec = 42 tpf = lk.search_targetpixelfile(target='CD Ind', mission='TESS', sector=1).download(quality_bitmask=0) else: print('***ERROR*** BAD OBJECT NUMBER:', obj) # pass:if assert (tpf is not None) # # Plot the 2nd frame of the TPF ax = tpf.plot(frame=1, cmap='gray_r') #
def showStar(self, updateOnly=False): plt.close('all') ## Check to see if we've reached the end of the list if (len(self.RA) == 0): self.changeCounter(0) self.errorWindow("ALL DONE.") self.updateObjectList() return self.apthresh = float(self.apselectEntry.get()) ## Change RA/dec if this is a new star if (not updateOnly): ## clear marked values and update RA/DEC self.clearValues() self.changeRADEC() self.changeCounter() ## get the coordinates of the next star coord = SkyCoord(self.RA[-1], self.DE[-1], unit="deg") ## get the name of this star from Simbad and update GUI try: self.starName = Simbad.query_region( coord, radius='0d0m2s')['MAIN_ID'][0] except: self.starName = "Unknown" self.changeTIC() ## download the TPFs for every possible sector self.tpf = search_tesscut(coord).download_all(cutout_size=(10, 10)) print(self.tpf) ## make sure the 1st sector is OK ntrgtpix = 0 while (ntrgtpix == 0 and hasattr(self.tpf, "__len__") and len(self.tpf) > 0): tmsk = self.tpf[0].create_threshold_mask(threshold=self.apthresh) ntrgtpix = tmsk.sum() if (ntrgtpix == 0): print('sector %d...SKIPPED.' % (self.tpf[0].sector), flush=True) self.tpf = self.tpf[1:] if (hasattr(self.tpf, "__len__") and len(self.tpf) > 0): self.NSECS[self.NDONE] = len(self.tpf) print('sector %d...' % (self.tpf[0].sector), end='', flush=True) ## create an aperture mask for the target star self.target_mask0 = self.tpf[0].create_threshold_mask( threshold=self.apthresh) n_target_pixels = self.target_mask0.sum() ## create the lightcurve for the first sector using aperture raw_lc = self.tpf[0].to_lightcurve(aperture_mask=self.target_mask0) ## create a mask for the background signal self.bkgr_mask0 = ~self.tpf[0].create_threshold_mask( threshold=0.001, reference_pixel=None) n_background_pixels = self.bkgr_mask0.sum() ## create a lightcurve for the background and scale it to the target aperture bkgr_lc = self.tpf[0].to_lightcurve( aperture_mask=self.bkgr_mask0 ) / n_background_pixels * n_target_pixels ## subtract the background from the signal self.star_lc = (raw_lc - bkgr_lc.flux) ## normalize the flux and remove problem points forFeatures = self.star_lc.remove_nans().remove_outliers(sigma=6) self.star_lc = forFeatures.normalize() #self.star_lc = self.star_lc.remove_nans().remove_outliers(sigma=6).normalize() #self.star_lc = self.star_lc[(self.star_lc.flux>0.6) & (self.star_lc.flux<1.6)] print('DONE.', flush=True) for itpf in self.tpf[1:]: print('sector %d...' % (itpf.sector), end='', flush=True) ## create an aperture mask for the target star target_mask = itpf.create_threshold_mask( threshold=self.apthresh) n_target_pixels = target_mask.sum() ## check to make sure the mask is OK if (n_target_pixels == 0): print('SKIPPED.', flush=True) continue ## create the lightcurve for the first sector using aperture raw_lc = itpf.to_lightcurve(aperture_mask=target_mask) ## create a mask for the background signal bkgr_mask = ~itpf.create_threshold_mask(threshold=0.001, reference_pixel=None) n_background_pixels = bkgr_mask.sum() ## create a lightcurve for the background and scale it to the target aperture bkgr_lc = itpf.to_lightcurve( aperture_mask=bkgr_mask ) / n_background_pixels * n_target_pixels ## subtract the background from the signal temp_lc = (raw_lc - bkgr_lc.flux) ## normalize the flux and remove problem points temp_lc = temp_lc.remove_nans().remove_outliers(sigma=6) forFeatures = forFeatures.append(temp_lc) #temp_lc = temp_lc.remove_nans().remove_outliers(sigma=6).normalize() #temp_lc = temp_lc[(temp_lc.flux>0.6) & (temp_lc.flux<1.6)] ## add this sector to the previous self.star_lc = self.star_lc.append(temp_lc.normalize()) #self.star_lc = self.star_lc.append(temp_lc) print('DONE.', flush=True) # mask out bad data selection(s) self.star_lc_all = self.star_lc.copy() bddt_msk = np.ones(len(self.star_lc), dtype=bool) for item in self.lc_spans: bddt_msk[int(item[0]):int(item[1]) + 1] = False self.star_lc = self.star_lc[bddt_msk] # get peaks self.peaks = find_peaks(self.star_lc.flux, prominence=0.25)[0] # do a LombScargle analysis of the lightcurve self.lspg = self.star_lc.to_periodogram(maximum_frequency=12.0, oversample_factor=50) # determine Fourier features of the lightcurve forFeatures = forFeatures[bddt_msk] self.lc_features = getFeatures(forFeatures, self.lspg.period_at_max_power.value) #print(self.lc_features) else: self.errorWindow("NOT IN SECTOR") self.saveStar() return ## Make plots self.updatePlots()
def lk_tesscut(tic, ra=None, dec=None, size=50, bkg_subtract=True, bkg_n=300, k=100, n=100, l2_reg=[0.1], exclusion_size=5, apt_size=1, pred_pix_method="similar_brightness", add_poly=False, poly_scale=2, poly_num_terms=4): #search light curve for given TIC ID search_res = lk.search_tesscut('TIC ' + str(tic)) #initialize SPOC found,first found tesscut_found = False tesscut_first = False try: authors = search_res.table['author'] except: tc_avail = False tesscut_lc = median_im = im_header = pd.DataFrame() return (tesscut_lc, median_im, im_header, tc_avail) if 'TESScut' in authors: tc_avail = True else: tc_avail = False tesscut_lc = median_im = im_header = pd.DataFrame() return (tesscut_lc, median_im, im_header, tc_avail) lc_holder = [] for i in range(len(search_res)): #select search result object search_i = search_res[i] #skip if not TESScut if (search_i.author[0] == 'TESScut' ): #& (search_i.exptime.data[0] == 120): print("Found " + str(search_i.mission[0]) + " TESScut data for TIC " + str(tic) + "!") tesscut_found = True if (tesscut_first == False) & (tesscut_first is not None): tesscut_first = True else: continue #download this sector's tesscut lk_tesscut_obj = search_res[i].download(cutout_size=size) # #instantiate cpm_obj # cpm_obj = cpm_int(tic = tic,ra = ra,dec = dec) # #get cpm_lc for this sector by passing lk_tess_obj to cpm_obj # if i == 0: # med_im_header = True # lc_df,median_im,im_header = cpm_obj.lk_cpm_lc(lk_tesscut_obj = lk_tesscut_obj, # med_im_header = med_im_header) # else: # med_im_header = False # lc_df = cpm_obj.lk_cpm_lc(lk_tesscut_obj = lk_tesscut_obj, # med_im_header = med_im_header) #get cpm_lc for this sector by passing lk_tess_obj to lk_cpm_lc function if i == 0: med_im_header = True lc_df, median_im, im_header = lk_cpm_lc( lk_tesscut_obj=lk_tesscut_obj, med_im_header=med_im_header, bkg_subtract=bkg_subtract, bkg_n=bkg_n, k=k, n=n, l2_reg=l2_reg, exclusion_size=exclusion_size, apt_size=apt_size, pred_pix_method=pred_pix_method, add_poly=add_poly, poly_scale=poly_scale, poly_num_terms=poly_num_terms) else: med_im_header = False lc_df = lk_cpm_lc(lk_tesscut_obj=lk_tesscut_obj, med_im_header=med_im_header, bkg_subtract=bkg_subtract, bkg_n=bkg_n, k=k, n=n, l2_reg=l2_reg, exclusion_size=exclusion_size, apt_size=apt_size, pred_pix_method=pred_pix_method, add_poly=add_poly, poly_scale=poly_scale, poly_num_terms=poly_num_terms) #append to lc_holder for later concatenation lc_holder.append(lc_df) #store in lc_holder # #save median_im and im_header if i == 0 # if i == 0: # median_im = cpm_obj.median_im # im_header = cpm_obj.im_header #delete stuff path = lk_tesscut_obj.path #del cpm_obj del lk_tesscut_obj os.remove(path=path) if tesscut_found == False: print("No TESScut data found for TIC " + str(tic) + ".") tesscut_lc = median_im = im_header = pd.DataFrame() else: tesscut_lc = pd.concat(lc_holder) #combine lc into 1 pandas dataframe return (tesscut_lc, median_im, im_header, tc_avail)
def download_tesscuts_single(TIC, outputdir=Path.cwd(), imsize=20, overwrite=False, max_tries_download=10, max_tries_save=2, max_tries_query=3, name_pattern='tess{TIC}_sec{SECTOR}.fits', onlysectors=None): ''' Purpose: Downoad the TESS cut for all the available sectors given the TIC number Args: - TIC: string TIC number of the target star. - outputdir: pathlib.Path Directory where to store the images to be downloaded. If the directory does not exist, it will be created - imsize: int Size in pixels of the square images to be downloaded. - overwrite: bool If True, then overwrite the FITS images. Note that the code actually skips the files that havealready been downloaded and so, ovewrite=True should not be needed. - max_tries_download: int Maximum number of attempts to download a same TESS sector. - max_tries_save: int Maximum number of attempts to save a same FITS image. - max_tries_query: int Maximum number of attempts to querry MAST for a particular TIC. - name_pattern: str Pattern use to name the files to be saved. The five charachters {TIC} and the eight characters {SECTOR} are mandatory in the pattern and will replaced for the TIC number and sector number, respectively. ''' # Ensure TIC is a string (and not a number) if not isinstance(TIC, str): raise TypeError('TIC must be a string instance. Ex: TIC="349092922"') # Ensure outputdir is a Path instance if not isinstance(outputdir, Path): raise TypeError( 'outputdir must be a Path instance. Ex: outputdir=pathlib.Path.cwd()' ) # Ensure imsize is an integer instance if not isinstance(imsize, int): raise TypeError('imsize must be an int instance. Ex: imsize=20') # Ensure name_pattern is a string instance if not isinstance(name_pattern, str): raise TypeError( 'name_pattern must be a string instance containing the characters {TIC} and {SECTOR}. Ex: "tess{TIC}_sec{SECTOR}.fits"' ) # Ensure name_pattern contains characters {TIC} and {SECTOR} and ends with .fits else: if (not '{TIC}' in name_pattern) \ or (not '{SECTOR}' in name_pattern) \ or (not name_pattern.endswith('.fits')): raise TypeError( 'name_pattern must be a string instance containing the characters {TIC} and {SECTOR}. Ex: "tess{TIC}_sec{SECTOR}.fits"' ) # Create the output directory if needed if outputdir.exists(): if not outputdir.is_dir(): raise ValueError( 'The outputdir exist but is not a directory. It must be a directory' ) else: outputdir.mkdir() # Search MAST for Full Frame Images availables for TIC in question tries_query = 1 while True: if tries_query > max_tries_query: print( f'Skipped TIC = {TIC}: Maximum number of MAST query retries ({max_tries_query}) exceeded' ) return try: tesscuts = lk.search_tesscut(f'TIC {TIC}') break except Exception as e: # If exception rised ename = e.__class__.__name__ print( f'MAST query attempt {tries_query}, TIC = {TIC}. Excepion {ename}: {e}' ) # Count it as one attempt tries_query += 1 if len(tesscuts) == 0: print(f'No images found for TIC={TIC}') return # Check that the returned ids match the TIC number ids = np.unique(tesscuts.table['targetid'].data) if not ids.size == 1: print(f'The MAST query returned multiple ids: {ids}') print('No FITS files saved') return _TIC = re.match('TIC (\d+)', ids.item()).group(1) if TIC != _TIC: print(f'The MAST query returned a different id: {ids}') print('No FITS files saved') return # Get the sector numbers sectors = np.array([ re.match('TESS Sector (\d+)', text).group(1) for text in tesscuts.table['observation'] ]) # Filter only requested sectors if not onlysectors is None: ind = [ True if sec in onlysectors else False for sec in sectors.astype('int32') ] tesscuts = tesscuts[ind] # Get the sector numbers sectors = np.array([ re.match('TESS Sector (\d+)', text).group(1) for text in tesscuts.table['observation'] ]) # Generate the output names outputnames = np.array([ outputdir / Path(name_pattern.format(TIC=TIC, SECTOR=s)) for s in sectors ]) # Skip already downloaded files files = np.array([file.exists() for file in outputnames]) ind = np.argwhere(files == True).flatten() if len(ind) > 0: print( f'Skipped already downloaded sectors for TIC {TIC} = {sectors[ind]}' ) ind = np.argwhere(files == False).flatten().tolist() tesscuts = tesscuts[ind] if len(tesscuts) == 0: print(f'Skipped: No new images to download for TIC={TIC}') return # Download the cut target pixel files tries = 1 while True: if tries > max_tries_download: print( f'Skipped TIC = {TIC}: Maximum number of retries ({max_tries_download}) exceeded' ) return try: tpfs = tesscuts.download_all(cutout_size=imsize) break except TypeError as e: ename = e.__class__.__name__ print( f'Skipped TIC = {TIC}: There seems to be a problem with the requested image: Excepion {ename}: {e}.' ) return except Exception as e: # If exception rised ename = e.__class__.__name__ if ename == 'SearchError': print( f'Skipped TIC = {TIC}: There seems to be a problem with the requested image: Excepion {ename}: {e}.' ) return print(f'Attempt {tries}, TIC = {TIC}. Excepion {ename}: {e}') # Count it as one attempt tries += 1 # Save as FITS files for tpf in tpfs: # Store TIC number in the header tpf.header.set('TICID', value=TIC) sector = tpf.sector outputname = outputdir / Path( name_pattern.format(TIC=TIC, SECTOR=sector)) counter = 1 # Attempt to write FITS file while True: if counter > max_tries_save: print( f'Skipped TIC = {TIC}: Maximum number of retries ({max_tries_save}) exceeded' ) return try: tpf.to_fits(outputname.as_posix(), overwrite=overwrite) break except Exception as e: # If exception rised ename = e.__class__.__name__ print( f'Attempt {counter} when saving FITS file, TIC = {TIC}. Excepion {ename}: {e}' ) time.sleep(0.5) # Count it as one attempt counter += 1 print(f'Saved: {outputname.as_posix()}')
def cpm_multi_lk(tic, sectors=None, size=[32], bkg_subtract=[False], bkg_n=[40], k=[5], n=[35], exclusion_size=[5], apt_size=[1], l2_reg=[[0.1]], pred_pix_method=["cosine_similarity"], add_poly=False, poly_scale=2, poly_num_terms=4, med_im_header=False, obj_num=None): #search light curve for given TIC ID search_res = lk.search_tesscut('TIC ' + str(tic)) #initialize SPOC found,first found tesscut_found = False tesscut_first = False try: authors = search_res.table['author'] except: tc_avail = False tesscut_lc = median_im = im_header = pd.DataFrame() return (multi_lc_df, tc_avail) if 'TESScut' in authors: tc_avail = True else: tc_avail = False tesscut_lc = median_im = im_header = pd.DataFrame() return (multi_lc_df, tc_avail) lc_holder = [] for i in range(len(search_res)): #select search result object search_i = search_res[i] #skip if not TESScut if (search_i.author[0] == 'TESScut' ): #& (search_i.exptime.data[0] == 120): if sectors is None: print("Found " + str(search_i.mission[0]) + " TESScut data for TIC " + str(tic) + "!") tesscut_found = True if (tesscut_first == False) & (tesscut_first is not None): tesscut_first = True else: table_sector = search_i.table['sequence_number'][0] if (table_sector in np.array(sectors, dtype='int')) == False: print("Found TESScut, but not in desired sector.") continue else: print("Found " + str(search_i.mission[0]) + " TESScut data for TIC " + str(tic) + "!") tesscut_found = True if (tesscut_first == False) & (tesscut_first is not None): tesscut_first = True else: continue #download this sector's tesscut, run multi extract j = 0 for sz in size: lk_tesscut_obj = search_res[i].download(cutout_size=sz) for bkg_sub in bkg_subtract: for bkg_N in bkg_n: for N in n: for exclusion in exclusion_size: for apt_s in apt_size: for choose_pix in pred_pix_method: for K in k: for reg in l2_reg: flux_type = choose_pix[ 0] + '_bkg=' + str(bkg_sub)[0] if bkg_sub: flux_type = flux_type + '_bkgN' + str( bkg_N) else: flux_type = flux_type + '_bkgNa' flux_type = flux_type + '_s' + str( sz ) + '_n' + str(N) + '_ex' + str( exclusion) + '_apt' + str( apt_s) + '_k' + str( K) + '_l2-' + str( reg[0]) print("Flux type: " + str(flux_type)) if obj_num is not None: print("Object number " + str(obj_num) + ".") if med_im_header == False: temp_lc = lk_cpm_lc( lk_tesscut_obj= lk_tesscut_obj, med_im_header=med_im_header, bkg_subtract=bkg_sub, bkg_n=bkg_N, k=K, n=N, exclusion_size=exclusion, apt_size=apt_s, l2_reg=reg, pred_pix_method=choose_pix) if med_im_header == True: temp_lc, _, _ = lk_cpm_lc( lk_tesscut_obj= lk_tesscut_obj, med_im_header=med_im_header, bkg_subtract=bkg_sub, bkg_n=bkg_N, k=K, n=N, exclusion_size=exclusion, apt_size=apt_s, l2_reg=reg, pred_pix_method=choose_pix) ## add cutout size to flux title! if j == 0: multi_sector_df = temp_lc.rename( columns={'cpm': flux_type}) if j > 0: multi_sector_df[ flux_type] = temp_lc['cpm'] j = j + 1 #delete stuff path = lk_tesscut_obj.path #del cpm_obj del lk_tesscut_obj time.sleep(5) os.remove(path=path) #add multi sector df to lc holder at end of each sector extraction lc_holder.append(multi_sector_df) if tesscut_found == False: print("No TESScut data found for TIC " + str(tic) + "in desired sectors.") multi_lc_df = pd.DataFrame() else: multi_lc_df = pd.concat(lc_holder) #combine lc into 1 pandas dataframe return (multi_lc_df, tc_avail)
def test_tpf_with_zero_flux_cadence(): """Regression test for #873.""" tpf = search_tesscut("TIC 123835353", sector=6).download(cutout_size=5) tpf.to_corrector("pld").correct()