Beispiel #1
0
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
Beispiel #2
0
def checkStar(star, savefile=True):
    """
    Returns the a file with TESS observations for a given star
    
    Parameters
    ----------
    star: str
        Name of the star
    savefile: bool
        True if we want a txt file with the schedule
        
    Returns
    -------
    data: array
        Observation schedule of the given stars
    """
    #our coordinates
    ra, dec = _checkStarCoordinates(star)
    #giving ids to the stars
    star_id = [1]
    #Lets see if TESS will look at it
    outID, outEclipLong, outEclipLat, \
    outSec, outCam, outCcd, \
    outColPix, outRowPix, scinfo = tess_stars2px_function_entry(star_id,ra,dec)
    observed_sectors = []
    for i, j in enumerate(star_id):
        sector = []
        for ii, jj in enumerate(outID):
            if j == jj:
                sector.append(outSec[ii])
        observed_sectors.append(sector)
    #because I prefer the name of the start instead of RA and DEC
    allStarList = [[i] for i in [star]]
    for i, j in enumerate([star]):
        if len(observed_sectors[i]) == 0:
            allStarList[i].append(" Star not observed")
        else:
            for ii, jj in enumerate(observed_sectors[0]):
                result = [
                    " Observed in sector {0}: ".format(jj),
                    sectors[int(observed_sectors[0][ii]) - 1][1], " to ",
                    sectors[int(observed_sectors[0][ii]) - 1][2]
                ]
                result = "".join(result)
                allStarList[i].append(result)
    #now a final list with start and end observations
    data = np.squeeze(np.array(allStarList))
    if savefile:
        np.savetxt('star_observations.txt',
                   data,
                   delimiter='\t',
                   newline='\r\n',
                   comments='',
                   fmt='%s')
    return data
Beispiel #3
0
def checkList(star_file, header=0):
    """
        Returns the a file with TESS observations for a given list of stars
        Parameters:
            star_file = file with the list of stars
            header = number of lines used as header
    """
    #our stars
    stars = np.loadtxt(star_file, skiprows=0, unpack=True, dtype='str')
    #our coordinates
    ra, dec = _checkListCoordinates(star_file, header=header)
    #giving ids to the stars
    star_id = np.linspace(1, len(stars), len(stars))
    
    #Lets see if TESS will look at it
    outID, outEclipLong, outEclipLat, \
    outSec, outCam, outCcd, \
    outColPix, outRowPix, scinfo = tess_stars2px_function_entry(star_id,ra,dec)
    
    observed_sectors = []
    for i, j in enumerate(star_id):
        sector = []
        for ii, jj in enumerate(outID):
            if j==jj:
                sector.append(outSec[ii])
        observed_sectors.append(sector)
    
    #date of observation for each sector
    sectors = np.loadtxt("utils/sectors.txt", skiprows=0, unpack=True, dtype='str')
    sectors = sectors.T
    
    #because I prefer the name of the start instead of RA and DEC
    allStarList = [[i] for i in stars]
    for i, j in enumerate(stars):
        if len(observed_sectors[i]) == 0:
            allStarList[i].append("Star not observed")
        else:
            result = ["Observed from ", sectors[int(observed_sectors[i][0])-1,1], 
                      " to ", sectors[int(observed_sectors[i][-1])-1, 2]]
            result = "".join(result)
            allStarList[i].append(result)
            
    #now a final list with start and end observations
    data = np.array(allStarList)
    np.savetxt('star_observations.txt', data, 
               delimiter='\t', comments='', fmt='%s')
    return data
for i, j in enumerate(galah_dr3[1].data):
	mass_id.append(j[0])
	source_ids.append(j[1])
	target_ra[i] = j[445]
	target_dec[i] = j[447]

beg_ind = int(sys.argv[1])
end_ind = int(sys.argv[2])

best_fit_period = np.zeros(len(mass_id[beg_ind:end_ind]))
best_fit_uncert = np.zeros(len(mass_id[beg_ind:end_ind]))
#data_source = np.zeros(len(mass_id[beg_ind:end_ind]))
for j,i in enumerate(mass_id[beg_ind:end_ind]):
	print(i)
	coords = SkyCoord(ra=float(target_ra[j]), dec=float(target_dec[j]), unit=(u.deg, u.deg))
	outID,outEclipLong,outEclipLat,outSec,outCam,outCcd,outColPix, outRowPix, scinfo = tess_stars2px_function_entry(j, float(target_ra[j]), float(target_dec[j]))
	sector_source = []			   #array of where the data came from length of the amount of sectors
	#lightcurves = lk.LightCurveCollection()
	for num, sector in enumerate(outSec):
		if sector <= 31:
	###first try to find 2-min data for this sector
			try:
				lc = lk.search_lightcurvefile(coords, mission='TESS', sector=sector).download().PDCSAP_FLUX.remove_nans()
				if sector == outSec[0]:
					lightcurves = lk.LightCurveCollection(lc)
				else:
					lightcurves.append(lc)
				sector_source.append('2-min')
				print('Sector {} downloaded with LightKurve'.format(sector))
			except KeyboardInterrupt:
				raise
Beispiel #5
0
def make_stellar_scene(pixelData, ticData, ticName, dMagThreshold=4):
    catalogData = {}

    # compute mjd for the Gaia epoch J2015.5 = 2015-07-02T21:00:00
    t = Time("2015-07-02T21:00:00", format='isot', scale='utc')
    bjdJ2015p5 = t.jd - 2457000
    bjd = np.mean(pixelData["time"])
    mas2deg = 1 / (3600 * 1000)
    dt = (bjd - bjdJ2015p5) / 365
    #    print("dt = " + str(dt) + " years")

    searchRadius = (np.linalg.norm([
        pixelData["flux"].shape[1], pixelData["flux"].shape[2]
    ])) * 21 / 3600 / 2  # assumes 21 arcsec pixels
    ticCatalog = get_tic(ticData["raDegrees"], ticData["decDegrees"],
                         searchRadius)
    #    print(list(ticCatalog))
    dRa = mas2deg * dt * ticCatalog["pmRA"] / np.cos(
        ticCatalog["Dec_orig"] * np.pi / 180)
    dRa[np.isnan(dRa)] = 0
    dDec = mas2deg * dt * ticCatalog["pmDEC"]
    dDec[np.isnan(dDec)] = 0
    #    print("mean dRa in arcsec = " + str(3600*np.mean(dRa)))
    #    print("mean dDec in arcsec = " + str(3600*np.mean(dDec)))
    ticCatalog["correctedRa"] = ticCatalog["RA_orig"] + dRa
    ticCatalog["correctedDec"] = ticCatalog["Dec_orig"] + dDec

    targetIndex = np.where(
        np.array(ticCatalog["ID"]).astype(int) == ticData["id"])[0][0]

    outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \
    refColPix, refRowPix, scinfo = trdp.tess_stars2px_function_entry(
        ticData["id"], pixelData["referenceRa"], pixelData["referenceDec"], aberrate=True, trySector=pixelData["sector"])
    onPix = (outSec == pixelData["sector"]) & (
        outCam == pixelData["camera"]) & (outCcd == pixelData["ccd"])
    outID = outID[onPix]
    catalogData["refColPix"] = refColPix[onPix]
    catalogData["refRowPix"] = refRowPix[onPix]
    #    print([catalogData["refColPix"], catalogData["refRowPix"]])

    outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \
    targetColPix, targetRowPix, scinfo = trdp.tess_stars2px_function_entry(
        ticData["id"], ticCatalog["correctedRa"][targetIndex], ticCatalog["correctedDec"][targetIndex], aberrate=True, trySector=pixelData["sector"], scInfo=scinfo)
    onPix = (outSec == pixelData["sector"]) & (
        outCam == pixelData["camera"]) & (outCcd == pixelData["ccd"])
    outID = outID[onPix]
    catalogData["targetColPix"] = targetColPix[onPix]
    catalogData["targetRowPix"] = targetRowPix[onPix]
    #    print([catalogData["targetColPix"], catalogData["targetRowPix"]])

    ticID, outEclipLong, outEclipLat, outSec, outCam, outCcd, ticColPix, ticRowPix, scinfo \
        = trdp.tess_stars2px_function_entry(
            ticCatalog["ID"], ticCatalog["correctedRa"], ticCatalog["correctedDec"],
            aberrate=True, trySector=pixelData["sector"], scInfo=scinfo)
    theseStars = (outSec == pixelData["sector"]) & (
        outCam == pixelData["camera"]) & (outCcd == pixelData["ccd"])

    separation = 3600 * np.sqrt(
        np.cos(ticCatalog["correctedDec"][targetIndex] * np.pi / 180)**2 *
        (ticCatalog["correctedRa"] -
         ticCatalog["correctedRa"][targetIndex])**2 +
        (ticCatalog["correctedDec"] -
         ticCatalog["correctedDec"][targetIndex])**2)

    catalogData["ticID"] = ticID[theseStars]
    catalogData["ticColPix"] = ticColPix[theseStars]
    catalogData["ticRowPix"] = ticRowPix[theseStars]
    catalogData["separation"] = separation[np.isin(ticCatalog["ID"],
                                                   catalogData["ticID"])]
    catalogData["ticMag"] = ticCatalog["Tmag"][np.isin(ticCatalog["ID"],
                                                       catalogData["ticID"])]
    catalogData["ticFlux"] = mag2flux(catalogData["ticMag"])
    catalogData["ticFluxNorm"] = np.sqrt(0.999 * catalogData["ticFlux"] /
                                         np.max(catalogData["ticFlux"]) +
                                         0.001)
    #    print([len(catalogData["ticID"]), len(catalogData["ticMag"])])

    #    extent = (pixelData["cornerCol"], pixelData["cornerCol"] + 20, pixelData["cornerRow"], pixelData["cornerRow"] + 20)
    #    extent = (pixelData["cornerRow"]-0.5, pixelData["cornerRow"]-0.5 + 20, pixelData["cornerCol"]-0.5, pixelData["cornerCol"]-0.5 + 20)
    catalogData["extent"] = (pixelData["cornerCol"], pixelData["cornerCol"] +
                             pixelData["flux"].shape[1],
                             pixelData["cornerRow"], pixelData["cornerRow"] +
                             pixelData["flux"].shape[2])
    #    print(pixelData["flux"].shape)
    #    print(catalogData["extent"])
    catalogData["dRow"] = catalogData["refRowPix"] - (
        pixelData["referenceRow"] + catalogData["extent"][2] - 0.5)
    catalogData["dCol"] = catalogData["refColPix"] - (
        pixelData["referenceCol"] + catalogData["extent"][0] - 0.5)

    closeupOffset = 8
    closeupSize = 5
    catalogData["extentClose"] = (pixelData["cornerCol"] + 8,
                                  pixelData["cornerCol"] + 8 + closeupSize,
                                  pixelData["cornerRow"] + 8,
                                  pixelData["cornerRow"] + 8 + closeupSize)

    return catalogData
Beispiel #6
0
def tess_pixels(tic_id, tess_ra, tess_dec):
    '''Authors:
		Patrick Tamburo, Boston University, July 2020
	Purpose:
        Given a target's position when it was observed with TESS, returns the column and row of the pixel that the target fell on. 
	Inputs:
        tic_id (str): The target's TIC ID (e.g., 'TIC 326109505')
        tess_ra (float): The target's DECIMAL RA at the TESS epoch when this target was observed
        tess_dec (float): The target's DECIMAL Dec at the TESS epoch when this target was observed
    Outputs:
        out_col_pix, out_row_pix (float): The propagated position of the target at target_epoch.
        out_sec, out_cam, out_ccd: sector, camera, and ccd, respectively
	TODO:
    '''
    tid = int(tic_id.split(' ')[-1])
    out_id, out_eclip_long, out_eclip_lat, out_sec, out_cam, out_ccd, out_col_pix, out_row_pix, scinfo = tess_stars2px.tess_stars2px_function_entry(
        tid, tess_ra, tess_dec)
    return out_col_pix, out_row_pix, out_sec, out_cam, out_ccd
                    useURL = 'https://mast.stsci.edu/api/v0/download/file?uri=' + dataURI
                    dvLines.append('<a href="{0}" target="_blank">{0}</a><br>'.format(useURL))
            dvStr = ' '.join(dvLines)        
    
        else:
            dvStr = 'No DV Results for this target at MAST<br>'
    else:
        print('Timeout on the DV report search at MAST')
        dvStr = '***DV report search at MAST timed out.  Try Later***<br>'
    
    # Do an optional report that shows which sectors target is TESS observable
    #  One needs tess-point install for this to work
    tesspStr = '<br>'
    if foo_have_tp:
            outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \
            outColPix, outRowPix, scinfo = tess_stars2px_function_entry(
                    useTIC, gaiaPredRa, gaiaPredDec)
            tpLines = ['<br>TESS Observe - Sec Cam Ccd  Col  Row<br>']
            for i, curTIC in enumerate(outID):
                tpLines.append('{0:d} {1:d} {2:d} {3:d} {4:.2f} {5:.2f}<br>'.format(outID[i], \
                               outSec[i],outCam[i], outCcd[i], outColPix[i], outRowPix[i]))
            tesspStr = ' '.join(tpLines)


    # Wkhtmltopdf is used to convert html to pdf
    #  On certain platforms URLs don't work unless they are one per line
    #  with args.noweb use a html line break
    URLBreak = '|'
    if args.noweb:
        URLBreak = '<br>'
    # We had all the HTML strings, put them in a dictionary that will
    #  will be used for replacement in HTML template below        
Beispiel #8
0
                "format": "json",
                "removenullcolumns": True
            }

            headers, outString = utils.mastQuery(request)

            outObject = json.loads(outString)

            if len(outObject["data"]) == 0:
                sys.exit('{} is not a valid TIC ID number. Please try again.'.
                         format(tic))

            ra = np.array([x["ra"] for x in outObject["data"]])[0]
            dec = np.array([x["dec"] for x in outObject["data"]])[0]

            _, _, _, sectors_all, _, _, _, _, _ = tess_stars2px_function_entry(
                tic, ra, dec)

            # --------

        # --------------------------------
        # If either the TIC or the sectors or both have not already been identified, run Tkinter (interactive tools)

        else:

            # make a GUI interface with TKinter
            ROOT = tk.Tk()
            ROOT.withdraw()

            # if this hasn't already been identified as an FFI through the command line, give the option to chose this when entering the TIC ID
            if args.FFI == False:
                # -----------
Beispiel #9
0
# -*- coding: utf-8 -*-
"""
Created on Sun Jan  6 09:14:04 2019

@author: cjburke
"""

import numpy as np
from tess_stars2px import tess_stars2px_function_entry

if __name__ == '__main__':
    # This is an example of using tess_stars2px functionality
    # from a program rather than the typical command line interface
    # read in multiple targets from a prexisting file and output
    #  how many sectors each target is observable
    #  Also filter for the Year 4 sectors

    dataBlock = np.genfromtxt('a_list_of_tics_ras_decs.txt',
                              dtype=['i8', 'f8', 'f8'])
    ticids = np.array(dataBlock['f0'])
    ras = np.array(dataBlock['f1'])
    decs = np.array(dataBlock['f2'])

    outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \
            outColPix, outRowPix, scinfo = tess_stars2px_function_entry(
                    ticids, ras, decs)

    for curtic in ticids:
        idx = np.where((outID == curtic) & (outSec >= 40) & (outSec <= 55))[0]
        print('{0:d} {1:d}'.format(curtic, len(idx)))
    # the function example only takes ra and dec [deg]
    #  Your program should provide these
    #  The other ways of getting coordinates 'TIC MAST query' 'By name' 'file list'
    #  are not supported in the wrapper function.  Just ra and decs
    # Location for pi mensae
    ra = 84.291188
    dec = -80.469119
    ticid = 261136679  # code doesn't actually use ticid, so this can be
    # any integer you like.  It is included just for convenience of
    # keeping track of target in the output because
    # for a given target it is not known ahead of time how many
    # output entries a target will have.  Thus the user
    # should make sure to match the output ticid (outID)
    #  with the ticid they are using
    outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \
            outColPix, outRowPix, scinfo = tess_stars2px_function_entry(
                    ticid, ra, dec)
    for i in range(len(outID)):
        print('{0:d} {1:d} {2:d} {3:d} {4:f} {5:f}'.format(outID[i], outSec[i], \
          outCam[i], outCcd[i], outColPix[i], outRowPix[i]))

    # For efficiency purposes if you save scinfo between calls
    #  you will save time in setting up the the telescope fields
    outID, outEclipLong, outEclipLat, outSec, outCam, outCcd, \
            outColPix, outRowPix, scinfo = tess_stars2px_function_entry(
                    ticid, ra, dec, scInfo=scinfo)
    print('Faster to re-use scinfo in repeated calls')
    for i in range(len(outID)):
        print('{0:d} {1:d} {2:d} {3:d} {4:f} {5:f}'.format(outID[i], outSec[i], \
          outCam[i], outCcd[i], outColPix[i], outRowPix[i]))

    print('Also accepts multiple targets')
Beispiel #11
0
def locate(
    target: Union[SkyCoord, str],
    time: Union[Time, str, List[str]] = None,
    sector: Union[int, List[int]] = None,
    aberrate: bool = True,
) -> TessCoordList:
    """Locate a target in the TESS FFI data set."""
    # Allow the target coordinate to be instantiated from a string
    if isinstance(target, str):
        target = SkyCoord.from_name(target)

    # Allow time to be instantiated from a string
    if time and not isinstance(time, Time):
        time = Time(time)

    # If `time` is given, convert it to a list of sectors
    if time:
        time = np.atleast_1d(time)
        if not target.isscalar and len(target) != len(time):
            raise ValueError("`target` and `time` must have matching lengths")
        sectors_to_search = time_to_sector(time)
    else:
        # Else, ensure `sector` is iterable
        if sector:
            sectors_to_search = np.atleast_1d(sector)
        else:
            sectors_to_search = [None]
        if not target.isscalar and len(target) != len(sectors_to_search):
            raise ValueError(
                "`target` and `sector` must have matching lengths")

    ra = np.atleast_1d(target.ra.to("deg").value)
    dec = np.atleast_1d(target.dec.to("deg").value)
    result = []
    for idx in range(len(ra)):
        (
            _,
            _,
            _,
            out_sector,
            out_camera,
            out_ccd,
            out_col,
            out_row,
            scinfo,
        ) = tess_stars2px_function_entry(0,
                                         ra[idx],
                                         dec[idx],
                                         trySector=sectors_to_search[idx],
                                         aberrate=aberrate)

        for idx_out in range(len(out_sector)):
            if out_sector[idx_out] < 0:
                # tess-point returns -1 if no sector is found
                continue
            try:
                crd = TessCoord(
                    sector=out_sector[idx_out],
                    camera=out_camera[idx_out],
                    ccd=out_ccd[idx_out],
                    column=out_col[idx_out],
                    row=out_row[idx_out],
                )
                if time:
                    crd.time = time[idx]
                result.append(crd)
            except ValueError:
                pass  # illegal column or row, i.e. just off edge

    return TessCoordList(result)