def eleanor_target_download(targID, sectors='all', sc=False, lc_format='pdc'): import eleanor if sectors == 'all': sector_array = np.array([1, 2]) tic_times, tic_sap_flux, tic_pdc_flux, tic_errors = [], [], [], [] for sector in sector_array: try: ticstar = eleanor.Source(tic=targID, sector=sector) ticdata = eleanor.TargetData(ticstar, height=15, width=15, bkg_size=31, do_psf=True, do_pca=True) qflag0 = ticdata.quality == 0 tic_time, tic_raw_flux, tic_corr_flux, tic_error = ticdata.time[ qlfag0], ticdata.raw_flux[qflag0], ticdata.corr_flux[ qflag0], ticdata.flux_err[qflag0] tic_times.append(tic_time) tic_sap_flux.append(tic_raw_flux) tic_pdc_flux.append(tic_pdc_flux) tic_errors.append(tic_error) except: pass if lc_format == 'pdc': return tic_times, tic_pdc_flux, tic_errors elif lc_format == 'sap': return tic_times, tic_sap_flux, tic_errors
def download_tess_cuts( ticid, lower_sector_limit=0, upper_sector_limit=1000, tesscut_path="/Users/rangus/projects/TESS-rotation/data/TESScut"): # Download light curves sectors, star = get_sectors(ticid, lower_sector_limit=lower_sector_limit, upper_sector_limit=upper_sector_limit) path_to_tesscut = "{0}/astrocut_{1:12}_{2:13}_{3}x{4}px".format( tesscut_path, star.coords[0], star.coords[1], 68, 68) for sector in sectors: print("sector = ", int(sector)) star = eleanor.Source(tic=ticid, sector=int(sector), tc=True) fits_only = "tess-s{0}-{1}-{2}_{3:.6f}_{4:.6f}_{5}x{6}_astrocut.fits" \ .format(str(int(sector)).zfill(4), star.camera, star.chip, star.coords[0], star.coords[1], 68, 68) full_path = os.path.join(path_to_tesscut, fits_only) if not os.path.exists(full_path): print("No cached file found. Downloading", full_path) if not os.path.exists(path_to_tesscut): os.mkdir(path_to_tesscut) print("Downloading sector", sector, "for TIC", ticid) hdulist = Tesscut.download_cutouts( objectname="TIC {}".format(ticid), sector=sector, size=68, path=path_to_tesscut) else: print("Found cached file ", full_path)
def eleanor_corr(ticid, sector, pxsize = 19): import eleanor star = eleanor.Source(tic = ticid, sector = sector) data = eleanor.TargetData(star, height=pxsize, width=pxsize, bkg_size=31, do_psf=False, do_pca=True) return data.time, data.corr_flux, data.quality
def get_sectors(ticid, lower_sector_limit=0, upper_sector_limit=1000): star = eleanor.Source(tic=ticid) outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, outColPix, \ outRowPix, scinfo = tess_stars2px_function_entry( int(ticid), star.coords[0], star.coords[1]) sectors = outSec[(lower_sector_limit < outSec) & (outSec < upper_sector_limit)] return sectors, star
def inject_signal(ticid, period, amplitude, baseline, tesscut_path, upper_sector_limit, xpix=68, ypix=68): sectors, star = get_sectors(ticid, upper_sector_limit=upper_sector_limit) # Eleanor object print("Finding Eleanor object...") time, inds, max_inds = [], [], 0 elstar = [] for sector in sectors: print("sector", sector) star = eleanor.Source(tic=ticid, sector=int(sector), tc=True) sec, camera, ccd = star.sector, star.camera, star.chip colrowpix = star.position_on_chip elstar.append(star) fits_image_filename = get_fits_filenames(tesscut_path, sec, camera, ccd, star.coords[0], star.coords[1]) # Load the TESScut FFI data (get time array) hdul = fits.open(fits_image_filename) postcard = hdul[1].data t = postcard["TIME"]*1. flux = postcard["FLUX"]*1. time.append(t) # Create the multi-sector signal time_array = np.array([i for j in time for i in j]) signal = baseline + get_random_light_curve(time_array, period, amplitude) for i, sector in enumerate(sectors): print("sector", sector) star = elstar[i] sec, camera, ccd = star.sector, star.camera, star.chip colrowpix = star.position_on_chip fits_image_filename = get_fits_filenames(tesscut_path, sec, camera, ccd, star.coords[0], star.coords[1]) path_to_tesscut = "{0}/astrocut_{1:12}_{2:13}_{3}x{4}px".format( tesscut_path, star.coords[0], star.coords[1], xpix, ypix) inj_dir = "{0}/injected".format(path_to_tesscut) injection_filename = "{0}/tess-s{1}-{2}-{3}_{4:.6f}_{5:.6f}_{6}x{7}_astrocut.fits".format( inj_dir, str(int(sector)).zfill(4), camera, ccd, star.coords[0], star.coords[1], xpix, ypix) mask = (time[i][0] <= time_array) & (time_array <= time[i][-1]) assert len(signal[mask]) == len(time[i]) inject_one_sector_starry(ticid, sector, signal[mask], camera, ccd, colrowpix, fits_image_filename, injection_filename) return time_array, signal
def load_data(self): """Allows for the option to pass in multiple files. """ if self.multi is True: self.star, self.data = [], [] for fn in self.file: s = eleanor.Source(fn=fn, fn_dir=self.directory) d = eleanor.TargetData(s) self.star.append(s) self.data.append(d) self.star = np.array(self.star) self.data = np.array(self.data) self.tic = self.star[0].tic self.coords = self.star[0].coords else: self.star = eleanor.Source(fn=self.file, fn_dir=self.directory) self.data = eleanor.TargetData(self.star) self.tic = self.star.tic self.coords = self.star.coords return
def __init__(self, ticid, tesscut_path, lower_sector_limit=0, upper_sector_limit=1000, xpix=68, ypix=68): self.ticid = ticid self.upper_sector_limit = upper_sector_limit self.lower_sector_limit = lower_sector_limit self.xpix, self.ypix = 68, 68 print("Finding the sectors that star was observed in.") sectors, _ = get_sectors(self.ticid, upper_sector_limit=self.upper_sector_limit, lower_sector_limit=self.lower_sector_limit) self.sectors = sectors print("Found sectors", sectors) # Now get the list of eleanor star objects, one for each sector, and # the names of fits files for each sector. # Also, load the time arrays print("Loading time arrays") time, inj_file_names = [], [] elstar, fits_file_names = [], [] for i, sector in enumerate(self.sectors): print("sector", sector) s = eleanor.Source(tic=self.ticid, sector=int(sector), tc=True) elstar.append(s) # Get file names f = get_fits_filenames(tesscut_path, sector, s.camera, s.chip, s.coords[0], s.coords[1]) fits_file_names.append(f) # Load the TESScut FFI data (get time array) hdul = fits.open(f) postcard = hdul[1].data t = postcard["TIME"]*1. flux = postcard["FLUX"]*1. time.append(t) # Get injection file names path_to_tesscut = "{0}/astrocut_{1:12}_{2:13}_{3}x{4}px".format( tesscut_path, s.coords[0], s.coords[1], xpix, ypix) inj_dir = "{0}/injected".format(path_to_tesscut) injection_filename = \ "{0}/tess-s{1}-{2}-{3}_{4:.6f}_{5:.6f}_{6}x{7}_astrocut.fits"\ .format(inj_dir, str(int(sector)).zfill(4), s.camera, s.chip, s.coords[0], s.coords[1], xpix, ypix) inj_file_names.append(injection_filename) self.elstar = elstar self.fits_file_names = fits_file_names self.time = time self.time_array = np.array([i for j in self.time for i in j]) self.inj_file_names = inj_file_names
def from_eleanor(ticid): star = eleanor.Source(tic=ticid, sector=2, tc=True) #note: update to get all Sectors print('data found! for: ', ticid) data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=True, do_pca=True, try_load=True) return data
def build_eleanor_lc(self): """ This function constructs a `Lightkurve` object from downloaded `eleanor` light curves. It also stores the light curve for each object it reads in, a well as the full Eleanor Target Pixel File data. """ datum = eleanor.TargetData( eleanor.Source(fn=f'lc_sector_{self.j.sectors[0]}.fits', fn_dir=f'{self.j.output_path}/{self.j.gaiaid}/')) q = datum.quality == 0 lc = lk.LightCurve(time=datum.time[q], flux=datum.corr_flux[q]) self.clc = lc.normalize().remove_nans().remove_outliers() # Store the datum and light curve self.j.void[f'datum_{self.j.sectors[0]}'] = datum self.j.void[f'clc_{self.j.sectors[0]}'] = self.clc if len(self.j.sectors) > 1: # Looping and appending all sectors for s in self.j.sectors[1:]: datum = eleanor.TargetData( eleanor.Source( fn=f'lc_sector_{s}.fits', fn_dir=f'{self.j.output_path}/{self.j.gaiaid}/')) q = datum.quality == 0 lc = lk.LightCurve(time=datum.time[q], flux=datum.corr_flux[q]) self.clc = self.clc.append( lc.normalize().remove_nans().remove_outliers()) # Store the datum and light curve self.j.void[f'datum_{s}'] = datum self.j.void[f'clc_{s}'] = lc.normalize().remove_nans( ).remove_outliers() self.j.void[f'clc_all'] = self.clc
def CPM_recover(ticid, tesscut_path, lower_sector_limit=0, upper_sector_limit=1000): print("Searching for observed sectors...") sectors, star = get_sectors(ticid, lower_sector_limit=lower_sector_limit, upper_sector_limit=upper_sector_limit) print("sectors found: ", sectors) print("Creating light curve..") xs, ys = [], [] for sector in sectors: print("sector", sector) star = eleanor.Source(tic=ticid, sector=int(sector), tc=True) x, y = CPM_one_sector(ticid, tesscut_path, sector, star.camera, star.chip, star.coords[0], star.coords[1]) xs.append(x) ys.append(y) return xs, ys, sectors
def CPM_one_sector(ticid, tesscut_path, sector, camera, ccd, ra, dec): fits_file = get_fits_filenames(tesscut_path, sector, camera, ccd, ra, dec, xpix=68, ypix=68) # Get the Eleanor aperture star = eleanor.Source(tic=ticid, sector=int(sector), tc=True) data = eleanor.TargetData(star) xpixels, ypixels = get_CPM_aperture(data.aperture) # Create CPM light curve # _, _, fig = select_aperture(sector, ypixels, xpixels, fits_file, plot=False) x, y = make_lc_single_sector(sector, ypixels, xpixels, fits_file, plot=False, save_to_file=False) return x, y
def eleanor_lc_download(target_ID, sector, plot_raw=False, plot_corr=False, plot_pca=False, from_file=False, save_path=''): """ Downloads and returns the various lightcurves produced by the eleanor pipeline: raw_lc = lc with flux from simple aperture photometry corr_lc = lc with flux 'corrected' for poitning errors etc (though often not trustworthy) pca_lc = lc with flux based on principal component analysis psf_lc = lc with flux based on point spread function modelling - n.b. sometimes has problems depending on tensorflow version in python """ if from_file == True: table_data = Table.read("BANYAN_XI-III_members_with_TIC.csv", format='ascii.csv') # Obtains ra and dec for object from target_ID i = list(table_data['main_id']).index(target_ID) ra = table_data['ra'][i] dec = table_data['dec'][i] tic = table_data['MatchID'][i] else: # Find ra, dec and tic # via the TIC (typically based on Gaia DR2) TIC_table = Catalogs.query_object(target_ID, catalog="TIC") # ra = TIC_table['ra'][0] # dec = TIC_table['dec'][0] # tic = TIC_table['ID'][0] tic = target_ID # Locates star in data star = eleanor.Source(tic, sector=sector) #star = eleanor.Source(coords=(49.4969, -66.9268), sector=1) # Extract target pixel file, perform aperture photometry and complete some systematics corrections data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=False) q = data.quality == 0 # Plot raw flux raw_lc = lightkurve.LightCurve(data.time[q], flux=data.raw_flux[q] / np.median(data.raw_flux[q]), flux_err=data.flux_err[q], targetid=target_ID) if plot_raw == True: raw_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.raw_flux[q] / np.median(data.raw_flux[q]), s=1, c='k') plt.ylabel('Normalized Flux') plt.xlabel('Time') plt.title( '{} - eleanor light curve from FFIs - raw flux'.format(target_ID)) # raw_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor raw flux.png'.format(target_ID, sector)) #plt.close(raw_eleanor_fig) plt.show() # Plot corrected flux corr_lc = lightkurve.LightCurve(data.time[q], flux=data.corr_flux[q] / np.median(data.corr_flux[q]), flux_err=data.flux_err[q], targetid=target_ID) if plot_corr == True: corr_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.corr_flux[q] / np.median(data.corr_flux[q]), s=1, c='r') plt.ylabel('Normalized Flux') plt.xlabel('Time') plt.title( '{} - eleanor light curve from FFIs - corr flux'.format(target_ID)) #corr_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor corr flux.png'.format(target_ID, sector)) #plt.close(corr_eleanor_fig) plt.show() # Plot pca flux eleanor.TargetData.pca(data, flux=data.raw_flux, modes=4) pca_lc = lightkurve.LightCurve(data.time[q], flux=data.pca_flux[q] / np.median(data.pca_flux[q]), flux_err=data.flux_err[q], targetid=target_ID) if plot_pca == True: pca_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.pca_flux[q] / np.median(data.pca_flux[q]), s=1, c='g') plt.ylabel('Normalized Flux') plt.xlabel('Time') plt.title( '{} - eleanor light curve from FFIs - pca flux'.format(target_ID)) pca_eleanor_fig.savefig( save_path + '{} - Sector {} - eleanor pca flux.png'.format(target_ID, sector)) plt.close(pca_eleanor_fig) #plt.show() # Plot psf flux #eleanor.TargetData.psf_lightcurve(data, model='gaussian', likelihood='poisson') #psf_lc = lightkurve.LightCurve(data.time[q], flux = data.psf_flux[q]/np.median(data.psf_flux[q]), flux_err = data.flux_err[q], targetid = target_ID) #psf_eleanor_fig = plt.figure() #plt.scatter(data.time[q], data.psf_flux[q]/np.median(data.psf_flux[q]), s=1, c= 'g') #plt.ylabel('Normalized Flux') #plt.xlabel('Time') #plt.title('{} - eleanor light curve from FFIs - psf flux'.format(target_ID)) #psf_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor psf flux.png'.format(target_ID, sector)) #plt.show() return raw_lc, corr_lc, pca_lc #, psf_lc
def from_eleanor(self, ticid, save_postcard=False): """Download light curves from Eleanor for desired target. Eleanor light curves include: - raw : raw flux light curve - corr : corrected flux light curve - pca : principle component analysis light curve - psf : point spread function photometry light curve Parameters ---------- ticid : int TIC ID of desired target Returns ------- LightCurveCollection : ~lightkurve.LightCurveCollection containing raw and corrected light curves. """ ''' # BUGFIX FOR ELEANOR (DEPRICATED) # ------------------------------- from astroquery.mast import Observations server = 'https://mast.stsci.edu' Observations._MAST_REQUEST_URL = server + "/api/v0/invoke" Observations._MAST_DOWNLOAD_URL = server + "/api/v0.1/Download/file" Observations._COLUMNS_CONFIG_URL = server + "/portal/Mashup/Mashup.asmx/columnsconfig" ''' # search TESScut to figure out which sectors you need (there's probably a better way to do this) sectors = self._find_sectors(ticid) if isinstance(ticid, str): ticid = int(re.search(r'\d+', str(ticid)).group()) self.ticid = ticid print( f'Creating light curve for target {ticid} for sectors {sectors}.') # download target data for the desired source for only the first available sector star = eleanor.Source(tic=ticid, sector=int(sectors[0]), tc=True) try: data = eleanor.TargetData(star, height=11, width=11, bkg_size=27, do_psf=True, do_pca=True, try_load=True, save_postcard=save_postcard) except: data = eleanor.TargetData(star, height=7, width=7, bkg_size=21, do_psf=True, do_pca=True, try_load=True, save_postcard=save_postcard) q = data.quality == 0 # create raw flux light curve raw_lc = lk.LightCurve(time=data.time[q], flux=data.raw_flux[q], flux_err=data.flux_err[q], label='raw', time_format='btjd').remove_nans().normalize() corr_lc = lk.LightCurve(time=data.time[q], flux=data.corr_flux[q], flux_err=data.flux_err[q], label='corr', time_format='btjd').remove_nans().normalize() pca_lc = lk.LightCurve(time=data.time[q], flux=data.pca_flux[q], flux_err=data.flux_err[q], label='pca', time_format='btjd').remove_nans().normalize() psf_lc = lk.LightCurve(time=data.time[q], flux=data.psf_flux[q], flux_err=data.flux_err[q], label='psf', time_format='btjd').remove_nans().normalize() #track breakpoints between sectors self.breakpoints = [raw_lc.time[-1]] # iterate through extra sectors and append the light curves if len(sectors) > 1: for s in sectors[1:]: try: # some sectors fail randomly star = eleanor.Source(tic=ticid, sector=int(s), tc=True) data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=True, do_pca=True, try_load=True) q = data.quality == 0 raw_lc = raw_lc.append( lk.LightCurve( time=data.time[q], flux=data.raw_flux[q], flux_err=data.flux_err[q], time_format='btjd').remove_nans().normalize()) corr_lc = corr_lc.append( lk.LightCurve( time=data.time[q], flux=data.corr_flux[q], flux_err=data.flux_err[q], time_format='btjd').remove_nans().normalize()) pca_lc = pca_lc.append( lk.LightCurve( time=data.time[q], flux=data.pca_flux[q], flux_err=data.flux_err[q], time_format='btjd').remove_nans().normalize()) psf_lc = psf_lc.append( lk.LightCurve( time=data.time[q], flux=data.psf_flux[q], flux_err=data.flux_err[q], time_format='btjd').remove_nans().normalize()) self.breakpoints.append(raw_lc.time[-1]) except: continue # store in a LightCurveCollection object and return return lk.LightCurveCollection([raw_lc, corr_lc, pca_lc, psf_lc])
def eleanor_lc_download(target_ID, sector, plot_raw = False, plot_corr = False, plot_pca = False, from_file = False, save_path = ''): """ Downloads and returns the various lightcurves produced by the eleanor pipeline: raw_lc = lc with flux from simple aperture photometry corr_lc = lc with flux 'corrected' for poitning errors etc (though often not trustworthy) pca_lc = lc with flux based on principal component analysis psf_lc = lc with flux based on point spread function modelling - n.b. sometimes has problems depending on tensorflow version in python """ ra, dec, tic = find_tic(target_ID, from_file = from_file) # Locates star in data star = eleanor.Source(tic, sector = sector) #star = eleanor.Source(coords=(49.4969, -66.9268), sector=1) # Extract target pixel file, perform aperture photometry and complete some systematics corrections data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=False) q = data.quality == 0 # Plot raw flux raw_lc = lightkurve.LightCurve(data.time[q],flux = data.raw_flux[q]/np.median(data.raw_flux[q]), flux_err = data.flux_err[q], targetid = target_ID) if plot_raw == True: raw_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.raw_flux[q]/np.median(data.raw_flux[q]), s=1, c = 'k') plt.ylabel('Normalized Flux') plt.xlabel('Time') plt.title('{} - eleanor light curve from FFIs - raw flux'.format(target_ID)) # raw_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor raw flux.png'.format(target_ID, sector)) #plt.close(raw_eleanor_fig) plt.show() # Plot corrected flux corr_lc = lightkurve.LightCurve(data.time[q],flux = data.corr_flux[q]/np.median(data.corr_flux[q]), flux_err = data.flux_err[q], targetid = target_ID) if plot_corr == True: corr_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.corr_flux[q]/np.median(data.corr_flux[q]), s=1, c= 'r') plt.ylabel('Normalized Flux') plt.xlabel('Time') plt.title('{} - eleanor light curve from FFIs - corr flux'.format(target_ID)) #corr_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor corr flux.png'.format(target_ID, sector)) #plt.close(corr_eleanor_fig) plt.show() # Plot pca flux eleanor.TargetData.pca(data, flux=data.raw_flux, modes=4) pca_lc = lightkurve.LightCurve(data.time[q], flux = data.pca_flux[q]/np.median(data.pca_flux[q]), flux_err = data.flux_err[q], targetid = target_ID) if plot_pca == True: pca_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.pca_flux[q]/np.median(data.pca_flux[q]), s=1, c= 'g') plt.ylabel('Normalized Flux') plt.xlabel('Time') plt.title('{} - eleanor light curve from FFIs - pca flux'.format(target_ID)) #pca_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor pca flux.png'.format(target_ID, sector)) #plt.close(pca_eleanor_fig) plt.show() # Plot psf flux #eleanor.TargetData.psf_lightcurve(data, model='gaussian', likelihood='poisson') #psf_lc = lightkurve.LightCurve(data.time[q], flux = data.psf_flux[q]/np.median(data.psf_flux[q]), flux_err = data.flux_err[q], targetid = target_ID) #psf_eleanor_fig = plt.figure() #plt.scatter(data.time[q], data.psf_flux[q]/np.median(data.psf_flux[q]), s=1, c= 'g') #plt.ylabel('Normalized Flux') #plt.xlabel('Time') #plt.title('{} - eleanor light curve from FFIs - psf flux'.format(target_ID)) #psf_eleanor_fig.savefig(save_path + '{} - Sector {} - eleanor psf flux.png'.format(target_ID, sector)) #plt.show() return raw_lc, corr_lc, pca_lc #,psf_lc
def view_next(main, RA, DE, coord, sectors): def var_states(): states[0] = typeA.get() states[1] = typeB.get() states[2] = typeC.get() states[3] = Data.get() if (len(RA) == 0): call_file_name() else: #window = tkinter.Tk() #w, h = 300, 200 #window.title("Star Images") #canvas = tkinter.Canvas(window, width=w, height=h) #label = tkinter.Label(window, text='We have data') #label.pack() states = [0, 0, 0, 0] star = eleanor.Source(coords=coord, sector=sectors[0], tc=True) data = eleanor.TargetData(star, try_load=True, do_psf=True, do_pca=True) main.destroy() vis = eleanor.Visualize(data) viewer = tkinter.Tk() button_1 = tkinter.Button( viewer, text="Submit", fg="green", command=lambda: save_to_file_finished(viewer, RA, DE, states)) button_2 = tkinter.Button( viewer, text="Review", fg="blue", command=lambda: save_to_file_review(viewer, RA, DE)) button_3 = tkinter.Button( viewer, text="Save Remaining", fg="orange", command=lambda: save_remaining_and_quit(viewer, RA, DE)) button_4 = tkinter.Button(viewer, text="Store State Values", fg="green", command=lambda: var_states()) button_1.grid(row=5) button_2.grid(row=5, column=2) button_3.grid(row=5, column=3) button_4.grid(row=5, column=1) typeA = tkinter.IntVar() typeB = tkinter.IntVar() typeC = tkinter.IntVar() Data = tkinter.IntVar() check_1 = tkinter.Checkbutton(viewer, text="No Data", variable=Data) check_2 = tkinter.Checkbutton(viewer, text="Type A", variable=typeA) check_3 = tkinter.Checkbutton(viewer, text="Type B", variable=typeB) check_4 = tkinter.Checkbutton(viewer, text="Type C", variable=typeC) check_1.grid(row=4, column=4) check_2.grid(row=1, column=4) check_3.grid(row=2, column=4) check_4.grid(row=3, column=4) fig1 = vis.pixel_by_pixel(colrange=[4, 10], rowrange=[4, 10], data_type="periodogram", color_by_pixel=True) chart_type = FigureCanvasTkAgg(fig1, viewer) chart_type.get_tk_widget().grid(row=0, sticky=tkinter.E)
try: index = target_id.index(flare) good_shot_ra.append(target_ra[index]) good_shot_dec.append(target_dec[index]) good_shot_sector.append(target_sector[index]) good_shot_start.append(target_start_mjd[index]) good_shot_end.append(target_end_mjd[index]) except Exception as e: print(e) ### for index, target in enumerate(good_shot_flares): try: print(target) coords = SkyCoord(ra=float(good_shot_ra[index]), dec=float(good_shot_dec[index]), unit=(u.deg,u.deg)) source = eleanor.Source(coords=coords, sector=good_shot_sector[index]) data = eleanor.TargetData(source, aperture_mode='small') time = [] flux = [] background = [] tpf_qual = [] q = data.quality == 0 time.append(data.time[q]) flux.append(data.corr_flux[q]/np.median(data.corr_flux[q])) background.append(data.flux_bkg[q]) tpf_qual.append(data.tpf[q]) time = time[0] flux = flux[0]
import numpy as np import matplotlib.pyplot as plt import eleanor from astropy.coordinates import SkyCoord, Angle from astropy import units as u import sys, os ra = 11.096438 # In degrees dec = -63.56094 # In degrees coords = SkyCoord(Angle(ra, u.deg), Angle(dec, u.deg)) star = eleanor.Source(coords=coords) data0 = eleanor.TargetData(star, bkg_type='2d_bkg') data1 = eleanor.TargetData(star, bkg_type='constant') q = data0.quality == 0 plt.plot(data0.time[q], data0.corr_flux[q] / np.nanmedian(data0.corr_flux[q]), 'k.', label=str(data0.bkg_type)) plt.plot(data1.time[q], data1.corr_flux[q] / np.nanmedian(data1.corr_flux[q]), 'r.', label=str(data1.bkg_type)) plt.title('The labels in the legend should be 2D_BKG and CONSTANT.') plt.legend() plt.show() plt.close() print("Is FFIINDEX working?")
print('Final lc created') print(len(t_arrcf), len(f_arrcf)) lc = lk.LightCurve(time=t_arrcf, flux=f_arrcf) data_source.append('30-min') print("Sector {} found locally with eleanor".format( target_sector[index])) except Exception as e: print(e) print( 'File does not already exist, downloading postcards instead' ) try: ###then trying 30-min data coords = (float(target_ra[index]), float(target_dec[index])) source = eleanor.Source(coords=coords, sector=target_sector[index]) data = eleanor.TargetData(source, aperture_mode='small') data.save(output_fn='{}_s{}_eleanor_data.fits'.format( ids, target_sector[index]), directory= '/data/wallaby/rmorris/GALAH/all_target_lc/') data_source.append('30-min') ###only using quality points time = [] flux = [] background = [] q = data.quality == 0 time.append(data.time[q])
def eleanor_lc(savepath, RADECfile, plotting=True): """ retrieves + produces eleanor light curves from FFI files """ import eleanor from astropy import units as u from astropy.coordinates import SkyCoord import warnings warnings.filterwarnings('ignore') from eleanor.utils import SearchError from scipy.linalg.misc import LinAlgError download_dir_tesscut = os.path.join(os.path.expanduser('~'), '.eleanor', 'tesscut') download_dir_mastdownload = os.path.join(os.path.expanduser('~'), '.eleanor', 'mastDownload') print(download_dir_tesscut, download_dir_mastdownload) with open(RADECfile, 'r') as f: lines = f.readlines() for line in lines: ID, RA, DEC, sector = line.split(',') print(ID, RA, DEC, sector) sector_int = int(sector) filepath = savepath + ID + "_s" + str(sector_int) + "_lc.txt" if not os.path.isfile(filepath): try: coords = SkyCoord(ra=RA, dec=DEC, unit=(u.deg, u.deg)) files = eleanor.Source(coords=coords, tic=0, gaia=0, sector=sector_int) #print("files found: ", len(files)) print( 'Found TIC {0} (Gaia {1}), with TESS magnitude {2}, RA {3}, and Dec {4}' .format(files.tic, files.gaia, files.tess_mag, files.coords[0], files.coords[1])) #try: data = eleanor.TargetData(files, do_pca=True) q = data.quality == 0 timeandflux = np.asarray((data.time[q], data.corr_flux[q])) plt.scatter(data.time[q], data.raw_flux[q], label="raw") plt.scatter(data.time[q], data.corr_flux[q], label="corr") plt.legend(loc="upper left") plt.show() np.savetxt(filepath, timeandflux) except (SearchError, ValueError): print("******************************") print("Search Error or ValueError occurred") print("******************************") except OSError: print("******************************") print("Empty or corrupt FITS file") print("******************************") except LinAlgError: print("******************************") print("SVD did not converge") print("******************************") except IndexError: print("******************************") print("Couldn't find these coordinates in") print("******************************") #except TypeError: # print("******************************") # print("Issue with internal function while trying to read file") # print("******************************") else: print("Already found this target") for root, dirs, files in os.walk(download_dir_tesscut): for file in files: try: os.remove(os.path.join(root, file)) print("Deleted") except (PermissionError, OSError): #print("Unable to delete", os.path.join(root, file)) continue for root, dirs, files in os.walk(download_dir_mastdownload): for file in files: try: os.remove(os.path.join(root, file)) print("Deleted") except (PermissionError, OSError): #print("Deleted", os.path.join(root, file)) continue return
##plt.close(tpf_plot) # ## Remove plot base lc #tpf_30min.to_lightcurve(aperture_mask = aperture_mask).plot() ##sigma_cut_lc_fig.savefig(save_path + '{} - Sector {} - 3 sigma lightcurve.png'.format(target_ID, tpf.sector)) ##plt.close(sigma_cut_lc_fig) # ## Convert to lightcurve object #lc_30min = tpf_30min.to_lightcurve(aperture_mask = aperture_mask) #lc_30min = lc_30min[(lc_30min.time < 1346) | (lc_30min.time > 1350)] #lc_30min.scatter() #plt.title('{} - 30min FFI base lc'.format(target_ID)) # ############################# eleanor lc ####################################### star = eleanor.Source(coords=(ra, dec), sector=1) #star = eleanor.Source(coords=(49.4969, -66.9268), sector=1) # Extract target pixel file, perform aperture photometry and complete some systematics corrections data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=False) q = data.quality == 0 # Plot raw flux raw_eleanor_fig = plt.figure() plt.scatter(data.time[q], data.raw_flux[q] / np.median(data.raw_flux[q]), s=1, c='k') plt.ylabel('Normalized Flux') plt.xlabel('Time')
import eleanor import numpy as np from astropy import units as u import matplotlib.pyplot as plt from astropy.coordinates import SkyCoord import lightkurve as lk #eleanor.Update(sector=1) star = eleanor.Source(name='WASP-100', sector=3) print(star.gaia) data = eleanor.TargetData(star, do_psf=True, do_pca=True) #plt.title('2D background') #plt.imshow(data.post_obj.background2d[100], vmin=0, vmax=20) #plt.colorbar() #plt.show() #print(data.bkg_type) #plt.figure(figsize=[14,4]) #plt.plot(data.time, data.post_obj.bkg, 'b', lw=3) #plt.xlabel('time [bjd-2457000]') #plt.ylabel('background flux') #plt.show() #plt.imshow(data.tpf[100]) #plt.imshow(data.aperture, alpha =0.4, cmap='Greys_r') #plt.show()
flares = Table.read( "/Users/jshabazz/flareDetectCode/textfiles/guenther_flares.csv", format='ascii') ids = flares['tic_id'] sector = flares['sector'] duration = flares['duration'] #%% for i, this_id in enumerate(ids): if duration[i] > 0.32: print(i) print(this_id) print(sector[i]) star = eleanor.Source(tic=int(this_id), sector=int(sector[i])) print( 'Found TIC {0} (Gaia {1}), with TESS magnitude {2}, RA {3}, and Dec {4}' .format(star.tic, star.gaia, star.tess_mag, star.coords[0], star.coords[1])) data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=True, do_pca=True) plt.figure(figsize=(15, 5)) q = data.quality == 0 #plt.plot(data.time[q], data.raw_flux[q]/np.nanmedian(data.raw_flux[q])+0.06, 'k')
for a in indexes]) / binsize else: # Make them zeros. binned_lc.flux_err = np.zeros(len(binned_lc.raw_flux[q])) return binned_lc ############################################################################### # Main log = logging.getLogger(__name__) # Assign star of interest #star = eleanor.Source(tic=29857954, sector=1) star = eleanor.Source(coords=(319.94962, -58.1489), sector=1) #star = eleanor.Source(gaia=4675352109658261376, sector=1) # Extract target pixel file, perform aperture photometry and complete some systematics corrections #data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=False) data = eleanor.TargetData(star) q = data.quality == 0 # Plot a lightcurve or a few... plt.figure() plt.plot(data.time[q], data.raw_flux[q] / np.median(data.raw_flux[q]) - 0.01, 'k') plt.plot(data.time[q], data.corr_flux[q] / np.median(data.corr_flux[q]) + 0.01, 'r') #plt.plot(data.time[q], data.pca_flux[q]/np.median(data.pca_flux[q]) + 0.03, 'y')
lc = lk.LightCurve(time=time_bkg, flux=flux_bkg) #print('test line') if sector == outSec[0]: lightcurves = lk.LightCurveCollection(lc) else: lightcurves.append(lc) #print('test line 2') sector_source.append('30-min') print("Sector {} found locally with eleanor".format(sector)) except Exception as e: print(e) print('File does not already exist, downloading postcards instead') try: ###otherwise download with eleanor and save star = eleanor.Source(coords=coords, sector=int(sector), post_dir='/data/wallaby/postcards/') datum = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=False, do_pca=False, aperture_mode='small') datum.save(output_fn='{}_s{}_eleanor_data.fits'.format(i,sector),directory='/data/wallaby/rmorris/GALAH/all_target_lc/') time = [] flux = [] background = [] q = datum.quality == 0 time.append(datum.time[q]) flux.append(datum.corr_flux[q]/np.median(datum.corr_flux[q])) background.append(datum.flux_bkg[q]) time_bkg = np.zeros(len(background)) flux_bkg = np.zeros(len(background))
import eleanor import numpy as np from astropy import units as u import matplotlib.pyplot as plt from astropy.coordinates import SkyCoord star = eleanor.Source(tic=38846515, sector=1) print('Found TIC {0} (Gaia {1}), with TESS magnitude {2}, RA {3}, and Dec {4}'. format(star.tic, star.gaia, star.tess_mag, star.coords[0], star.coords[1])) data = eleanor.TargetData(star, height=15, width=15, bkg_size=31, do_psf=True, do_pca=True) plt.figure(figsize=(15, 5)) q = data.quality == 0 plt.plot(data.time[q], data.raw_flux[q] / np.nanmedian(data.raw_flux[q]) + 0.06, 'k') plt.plot(data.time[q], data.corr_flux[q] / np.nanmedian(data.corr_flux[q]) + 0.03, 'r') plt.plot(data.time[q], data.pca_flux[q] / np.nanmedian(data.pca_flux[q]), 'g') plt.plot(data.time[q], data.psf_flux[q] / np.nanmedian(data.psf_flux[q]) - 0.02, 'b') plt.ylabel('Normalized Flux')