Beispiel #1
0
def make_circ_lc(image_list, maskmap, times, start_center, ap_radii,
                 output_filename, fw_box=9, ap_type="circular", 
                 ellipse_kwargs=None):
    """
    Make a lightcurve by computing aperture photometry for 
    all images in a target pixel file.

    inputs:
    -------

    image_list: array-like
        fluxes at every epoch from TPF

    maskmap: array-like

    times: array-like

    start_center: array-like
        initial pixel coordinates for star

    ap_radii: array-like
        aperture radii (for circular apertures), or
        multiplicative factors (for elliptical apertures)

    output_filename: string, ending in .csv

    fw_box: odd integer, default=9
        box size for flux-weighted centroid

    ap_type: string
        "circular" (default) or "elliptical"

    ellipse_kwargs: dict, required for ap_type=="elliptical"
        a, b, and theta for the elliptical aperture
        (might be better to fit for theta every time?)
    """
    
    # Open the output file and write the header line
    f = open(output_filename,"w")
    f.write("i,t,x,y")
    for r in ap_radii:
        f.write(",flux_{0:.1f},bkgd_{0:.1f}".format(r))
        
    # Do aperture photometry at every step, and save the results
    for i, time in enumerate(times):
        f.write("\n{0},{1:.6f}".format(i,time))
        
        # Find the actual centroid in this image, using start_center as a guess
        # (I should make a flag if the centroid has moved more than a pixel or two)
        #logging.debug(time)
        coords = centroid.flux_weighted_centroid(image_list[i], fw_box,
                                                 init=start_center,
                                                 to_plot=False)

        # Write out the centroid pixel coordinates
        f.write(",{0:.6f},{1:.6f}".format(coords[0],coords[1]))
        
        if (np.any(np.isfinite(coords[:2])==False) or 
            (coords[0]<0) or (coords[1]<0) or 
            (coords[0]>100) or (coords[1]>100)
            ):
            logging.debug(coords[:2])
            f.write(",NaN,NaN"*len(ap_radii)) 
        else:

            # Now run the aperture photometry on the image
            if ap_type=="circular":
                ap_fluxes, bkgd_fluxes = circ_flux(image_list[i], maskmap, 
                                                   coords[::-1], ap_radii)
            elif ap_type=="elliptical":
                ap_fluxes, bkgd_fluxes = ellip_flux(image_list[i], maskmap,
                                                    coords, ap_radii,
                                                    **ellipse_kwargs)

            # Write out the fluxes and background level for each aperture
            for i, r in enumerate(ap_radii):
                f.write(",{0:.6f},{1:.6f}".format(ap_fluxes[i],
                                                  bkgd_fluxes[i]))
            
    f.close()
Beispiel #2
0
def plot_one(filename, ap=None, fw_box=None):

    outfilename = filename.split("/")[-1][:-14]
    logging.info(outfilename)
    table, times, pixels, maskmap, maskheader, kpmag = tpf_io.get_data(filename)

    init = centroid.init_pos(maskheader)
    logging.info("init %f %f", init[0], init[1])

    if fw_box is None:
        min_ax = np.argmin(np.shape(maskmap))
        min_box = np.shape(maskmap)[min_ax]
        if min_box>=9:
           min_box = 9
           logging.debug("min_box set to 9")
        elif min_ax==0:
            for row in maskmap:
                row_len = len(np.where(row>0)[0])
                if row_len < min_box:
                    min_box = row_len
                    logging.debug("new min_box %d", min_box)
        else:
            for i in range(np.shape(maskmap)[1]):
                col = maskmap[:, i]
                col_len = len(np.where(col>0)[0])
                if col_len < min_box:
                    min_box = row_len
                logging.debug("new min_box %d", min_box)
        
        fw_box = (min_box / 2) * 2 + 1
    
    logging.info("fw box %d",fw_box)

    coadd = np.sum(pixels,axis=0)
    coords = centroid.flux_weighted_centroid(coadd, fw_box, init=init)
    mean, median, std = sigma_clipped_stats(coadd, mask=(maskmap==0),
                                            sigma=3.0, iters=3)
    coadd_bkgd = median

    if np.sqrt((coords[0] - init[0])**2 + (coords[1] - init[1])**2)>1:
        logging.warning("Centroid (%f %f) far from init (%f %f)", 
                        coords[0], coords[1], init[0], init[1])
    else:
        logging.debug("coords %f %f", coords[0], coords[1])

    dkwargs = {"fwhm":2.5, "threshold":coadd_bkgd,  
               "sharplo":0.01,"sharphi":5.0}
    sources, n_sources = centroid.daofind_centroid(coadd, None, dkwargs)
    if n_sources==0:
        logging.info("bkgd: %f max: %f", coadd_bkgd, max(coadd.flatten()))
    logging.debug("sources")
    logging.debug(sources)

    ap_min, ap_max, ap_step = 2, 7, 0.5
    radii = np.arange(ap_min, ap_max, ap_step)


    epic = outfilename.split("-")[0][4:]
    logging.info(epic)
#    plot.lcs("lcs/{}.csv".format(outfilename), epic=epic)

    plot.plot_four(epic, filename, coadd, maskmap, maskheader, init, coords, 
                   sources, ap=ap, campaign=4)
    plt.savefig("plot_outputs/ktwo{}-c04_fourby.png".format(epic))
def run_one(filename, output_f=None, extract_companions=False, fw_box=None):
    """ 
    Extract a light curve for one star. 

    Inputs
    ------
    filename: string
        filename for target pixel file

    output_f: string (optional)
        if provided, statistics from the extraction will be printed to this file

    extract_companions: boolean (optional; default=False)
        if true, light curves and plots will also be generated for any other
        DAOfind sources in the coadded image

    fw_box: odd integer (optional)
        size of the box within which to calculate the flux-weighted centroid.
        Must be odd. Defaults to the shortest dimension of the pixel stamp,
        or 9 if larger than 9. 

    """

    # Clip part of the filename for use in saving outputs
    outfilename = filename.split("/")[-1][:-14]
    logging.info(outfilename)
    # Retrieve the data
    table, times, pixels, maskmap, maskheader, kpmag = tpf_io.get_data(filename)

    # Use the RA/Dec from the header as the initial position for calculation
    init = centroid.init_pos(maskheader)
    logging.info("init %f %f", init[0], init[1])

    # If not provided, calculate the maximum possible centroid box size.
    # Maximum possible box is 9, unless set larger by the user with fw_box
    if fw_box is None:
        min_ax = np.argmin(np.shape(maskmap))
        min_box = np.shape(maskmap)[min_ax]
        if min_box>=9:
           min_box = 9
           logging.debug("min_box set to 9")
        elif min_ax==0:
            for row in maskmap:
                row_len = len(np.where(row>0)[0])
                if row_len < min_box:
                    min_box = row_len
                    logging.debug("new min_box %d", min_box)
        else:
            for i in range(np.shape(maskmap)[1]):
                col = maskmap[:, i]
                col_len = len(np.where(col>0)[0])
                if col_len < min_box:
                    min_box = row_len
                logging.debug("new min_box %d", min_box)
        
        fw_box = (min_box / 2) * 2 + 1
    
    logging.info("fw box %d",fw_box)

    # Co-add all the sub-images and calculate the flux-weighted centroid
    coadd = np.sum(pixels,axis=0)
    coords = centroid.flux_weighted_centroid(coadd, fw_box, init=init)

    # Background of the co-added stampl is just the sigma-clipped median
    mean, median, std = sigma_clipped_stats(coadd, mask=(maskmap==0),
                                            sigma=3.0, iters=3)
    coadd_bkgd = median

    # Warn the user if the calculated initial coordinates are too far
    # from the initial coordinates (indicting that there's a brighter nearby 
    # star pulling the centroid off of the target)
    if np.sqrt((coords[0] - init[0])**2 + (coords[1] - init[1])**2)>1:
        logging.warning("Centroid (%f %f) far from init (%f %f)", 
                        coords[0], coords[1], init[0], init[1])
    else:
        logging.debug("coords %f %f", coords[0], coords[1])

    # Set keyword arguments for DAOFIND - trying to find anything other 
    # real sources in the image
    dkwargs = {"fwhm":2.5, "threshold":coadd_bkgd,  
               "sharplo":0.01,"sharphi":5.0}
    sources, n_sources = centroid.daofind_centroid(coadd, None, dkwargs)
    if n_sources==0:
        logging.info("bkgd: %f max: %f", coadd_bkgd, max(coadd.flatten()))
    logging.debug("sources")
    logging.debug(sources)

    # Set the minimum and maximum aperture sizes for the extraction
    # and the step in aperture sizes
    ap_min, ap_max, ap_step = 2, 7, 1
    radii = np.arange(ap_min, ap_max, ap_step)

    # Always use circular apertures, I think ap_type is now defunct actually...
    ap_type = "circ"
    phot.make_circ_lc(pixels, maskmap, times, init, radii,
                 "lcs/{}.csv".format(outfilename), fw_box)

    # get the EPIC ID
    epic = outfilename.split("-")[0][4:]
    logging.info(epic)

    # If an output filename is provided, save the output
    if output_f is not None:
        output_f.write("\n{},{}".format(outfilename,epic))
        output_f.write(",{0:.6f},{1:.6f}".format(maskheader["RA_OBJ"],
                                                 maskheader["DEC_OBJ"]))
        print type(init[0]), type(init[1])
        print init[0].dtype, init[1].dtype
        print init[0], init[1]
        output_f.write(",{0:.6f},{1:.6f}".format(np.float64(init[0]),
                                                 np.float64(init[1])))
        output_f.write(",{0:.2f},{1}".format(kpmag, n_sources))
        output_f.write(",{0:.2f},{1:.6f}".format(dkwargs["fwhm"], 
                                                 dkwargs["threshold"]))
        output_f.write(",{0:.2f},{1:.2f}".format(dkwargs["sharplo"],  
                                                 dkwargs["sharphi"]))
        output_f.write(",{0:.2f},{1}".format(fw_box,ap_type))
        output_f.write(",{0:.2f},{1:.2f},{2:.2f}".format(ap_min, ap_max,   
                                                         ap_step))