def loadLC(folderName, downloadDir, errorIfNot2Min=True, dumpHeader=False, delimiter="|", fluxType="PDCSAP", normalised=True):
    """
    Loads multiple and single Tess light curves and creates a Lightkurve object to store them in. 
    Multiple LCs are detected when the folderName string contains a delimiter.
    
    :param folderName: name of the data folder
    :param downloadDir: name of the root data folder
    :param errorIfNot2Min: behaviour if cadence is not 2 min if `True` (default), raises an error, else warning
    :param dumpHeader: if `True` prints the header of the data
    :param delimiter: delimiter chosen to separate the data path, defualt: |
    :param fluxType: SAP or PDCSAP
    :param normalised: if `True` returns the median-normalised flux
    """

    lc = None
    if "|" in folderName:
        folderNames = folderName.split(delimiter)
    else:
        folderNames = [folderName]
        
    for folderName in folderNames:
        imgFname = "{}_lc.fits".format(folderName)
        imgFname = os.path.join(downloadDir, folderName, imgFname)
        head = fits.getheader(imgFname)
        sector = head["sector"]
        if dumpHeader:
            print(repr(head))
        lightCurveData = Table.read(imgFname)
        cadeances = np.nanmedian((lightCurveData["TIME"][1:] - lightCurveData["TIME"][:-1])*24*60)
        if np.abs(cadeances-2.) < 0.5:
            logger.info("Cadence is 2 min for {}".format(imgFname))
        else:
            if errorIfNot2Min:
                raise RuntimeError("Cadence is {:1.1f} min for {}".format(cadeances, imgFname))
            else:
                logger.warning("Cadence is {:1.1f} min for {}".format(cadeances, imgFname))
        
        lightCurveData["TIME"].unit = u.day
        time = lightCurveData["TIME"]
        flux = lightCurveData["{}_FLUX".format(fluxType)] 
        fluxErr = lightCurveData["{}_FLUX_ERR".format(fluxType)]

        meta = {
            "TIME": lightCurveData["TIME"],
            "MOM_CENTR1": lightCurveData["MOM_CENTR1"],
            "MOM_CENTR2": lightCurveData["MOM_CENTR2"],
            "MOM_CENTR1_ERR": lightCurveData["MOM_CENTR1_ERR"],
            "MOM_CENTR2_ERR": lightCurveData["MOM_CENTR2_ERR"],
            "POS_CORR1": lightCurveData["POS_CORR1"],
            "POS_CORR2": lightCurveData["POS_CORR2"],
            }

        lcTemp = LightCurve(time=time, flux=flux, flux_err=fluxErr, meta=meta)
        lcTemp = lcTemp.remove_nans()
        if normalised:
            lcTemp = lcTemp.normalize()
            
        if lc is None:
            lc = lcTemp
            sectors = sector
        else:
            lc = lc.append(lcTemp)
            sectors = "{},{}".format(sectors, sector)
    
    ids = np.argsort(lc.time)
    lc = lc[ids]
    
    return lc, sectors
Ejemplo n.º 2
0
def get_mlffi(tic=None,
              ra=None,
              dec=None,
              sectors='all',
              flux_type='corr',
              out_sec=False):
    """
    For use on tesseract only. Fetches FFI light curves made by Brian Powell.

    Parameters
    ----------
    tic : int or None
       TIC ID of target. If None, both ra and dec must not be None.
    ra : float or None
       RA of target. If None, tic must not be None. If not None, dec must also
       not be None.
    dec : float or None
       Dec of target. If None, tic must not be None. If not None, ra must also 
       not be None.
    sectors : str or list or array
       The desired sectors to make the light curve from. May be set to 'all' to
       use all available light curves.
    flux_type : str
       The type of correction applied to the light curve. Options are 'raw', 
       'corr', and 'pca'.
    out_sec : bool
       Flag determining whether or not the sectors that the light curve was
       generated from are output. If True, an additional output will be 
       expected.

    Returns
    -------
    lc : 'LightCurve' object
       The combined light curve.
    sectors : array
       The sectors from which the output light curve was generated.
    """
    if not tic and not ra and not dec:
        raise ValueError('Please provide valid input for either tic or ra/dec')

    if sectors == 'all':
        if not ra and not dec:
            info = tessobs_info(tic=tic)
        else:
            info = tessobs_info(ra=ra, dec=dec)

        sectors = list(set(info['sector']))

    if not isinstance(sectors, list):
        raise ValueError('Sectors must be a list!')

    if not tic:
        tic = coord_to_tic(ra, dec)

    camera_arr = []
    chip_arr = []
    Tmag_arr = []

    sects = sectors

    if not os.path.isdir('/data/tessraid/bppowel1/'):
        raise ValueError('Not on tesseract')

    for i in range(len(sects)):
        path = '/data/tessraid/bppowel1/tesslcs_sector_' + str(
            sects[i]) + '_104'
        lc_files = []

        for (dirpath, dirnames, filenames) in os.walk(path):
            for name in filenames:
                lc_files.append(os.path.join(dirpath, name))

        lc_files = [t for t in lc_files if 'tesslc_' in t]
        tics = [int(t.split('.')[0].split('_')[-1]) for t in lc_files]

        path = [s for s in lc_files if str(tic) in s]

        try:
            fp = open(str(path[0]), 'rb')
        except:
            print('Target not found in Sector %s' % sects[i])
            sects.remove(sects[i])  #trouble line, may cause silent error
            continue

        data = pickle.load(fp)
        fp.close()

        Tmag_arr.append(data[2])
        camera_arr.append(data[4])
        chip_arr.append(data[5])

        time = data[6]
        flux_err = data[10]

        if flux_type == 'corr':
            flux = data[8]
        elif flux_type == 'raw':
            flux = data[7]
        elif flux_type == 'pca':
            flux = data[9]

        if i == 0:
            lc = LightCurve(time, flux, flux_err=flux_err)
        else:
            sec_lc = LightCurve(time, flux, flux_err=flux_err)
            lc.append(sec_lc)

    lc = lc.normalize()

    lc.Tmag = Tmag_arr
    lc.camera = camera_arr
    lc.chip = chip_arr

    if out_sec:
        return lc, sects
    else:
        return lc