def plot_phase(times, fluxs, fit_period, fit_t0, ax, s=4, alpha=0.3):

    phzd = phase_magseries(times,
                           fluxs,
                           fit_period,
                           fit_t0,
                           wrap=True,
                           sort=True)

    phase = phzd['phase']
    phz_flux = phzd['mags']

    #ax.scatter(phase, phz_flux, c='k', alpha=0.2, zorder=1, s=6,
    #           rasterized=True, linewidths=0)
    ax.scatter(phase,
               phz_flux,
               c='k',
               alpha=alpha,
               zorder=1,
               s=s,
               rasterized=True,
               linewidths=0)
Exemple #2
0
def reduce_WASP_4b(plname='WASP-4b_dataset0'):

    # options when running
    try_to_recover_periodograms = False
    make_lc_plots = True

    # table 1 of Hellier et al 2009 discovery paper
    period, epoch = 1.3382282, 2454365.91464
    # decimal ra, dec of target used only for BJD conversion
    ra, dec = 353.56283333, -42.06141667

    # file parsing
    lcdir = '../data/WASP_lightcurves/'
    wasp_lcs = [f for f in glob(lcdir+'*.tbl') if plname in f]
    if not len(wasp_lcs)==1:
        raise AssertionError
    lcfile = wasp_lcs[0]

    fit_savdir = '../results/WASP_lightcurves/'
    chain_savdir = '/home/luke/local/emcee_chains/'
    savdir='../results/WASP_lightcurves/'
    for sdir in [fit_savdir, chain_savdir, savdir]:
        if not os.path.exists(sdir):
            os.mkdir(sdir)

    #########
    # begin #
    #########
    tempdf = read_WASP_lightcurve(lcfile)
    df = wrangle_WASP_lightcurve(tempdf, ra, dec, plname)

    times, mags, errs = (nparr(df['BJD_TDB']), nparr(df['RELMAG']),
                         nparr(df['ERR']))

    stimes, smags, serrs = sigclip_magseries(times, mags, errs, sigclip=[5,5],
                                             magsarefluxes=False)

    phzd = phase_magseries(stimes, smags, period, epoch, wrap=True, sort=True)

    # convert from mags to relative fluxes for fitting
    # m_x - m_x0 = -5/2 log10( f_x / f_x0 )
    # so
    # f_x = f_x0 * 10 ** ( -2/5 (m_x - m_x0) )
    m_x0, f_x0 = 10, 1e3 # arbitrary
    sfluxs = f_x0 * 10**( -0.4 * (smags - m_x0) )
    sfluxs /= np.nanmedian(sfluxs)

    if try_to_recover_periodograms:
        run_wasp_periodograms(stimes, smags, serrs)

    if make_lc_plots:
        plot_old_lcs(times, mags, stimes, smags, phzd, period, epoch, sfluxs,
                     plname, savdir=savdir, telescope='WASP')

    ####################################################################
    # fit the lightcurve, show the phased result, get the transit time #
    ####################################################################

    n_mcmc_steps = 500
    overwrite=1

    savstr = 'wasp_errs_1d'
    # use physical parameters from Wilson+ 2008 as fixed parameters
    empirical_errs = fit_lightcurve_get_transit_time(stimes, sfluxs, serrs,
                                                     savstr, plname, period, epoch,
                                                     n_mcmc_steps=n_mcmc_steps,
                                                     overwriteexistingsamples=overwrite)


    # the WASP errors are good for fitting an initial model to the data, but
    # they may be over/under-estimates. instead use the "empirical errors",
    # which are the measured 1-sigma standard deviations of the residual.

    savstr = 'wasp_empirical_errs_1d'
    eerrs = np.ones_like(serrs)*empirical_errs

    _ = fit_lightcurve_get_transit_time(stimes, sfluxs, eerrs,
                                        savstr, plname, period, epoch,
                                        n_mcmc_steps=n_mcmc_steps,
                                        overwriteexistingsamples=overwrite)
def reduce_WASP_121b():

    # options when running
    try_to_recover_periodograms = False
    make_lc_plots = True

    plname = 'WASP-121b'
    # table 1 of Delrez et al 2016 discovery paper. (BJD_TDB)
    period = 1.2749255
    epoch = 2456636.345762 + period / 2
    # decimal ra, dec of target used only for BJD conversion
    ra, dec = 107.60023116745, -39.09727045928

    # file parsing
    lcdir = '../data/ASAS_lightcurves/'
    asas_lcs = [f for f in glob(lcdir + '*.txt') if 'WASP-121' in f]
    lcfile = asas_lcs[0]

    fit_savdir = '../results/ASAS_lightcurves/'
    chain_savdir = '/home/luke/local/emcee_chains/'
    savdir = '../results/ASAS_lightcurves/'

    #########
    # begin #
    #########
    tempdf, dslices = read_ASAS_lightcurve(lcfile)
    df = wrangle_ASAS_lightcurve(tempdf, dslices, ra, dec)

    times, mags, errs = (nparr(df['BJD_TDB']), nparr(df['SMAG_bestap']),
                         nparr(df['SERR_bestap']))

    stimes, smags, serrs = sigclip_magseries(times,
                                             mags,
                                             errs,
                                             sigclip=[5, 5],
                                             magsarefluxes=False)

    phzd = phase_magseries(stimes, smags, period, epoch, wrap=True, sort=True)

    # convert from mags to relative fluxes for fitting
    # m_x - m_x0 = -5/2 log10( f_x / f_x0 )
    # so
    # f_x = f_x0 * 10 ** ( -2/5 (m_x - m_x0) )
    m_x0, f_x0 = 10, 1e3  # arbitrary
    sfluxs = f_x0 * 10**(-0.4 * (smags - m_x0))
    sfluxs /= np.nanmedian(sfluxs)

    if try_to_recover_periodograms:
        run_asas_periodograms(stimes, smags, serrs)

    if make_lc_plots:
        plot_old_lcs(times, mags, stimes, smags, phzd, period, epoch, sfluxs,
                     'WASP-121b')

    savdf = pd.DataFrame({
        'time_BJDTDB': stimes,
        'sigclipped_mag_bestap': smags,
        'err_mag_from_ASAS': serrs
    })
    savdfpath = '../results/ASAS_lightcurves/wasp121b_asas_mag_time_err.csv'
    savdf.to_csv(savdfpath, index=False)
    print('made {}'.format(savdfpath))

    ####################################################################
    # fit the lightcurve, show the phased result, get the transit time #
    ####################################################################

    savstr = 'asas_errs_1d'

    empirical_errs = fit_lightcurve_get_transit_time(
        stimes,
        sfluxs,
        serrs,
        savstr,
        plname,
        period,
        epoch,
        n_mcmc_steps=1000,
        overwriteexistingsamples=True,
        true_b=0.16,
        true_t0=epoch,
        true_rp=np.sqrt(0.01551),
        true_sma=3.754,
        sma_au=None,
        rstar=None,
        u_linear=0.4081,
        u_quad=0.2533)

    # the ASAS errors are good for fitting an initial model to the data, but
    # they may be over/under-estimates. instead use the "empirical errors",
    # which are the measured 1-sigma standard deviations of the residual.

    savstr = 'empirical_errs_1d'
    eerrs = np.ones_like(serrs) * empirical_errs

    _ = fit_lightcurve_get_transit_time(stimes,
                                        sfluxs,
                                        eerrs,
                                        savstr,
                                        plname,
                                        period,
                                        epoch,
                                        n_mcmc_steps=1000,
                                        overwriteexistingsamples=True,
                                        true_b=0.16,
                                        true_t0=epoch,
                                        true_rp=np.sqrt(0.01551),
                                        true_sma=3.754,
                                        sma_au=None,
                                        rstar=None,
                                        u_linear=0.4081,
                                        u_quad=0.2533)
def reduce_all():
    # options when running
    make_lc_plots = True

    df = pd.read_csv('../data/asas_all_well-studied_HJs_depthgt1pct_'
                     'Vlt11_Plt10_manual_points.csv')
    df = df.drop(columns='System.1')

    sel = (df['asas_N_obs'] > 0)

    print('{:d} HJs from TEPCAT with V<11, P<10day, depth>1%'.format(len(df)))
    df = df[sel]
    print('{:d} with >0 ASAS data points'.format(len(df)))

    df['plname'] = nparr(df['System']) + 'b'
    df = df.rename(index=str,
                   columns={
                       'Period(day)': 'period',
                       'T0 (HJD or BJD)': 'epoch_HJD_or_BJD'
                   })
    c = SkyCoord(nparr(df['asas_query_str']), unit=(u.hourangle, u.deg))
    df['ra_decimal'] = c.ra.value
    df['dec_decimal'] = c.dec.value

    lcdir = '../data/ASAS_lightcurves/'
    df['lcpath'] = lcdir + nparr(df['asas_lc_name'])

    #FIXME: super janky that the epoch is in HJD OR BJD. which is it, for each
    #case?...
    df['epoch_is_BJD'] = np.ones_like(list(range(len(df))))

    fit_savdir = '../results/ASAS_lightcurves/'
    chain_savdir = '/home/luke/local/emcee_chains/'
    savdir = '../results/ASAS_lightcurves/'

    for plname, period, epoch_HJD_or_BJD, ra, dec, lcfile, epoch_is_BJD in list(
            zip(
                nparr(df['plname']),
                nparr(df['period']),
                nparr(df['epoch_HJD_or_BJD']),
                nparr(df['ra_decimal']),
                nparr(df['dec_decimal']),
                nparr(df['lcpath']),
                nparr(df['epoch_is_BJD']),
            )):

        tempdf, dslices = read_ASAS_lightcurve(lcfile)
        df = wrangle_ASAS_lightcurve(tempdf, dslices, ra, dec)

        times, mags, errs = (nparr(df['BJD_TDB']), nparr(df['SMAG_bestap']),
                             nparr(df['SERR_bestap']))

        stimes, smags, serrs = sigclip_magseries(times,
                                                 mags,
                                                 errs,
                                                 sigclip=[5, 5],
                                                 magsarefluxes=False)

        if epoch_is_BJD:
            epoch = epoch_HJD_or_BJD
        else:
            raise NotImplementedError

        phzd = phase_magseries(stimes,
                               smags,
                               period,
                               epoch,
                               wrap=True,
                               sort=True)

        # convert from mags to relative fluxes for fitting
        # m_x - m_x0 = -5/2 log10( f_x / f_x0 )
        # so
        # f_x = f_x0 * 10 ** ( -2/5 (m_x - m_x0) )
        m_x0, f_x0 = 10, 1e3  # arbitrary
        sfluxs = f_x0 * 10**(-0.4 * (smags - m_x0))
        sfluxs /= np.nanmedian(sfluxs)

        if make_lc_plots:
            plot_old_lcs(times, mags, stimes, smags, phzd, period, epoch,
                         sfluxs, plname)
def reduce_WASP_18b():

    # options when running
    try_to_recover_periodograms = False
    make_lc_plots = True

    plname = 'WASP-18b'
    # table 1 of Hellier et al 2009 discovery paper
    period, epoch = 0.94145299, 2454221.48163
    # decimal ra, dec of target used only for BJD conversion
    ra, dec = 24.354311, -45.677887

    # file parsing
    lcdir = '../data/ASAS_lightcurves/'
    asas_lcs = [f for f in glob(lcdir + '*.txt') if 'WASP-18' in f]
    lcfile = asas_lcs[0]

    fit_savdir = '../results/ASAS_lightcurves/'
    chain_savdir = '/home/luke/local/emcee_chains/'
    savdir = '../results/ASAS_lightcurves/'

    #########
    # begin #
    #########
    tempdf, dslices = read_ASAS_lightcurve(lcfile)
    df = wrangle_ASAS_lightcurve(tempdf, dslices, ra, dec)

    times, mags, errs = (nparr(df['BJD_TDB']), nparr(df['SMAG_bestap']),
                         nparr(df['SERR_bestap']))

    stimes, smags, serrs = sigclip_magseries(times,
                                             mags,
                                             errs,
                                             sigclip=[5, 5],
                                             magsarefluxes=False)

    phzd = phase_magseries(stimes, smags, period, epoch, wrap=True, sort=True)

    # convert from mags to relative fluxes for fitting
    # m_x - m_x0 = -5/2 log10( f_x / f_x0 )
    # so
    # f_x = f_x0 * 10 ** ( -2/5 (m_x - m_x0) )
    m_x0, f_x0 = 10, 1e3  # arbitrary
    sfluxs = f_x0 * 10**(-0.4 * (smags - m_x0))
    sfluxs /= np.nanmedian(sfluxs)

    if try_to_recover_periodograms:
        run_asas_periodograms(stimes, smags, serrs)

    if make_lc_plots:
        plot_old_lcs(times, mags, stimes, smags, phzd, period, epoch, sfluxs,
                     'WASP-18b')

    savdf = pd.DataFrame({
        'time_BJDTDB': stimes,
        'sigclipped_mag_bestap': smags,
        'err_mag_from_ASAS': serrs
    })
    savdfpath = '../results/ASAS_lightcurves/wasp18b_asas_mag_time_err.csv'
    savdf.to_csv(savdfpath, index=False)
    print('made {}'.format(savdfpath))
    #FIXME
    assert 0

    ####################################################################
    # fit the lightcurve, show the phased result, get the transit time #
    ####################################################################

    savstr = 'asas_errs_1d'
    # use physical parameters from Hellier+ 2009 as fixed parameters
    plname = 'WASP-18b'
    period = 0.94145299
    epoch = 2454221.48163
    empirical_errs = fit_lightcurve_get_transit_time(
        stimes,
        sfluxs,
        serrs,
        savstr,
        plname,
        period,
        epoch,
        n_mcmc_steps=10,
        overwriteexistingsamples=False)

    # the ASAS errors are good for fitting an initial model to the data, but
    # they may be over/under-estimates. instead use the "empirical errors",
    # which are the measured 1-sigma standard deviations of the residual.

    savstr = 'empirical_errs_1d'
    eerrs = np.ones_like(serrs) * empirical_errs

    _ = fit_lightcurve_get_transit_time(stimes,
                                        sfluxs,
                                        eerrs,
                                        savstr,
                                        n_mcmc_steps=100,
                                        overwriteexistingsamples=False)
def plot_phasefold(picklepath, xlim=None, ylim0=None, ylim1=None):

    # d['magseries'].keys()
    # dict_keys(['times', 'mags', 'errs', 'magsarefluxes'])
    # d['fitinfo'].keys()
    # dict_keys(['initialparams', 'initialmags', 'fixedparams',
    #            'finalparams', 'finalparamerrs', 'fitmags', 'fitepoch'])
    # d['fitinfo']['finalparams'].keys()
    # dict_keys(['incl', 'period', 'rp', 'sma', 't0', 'u_linear', 'u_quad'])
    d = pickle.load(open(picklepath, 'rb'))

    times = d['magseries']['times']
    fluxs = d['magseries']['mags']
    fitfluxs = d['fitinfo']['fitmags']
    errs = d['magseries']['errs']

    fit_t0 = d['fitinfo']['finalparams']['t0']
    # NOTE: might want to use the best-fit value from the tables, instead of
    # the BLS period here.
    fit_period = d['fitinfo']['finalparams']['period']

    phzd = phase_magseries(times,
                           fluxs,
                           fit_period,
                           fit_t0,
                           wrap=True,
                           sort=True)
    fit_phzd = phase_magseries(times,
                               fitfluxs,
                               fit_period,
                               fit_t0,
                               wrap=True,
                               sort=True)

    phase = phzd['phase']
    phz_flux = phzd['mags']
    fit_phz_flux = fit_phzd['mags']

    binsize = 0.003
    bin_phzd = phase_bin_magseries(phase, phz_flux, binsize=binsize)
    bin_phase = bin_phzd['binnedphases']
    bin_fluxs = bin_phzd['binnedmags']
    fit_bin_phzd = phase_bin_magseries(phase, fit_phz_flux, binsize=binsize)
    fit_bin_phase = fit_bin_phzd['binnedphases']
    fit_bin_fluxs = fit_bin_phzd['binnedmags']

    ##########################################
    plt.close('all')
    f, (a0, a1) = plt.subplots(nrows=2,
                               ncols=1,
                               sharex=True,
                               figsize=(0.8 * 6, 0.8 * 4),
                               gridspec_kw={'height_ratios': [3, 1]})

    a0.scatter(phase * fit_period * 24,
               phz_flux,
               c='k',
               alpha=0.12,
               label='data',
               zorder=1,
               s=10,
               rasterized=True,
               linewidths=0)
    a0.plot(bin_phase * fit_period * 24,
            bin_fluxs,
            alpha=1,
            mew=0.5,
            zorder=8,
            label='binned',
            markerfacecolor='yellow',
            markersize=8,
            marker='.',
            color='black',
            lw=0,
            rasterized=True)
    a0.plot(phase * fit_period * 24,
            fit_phz_flux,
            c='#4346ff',
            zorder=2,
            rasterized=True,
            lw=1.5,
            alpha=0.7,
            label='model')

    trans = transforms.blended_transform_factory(a0.transAxes, a0.transData)
    a0.errorbar(0.88,
                0.97,
                yerr=np.median(errs),
                fmt='none',
                ecolor='gray',
                elinewidth=1,
                capsize=2,
                transform=trans)

    a1.scatter(phase * fit_period * 24,
               phz_flux - fit_phz_flux,
               c='k',
               alpha=0.12,
               rasterized=True,
               s=10,
               linewidths=0,
               zorder=1)
    a1.plot(bin_phase * fit_period * 24,
            bin_fluxs - fit_bin_fluxs,
            alpha=1,
            mew=0.5,
            zorder=8,
            markerfacecolor='yellow',
            markersize=8,
            marker='.',
            color='black',
            lw=0,
            rasterized=True)
    a1.plot(phase * fit_period * 24,
            fit_phz_flux - fit_phz_flux,
            c='#4346ff',
            zorder=2,
            rasterized=True,
            lw=1.5,
            alpha=0.7)

    a1.set_xlabel('Time from mid-transit [hours]')
    a0.set_ylabel('Relative flux')
    a1.set_ylabel('Residual')
    for a in [a0, a1]:
        a.get_yaxis().set_tick_params(which='both', direction='in')
        a.get_xaxis().set_tick_params(which='both', direction='in')
        if xlim:
            a.set_xlim(xlim)
    if ylim0:
        a0.set_ylim(ylim0)
    if ylim1:
        a1.set_ylim(ylim1)
    a0.legend(loc='best', fontsize='small')

    f.tight_layout(h_pad=-.3, w_pad=0)
    savpath = '../results/phasefold.png'
    f.savefig(savpath, dpi=600, bbox_inches='tight')
    print('made {}'.format(savpath))
    copyfile(savpath, '../paper/f2.png')
    print('saved ../paper/f2.png')
Exemple #7
0
def plot_phase_PC(fpath, ax, ind, s=4, alpha=0.3, show_model=True):
    #
    # get data. fpath here is a png file of the phase-folded model LC.
    #
    fitdir = os.path.dirname(fpath)

    fitpkl = glob(os.path.join(fitdir, '*empiricalerrs.pickle'))
    assert len(fitpkl) == 1
    fitpkl = fitpkl[0]
    with open(fitpkl, mode='rb') as f:
        d = pickle.load(f)

    fitcsv = glob(os.path.join(fitdir, '*fitparameters.csv'))
    assert len(fitcsv) == 1
    fitcsv = fitcsv[0]
    fit_df = pd.read_csv(fitcsv, sep="|")

    period = float(fit_df['period'])
    t0 = float(fit_df['epoch'])
    duration = float(fit_df['duration']) / 24

    time, flux = d['magseries']['times'], d['magseries']['mags']
    assert d['magseries']['magsarefluxes']

    #
    # phase data
    #
    phzd = phase_magseries(time, flux, period, t0, wrap=True, sort=True)

    phase = phzd['phase']
    phz_flux = phzd['mags']

    #
    # plot data
    #
    ax.scatter(phase * period * 24,
               phz_flux,
               c='k',
               alpha=alpha,
               zorder=3,
               s=s,
               rasterized=True,
               linewidths=0)

    ax.text(0.96,
            0.06,
            '{:.2f}d'.format(period),
            transform=ax.transAxes,
            ha='right',
            va='bottom')

    ax.text(0.04,
            0.06,
            '{}'.format(ind),
            transform=ax.transAxes,
            ha='left',
            va='bottom')

    ax.set_xlim((-4 * duration * 24, 4 * duration * 24))

    #
    # get and plot model
    #
    if show_model:
        modeltime = time
        modelflux = d['fitinfo']['fitmags']

        model_phzd = phase_magseries(modeltime,
                                     modelflux,
                                     period,
                                     t0,
                                     wrap=True,
                                     sort=True)
        model_phase = model_phzd['phase']
        model_phz_flux = model_phzd['mags']

        ax.plot(model_phase * period * 24,
                model_phz_flux,
                zorder=2,
                linewidth=0.5,
                alpha=0.9,
                color='C0',
                rasterized=True)
Exemple #8
0
def generate_verification_page(lcd, ls, freq, power, cutoutpaths, c_obj,
                               outvppath, outd, show_binned=True):
    """
    Make the verification page, which consists of:

    top row: entire light curve (with horiz bar showing rotation period)

    bottom row:
        lomb scargle periodogram  |  phased light curve  |  image w/ aperture

    ----------
    args:

        lcd (dict): has the light curve, aperture positions, some lomb
        scargle results.

        ls: LombScargle instance with everything passed.

        cutoutpaths (list): FFI cutout FITS paths.

        c_obj (SkyCoord): astropy sky coordinate of the target

        outvppath (str): path to save verification page to
    """
    cutout_wcs = lcd['cutout_wcss'][0]

    mpl.rcParams['xtick.direction'] = 'in'
    mpl.rcParams['ytick.direction'] = 'in'

    plt.close('all')

    fig = plt.figure(figsize=(12,12))

    #ax0 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
    #ax1 = plt.subplot2grid((3, 3), (1, 0), colspan=3)
    #ax2 = plt.subplot2grid((3, 3), (2, 0))
    #ax3 = plt.subplot2grid((3, 3), (2, 1))
    #ax4 = plt.subplot2grid((3, 3), (2, 2), projection=cutout_wcs)

    ax0 = plt.subplot2grid((3, 3), (1, 0), colspan=3)
    ax1 = plt.subplot2grid((3, 3), (2, 0), colspan=3)
    ax2 = plt.subplot2grid((3, 3), (0, 0))
    ax3 = plt.subplot2grid((3, 3), (0, 1))
    ax4 = plt.subplot2grid((3, 3), (0, 2), projection=cutout_wcs)

    #
    # row 0: entire light curve, pre-detrending (with horiz bar showing
    # rotation period). plot model LC too.
    #
    try:
        ax0.scatter(lcd['predetrending_time'], lcd['predetrending_rel_flux'],
                    c='k', alpha=1.0, zorder=3, s=10, rasterized=True,
                    linewidths=0)
    except KeyError as e:
        print('ERR! {}\nReturning.'.format(e))
        return


    try:
        model_flux = nparr(lcd['predetrending_rel_flux']/lcd['rel_flux'])
    except ValueError:
        model_flux = 0

    if isinstance(model_flux, np.ndarray):
        ngroups, groups = find_lc_timegroups(lcd['predetrending_time'], mingap=0.5)
        for group in groups:
            ax0.plot(lcd['predetrending_time'][group], model_flux[group], c='C0',
                     alpha=1.0, zorder=2, rasterized=True, lw=2)

    # add the bar showing the derived period
    ymax = np.percentile(lcd['predetrending_rel_flux'], 95)
    ymin = np.percentile(lcd['predetrending_rel_flux'], 5)
    ydiff = 1.15*(ymax-ymin)

    epoch = np.nanmin(lcd['predetrending_time']) + lcd['ls_period']
    ax0.plot([epoch, epoch+lcd['ls_period']], [ymax, ymax], color='red', lw=2,
             zorder=4)

    ax0.set_ylim((ymin-ydiff,ymax+ydiff))

    #ax0.set_xlabel('Time [BJD$_{\mathrm{TDB}}$]')
    ax0.set_xticklabels('')
    ax0.set_ylabel('Raw flux')

    name = outd['name']
    group_id = outd['group_id']
    if name=='nan':
        nstr = 'Group {}'.format(group_id)
    else:
        nstr = '{}'.format(name)


    if not np.isfinite(outd['teff']):
        outd['teff'] = 0

    ax0.text(0.98, 0.97,
        'Teff={:d}K. {}'.format(int(outd['teff']), nstr),
             ha='right', va='top', fontsize='large', zorder=2,
             transform=ax0.transAxes
    )

    #
    # row 1: entire light curve (with horiz bar showing rotation period)
    #
    ax1.scatter(lcd['time'], lcd['rel_flux'], c='k', alpha=1.0, zorder=2, s=10,
                rasterized=True, linewidths=0)

    # add the bar showing the derived period
    ymax = np.percentile(lcd['rel_flux'], 95)
    ymin = np.percentile(lcd['rel_flux'], 5)
    ydiff = 1.15*(ymax-ymin)

    epoch = np.nanmin(lcd['time']) + lcd['ls_period']
    ax1.plot([epoch, epoch+lcd['ls_period']], [ymax, ymax], color='red', lw=2)

    ax1.set_ylim((ymin-ydiff,ymax+ydiff))

    ax1.set_xlabel('Time [BJD$_{\mathrm{TDB}}$]')
    ax1.set_ylabel('Detrended flux')

    #
    # row 2, col 0: lomb scargle periodogram
    #
    ax2.plot(1/freq, power, c='k')
    ax2.set_xscale('log')
    ax2.text(0.03, 0.97, 'FAP={:.1e}\nP={:.1f}d'.format(
        lcd['ls_fap'], lcd['ls_period']), ha='left', va='top',
        fontsize='large', zorder=2, transform=ax2.transAxes
    )
    ax2.set_xlabel('Period [day]', labelpad=-1)
    ax2.set_ylabel('LS power')

    #
    # row 2, col 1: phased light curve 
    #
    phzd = phase_magseries(lcd['time'], lcd['rel_flux'], lcd['ls_period'],
                           lcd['time'][np.argmin(lcd['rel_flux'])], wrap=False,
                           sort=True)

    ax3.scatter(phzd['phase'], phzd['mags'], c='k', rasterized=True, s=10,
                linewidths=0, zorder=1)

    if show_binned:
        try:
            binphasedlc = phase_bin_magseries(phzd['phase'], phzd['mags'],
                                              binsize=1e-2, minbinelems=5)
            binplotphase = binphasedlc['binnedphases']
            binplotmags = binphasedlc['binnedmags']

            ax3.scatter(binplotphase, binplotmags, s=10, c='darkorange',
                        linewidths=0, zorder=3, rasterized=True)
        except TypeError as e:
            print(e)
            pass

    xlim = ax3.get_xlim()
    ax3.hlines(1.0, xlim[0], xlim[1], colors='gray', linestyles='dotted',
               zorder=2)
    ax3.set_xlim(xlim)

    ymax = np.percentile(lcd['rel_flux'], 95)
    ymin = np.percentile(lcd['rel_flux'], 5)
    ydiff = 1.15*(ymax-ymin)
    ax3.set_ylim((ymin-ydiff,ymax+ydiff))

    ax3.set_xlabel('Phase', labelpad=-1)
    ax3.set_ylabel('Flux', labelpad=-0.5)

    #
    # row2, col2: image w/ aperture. put on the nbhr stars as dots too, to
    # ensure the wcs isn't wonky!
    #

    # acquire neighbor stars.
    radius = 2.0*u.arcminute

    nbhr_stars = Catalogs.query_region(
        "{} {}".format(float(c_obj.ra.value), float(c_obj.dec.value)),
        catalog="TIC",
        radius=radius
    )

    try:
        Tmag_cutoff = 15
        px,py = cutout_wcs.all_world2pix(
            nbhr_stars[nbhr_stars['Tmag'] < Tmag_cutoff]['ra'],
            nbhr_stars[nbhr_stars['Tmag'] < Tmag_cutoff]['dec'],
            0
        )
    except Exception as e:
        print('ERR! wcs all_world2pix got {}'.format(repr(e)))
        return

    tmags = nbhr_stars[nbhr_stars['Tmag'] < Tmag_cutoff]['Tmag']

    sel = (px > 0) & (px < 19) & (py > 0) & (py < 19)
    px,py = px[sel], py[sel]
    tmags = tmags[sel]

    ra, dec = float(c_obj.ra.value), float(c_obj.dec.value)
    target_x, target_y = cutout_wcs.all_world2pix(ra,dec,0)

    #
    # finally make it
    #

    img = lcd['median_imgs'][0]

    # some images come out as nans.
    if np.all(np.isnan(img)):
        img = np.ones_like(img)

    interval = vis.PercentileInterval(99.9)
    vmin,vmax = interval.get_limits(img)
    norm = vis.ImageNormalize(
        vmin=vmin, vmax=vmax, stretch=vis.LogStretch(1000))

    cset = ax4.imshow(img, cmap='YlGnBu_r', origin='lower', zorder=1,
                      norm=norm)

    ax4.scatter(px, py, marker='x', c='r', s=5, rasterized=True, zorder=2,
                linewidths=1)
    ax4.plot(target_x, target_y, mew=0.5, zorder=5, markerfacecolor='yellow',
             markersize=7, marker='*', color='k', lw=0)

    #ax4.coords.grid(True, color='white', ls='dotted', lw=1)
    lon = ax4.coords['ra']
    lat = ax4.coords['dec']

    lon.set_ticks(spacing=1*u.arcminute)
    lat.set_ticks(spacing=1*u.arcminute)

    lon.set_ticklabel(exclude_overlapping=True)
    lat.set_ticklabel(exclude_overlapping=True)

    ax4.coords.grid(True, color='white', alpha=0.3, lw=0.3, ls='dotted')

    #cb0 = fig.colorbar(cset, ax=ax4, extend='neither', fraction=0.046, pad=0.04)

    # overplot aperture
    radius_px = 3
    circle = plt.Circle((target_x, target_y), radius_px,
                         color='C1', fill=False, zorder=5)
    ax4.add_artist(circle)

    #
    # cleanup
    # 
    for ax in [ax0,ax1,ax2,ax3,ax4]:
        ax.get_yaxis().set_tick_params(which='both', direction='in',
                                       labelsize='small', top=True, right=True)
        ax.get_xaxis().set_tick_params(which='both', direction='in',
                                       labelsize='small', top=True, right=True)

    fig.tight_layout(w_pad=0.5, h_pad=0)

    #
    # save
    #
    fig.savefig(outvppath, dpi=300, bbox_inches='tight')
    print('made {}'.format(outvppath))
Exemple #9
0
def plot_phase(fpath,
               ax,
               ind,
               s=3,
               alpha=0.3,
               lctype='IRM2',
               periodogramtype=None,
               peakindex=0,
               plot_bin_phase=False,
               overwritecsv=1):

    outsavpath = os.path.join(
        OUTDIR,
        'quilt_s6_s7_' + os.path.basename(fpath).replace('.fits', '.csv'))

    if os.path.exists(outsavpath) and not overwritecsv:
        df = pd.read_csv(outsavpath)
        phase = nparr(df['phase'])
        phz_flux = nparr(df['phz_flux'])
        period = nparr(df['period'])[0]

    else:
        #
        # get data. fpath here is a fits LC file. apply the periodogram requested.
        #
        time = iu.get_data_keyword(fpath, 'TMID_BJD', ext=1)
        mag = iu.get_data_keyword(fpath, lctype, ext=1)

        f_x0 = 1e4
        m_x0 = 10
        flux = f_x0 * 10**(-0.4 * (mag - m_x0))
        flux /= np.nanmedian(flux)

        time, flux = moe.mask_orbit_start_and_end(time, flux)

        # fit out long term trend (light detrending) with median filter of 5 days.
        if 'IRM' in lctype:
            ngroups, groups = lcmath.find_lc_timegroups(time, mingap=0.5)
            assert ngroups == 2

            windowsize = 48 * 5 + 1  # 5 days
            tg_smooth_flux = []
            for group in groups:

                #
                # fit out arbitrary order legendre series
                # p(x) = c_0*L_0(x) + c_1*L_1(x) + c_2*L_2(x) + ... + c_n*L_n(x)
                #
                legendredeg = 2
                p = Legendre.fit(time[group], flux[group], legendredeg)
                coeffs = p.coef
                fit_flux = p(time[group])

                tg_smooth_flux.append(flux[group] / fit_flux)

            flux = np.concatenate(tg_smooth_flux)

        if periodogramtype == 'tls':
            period_min, period_max = 0.5, 5
            tlsp = periodbase.tls_parallel_pfind(
                time,
                flux,
                1e-3 * flux,
                magsarefluxes=True,
                tls_rstar_min=0.1,
                tls_rstar_max=10,
                tls_mstar_min=0.1,
                tls_mstar_max=5.0,
                tls_oversample=8,
                tls_mintransits=1,
                tls_transit_template='default',
                nbestpeaks=5,
                sigclip=None,
                nworkers=52)

            period = tlsp['nbestperiods'][peakindex]
            t0 = tlsp['tlsresult']['T0']
            if peakindex == 1:
                t0 += period / 2

        elif periodogramtype == 'gls':
            period_min, period_max = 0.1, 5
            ls = LombScargle(time, flux, flux * 1e-3)
            freq, power = ls.autopower(minimum_frequency=1 / period_max,
                                       maximum_frequency=1 / period_min,
                                       samples_per_peak=20)
            period = 1 / freq[np.argmax(power)]
            t0 = time[np.argmin(flux)]

        else:
            raise NotImplementedError(
                'got {}, not imlemented'.format(periodogramtype))

        #
        # phase data
        #
        phzd = phase_magseries(time, flux, period, t0, wrap=True, sort=True)

        phase = phzd['phase']
        phz_flux = phzd['mags']

    #
    # plot data
    #
    ax.scatter(phase,
               phz_flux,
               c='k',
               alpha=alpha,
               zorder=3,
               s=s,
               rasterized=True,
               linewidths=0)

    ax.text(0.88,
            0.03,
            '{:.2f}d'.format(period),
            transform=ax.transAxes,
            ha='right',
            va='bottom')

    ax.text(0.04,
            0.06,
            '{}'.format(ind),
            transform=ax.transAxes,
            ha='left',
            va='bottom')

    if overwritecsv:
        outdf = pd.DataFrame({
            'phase': phase,
            'phz_flux': phz_flux,
            'period': np.ones_like(phase) * period
        })
        outdf.to_csv(outsavpath, index=False)

    if plot_bin_phase:

        binphasedlc = phase_bin_magseries(phase,
                                          phz_flux,
                                          binsize=2e-2,
                                          minbinelems=3)
        binplotphase = binphasedlc['binnedphases']
        binplotmags = binphasedlc['binnedmags']

        ax.scatter(binplotphase,
                   binplotmags,
                   c='orange',
                   alpha=alpha,
                   zorder=4,
                   s=s,
                   rasterized=True,
                   linewidths=0)