def get_ffi_image(target, cutout_deg=0.1):

    ra = target['ra']
    dec = target['dec']

    coord = SkyCoord(ra, dec, unit="deg")
    print(coord)

    npixels = 2 * np.ceil(
        cutout_deg * 3600 / 21) + 4  #This assumes 21arcsecond pixels)

    if npixels > 60:
        npixels = 60
        print("Warning: cutout size set to 80 pixels.")
    if npixels < 10:
        npixels = 10

    sector_tab = Tesscut.get_sectors(coordinates=coord)

    try:
        hdulist = Tesscut.get_cutouts(coord,
                                      size=npixels,
                                      sector=sector_tab[0]['sector'])
    except:
        print("Cutout not available")
        return [[0][0]], "no wcs"

    hdu = hdulist[0]
    aveImage = (hdu[1].data['FLUX'][0] + hdu[1].data['FLUX'][1] +
                hdu[1].data['FLUX'][2]) / 3

    wcs = WCS(hdu[2].header)

    return aveImage, wcs
Ejemplo n.º 2
0
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')
Ejemplo n.º 3
0
    def locate_with_tesscut(self):
        """Finds the best TESS postcard(s) and the position of the source on postcard.
        Sets attributes postcard, position_on_postcard, all_postcards.
         sector, camera, chip, position_on_chip.
        
        """
        self.postcard = []
        self.position_on_postcard = []
        self.all_postcards = []
        
        self.tc = True
        
        coord = SkyCoord(self.coords[0], self.coords[1], unit="deg")
        
        sector_table = Tesscut.get_sectors(coord)

        manifest = Tesscut.download_cutouts(coord, 31, sector = self.usr_sec)

        self.sector = self.usr_sec
        self.camera = sector_table[sector_table['sector'] == self.sector]['camera'].quantity[0]
        self.chip = sector_table[sector_table['sector'] == self.sector]['ccd'].quantity[0]

        whichtc = np.where(sector_table['sector'] == self.usr_sec)[0][0]

        cutout = fits.open(manifest['Local Path'][0])
        
        self.cutout = cutout
        
        xcoord = cutout[1].header['1CRV4P']
        ycoord = cutout[1].header['2CRV4P']
        
        self.position_on_chip = np.array([xcoord, ycoord])
Ejemplo n.º 4
0
def set_quality_flags(sector=np.arange(1, 14, 1)):
    """ Uses the quality flags in a 2-minute target to create quality flags
        in the postcards.
    We create our own quality flag as well, using our pointing model.
    """

    coord = SkyCoord('04:35:50.330 -64:01:37.33', unit=(u.hourangle, u.deg))

    sector_table = Tesscut.get_sectors(coord)

    manifest = Tesscut.download_cutouts(coordinates=coord,
                                        size=31,
                                        sector=sector)

    cutout = fits.open(manifest['Local Path'][0])
    ffi_time = cutout[1].data['TIME'] - cutout[1].data['TIMECORR']

    shortCad_fn = 'eleanor/metadata/s{0:04d}/target_s{0:04d}.fits'.format(
        sector)

    # Binary string for values which apply to the FFIs
    ffi_apply = int('100010101111', 2)

    # Obtains information for 2-minute target
    twoMin = fits.open(shortCad_fn)
    twoMinTime = twoMin[1].data['TIME'] - twoMin[1].data['TIMECORR']
    finite = np.isfinite(twoMinTime)
    twoMinQual = twoMin[1].data['QUALITY']

    twoMinTime = twoMinTime[finite]
    twoMinQual = twoMinQual[finite]

    convolve_ffi = []
    nodata = np.zeros_like(ffi_time)
    for i in range(len(ffi_time)):
        where = np.where(
            np.abs(ffi_time[i] -
                   twoMinTime) == np.min(np.abs(ffi_time[i] -
                                                twoMinTime)))[0][0]

        sflux = np.sum(cutout[1].data['FLUX'][i])
        if sflux == 0:
            nodata[i] = 4096

        if (ffi_time[i] > 1420) and (ffi_time[i] < 1424):
            nodata[i] = 4096

        v = np.bitwise_or.reduce(twoMinQual[where - 7:where + 8])
        convolve_ffi.append(v)

    convolve_ffi = np.array(convolve_ffi)

    flags = np.bitwise_and(convolve_ffi, ffi_apply)

    np.savetxt('eleanor/metadata/s{0:04d}/quality_s{0:04d}.txt'.format(sector),
               flags + nodata,
               fmt='%i')

    return flags
Ejemplo n.º 5
0
    def __init__(self, sector=None):

        if sector is None:
            print('Please pass a sector into eleanor.Update()!')
            return

        self.sector = sector

        try:
            os.mkdir(eleanorpath + '/metadata/s{:04d}'.format(sector))
            success = 1
        except FileExistsError:
            print('Sector {:d} metadata directory exists already!'.format(
                sector))
            success = 0

        if success == 1:

            tic_north_cvz = 198237770
            tic_south_cvz = 38846515

            if self.sector < 13.5:
                self.tic = tic_south_cvz
            elif self.sector < 26.5:
                self.tic = tic_north_cvz
            else:
                self.tic = tic_south_cvz

            if self.tic == 198237770:
                coord = SkyCoord('16:35:50.667 +63:54:39.87',
                                 unit=(u.hourangle, u.deg))
            elif self.tic == 38846515:
                coord = SkyCoord('04:35:50.330 -64:01:37.33',
                                 unit=(u.hourangle, u.deg))

            sector_table = Tesscut.get_sectors(coord)

            manifest = Tesscut.download_cutouts(coord, 31, sector=self.sector)

            self.cutout = fits.open(manifest['Local Path'][0])

            print(
                'This is the first light curve you have made for this sector. Getting eleanor metadata products for Sector {0:2d}...'
                .format(self.sector))
            print(
                'This will only take a minute, and only needs to be done once. Any other light curves you make in this sector will be faster.'
            )
            self.get_target()
            print('Target Acquired')
            self.get_cadences()
            print('Cadences Calculated')
            self.get_quality()
            print('Quality Flags Assured')
            self.get_cbvs()
            print('CBVs Made')
            print('Success! Sector {:2d} now available.'.format(self.sector))

            self.try_next_sector()
Ejemplo n.º 6
0
    def locate_with_tesscut(self):
        """
        Finds the best TESS postcard(s) and the position of the source on postcard.

        Attributes
        ----------
        postcard : list
        postcard_path : str
        position_on_postcard : list 
        all_postcards : list
        sector : int
        camera : int
        chip : int
        position_on_chip : np.array

        """
        self.postcard = []
        self.position_on_postcard = []
        self.all_postcards = []

        self.tc = True

        coord = SkyCoord(self.coords[0], self.coords[1], unit="deg")

        sector_table = Tesscut.get_sectors(coord)
        self.sector = self.usr_sec

        self.camera = sector_table[sector_table['sector'] ==
                                   self.sector]['camera'].quantity[0].value
        self.chip = sector_table[sector_table['sector'] ==
                                 self.sector]['ccd'].quantity[0].value

        download_dir = self.tesscut_dir()

        fn_exists = self.search_tesscut(download_dir, coord)

        if fn_exists is None:
            manifest = Tesscut.download_cutouts(coord,
                                                self.tesscut_size,
                                                sector=self.usr_sec,
                                                path=download_dir)
            cutout = fits.open(manifest['Local Path'][0])
            self.postcard_path = manifest['Local Path'][0]
        else:
            self.postcard_path = fn_exists
            cutout = fits.open(fn_exists)

        self.cutout = cutout
        self.postcard = self.postcard_path.split('/')[-1]

        xcoord = cutout[1].header['1CRV4P']
        ycoord = cutout[1].header['2CRV4P']

        self.position_on_chip = np.array([xcoord, ycoord])
Ejemplo n.º 7
0
def get_fficutout(c_obj, cutoutdir=None, sector=None):
    # c_obj (SkyCoord): location of target star

    print('beginning download tesscut for {}'.format(repr(c_obj)))
    try:
        tab = Tesscut.download_cutouts(c_obj, size=20, sector=sector,
                                       path=cutoutdir)
    except (requests.exceptions.HTTPError,
            requests.exceptions.ConnectionError) as e:
        print('got {}, try again'.format(repr(e)))
        tab = Tesscut.download_cutouts(c_obj, size=20, sector=sector,
                                       path=cutoutdir)
Ejemplo n.º 8
0
    def getTessCut(self):
        """
        Perform tesscut.
        Not Done, come back.
        """

        manifest = Tesscut.get_cutouts(self.coord, size)
Ejemplo n.º 9
0
 def _find_sectors(self, ticid):
     """Helper function to read sectors from a search result."""
     from astroquery.mast import Tesscut
     sectors = []
     for s in Tesscut().get_sectors(objectname=ticid)['sector']:
         sectors.append(s)
     return sectors
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
    def __init__(self, ID: int, sectors: np.ndarray, search_radius: int = 10):
        """
        Queries TIC for sources near the target and obtains a cutout
        of the pixels enclosing the target.
        Args:
            ID (int): TIC ID of the target.
            sectors (numpy array): Sectors in which the target
                                   has been observed.
            search_radius (int): Number of pixels from the target
                                 star to search.
        """
        self.ID = ID
        self.sectors = sectors
        self.search_radius = search_radius
        self.N_pix = 2 * search_radius + 2
        # query TIC for nearby stars
        pixel_size = 20.25 * u.arcsec
        df = Catalogs.query_object("TIC" + str(ID),
                                   radius=search_radius * pixel_size,
                                   catalog="TIC")
        new_df = df["ID", "Tmag", "ra", "dec", "mass", "rad", "Teff", "plx"]
        stars = new_df.to_pandas()
        self.stars = stars

        TESS_images = []
        col0s, row0s = [], []
        pix_coords = []
        # for each sector, get FFI cutout and transform RA/Dec into
        # TESS pixel coordinates
        for j, sector in enumerate(sectors):
            Tmag = stars["Tmag"].values
            ra = stars["ra"].values
            dec = stars["dec"].values
            cutout_coord = SkyCoord(ra[0], dec[0], unit="deg")
            cutout_hdu = Tesscut.get_cutouts(cutout_coord,
                                             size=self.N_pix,
                                             sector=sector)[0]
            cutout_table = cutout_hdu[1].data
            hdu = cutout_hdu[2].header
            wcs = WCS(hdu)
            TESS_images.append(np.mean(cutout_table["FLUX"], axis=0))
            col0 = cutout_hdu[1].header["1CRV4P"]
            row0 = cutout_hdu[1].header["2CRV4P"]
            col0s.append(col0)
            row0s.append(row0)

            pix_coord = np.zeros([len(ra), 2])
            for i in range(len(ra)):
                RApix = np.asscalar(wcs.all_world2pix(ra[i], dec[i], 0)[0])
                Decpix = np.asscalar(wcs.all_world2pix(ra[i], dec[i], 0)[1])
                pix_coord[i, 0] = col0 + RApix
                pix_coord[i, 1] = row0 + Decpix
            pix_coords.append(pix_coord)

        self.TESS_images = TESS_images
        self.col0s = col0s
        self.row0s = row0s
        self.pix_coords = pix_coords
        return
Ejemplo n.º 12
0
 def get_tess_cuts(coordinates, cube_side_size):
     """Gets the TESS cuts for a given set of coordinates, repeating on errors."""
     cutouts = None
     while True:  # This loop plus try is used to repeat if a connection error happens.
         try:
             cutouts = Tesscut.get_cutouts(coordinates, cube_side_size)
             break
         except HTTPError:
             print('HTTP error, trying again...')
             continue
     return cutouts
Ejemplo n.º 13
0
def diff_image_lc_download(target_ID, sector, plot_lc = False, from_file = True, save_path = '/home/u1866052/Lowess detrending/TESS S5/'):
    """
    Downloads and returns 30min cadence lightcurves based on Oelkers & Stassun
    difference imaging analysis method of lightcurve extraction
    """
    DIAdir = '/ngts/scratch/tess/FFI-LC/S{}/lc/clean/'.format(sector)
    
    ra, dec, tic = find_tic(target_ID, from_file = from_file) 
    
    object_coord = SkyCoord(ra, dec, unit="deg")
    sector_info = Tesscut.get_sectors(object_coord)
    
    for i in range(len(sector_info)):
        if sector_info[i][1] == sector:
            index = i
            
    camera = sector_info[index][2]
    ccd = sector_info[index][3]
    
#    star = eleanor.Source(coords=(ra, dec), sector=1)
##    camera = 
#    ccd = star.chip
    
    filename = '{}_sector0{}_{}_{}.lc'.format(tic, sector, camera, ccd)
#    filename = '{}_sector0{}_{}_{}.lc'.format(tic, sector, camera, ccd)
#    filename = '410214986_sector01_3_2.lc'

    
    try:
        #lines = loadtxt(filename, delimiter = ' ') # For when in local directory
        lines = loadtxt(DIAdir+filename, delimiter = ' ') # For when on ngtshead
        DIA_lc = list(map(list, zip(*lines)))
        DIA_mag = np.array(DIA_lc[1])
        
        # Convert TESS magnitudes to flux
        DIA_flux =  10**(-0.4*(DIA_mag - 20.60654144))
        norm_flux = DIA_flux/np.median(DIA_flux)
        
        # Plot Difference imaged data
        if plot_lc == True:
            diffImage_fig = plt.figure()
            plt.scatter(DIA_lc[0], norm_flux, s=1, c= 'k')
            plt.ylabel('Normalized Flux')
            plt.xlabel('Time')
            plt.title('{} - Difference imaged light curve from FFIs'.format(target_ID))
#            diffImage_fig.savefig(save_path + '{} - Sector {} - DiffImage flux.png'.format(target_ID, sector))
#            plt.close(diffImage_fig)
            plt.show()
        
        lc = lightkurve.LightCurve(time = DIA_lc[0],flux = norm_flux, flux_err = DIA_lc[2], targetid = target_ID)
        
        return lc, filename
    except:
        print('The file {} does not exist - difference imaging data not available for {}'.format(filename,target_ID))
Ejemplo n.º 14
0
def download_TESS_cutouts_ID(target_ID_list, cutout_size=[11, 11]):
    """
    This function downloads the TESS-cutouts for a specified list of target IDs
    and returns a dictionary of the associated filename(s) for each target
    
    Inputs:
        Name                    type              description
        -----------------------------------------------------------------------
        target_ID_ list         [n x 1] list      list of target IDs as strings
        cutout_size             [2 x 1] list      postcard cutout size
    
    Output:
        target_filenames         n x 2 dictionary with target ids and target filenames
    """

    filename = "BANYAN_XI-III_combined_members.csv"

    data = Table.read(filename, format='ascii.csv')

    target_filenames = {}

    for target_id in target_ID_list:
        i = list(data['main_id']).index(target_id)
        ra = data['ra'][i]
        dec = data['dec'][i]
        object_coord = SkyCoord(ra, dec, unit="deg")
        manifest = Tesscut.download_cutouts(object_coord,
                                            cutout_size,
                                            path='./TESS_Sector_1_cutouts')
        sector_info = Tesscut.get_sectors(object_coord)
        if len(manifest['Local Path']) == 1:
            target_filenames[target_id] = manifest['Local Path'][0][2:]
        elif len(manifest['Local Path']) > 1:
            target_filenames[target_id] = []
            for filename in manifest['Local Path']:
                target_filenames[target_id].append(filename[2:])
        else:
            print(
                'Cutout for target {} can not be downloaded'.format(target_id))

    return target_filenames, sector_info
Ejemplo n.º 15
0
def getTessCutout(coord, size_pixels, sector):
    """
    Returns first returned for that sector.
    """

    hdulist = Tesscut.get_cutouts(coord, size_pixels, sector=sector)

    if len(hdulist) < 1:
        raise IOError

    hdu = hdulist[0]
    return hdu[1].data, hdu[1].header, hdu[2].header
Ejemplo n.º 16
0
def convolve_cbvs(sectors=np.arange(1, 14, 1)):
    """
   Bins the co-trending basis vectors into FFI times;
   Calls download_cbvs to get filenames
   Input
   -----
      type(sectors) == list
    """
    # Gets the cutout for a target in the CVZ
    coord = SkyCoord('04:35:50.330 -64:01:37.33', unit=(u.hourangle, u.deg))
    sector_table = Tesscut.get_sectors(coord)

    for sector in sectors:
        files = download_cbvs(int(sector))
        manifest = Tesscut.download_cutouts(coordinates=coord,
                                            size=31,
                                            sector=sector)
        cutout = fits.open(manifest['Local Path'][0])
        time = cutout[1].data['TIME'] - cutout[1].data['TIMECORR']

        for c in trange(len(files)):
            cbv = fits.open(files[c])
            camera = cbv[1].header['CAMERA']
            ccd = cbv[1].header['CCD']
            cbv_time = cbv[1].data['Time']

            new_fn = './eleanor/metadata/s{0:04d}/cbv_components_s{0:04d}_{1:04d}_{2:04d}.txt'.format(
                sector, camera, ccd)

            convolved = np.zeros((len(time), 16))

            for i in range(len(time)):
                g = np.argmin(np.abs(time[i] - cbv_time))
                for j in range(16):
                    index = 'VECTOR_{0}'.format(j + 1)
                    cads = np.arange(g - 7, g + 8, 1)
                    convolved[i, j] = np.mean(cbv[1].data[index][cads])

            np.savetxt(new_fn, convolved)
Ejemplo n.º 17
0
    def checkCoordInSector(self, coord, sector):
        """
        Determine if there is data on the Sector requested for the target.
        """

        sectorTable = Tesscut.get_sectors(coord)

        if sector in sectorTable['sector']:
            sectorExists = True
        else:
            sectorExists = False

        return sectorExists
Ejemplo n.º 18
0
def tessobs_info(tic=None, ra=None, dec=None):
    #!!Update to include exp time, pixel location, other observation-specific
    #  quantities!!
    """
    Function to retrieve observation information for objects observed by TESS.

    Parameters
    ----------
    tic : int or None
       TIC ID of target to be queried. Must not be None if ra and dec are None.
    ra : float or None
       RA of target to be queried. Must not be None if tic is None.
    dec : float or None
       Dec of target to be queried. Must not be None if tic is None.

    Returns
    -------
    info : dict
       Dictionary continaing TESS observation info.
    """
    if not tic and not ra and not dec:
        raise ValueError('Please provide either a TIC ID or both RA and Dec')

    if not ra or not dec:
        cat = Catalogs.query_criteria(catalog="TIC", ID=int(tic))
        ra = cat[0]['ra']
        dec = cat[0]['dec']

    coords = coord.SkyCoord(ra, dec, unit='deg')
    sector_table = Tesscut.get_sectors(coordinates=coords)
    
    if len(sector_table) == 0:
        print('Object not observed by TESS')

    sec_name = []
    sec = []
    cam = []
    ccd = []

    for i in range(len(sector_table)):
        sec_name.append(sector_table[i]['sectorName'])
        sec.append(sector_table[i]['sector'])
        cam.append(sector_table[i]['camera'])
        ccd.append(sector_table[i]['ccd'])

    info = {'sectorName' : sec_name, 'sector' : sec, 'camera' : cam,
            'ccd' : ccd}

    return info
Ejemplo n.º 19
0
def download_TESS_cutouts_coords(ra, dec, cutout_size=[11, 11]):
    """
    This function downloads the TESS-cutouts for a target with specified ra and
    dec coordinates and prints the resulting filename(s)
    
    Inputs:
        Name          unit           type                 description
        -----------------------------------------------------------------------
        ra            deg            float           right ascension of target
        dec           deg            float           declination of target
        cutout_size   ---            [2 x 1] list    postcard cutout size
    """
    cutout_coord = SkyCoord(ra, dec, unit="deg")
    manifest = Tesscut.download_cutouts(cutout_coord, cutout_size)
    print(manifest)
Ejemplo n.º 20
0
def call_astropy(main, RA, DE):
    if (len(RA) == 0):
        call_file_name
        return
    else:
        coord = SkyCoord(RA[len(RA) - 1], DE[len(DE) - 1], unit="deg")
        sector_table = Tesscut.get_sectors(coordinates=coord)
        if (len(sector_table) == 0):  # not in a sector (yet?)
            RA.pop()
            DE.pop()
            call_astropy(main, RA, DE)
        else:
            sectors = [0] * (len(sector_table))
            for i in range(len(sector_table)):
                sectors[i] = int(sector_table['sector'][i])
        view_next(main, RA, DE, coord, sectors)
Ejemplo n.º 21
0
    def locate_with_tesscut(self):
        """
        Finds the best TESS postcard(s) and the position of the source on postcard.

        Attributes
        ----------
        postcard : list
        postcard_path : str
        position_on_postcard : list 
        all_postcards : list
        sector : int
        camera : int
        chip : int
        position_on_chip : np.array

        """
        # Attributes only when using postcards
        self.all_postcards = None

        # Attribute for TessCut
        self.tc = True

        download_dir = self.tesscut_dir()

        coords = SkyCoord(self.coords[0], self.coords[1], unit=(u.deg, u.deg))

        fn_exists = self.search_tesscut(download_dir, coords)

        if fn_exists is None:
            manifest = Tesscut.download_cutouts(coords,
                                                self.tesscut_size,
                                                sector=self.sector,
                                                path=download_dir)
            cutout = fits.open(manifest['Local Path'][0])
            self.postcard_path = manifest['Local Path'][0]
        else:
            self.postcard_path = fn_exists
            cutout = fits.open(fn_exists)

        self.cutout = cutout
        self.postcard = self.postcard_path.split('/')[-1]

        xcoord = cutout[1].header['1CRV4P']
        ycoord = cutout[1].header['2CRV4P']

        self.position_on_chip = np.array([xcoord, ycoord])
Ejemplo n.º 22
0
def bert_tess_fullframe_main_1():
    """Extract light curve data from TESS full frame images for a given
    TIC ID.

    This Lambda function loops through full frame images. For each full frame
    image, it invokes :func:`bert_tess_fullframe_worker`.

    """
    from astropy.coordinates import SkyCoord
    from astroquery.mast import Catalogs, Tesscut

    work_queue, done_queue, ologger = utils.comm_binders(
        bert_tess_fullframe_main_1)

    # https://exo.mast.stsci.edu/exomast_planet.html?planet=WASP126b
    # Example event:
    # {
    #   "tic_id": "25155310",
    #   "radius": 2.5,
    #   "cutout_width": 30,
    #   "use_cache": "true"
    # }
    for event in work_queue:
        tic_id = event['tic_id']
        info = Catalogs.query_criteria(catalog='Tic', ID=tic_id)
        ra = info['ra'][0]  # deg
        dec = info['dec'][0]  # deg
        coo = SkyCoord(ra, dec, unit='deg')

        # TODO: Allow auto determination of radius from mag if not given.
        # mag = info['Tmag'][0]

        sector_resp = Tesscut.get_sectors(coordinates=coo)
        ologger.info(f'Found {len(sector_resp)} sectors for {tic_id}')

        # Process all the matched sectors.
        for sec_id in sector_resp['sectorName']:
            done_queue.put({
                'tic_id': tic_id,
                'sec_id': sec_id,
                'ra': ra,
                'dec': dec,
                'radius': event['radius'],
                'cutout_width': event['cutout_width'],
                'use_cache': event['use_cache']
            })
Ejemplo n.º 23
0
def test_pi_men():
    """Tests `locate()` against `astroquery.mast.Tesscut.get_sectors()`"""
    # Query using Tesscut
    crd = SkyCoord(ra=84.291188, dec=-80.46911982, unit="deg")
    mast_result = Tesscut.get_sectors(crd)
    # Query using our tool
    our_result = locate(crd)
    # Do the sector, camera, and ccd numbers all match?
    our_result_df = our_result.to_pandas().reset_index()[["sector", "camera", "ccd"]]
    mast_result_df = mast_result.to_pandas().reset_index()[["sector", "camera", "ccd"]]
    # Hack: MAST incorrectly returns Pi Men as having been observed in Sector 35, while in
    # reality it is just off the science area of the CCD, so we ignore the row for Sector 35.
    mast_result_df = mast_result_df.query("sector != 35").reset_index(drop=True)
    # Note: MAST may have less results because it only reports archived data
    assert our_result_df.iloc[0 : len(mast_result_df)].equals(mast_result_df)
    # Can we search by passing a string instead of the coordinates?
    our_result2 = locate("Pi Men")
    assert our_result.to_pandas().round(2).equals(our_result2.to_pandas().round(2))
Ejemplo n.º 24
0
def get_object_coords(ticid, sector, nFFI=10, cloud=False, local_dir="."):
    """
    Retrieve the camera, ccd, column row of the ticid of interest.
    Downloads a single FFI image in order to retrieve the FITS header.
    Input:
        ticid: tess ID
        sector : integer sector number
        nFFI: indicates which FFI cadence to use.
        cloud: False. Set to true if running on AWS
        local_dir: Is the location to store the FFI image before reading header.
        
    Returns:
        camera, ccd, column, row
        
        if they are all zero, then there is no data to be had
    """

    coord = ticid_to_coord(ticid)
    results = Tesscut.get_sectors(coord, radius=0)

    camera = 0
    ccd = 0
    col = 0
    row = 0

    if len(results) > 0:

        want = results['sector'] == sector
        if len(results[want]) > 0:

            camera = results[want]['camera'][0]
            ccd = results[want]['ccd'][0]

    if camera > 0:
        secid = make_secid(sector, camera, ccd)
        ffi_file_path = get_wcsfile(secid)
        #filtered = id_wcs_file(secid)

    #ffi_file_path = download_wcs_file(filtered, local_dir, n=nFFI, cloud=cloud)
    #I need to create a file lookup in here, but for the moment.

    col, row = get_xy(ffi_file_path, coord)

    return camera, ccd, col, row
Ejemplo n.º 25
0
def get_tess_visibility_given_ticid(tic_id):
    """
    This checks if a given TIC ID is visible in a TESS sector.

    Parameters
    ----------
    tic_id : str
        The TIC ID of the object as a string.

    Returns
    -------
    sector_str,full_sector_str : tuple of strings
        The first element of the tuple contains a string list of the sector
        numbers where the object is visible. The second element of the tuple
        contains a string list of the full sector names where the object is
        visible.

        For example, "[16, 17]" and "[tess-s0016-1-4, tess-s0017-2-3]". If
        empty, will return "[]" and "[]".
    """

    if not astroquery_dependency:
        LOGERROR(
            "The astroquery package is required for this function to work.")
        return None, None

    ticres = tic_objectsearch(tic_id)

    with open(ticres['cachefname'], 'r') as json_file:
        data = json.load(json_file)

    ra = data['data'][0]['ra']
    dec = data['data'][0]['dec']

    coord = SkyCoord(ra, dec, unit="deg")
    sector_table = Tesscut.get_sectors(coord)

    sector_str = list(sector_table['sector'])
    full_sector_str = list(sector_table['sectorName'])

    return sector_str, full_sector_str
Ejemplo n.º 26
0
def has_data(catalog,
             raname='ra',
             decname='dec',
             namename='Name',
             verbose=True,
             cutout=1):
    indices = []

    for j, name in enumerate(catalog[namename]):
        ra, dec = catalog[j][raname, decname]
        coords = SkyCoord(ra, dec, unit=(u.hourangle, u.deg))
        try:
            hdulist = Tesscut.get_cutouts(
                coords, cutout)  # actually downloads the FITS files! eep!
            if len(hdulist) != 0:
                indices.append(j)
                if verbose:
                    print('%s %.3f %.3f\n' %
                          (name, coords.ra.deg, coords.dec.deg))
        except:
            pass
    return indices
Ejemplo n.º 27
0
def get_multi_cutout_lst(coords, sz=(15, 15)):

    lst_hdu_elements = Tesscut.get_cutouts(coordinates=coords, size=sz)
    return (lst_hdu_elements)
Ejemplo n.º 28
0
def get_data(ra, dec, units="deg", size=64):
    c = SkyCoord(ra, dec, units=units)
    data_table = Tesscut.download_cutouts(c, size=size)
    return data_table
Ejemplo n.º 29
0
def data_dl(ra, dec, size):
    cutout_coord = SkyCoord(ra, dec, unit="deg")
    hdulist = Tesscut.get_cutouts(coordinates=cutout_coord, size=size)
    return hdulist
Ejemplo n.º 30
0
def raw_FFI_lc_download(target_ID, sector, plot_tpf = False, plot_lc = False, save_path = '', from_file = False):
    """
    Downloads and returns 30min cadence lightcurves based on SAP analysis of 
    the raw FFIs
    """    
    if from_file == True:
        with open('Sector_{}_target_filenames.pkl'.format(sector), 'rb') as f:
            target_filenames = pickle.load(f)
        f.close()
    else:
        target_filenames = {}
    
        ra, dec, tic = find_tic(target_ID, from_file = True) 
         
        object_coord = SkyCoord(ra, dec, unit="deg")
        manifest = Tesscut.download_cutouts(object_coord, [11,11], path = './TESS_Sector_1_cutouts')
#        sector_info = Tesscut.get_sectors(object_coord)
        if len(manifest['Local Path']) == 1:
            target_filenames[target_ID] = manifest['Local Path'][0][2:]
        elif len(manifest['Local Path']) > 1:
            target_filenames[target_ID] = []
            for filename in manifest['Local Path']:
                target_filenames[target_ID].append(filename[2:])
        else:
            print('Cutout for target {} can not be downloaded'.format(target_ID))
        
    if type(target_filenames[target_ID]) == str:
        filename = target_filenames[target_ID]
    else:
        filename = target_filenames[target_ID][0]
        
    
    # Load tpf
    tpf_30min = lightkurve.search.open(filename)
    
    # Attach target name to tpf
    tpf_30min.targetid = target_ID
    
    # Create a median image of the source over time
    median_image = np.nanmedian(tpf_30min.flux, axis=0)
    
    # Select pixels which are brighter than the 85th percentile of the median image
    aperture_mask = median_image > np.nanpercentile(median_image, 85)
    
    # Plot and save tpf
    if plot_tpf == True:
        tpf_30min.plot(aperture_mask = aperture_mask)
    #tpf_plot.savefig(save_path + '{} - Sector {} - tpf plot.png'.format(target_ID, tpf.sector))
    #plt.close(tpf_plot)
    
    # 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)]
    if plot_lc == True:
        lc_30min.scatter()
        plt.title('{} - 30min FFI base lc'.format(target_ID))
        plt.xlabel("Time - 2457000 (BTJD days)")
        plt.ylabel("Relative flux")
        plt.show()
    
    return lc_30min