예제 #1
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')
예제 #2
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])
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
예제 #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
예제 #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()
예제 #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])
예제 #7
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))
예제 #8
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
예제 #9
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
예제 #10
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)
예제 #11
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']
            })
예제 #12
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))
예제 #13
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
예제 #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
예제 #15
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
예제 #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)
예제 #17
0
def diff_image_lc_download(target_ID,
                           sector,
                           plot_lc=True,
                           from_file=True,
                           save_path=''):
    """
    Downloads and returns 30min cadence lightcurves based on Oelkers & Stassun
    difference imaging analysis method of lightcurve extraction
    """
    if sector < 3:
        DIAdir = '/tess/photometry/DIA_FFI/S{}/clean/'.format(sector)
    else:
        DIAdir = '/tess/photometry/DIA_FFI/S{}/lc/clean/'.format(sector)

    if from_file == True:
        # reads input table for targets
        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]
        #camera = table_data['S{}'.format(sector)][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]

    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 = DIAdir + '{}_sector0{}_{}_{}.lc'.format(tic, sector, camera,
                                                       ccd)
    #    filename = '{}_sector0{}_{}_{}.lc'.format(tic, sector, camera, ccd)
    #    filename = '410214986_sector01_3_2.lc'

    print('Trying file {}'.format(filename))
    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)
            diffImage_fig.show()

        lc = lightkurve.LightCurve(time=DIA_lc[0],
                                   flux=norm_flux,
                                   flux_err=DIA_lc[2],
                                   targetid=target_ID)
        print('Got the light-curve out')

        return lc, filename
    except:
        print(
            'The file {} does not exist - difference imaging data not available for {}'
            .format(filename, target_ID))
예제 #18
0
ralist = pd.read_csv('agn_catalogue.csv',
                     sep=',',
                     usecols=['Right Ascension'],
                     squeeze=True)
declist = pd.read_csv('agn_catalogue.csv',
                      sep=',',
                      usecols=['Declination'],
                      squeeze=True)

sector_column = np.array([['Start']])
for row in range(46000, 46001):
    print(row)
    #Return a list of sectors the object was observed
    coord = SkyCoord(ralist[row], declist[row], unit='deg')
    sector_table = Tesscut.get_sectors(coordinates=coord)
    sector_col = sector_table['sector']
    sector_list = []
    for numbers in sector_col:
        sector_list.append(numbers)
    if sector_list == None:
        sector_list = 0
    else:
        sector_string = np.array([[str(sector_list)]])

    sector_column = np.concatenate((sector_column, sector_string), axis=0)

np.savetxt('agn_sectors4.csv', sector_column, fmt='%s', delimiter=',')

#18286-18287
#40600-40601
예제 #19
0
def gather_lc(coords=None,
              tic=None,
              name=None,
              cadence='shortest',
              ffi_only=False,
              method='2min',
              sectors='all',
              eleanor_flag=False,
              return_method=False,
              return_sectors=False,
              obsinfo=None,
              verbose=False,
              **kwargs):
    #!!Add ability to support common names as inputs in absence of TIC!!
    #!!Add ability for sector cuts in FFI light curves!!
    #!!Add obsinfo keyword to pass obsinfo if it exists!!
    #!!Add keyword to track 'author' and 'cadence' keywords for each sector?!!
    """
    Function to gather the light curve of a given TIC using the specified 
    method. Currently, 2 minute SPOC pipeline light curves, machine learning FFI
    light curves, and eleanor light curves are supported.

    Parameters
    ----------
    coords : tuple or array
       Coords of input
    name : string
       common name
    ffi_only : bool
       whether to default to 2min or have everything be ffis
    tic : int
       TESS Input Catalog ID for desired target. At this time, common names are
       not accepted input, only TIC IDs.
    method : str
       The method with which the light curve will be acquired. Options are 
       '2min', 'ffi_ml', and 'eleanor'.
    sectors : str or list or numpy array
       List of sectors to be included in the fetching of the light curve. If
       'all' or None is passed, all available light curves will be fetched. 
       Thresholds can be passed according to the valid syntax of the method
       specified.
    return_method : bool
       A flag to indicate whether the method used to gather the light curve 
       will be returned. Useful if the chosen method is not known or expected to
       return a valid light curve. An additional output will be expected.
    return_sectors : bool
       A flag to indicate the sectors that the light curve was recovered from.
       An additional output will be expected. Currently in progress for most
       methods.
    obsinfo : dict
       A dictionary of observational information that can be passed to make some 
       processes run faster if inlc is specified. Assumes output format of
       transit_tools.tessobs_info command.
    **kwargs
       Additional arguments to be passed to the selected method fetching 
       function.

    Returns
    -------
    lc : 'LightCurve'
       Light curve containing light curves from all sectors contained within the
       query of sectors.
    method : str, optional
       The method with which the output light curve was gathered.
    sectors : numpy array, optional
       The sectors that the light curve was gathered from.
    """
    if coords is None and tic is None and name is None:
        raise ValueError("You must specify either (RA, Dec), a TIC ID, or " +
                         "the name of the target!")

    #Fetching the TESS sectors that the target was observed in
    if coords is not None:
        coordinates = SkyCoord(coords[0], coords[1], unit="deg")
        sector_table = Tesscut.get_sectors(coordinates=coordinates)
    else:
        if tic is not None:
            name = "TIC " + str(tic)

        sector_table = Tesscut.get_sectors(objectname=str(name))

    if len(sector_table) == 0:
        raise ValueError('No valid sectors found for specified target!')

    #Comprehension of sector inputs
    if sectors != 'all' and sectors != None:
        if not isinstance(sectors, list):
            sectors = list(sectors)

        secs = list(set(sector_table['sector'].value) & set(sectors))
    else:
        secs = sector_table['sector'].value

    sec_clipboard = secs

    #Trying to fetch light curves from MAST
    if not eleanor_flag:  #and not custom_only?
        try:
            lc, mast_sec = get_mastlc(tic=tic,
                                      name=name,
                                      coords=coords,
                                      sectors=sec_clipboard,
                                      out_sec=True,
                                      cadence=cadence,
                                      **kwargs)
            sec_clipboard = [x for x in sec_clipboard if x not in mast_sec]
        except:
            print(
                'No light curves found on the MAST. Trying another method...')

    #Trying to generate light curves from eleanor

    ####
    #ELEANOR FUNCITON NEEDS TO BE DOUBLE-CHECKED!
    ####
    if eleanor_flag == True and len(sec_clipboard) > 0:
        try:
            lc, el_sec = get_eleanor(tic=tic,
                                     sectors=secs,
                                     out_sec=True,
                                     **kwargs)
            sec_clipboard = [x for x in sec_clipboard if x not in el_sec]
        except:
            print('eleanor could not find light curves for these sectors.' +
                  ' Trying another method...')

    #Trying to generate light curves via FFI cutouts
    if len(sec_clipboard) > 0:
        try:
            lc, get_ffilc = ffi_cutout()
            sec_clipboard = [x for x in sec_clipboard if x not in cut_sec]
        except:
            print('Issue with fetching FFI cutouts!')

    #Printing the sectors (if any) that did not have light curves
    if len(sec_clipboard) > 0:
        print('Sectors ' + str(sec_clipboard) + ' did not have light curves!!')

    #Loop through sectors to fetch light curves
    #if ffi_only is not None:
    #    try:
    #        lc = get_mastlc()
    #if return_sectors:
    #    lc, sectors = get_2minlc(tic, secs, out_sec=return_sectors,
    #                             **kwargs)
    #else:
    #    lc = get_2minlc(tic, secs, out_sec=return_sectors, **kwargs)
    #    except:
    #        print('No TESS 2 minute light curves found! Trying FFIs...')
    #        method = 'ffi_ml'

    #if method == 'ffi_ml':
    #    try:
    #        if return_sectors:
    #            lc, sectors = get_mlffi(tic=tic, sectors=secs,
    #                                    out_sec=return_sectors, **kwargs)
    #        else:
    #            lc = get_mlffi(tic=tic, sectors=secs, out_sec=return_sectors,
    #                           **kwargs)
    #    except:
    #        print('No ML light curves found locally. Trying with eleanor...')
    #        method = 'eleanor'

    if method == 'eleanor':
        try:
            if return_sectors:
                lc, sectors = get_eleanor(tic=tic,
                                          sectors=secs,
                                          out_sec=return_sectors,
                                          **kwargs)
            else:
                lc = get_eleanor(tic=tic,
                                 sectors=secs,
                                 out_sec=return_sectors,
                                 **kwargs)
        except:
            raise ValueError(
                'No light curves found for the specified sectors!')

    if return_method and not return_sectors:
        return lc, method
    elif not return_method and return_sectors:
        return lc, secs
    elif return_method and return_sectors:
        return lc, method, secs
    elif not return_method and not return_sectors:
        return lc
예제 #20
0
def my_animation(ticid, istart, istop, flare=None):
    Writer = animation.writers['imagemagick']
    Writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)

    starName = "TIC " + str(ticid)
    radSearch = 4 / 60  #radius in degrees

    #Querying RA and DEC from Catalogs given a TIC ID
    catalogData = Catalogs.query_object(starName,
                                        radius=radSearch,
                                        catalog="TIC")
    ra = catalogData[0]['ra']
    dec = catalogData[0]['dec']

    #Gets Skycoord given RA and DEC then calls to TESScut
    obj_coord = SkyCoord(ra, dec, unit="deg")
    print(obj_coord)
    Tesscut.get_sectors(obj_coord)
    cutout_hdu = Tesscut.get_cutouts(obj_coord, size=20)[0]
    cutout_hdu.info()
    cutout_table = cutout_hdu[1].data
    cutout_table.columns

    def find_index(btjd):
        return (np.abs(cutout_table['TIME'] - btjd)).argmin()

    start = find_index(istart)
    end = find_index(istop)

    print(f"Frames {istart}-{istop} ({istop-istart} frames)")

    def make_animation(data_array,
                       start_frame=start,
                       end_frame=end,
                       vmin=None,
                       vmax=None,
                       delay=50):
        """
	    Function that takes an array where each frame is a 2D image array and make an animated plot
	    that runs through the frames.
	    
	    Note: This can take a long time to run if you have a lot of frames.    
	    Parameters
	    ----------
	    data_array : array
	        Array of 2D images.
	    start_frame : int
	        The index of the initial frame to show. Default is the first frame.
	    end_frame : int
	        The index of the final frame to show. Default is the last frame.
	    vmin : float
	        Data range min for the colormap. Defaults to data minimum value.
	    vmax : float
	        Data range max for the colormap. Defaults to data maximum value.
	    delay: 
	        Delay before the next frame is shown in milliseconds.

	    Returns
	    -------
	    response : `animation.FuncAnimation`
	    """

        if not vmin:
            vmin = np.min(data_array)
        if not vmax:
            vmax = np.max(data_array)

        if not end_frame:
            end_frame = len(data_array) - 1  # set to the end of the array

        num_frames = end_frame - start_frame + 1  # include the end frame

        def animate(i, fig, ax, binarytab, start=start):
            """Function used to update the animation"""
            ax.set_title("Epoch #" + str(i + start))
            fig.suptitle(f'TIC {ticid}')
            im = ax.imshow(binarytab[i + start],
                           cmap=plt.cm.YlGnBu_r,
                           vmin=vmin,
                           vmax=vmax)
            return im

        # Create initial plot.
        fig, ax = plt.subplots(figsize=(10, 10))
        ax.imshow(data_array[start_frame],
                  cmap=plt.cm.YlGnBu_r,
                  vmin=vmin,
                  vmax=vmax)

        ani = animation.FuncAnimation(fig,
                                      animate,
                                      fargs=(fig, ax, data_array, start_frame),
                                      frames=num_frames,
                                      interval=delay,
                                      repeat_delay=1000)

        ani.save('/Users/jshabazz/Work/TESScut_anims/' + str(ticid) +
                 '_flareevent' + str(flare) + '.gif',
                 writer=Writer)
        print('File created')
        plt.close()

        return ani

    make_animation(cutout_table['FLUX'], vmax=500)