Пример #1
0
def test_checkplot_twolsp_png():
    '''
    Tests if a two-LSP checkplot PNG can be made.

    '''

    outpath = os.path.join(os.path.dirname(LCPATH),
                           'test-twolsp-checkplot.png')

    lcd, msg = hatlc.read_and_filter_sqlitecurve(LCPATH)
    gls = periodbase.pgen_lsp(lcd['rjd'], lcd['aep_000'], lcd['aie_000'])

    assert isinstance(gls, dict)
    assert_allclose(gls['bestperiod'], 1.54289477)

    pdm = periodbase.stellingwerf_pdm(lcd['rjd'],
                                      lcd['aep_000'],
                                      lcd['aie_000'])

    assert isinstance(pdm, dict)
    assert_allclose(pdm['bestperiod'], 3.08578956)

    cpf = checkplot.twolsp_checkplot_png(
        gls, pdm,
        lcd['rjd'], lcd['aep_000'], lcd['aie_000'],
        outfile=outpath,
        objectinfo=lcd['objectinfo']
    )

    assert os.path.exists(outpath)
def run_asas_periodograms(times,
                          mags,
                          errs,
                          outdir='../results/ASAS_lightcurves/',
                          outname='WASP-18b_BLS_GLS.png'):

    blsdict = kbls.bls_parallel_pfind(times,
                                      mags,
                                      errs,
                                      magsarefluxes=False,
                                      startp=0.5,
                                      endp=1.5,
                                      maxtransitduration=0.3,
                                      nworkers=8,
                                      sigclip=[15, 3])
    gls = periodbase.pgen_lsp(times,
                              mags,
                              errs,
                              magsarefluxes=False,
                              startp=0.5,
                              endp=1.5,
                              nworkers=8,
                              sigclip=[15, 3])
    outpath = outdir + outname
    cpf = checkplot.twolsp_checkplot_png(blsdict,
                                         gls,
                                         times,
                                         mags,
                                         errs,
                                         outfile=outpath,
                                         objectinfo=None)
Пример #3
0
def do_period_finding_fitslc(lcpath,
                             fluxap='TFA2',
                             period_min=0.5,
                             outdir=None):

    if not outdir:
        outdir = os.path.dirname(lcpath)
    outfile = os.path.basename(lcpath).replace('.fits',
                                               '_spdm_blsp_checkplot.png')
    outpath = os.path.join(outdir, outfile)
    if os.path.exists(outpath):
        print('found & skipped {}'.format(outpath))
        return

    hdulist = fits.open(lcpath)
    hdr, lc = hdulist[0].header, hdulist[1].data

    times, mags, errs = (lc['TMID_BJD'], lc[fluxap], np.ones_like(lc[fluxap]) *
                         np.nanmedian(lc[fluxap]) / 1000)

    #glsp = periodbase.pgen_lsp(times,mags,errs)
    spdm = periodbase.stellingwerf_pdm(times, mags, errs)
    blsp = periodbase.bls_parallel_pfind(times,
                                         mags,
                                         errs,
                                         startp=period_min,
                                         get_stats=False)

    objectinfo = {}
    keys = ['objectid', 'ra', 'decl', 'pmra', 'pmdecl', 'teff', 'gmag']
    hdrkeys = [
        'Gaia-ID', 'RA[deg]', 'Dec[deg]', 'PM_RA[mas/yr]', 'PM_Dec[mas/year]',
        'teff_val', 'phot_g_mean_mag'
    ]
    for k, hk in zip(keys, hdrkeys):
        if hk in hdr:
            objectinfo[k] = hdr[hk]
        else:
            objectinfo[k] = np.nan

    cp = checkplot.twolsp_checkplot_png(blsp,
                                        spdm,
                                        times,
                                        mags,
                                        errs,
                                        objectinfo=objectinfo,
                                        outfile=outpath,
                                        sigclip=[50., 5.],
                                        plotdpi=100,
                                        phasebin=3e-2,
                                        phasems=6.0,
                                        phasebinms=12.0,
                                        unphasedms=6.0)
    print('did {}'.format(outpath))
Пример #4
0
def allvar_periodogram_checkplot(a):

    ap = int(a['ap'])
    time, flux, err = a['STIME'], a[f'SPCA{ap}'], a[f'SPCAE{ap}']

    spdm = periodbase.stellingwerf_pdm(time,
                                       flux,
                                       err,
                                       magsarefluxes=True,
                                       startp=0.05,
                                       endp=30,
                                       sigclip=5.0,
                                       nworkers=nworkers)

    lsp = periodbase.pgen_lsp(time,
                              flux,
                              err,
                              magsarefluxes=True,
                              startp=0.05,
                              endp=30,
                              autofreq=True,
                              sigclip=5.0,
                              nworkers=nworkers)

    objectinfo = {}
    keys = ['objectid', 'ra', 'decl', 'pmra', 'pmdecl', 'teff', 'gmag']
    hdrkeys = [
        'Gaia-ID', 'RA_OBJ', 'DEC_OBJ', 'PM_RA[mas/yr]', 'PM_Dec[mas/year]',
        'teff_val', 'phot_g_mean_mag'
    ]
    hdr = a['dtr_infos'][0][0]
    for k, hk in zip(keys, hdrkeys):
        if hk in hdr:
            objectinfo[k] = hdr[hk]
        else:
            objectinfo[k] = np.nan

    import matplotlib as mpl
    mpl.rcParams['axes.titlesize'] = 'xx-large'
    mpl.rcParams['axes.labelsize'] = 'xx-large'

    fig = checkplot.twolsp_checkplot_png(lsp,
                                         spdm,
                                         time,
                                         flux,
                                         err,
                                         magsarefluxes=True,
                                         objectinfo=objectinfo,
                                         varepoch='min',
                                         sigclip=None,
                                         plotdpi=100,
                                         phasebin=3e-2,
                                         phasems=6.0,
                                         phasebinms=14.0,
                                         unphasedms=6.0,
                                         figsize=(30, 24),
                                         returnfigure=True,
                                         circleoverlay=APSIZEDICT[ap] * 21,
                                         yticksize=20,
                                         trimylim=True)

    axs = fig.get_axes()

    for ax in axs:
        ax.get_yaxis().set_tick_params(which='both',
                                       direction='in',
                                       labelsize='xx-large')
        ax.get_xaxis().set_tick_params(which='both',
                                       direction='in',
                                       labelsize='xx-large')

    return fig, lsp, spdm, objectinfo
Пример #5
0
def test_twolsp_checkplot_png_varepoch_handling(capsys):
    '''This tests the various different ways to give varepoch
    to twolsp_checkplot_png.

    Uses the py.test capsys fixture to capture stdout and see if we reported the
    correct epoch being used.

    '''

    outpath = os.path.join(os.path.dirname(LCPATH),
                           'test-checkplot.png')

    lcd, msg = hatlc.read_and_filter_sqlitecurve(LCPATH)
    gls = periodbase.pgen_lsp(lcd['rjd'], lcd['aep_000'], lcd['aie_000'])
    pdm = periodbase.stellingwerf_pdm(lcd['rjd'],
                                      lcd['aep_000'],
                                      lcd['aie_000'])

    assert isinstance(gls, dict)
    assert_allclose(gls['bestperiod'], 1.54289477)

    # 1. usual handling where epoch is None
    # should use min(times) as epoch all the time
    cpf = checkplot.twolsp_checkplot_png(
        gls, pdm,
        lcd['rjd'], lcd['aep_000'], lcd['aie_000'],
        outfile=outpath,
        objectinfo=lcd['objectinfo'],
        varepoch=None
    )

    assert os.path.exists(outpath)

    # capture the stdout
    captured = capsys.readouterr()

    # see if we used the correct periods and epochs
    splitout = captured.out.split('\n')

    # plot output lines
    plotoutlines = [x for x in splitout if 'plotting phased LC' in x]

    # these are the periods and epochs to match per line
    lookfor = ['period 1.542895, epoch 56092.64056',
               'period 0.771304, epoch 56092.64056',
               'period 0.514234, epoch 56092.64056',
               'period 3.085790, epoch 56092.64056',
               'period 1.542895, epoch 56092.64056',
               'period 6.157824, epoch 56092.64056']

    for expected, plotline in zip(lookfor,plotoutlines):
        assert expected in plotline


    # 2. handle varepoch = 'min'
    cpf = checkplot.twolsp_checkplot_png(
        gls, pdm,
        lcd['rjd'], lcd['aep_000'], lcd['aie_000'],
        outfile=outpath,
        objectinfo=lcd['objectinfo'],
        varepoch='min'
    )

    assert os.path.exists(outpath)

    # capture the stdout
    captured = capsys.readouterr()

    # see if we used the correct periods and epochs
    splitout = captured.out.split('\n')

    # plot output lines
    plotoutlines = [x for x in splitout if 'plotting phased LC' in x]

    # these are the periods and epochs to match per line
    lookfor = ['period 1.542895, epoch 56341.11968',
               'period 0.771304, epoch 56856.46618',
               'period 0.514234, epoch 56889.88470',
               'period 3.085790, epoch 56828.62835',
               'period 1.542895, epoch 56341.11968',
               'period 6.157824, epoch 56154.33367']

    for expected, plotline in zip(lookfor,plotoutlines):
        assert expected in plotline


    # 3. handle varepoch = some float
    cpf = checkplot.twolsp_checkplot_png(
        gls, pdm,
        lcd['rjd'], lcd['aep_000'], lcd['aie_000'],
        outfile=outpath,
        objectinfo=lcd['objectinfo'],
        varepoch=56000.5
    )

    assert os.path.exists(outpath)

    # capture the stdout
    captured = capsys.readouterr()

    # see if we used the correct periods and epochs
    splitout = captured.out.split('\n')

    # plot output lines
    plotoutlines = [x for x in splitout if 'plotting phased LC' in x]

    # these are the periods and epochs to match per line
    lookfor = ['period 1.542895, epoch 56000.50000',
               'period 0.771304, epoch 56000.50000',
               'period 0.514234, epoch 56000.50000',
               'period 3.085790, epoch 56000.50000',
               'period 1.542895, epoch 56000.50000',
               'period 6.157824, epoch 56000.50000']

    for expected, plotline in zip(lookfor,plotoutlines):
        assert expected in plotline


    # 4. handle varepoch = list of floats
    cpf = checkplot.twolsp_checkplot_png(
        gls, pdm,
        lcd['rjd'], lcd['aep_000'], lcd['aie_000'],
        outfile=outpath,
        objectinfo=lcd['objectinfo'],
        varepoch=[[56000.1,56000.2,56000.3],
                  [56000.4,56000.5,56000.6]]
    )

    assert os.path.exists(outpath)

    # capture the stdout
    captured = capsys.readouterr()

    # see if we used the correct periods and epochs
    splitout = captured.out.split('\n')

    # plot output lines
    plotoutlines = [x for x in splitout if 'plotting phased LC' in x]

    # these are the periods and epochs to match per line
    lookfor = ['period 1.542895, epoch 56000.10000',
               'period 0.771304, epoch 56000.20000',
               'period 0.514234, epoch 56000.30000',
               'period 3.085790, epoch 56000.40000',
               'period 1.542895, epoch 56000.50000',
               'period 6.157824, epoch 56000.60000']

    for expected, plotline in zip(lookfor,plotoutlines):
        assert expected in plotline
Пример #6
0
def _periodicity_analysis(hatid,
                          times,
                          mags,
                          errs,
                          normlcd,
                          varperiod=None,
                          isresidual=False):
    '''
    Given times, magnitudes, and errors, run Phase Dispersion Minimization and
    Box Least Squares, then write the phase-folded LCs, periodograms, and
    header data to a checkplot pickle.
    Typically, in 03_EB_processing.py, mags will be (data+injected planet), or
    (data + injected planet - EB model).

    Args:
        hatid (str): HAT-XXX-XXXXXXX
        times (np.array): times of measurement (typically RJD)
        mags (np.array): measured magnitudes at observing times
        errs (np.array): measured error on mags
        normlcd: lightcurve dictionary from early reading / astrobase parsing
    Keyword Args:
        varperiod (float, default None): EB period, used to set upper and lower
        bounds of frequency search.
        isresidual (bool, default False): if `mags` is from residuals, use
        this. It will do a denser frequency search, at >~2x the EB period.
    Returns:
        nothing
    '''
    #TODO: fix args, add docs

    if not varperiod:
        #injection has happened
        smallest_p = 0.5
        cpwritepre = '../data/detachedEBs/injs/checkplot-inj-'
    elif isinstance(varperiod, float) and isresidual:
        smallest_p = varperiod * 2. + 0.1
        cpwritepre = '../data/detachedEBs/injres/checkplot-injresiduals-'
    else:
        raise ValueError('smallest_p never properly assigned')

    biggest_p = min((times[-1] - times[0]) / 2.01, 100.)

    print('\nStellingwerf...\n')
    spdmp = periodbase.stellingwerf_pdm(
        times,
        mags,
        errs,
        autofreq=True,
        startp=smallest_p,
        endp=biggest_p,
        normalize=False,
        stepsize=1.0e-5,
        phasebinsize=0.03,
        mindetperbin=9,
        nbestpeaks=5,
        periodepsilon=0.1,  # 0.1days
        sigclip=None,  # no sigma clipping
        nworkers=None)

    varinfo = {
        'objectisvar': True,
        'vartags': None,
        'varisperiodic': True,
        'varperiod': spdmp['bestperiod'],
        'varepoch': None
    }

    print('\nBLS...\n')
    blsp = periodbase.bls_parallel_pfind(times,
                                         mags,
                                         errs,
                                         startp=smallest_p,
                                         endp=biggest_p,
                                         stepsize=1.0e-5,
                                         mintransitduration=0.01,
                                         maxtransitduration=0.6,
                                         nphasebins=200,
                                         autofreq=False,
                                         nbestpeaks=5,
                                         periodepsilon=0.1,
                                         nworkers=None,
                                         sigclip=None)

    lspinfolist = [spdmp, blsp]
    cp = checkplot.checkplot_pickle(lspinfolist,
                                    times,
                                    mags,
                                    errs,
                                    nperiodstouse=3,
                                    objectinfo=normlcd['objectinfo'],
                                    varinfo=varinfo,
                                    findercmap='gray_r',
                                    normto='globalmedian',
                                    normmingap=4.,
                                    outfile=cpwritepre + hatid + '.pkl.gz',
                                    sigclip=[10., -3.],
                                    varepoch='min',
                                    phasewrap=True,
                                    phasesort=True,
                                    phasebin=0.002,
                                    plotxlim=[-0.6, 0.6],
                                    plotdpi=150,
                                    returndict=False,
                                    pickleprotocol=3,
                                    greenhighlight=False,
                                    xgridlines=[-0.5, 0., 0.5])

    #since we don't have easy checkplot_pickle to png written yet, use twolsp_checkplot_png
    #TODO: remove any png writing once happy with output
    if not varperiod:
        injpath = '../data/detachedEBs/plots/3_checkplot-inj-'
    elif isinstance(varperiod, float) and isresidual:
        injpath = '../data/detachedEBs/plots/5_checkplot-injresiduals-'
    else:
        raise ValueError('injpath never properly assigned')

    checkplot.twolsp_checkplot_png(spdmp,
                                   blsp,
                                   times,
                                   mags,
                                   errs,
                                   objectinfo=normlcd['objectinfo'],
                                   findercmap='gray_r',
                                   normto='globalmedian',
                                   normmingap=4.,
                                   outfile=injpath + hatid + '.png',
                                   sigclip=[10., -3.],
                                   varepoch='min',
                                   phasewrap=True,
                                   phasesort=True,
                                   phasebin=0.002,
                                   plotxlim=[-0.6, 0.6],
                                   plotdpi=150)
    plt.close('all')