Exemple #1
0
def process_lc(lcfile, tics_inj, args):

    chunk = (args.tmax + args.overlap * (args.chunks-1)) / float(args.chunks)
    step = chunk - args.overlap

    # create figure
    sb.set(style="white", context="paper")
    plt.style.use("dark_background")
    fig, ax = plt.subplots(figsize=(12,5))
    plt.subplots_adjust(left=0.005, right=0.995, top=0.99, bottom=0.01)

    # open the text file with the injected transit data. A file of mostly 0s and a couple of smaller numbers. 
    # first get the file name  
    # will need to change for GLAM

    injected_pl = glob("/kepler/kepler2/TESS/ETE-6/injected/Planets/Planets_*{:d}.txt".format(tics_inj))
    inj_pl = np.genfromtxt(str(injected_pl[0])) 

    # open the LC file and get all the information about the star as usual
    hdul    = pf.open(lcfile)

    tic_LC     = int(hdul[0].header['TICID'])
    sec     = int(hdul[0].header['SECTOR'])
    cam     = int(hdul[0].header['CAMERA'])
    chi     = int(hdul[0].header['CCD'])
    tessmag = hdul[0].header['TESSMAG']
    teff    = hdul[0].header['TEFF']
    srad    = hdul[0].header['RADIUS']

    scc     = '%02d%1d%1d' % (sec,cam,chi)
    
    print('TIC {:9d} SCC {:4s}'.format(tic_LC, scc))   # in the command line print how many files to go
    

    # make filters for the tic IDs where the SNR is what we want it to be.
    l_pl1 = np.where(pl['col1'] == tics_inj)[0]               
    l_eb  = np.where(eb['col1'] == tics_inj)[0]

    data    = hdul[1].data
    time    = data['TIME']
    flux    = data['PDCSAP_FLUX']  # the flux LC from the real data
    qual    = data['QUALITY']

    # --------------------------------------
    # before you do anything else with the flux of the LC - i.e. before binning and chunking etc, need to inject the transit.
    flux = inj_pl * flux
    # --------------------------------------

    hdul.close()
    t0      = time[0]
    time    -= t0
    l       = np.isfinite(time) * np.isfinite(flux) * (qual == 0)
    time    = time[l]
    flux    = flux[l]
    m       = np.median(flux)
    flux    = 1e2 * ((flux / m) - 1)
    N       = len(time)

    n       = int(np.floor(N/args.binfac)*args.binfac)
    X       = np.zeros((2,n))
    X[0,:]  = time[:n]
    X[1,:]  = flux[:n]
    Xb      = rebin(X, (2,int(n/args.binfac)))
    time1    = Xb[0]
    flux1    = Xb[1]

    if not args.no_binned:
        n = int(np.floor(N/args.binfac/10)*args.binfac*10)
        X = np.zeros((2,n))
        X[0,:] = time[:n]
        X[1,:] = flux[:n]
        Xb = rebin(X, (2,int(n/args.binfac/10)))
        time2 = Xb[0]
        flux2 = Xb[1]


    # -------------------------------------------------------------------------------------------
    # loop though each chunk, for each chunk create a new row in the manifest and save one image
    # i.e. each TIC ID will have 4 manifest inputs
    # -------------------------------------------------------------------------------------------
    
    im_name = []
    xmin_pix = []
    xmax_pix = []    
    xmin_time = []
    xmax_time = []

    feedback           = [ [] for i in range(10) ]  # for now assume that no LC will have more than 10 transits - may need to change
    feedback_id        = [ [] for i in range(10) ]
    feedback_width     = [ [] for i in range(10) ]
    feedback_success   = [ [] for i in range(10) ]
    feedback_failure   = [ [] for i in range(10) ]
    feedback_tolerance = [ [] for i in range(10) ]


    for j in range(args.chunks):
        xmin = j * step
        xmax = xmin + chunk
        ls1 = (time1 >= xmin) * (time1 <= xmax)  # create a mask for the points that are not within xmin and xmax
        if not args.no_binned:
            ls2 = (time2 >= xmin) * (time2 <= xmax)
        ichunk = j + 1

        ax.cla()  # clear the figure before plotting more data onto it

        nm = 0
        transit_duration = []

        for l in l_pl1:
            P = pl['col3'][l]
            T0 = pl['col4'][l] - t0
            transit_duration = pl['col9'][l]
            while T0 < time1[ls1].min():
                T0 += P
            while T0 < time1[ls1].max():
                if not args.no_mark and args.min_snr != None:
                    plt.axvline(T0,color='red',lw=5,alpha=0.5)
                nm += 1
                T0 += P

        for l in l_eb:
            P = eb['col3'][l]
            T0 = eb['col4'][l] - t0
            while T0 < time1[ls1].min():
                T0 += P
            while T0 < time1[ls1].max():
                if not args.no_mark and args.min_snr != None:
                    plt.axvline(T0,color='yellow',lw=5,alpha=0.5)
                nm += 1
                T0 += P

        if nm > 0: # only make figures and save files if there are transits in that chunk 

            # save the file name
            im_name.append('tess%09d_scc%04s_%02d_%09d_simulated.png' % (tic_LC,scc,ichunk,tics_inj)) # append the name of the image


            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
            # PLOT the image
            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
            points, = ax.plot(time1[ls1],flux1[ls1], 'w.', markersize=4) # needed to convert into pixels
    
            if not args.no_binned:
                points, = ax.plot(time1[ls1],flux1[ls1],'co') # needed to convert into pixels
    
            plt.subplots_adjust(left=0.001, right=0.998, top=0.999, bottom=0.005)
    
            # define that length on the x axis - don't want it to display the 0 point
            ax.set_xlim(xmin, xmax)  
    
            # Get the x and y data and transform it into pixel coordinates for the manifest (not sure how useful these will be but store anyway just in case_)
            x, y = points.get_data()
            xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
            xpix, ypix = xy_pixels.T
    
            xmin_time.append(xmin)
            xmax_time.append(xmax)
    
            xmin_pix.append(min(xpix))
            xmax_pix.append(max(xpix)) 
    
            delta_flux = np.max(flux1[ls1]) - np.min(flux1[ls1]) 
    
            # set the y lim. 
            percent_change = delta_flux * 0.1  
            ax.set_ylim(np.min(flux1[ls1]) - percent_change, np.max(flux1[ls1]) + percent_change)  # do we want to change this to be per figure and not per LC? 
            
            # label the axis.
            ax.xaxis.set_label_coords(0.063, 0.06) # position of the x-axis label 
    
    
            # tick mark/axis parameters
    
            minorLocator = AutoMinorLocator()
            ax.xaxis.set_minor_locator(minorLocator)
            ax.tick_params(direction='in', which ='minor', colors='grey',length=3, labelsize=13)
    
            minorLocator = AutoMinorLocator()
            ax.yaxis.set_minor_locator(minorLocator)
            ax.tick_params(direction='in', length = 3, which ='minor', colors='grey', labelsize=13)
    
            ax.tick_params(axis="y",direction="in", pad= -20)
            ax.tick_params(axis="x",direction="in", pad= -17)   
            ax.tick_params(axis='both', length = 7, left='on', top='on', right='on', bottom='on')
    
            ax.set_xlabel("DAYS",fontsize = 10)
            #ax.artists.append(circle1)
            #ax.artists.append(circle2)
    
            #ax.set_axis_bgcolor("#03012d")
            ax.set_facecolor("#03012d")
    
            # save the image - make sure the name of the saved image is the same as the name in the manifest.
    
            plt.savefig('%s/%s' % (args.outdir,im_name[-1]), format='png')
    

            # still for this one chunk, get the feedback information and add to a list
            # the list will need to have 
            # get the locations of the transits for the feedback functionality
        
            injtrans_pl, injtrans_eb, tic = transit_loc.transit_loc_single(tics_inj, xmin, xmax)
            transit_duration = ptc.deltat_to_pixel(transit_duration, xmin, xmax)
            
            
            # for each feedback we need a list of one entry per chunk
            for j,trans_loc in enumerate(injtrans_pl):
                
                if trans_loc == None: # if no transits exist in that quarter

                    print ("something went wrong") # something should also be present in the LC

                else:

                    trans_loc = [i - transit_duration/48 for i in trans_loc]  # offset the centre by half of the wdith
                    transit_list = transit_loc.pad(trans_loc, 10, '')  # list of 10 entries
                    print(transit_list)
                    for l,t in enumerate(transit_list):
                        feedback[l].append(t)
    
                        if t != '':
                            feedback_id[l].append("1111{}".format(l)) 
                            if (transit_duration/24) > 10:
                                feedback_width[l].append(transit_duration/24)    
                            else:
                                feedback_width[l].append(10)    
                            feedback_success[l].append("Awesome, you correctly marked a simulated transit!")  
                            feedback_failure[l].append("Not quite, but please don't be discouraged, transits can be very difficult to spot. You can also check out the field guide for more guidance.")  
                            if (transit_duration/24) > 15:
                                feedback_tolerance[l].append(transit_duration/24*1.5)
                            else:
                                feedback_tolerance[l].append(15)
                        else:
                            feedback_id[l].append(np.nan)
                            feedback_width[l].append(np.nan)    
                            feedback_success[l].append(np.nan)  
                            feedback_failure[l].append(np.nan)  
                            feedback_tolerance[l].append(np.nan)


    mnd = {} # define the dictonary 
    mnd['Magnitude'] = '{:.2f}'.format(float(tessmag))
    try:
        mnd['Temperature'] = '{:d}'.format(int(teff))
    except:
        mnd['Temperature'] = None
    try:
        mnd['Radius'] = '{:.3f}'.format(float(srad))
    except:
        mnd['Radius'] = None
    mnd['TICID'] = tics_inj
    mnd['TICLC'] = tic_LC
    mnd['Sector'] = sec
    mnd['Web_link'] = url
    mnd['sim'] = False
    mnd['im_name'] = im_name
    mnd['xmin_time'] = xmin_time

    mnd['xmax_time'] = xmax_time
    mnd['xmin_pix'] = xmin_pix
    mnd['xmax_pix'] = xmax_pix

    # define the target
    if tics_inj in pl['col1']:
        mnd['Target'] = "planet"
    elif tics_inj in eb['col1']:
        mnd['Target'] = "EB"
    else:
        mnd['Target'] = False
    
    # for the feedback, for each 'element' we have a list of 10 lists, each of which has 4 elements
    # we need to add the feedback to each feedback 'number' to the dictionary 
    for i in range(0,10):
        mnd['feedback{}'.format([i])] =  feedback[i]
        mnd['feedback_id{}'.format([i])] = feedback_id[i]
        mnd['feedback_width{}'.format([i])] = feedback_width[i]
        mnd['feedback_success{}'.format([i])] = feedback_success[i]
        mnd['feedback_failure{}'.format([i])] = feedback_failure[i]
        mnd['feedback_tolerance{}'.format([i])] = feedback_tolerance[i]

    return mnd        
Exemple #2
0
                TICLC.append(tic_LC)
                Sector.append(sec)
                Web_link.append(url)
                sim.append(True)

                if tics_inj[i] in pl['col1']:
                    Target.append("planet")
                elif tics_inj[i] in eb['col1']:
                    Target.append("EB")
                else:
                    Target.append("star")

                injtrans_pl, injtrans_eb, tic = transit_loc.transit_loc_single(
                    tics_inj[i], args.min_snr, xmin, xmax)

                transit_duration = ptc.deltat_to_pixel(transit_duration, xmin,
                                                       xmax)

                ## find oversll longest list
                #longest_list = 0
                #
                #for i in transit_locs_DF00['injtrans_pl']:
                #    if i != None:
                #        if len(i) > longest_list:
                #            longest_list = len(i)

                # select only the values that are in that chunk - for all chunks (have to loop through them again unofortunately)

                #transit_locs_DF0 = (xmin <= transit_locs_DF00['injtrans_pl']) & (transit_locs_DF00['injtrans_pl'] <= xmax)
                #transit_locs_DF = (xmin <= transit_locs_DF0['injtrans_eb']) & (transit_locs_DF0['injtrans_eb'] <= xmax)

                for j, trans_loc in enumerate(injtrans_pl):