def give_me_n_best_periods(i,model,n):

	# It's finding the rr_lyraes by index + fit that you specify
    rrlyrae = fetch_rrlyrae()
    lcid = rrlyrae.ids[i]
    t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
    metadata = rrlyrae.get_metadata(lcid)
    
    # these are the ids of the rr lyrae
    idx_of_plot = i
    lcid = rrlyrae.ids[i]
    metadata = rrlyrae.get_metadata(lcid)
    t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
    
    # Number of observations - original size
    nobs = t.size
    
    # Number of Observations + down-sampled n best periods to be returned
    returned_list=[]
    
    # Spelling out the number of periods that you gave
    no_of_periods_specified = n 
    
    # Let's fit it
    model.optimizer.period_range = (0.1, 1.) 
    
    # This is all fitted with 4.2 Truncated Fourier Models with VanderPlas paper
    model.fit(t,mag,dmag)
    model.best_period  
        
    # Finding the periods, and then sorting it by argument of the strongest power(score)
    periods = np.linspace(0.1, 1., 10000)
    scores = model.score(periods)
    idx = np.argsort(scores)
    ##tze_periods = periods[idx[-5:]]
    ##tze_scores = scores[idx[-5:]]
    tze_periods = np.array([])
    threshold = 5E-3
    for period in periods[idx][::-1]:
        if (np.abs(tze_periods - period) > threshold).all() or (len(tze_periods) < 1):
            tze_periods = np.append(tze_periods, [period])
        
        if len(tze_periods) >= no_of_periods_specified:
            break
    tze_periods = tze_periods[::-1]    
    ##print(tze_periods)
    ##print(tze_scores)
        
    # Getting the infomation to be returned
    ##No. of observations, 'n' number of periods, and the system's best ave
    combo = nobs,tze_periods,metadata['P']
    returned_list.append(combo)
    ##print(no_of_periods_specified,'no_of_periods_specified')
    
    return returned_list
예제 #2
0
def plot_LSST_sims(outfile, pointing_indices, ndays, gmags, template_indices):
    results_multi = 'resultsLSST.npy'
    results_ssm = 'resultsLSST_ssm_{0}.npy'

    # Get measured periods
    Pobs_multi = gather_results(results_multi,
                                pointing_indices=pointing_indices,
                                ndays=ndays,
                                gmags=gmags,
                                template_indices=template_indices)
    Pobs_multi[np.isnan(Pobs_multi)] = 0

    Pobs_ssm = np.array([gather_results(results_ssm.format(band),
                                        pointing_indices=pointing_indices,
                                        ndays=ndays,
                                        gmags=gmags,
                                        template_indices=template_indices)
                         for band in 'ugriz'])
    Pobs_ssm = Pobs_ssm[:, :, :, :, :, 0].transpose(1, 2, 3, 4, 0)
    Pobs_ssm[np.isnan(Pobs_ssm)] = 0

    # Get true periods
    rrlyrae = fetch_rrlyrae()
    Ptrue = np.reshape([rrlyrae.get_metadata(rrlyrae.ids[i])['P']
                        for i in template_indices.ravel()],
                       template_indices.shape)

    # Check for matches
    dphimax = 0.37
    matches_multi = olusei_period_criterion(Pobs_multi,
                                            Ptrue.reshape(Ptrue.shape + (1,)),
                                            ndays.reshape(ndays.shape + (1,)),
                                            dphimax=dphimax)
    results_multi = np.any(matches_multi, -1).mean(-1).mean(-1)

    matches_ssm = olusei_period_criterion(Pobs_ssm,
                                          Ptrue.reshape(Ptrue.shape + (1,)),
                                          ndays.reshape(ndays.shape + (1,)),
                                          dphimax=dphimax)
    results_ssm = np.any(matches_ssm, -1).mean(-1).mean(-1)

    fig, ax = plt.subplots()
    for t, frac_multi, frac_ssm in reversed(list(zip(ndays.ravel(),
                                                     results_multi.T,
                                                     results_ssm.T))):
        line = ax.plot(gmags.ravel(), frac_multi,
                       label='{0:.1f} years'.format(t / 365))
        ax.fill_between(gmags.ravel(), frac_ssm, frac_multi,
                        edgecolor='none',
                        facecolor=line[0].get_color(), alpha=0.3)
    ax.legend(loc='lower left')
    ax.set(xlabel='g-band magnitude',
           ylabel='Fraction of Periods among Top-5',
           title='Multiband Improvement over SuperSmoother for LSST',
           xlim=(20, 24.5), ylim=(0, 1))
예제 #3
0
def test_calc_sig_levels_cases():
    r"""Pytest cases for code/utils.py:
    calc_sig_levels

    """

    # Define function for testing cases.
    def test_calc_sig_levels(model,
                             sig_periods,
                             ref_sig_powers,
                             sigs=(95.0, 99.0),
                             num_shuffles=100):
        r"""Pytest for code/utils.py:
        calc_sig_levels

        """
        test_sig_powers = code.utils.calc_sig_levels(model=model,
                                                     sig_periods=sig_periods,
                                                     sigs=sigs,
                                                     num_shuffles=num_shuffles)
        for key in ref_sig_powers:
            assert np.all(np.isclose(ref_sig_powers[key],
                                     test_sig_powers[key]))
        return None

    # Test adapted from
    # https://github.com/astroML/gatspy/blob/master/examples/MultiBand.ipynb
    rrlyrae = gatspy_data.fetch_rrlyrae()
    lcid = rrlyrae.ids[0]
    (times, mags, mags_err, filts) = rrlyrae.get_lightcurve(lcid)
    model = gatspy_per.LombScargleMultiband(Nterms_base=6, Nterms_band=1)
    model.fit(t=times, y=mags, dy=mags_err, filts=filts)
    (min_period, max_period, _) = code.utils.calc_period_limits(times=times)
    model.optimizer.period_range = (min_period, max_period)
    sigs = (95.0, 99.0)
    num_shuffles = 100
    sig_periods = \
        [1.66051856e+03, 2.99875187e-02, 1.49938947e-02, 9.99595991e-03,
         7.49698121e-03, 5.99759039e-03, 4.99799500e-03, 4.28399755e-03,
         3.74849907e-03, 3.33200001e-03]
    ref_sig_powers = \
        {95.0: \
            [0.25057282, 0.26775067, 0.25570964, 0.27631931, 0.26301363,
             0.26418357, 0.2457524 , 0.24058861, 0.24839262, 0.24550175],
         99.0: \
            [0.32243259, 0.31730944, 0.29074282, 0.33228392, 0.29340864,
             0.29399481, 0.26595011, 0.26355087, 0.29701109, 0.2730018]}
    test_calc_sig_levels(model=model,
                         sig_periods=sig_periods,
                         ref_sig_powers=ref_sig_powers,
                         sigs=sigs,
                         num_shuffles=num_shuffles)
    # TODO: insert additional test cases here.
    return None
예제 #4
0
def test_ls_model_fluxes_rel_cases():
    r"""Pytest cases for code/utils.py:
    ls_model_fluxes_rel

    """

    # Define function for testing cases.
    def test_ls_model_fluxes_rel(params, model, ref_modeled_fluxes_rel):
        r"""Pytest for code/utils.py:
        ls_model_fluxes_rel

        """
        test_modeled_fluxes_rel = code.utils.ls_model_fluxes_rel(params=params,
                                                                 model=model)
        assert np.all(
            np.isclose(ref_modeled_fluxes_rel, test_modeled_fluxes_rel))
        return None

    # Test adapted from
    # https://github.com/astroML/gatspy/blob/master/examples/MultiBand.ipynb
    rrlyrae = gatspy_data.fetch_rrlyrae()
    lcid = rrlyrae.ids[0]
    (times, mags, mags_err, filts) = rrlyrae.get_lightcurve(lcid)
    fluxes_rel = np.empty_like(mags)
    fluxes_rel_err = np.empty_like(mags_err)
    for filt in np.unique(filts):
        tfmask = (filt == filts)
        fluxes_rel[tfmask] = \
            map(lambda mag_1: \
                    bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=np.median(mags[tfmask])),
                mags[tfmask])
        fluxes_rel_err[tfmask] = \
            map(lambda mag_1, mag_2: \
                    abs(1.0 - bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=mag_2)),
                np.add(mags[tfmask], mags_err[tfmask]),
                mags[tfmask])
    model = gatspy_per.LombScargleMultiband(Nterms_base=6, Nterms_band=1)
    best_period = rrlyrae.get_metadata(lcid)['P']
    params = (best_period)
    model.fit(t=times, y=fluxes_rel, dy=fluxes_rel_err, filts=filts)
    test_ls_model_fluxes_rel(params=params,
                             model=model,
                             ref_modeled_fluxes_rel=model.predict(
                                 t=model.t,
                                 filts=model.filts,
                                 period=best_period))
    # TODO: insert additional test cases here.
    return None
예제 #5
0
def test_ls_model_fluxes_rel_cases():
    r"""Pytest cases for code/utils.py:
    ls_model_fluxes_rel

    """
    # Define function for testing cases.
    def test_ls_model_fluxes_rel(params, model, ref_modeled_fluxes_rel):
        r"""Pytest for code/utils.py:
        ls_model_fluxes_rel

        """
        test_modeled_fluxes_rel = code.utils.ls_model_fluxes_rel(
            params=params, model=model)
        assert np.all(np.isclose(
            ref_modeled_fluxes_rel, test_modeled_fluxes_rel))
        return None
    # Test adapted from
    # https://github.com/astroML/gatspy/blob/master/examples/MultiBand.ipynb
    rrlyrae = gatspy_data.fetch_rrlyrae()
    lcid = rrlyrae.ids[0]
    (times, mags, mags_err, filts) = rrlyrae.get_lightcurve(lcid)
    fluxes_rel = np.empty_like(mags)
    fluxes_rel_err = np.empty_like(mags_err)
    for filt in np.unique(filts):
        tfmask = (filt == filts)
        fluxes_rel[tfmask] = \
            map(lambda mag_1: \
                    bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=np.median(mags[tfmask])),
                mags[tfmask])
        fluxes_rel_err[tfmask] = \
            map(lambda mag_1, mag_2: \
                    abs(1.0 - bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=mag_2)),
                np.add(mags[tfmask], mags_err[tfmask]),
                mags[tfmask])
    model = gatspy_per.LombScargleMultiband(Nterms_base=6, Nterms_band=1)
    best_period = rrlyrae.get_metadata(lcid)['P']
    params = (best_period)
    model.fit(t=times, y=fluxes_rel, dy=fluxes_rel_err, filts=filts)
    test_ls_model_fluxes_rel(
        params=params, model=model,
        ref_modeled_fluxes_rel=model.predict(
            t=model.t, filts=model.filts, period=best_period))
    # TODO: insert additional test cases here.
    return None
예제 #6
0
def test_calc_sig_levels_cases():
    r"""Pytest cases for code/utils.py:
    calc_sig_levels

    """
    # Define function for testing cases.
    def test_calc_sig_levels(
        model, sig_periods, ref_sig_powers, sigs=(95.0, 99.0),
        num_shuffles=100):
        r"""Pytest for code/utils.py:
        calc_sig_levels

        """
        test_sig_powers = code.utils.calc_sig_levels(
            model=model, sig_periods=sig_periods, sigs=sigs,
            num_shuffles=num_shuffles)
        for key in ref_sig_powers:
            assert np.all(np.isclose(ref_sig_powers[key], test_sig_powers[key]))
        return None
    # Test adapted from
    # https://github.com/astroML/gatspy/blob/master/examples/MultiBand.ipynb
    rrlyrae = gatspy_data.fetch_rrlyrae()
    lcid = rrlyrae.ids[0]
    (times, mags, mags_err, filts) = rrlyrae.get_lightcurve(lcid)
    model = gatspy_per.LombScargleMultiband(Nterms_base=6, Nterms_band=1)
    model.fit(t=times, y=mags, dy=mags_err, filts=filts)
    (min_period, max_period, _) = code.utils.calc_period_limits(times=times)
    model.optimizer.period_range = (min_period, max_period)
    sigs = (95.0, 99.0)
    num_shuffles = 100
    sig_periods = \
        [1.66051856e+03, 2.99875187e-02, 1.49938947e-02, 9.99595991e-03,
         7.49698121e-03, 5.99759039e-03, 4.99799500e-03, 4.28399755e-03,
         3.74849907e-03, 3.33200001e-03]
    ref_sig_powers = \
        {95.0: \
            [0.25057282, 0.26775067, 0.25570964, 0.27631931, 0.26301363,
             0.26418357, 0.2457524 , 0.24058861, 0.24839262, 0.24550175],
         99.0: \
            [0.32243259, 0.31730944, 0.29074282, 0.33228392, 0.29340864,
             0.29399481, 0.26595011, 0.26355087, 0.29701109, 0.2730018]}
    test_calc_sig_levels(
        model=model, sig_periods=sig_periods, ref_sig_powers=ref_sig_powers,
        sigs=sigs, num_shuffles=num_shuffles)
    # TODO: insert additional test cases here.
    return None
def give_me_nobs(i,model,n):
	
    # It's finding the rr_lyraes by index + fit that you specify
    rrlyrae = fetch_rrlyrae()
    lcid = rrlyrae.ids[i]
    t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
    metadata = rrlyrae.get_metadata(lcid)
    
    # these are the ids of the rr lyrae
    idx_of_plot = i
    lcid = rrlyrae.ids[i]
    metadata = rrlyrae.get_metadata(lcid)
    t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
    
    # Number of observations - original size
    nobs = t.size
    
    return nobs
예제 #8
0
def rr_info(i):
	'''
	This function takes all the rr_lyrae info in one convenient package

	Parameters
	----------  
	i : <type 'int'>
		The index number of light curve you want to examine
	
	Returns
	-------
	t: <type 'numpy.ndarray'>
		The time/period of each of the light curve of each RR_Lyrae

	mag: <type 'numpy.ndarray'>
		The magnitude of each of the light curve of each RR_Lyrae

	dmag: <type 'numpy.ndarray'>
		The error in magnitude of each of the light curve of each RR_Lyrae

	nobs: <type 'int'>
		The number of observations

	metadata: <type 'numpy.void'>
		All the information of each RR_Lyrae. Most important is metadata['P'] = Period

	'''
	# It's finding the rr_lyraes by index + fit that you specify
	rrlyrae = fetch_rrlyrae()
	lcid = rrlyrae.ids[i]
	t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)

	# Number of observations - original size
	nobs = t.size
	
	# The data with all the magnitude in different filter bands + Period
	metadata = rrlyrae.get_metadata(lcid)
		
	
	return t,mag,dmag,metadata,nobs
예제 #9
0
from gatspy import datasets, periodic
rrlyrae = datasets.fetch_rrlyrae()
lcid = rrlyrae.ids[0]
t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
mask = (filts == 'r')
t_r, mag_r, dmag_r = t[mask], mag[mask], dmag[mask]
model = periodic.LombScargleFast(fit_period=True)
model.optimizer.period_range = (0.2, 1.2)
model.fit(t_r, mag_r, dmag_r)
print(model.best_period)
metadata = rrlyrae.get_metadata(lcid)
true_period = metadata['P']
print(true_period)
import numpy as np
tfit = np.linspace(0, model.best_period, 4)
print(model.predict(tfit))
model = periodic.LombScargleFast(fit_period=True)
model.optimizer.period_range = (0.2, 1.2)
model.fit(t_r, mag_r, dmag_r)
print(model.best_period)
model = periodic.LombScargleFast(fit_period=True)
model.optimizer.set(period_range=(0.5, 0.7), first_pass_coverage=10)
model.fit(t_r, mag_r, dmag_r)
print(model.best_period)
예제 #10
0
def plot_LSST_sims(outfile, pointing_indices, ndays, gmags, template_indices):
    results_multi = 'resultsLSST.npy'
    results_ssm = 'resultsLSST_ssm_{0}.npy'

    # Get measured periods
    Pobs_multi = gather_results(results_multi,
                                pointing_indices=pointing_indices,
                                ndays=ndays,
                                gmags=gmags,
                                template_indices=template_indices)
    Pobs_multi[np.isnan(Pobs_multi)] = 0

    Pobs_ssm = np.array([
        gather_results(results_ssm.format(band),
                       pointing_indices=pointing_indices,
                       ndays=ndays,
                       gmags=gmags,
                       template_indices=template_indices) for band in 'ugriz'
    ])
    Pobs_ssm = Pobs_ssm[:, :, :, :, :, 0].transpose(1, 2, 3, 4, 0)
    Pobs_ssm[np.isnan(Pobs_ssm)] = 0

    # Get true periods
    rrlyrae = fetch_rrlyrae()
    Ptrue = np.reshape([
        rrlyrae.get_metadata(rrlyrae.ids[i])['P']
        for i in template_indices.ravel()
    ], template_indices.shape)

    # Check for matches
    dphimax = 0.37
    matches_multi = olusei_period_criterion(Pobs_multi,
                                            Ptrue.reshape(Ptrue.shape + (1, )),
                                            ndays.reshape(ndays.shape + (1, )),
                                            dphimax=dphimax)
    results_multi = np.any(matches_multi, -1).mean(-1).mean(-1)

    matches_ssm = olusei_period_criterion(Pobs_ssm,
                                          Ptrue.reshape(Ptrue.shape + (1, )),
                                          ndays.reshape(ndays.shape + (1, )),
                                          dphimax=dphimax)
    results_ssm = np.any(matches_ssm, -1).mean(-1).mean(-1)

    fig, ax = plt.subplots()
    for t, frac_multi, frac_ssm in reversed(
            list(zip(ndays.ravel(), results_multi.T, results_ssm.T))):
        line = ax.plot(gmags.ravel(),
                       frac_multi,
                       label='{0:.1f} years'.format(t / 365))
        ax.fill_between(gmags.ravel(),
                        frac_ssm,
                        frac_multi,
                        edgecolor='none',
                        facecolor=line[0].get_color(),
                        alpha=0.3)
    ax.legend(loc='lower left')
    ax.set(xlabel='g-band magnitude',
           ylabel='Fraction of Periods among Top-5',
           title='Multiband Improvement over SuperSmoother for LSST',
           xlim=(20, 24.5),
           ylim=(0, 1))
def Give_Me_Light_Curves_Down_Sampled(i,nobs,model,n,d_array):

    # Number of Observations + down-sampled n best periods to be returned
    returned_list=[]
    
    # Spelling out the number of periods that you gave
    no_of_periods_specified = n 
    
    # It's finding the rr_lyraes by index + fit that you specify
    rrlyrae = fetch_rrlyrae()
    lcid = rrlyrae.ids[i]
    t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
    metadata = rrlyrae.get_metadata(lcid)
    
    # these are the ids of the rr lyrae
    idx_of_plot = i
    lcid = rrlyrae.ids[i]
    metadata = rrlyrae.get_metadata(lcid)
    t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
    
    for items in d_array:
        
        # Down-sampling the data !!
        nobs = items
        legend ='# of Observation:',nobs
        dd = random.sample(zip(t,mag,dmag), nobs)
        
        # Shuffling the random sample back to their respective houses 
        ee = []
        ff= []
        gg = []
        for i in range(len(dd)):
            ee.append(dd[i][0])
            ff.append(dd[i][1])
            gg.append(dd[i][2])
        t = np.asarray(ee)   
        mag = np.asarray(ff)
        dmag = np.asarray(gg)
            
        # Let's fit it
        model.optimizer.period_range = (0.1, 1.) 
    
        # This is all fitted with 4.2 Truncated Fourier Models with VanderPlas paper
        model.fit(t,mag,dmag)
        model.best_period  
        
        # Finding the periods, and then sorting it by argument of the strongest power(score)
        periods = np.linspace(0.1, 1., 10000)
        scores = model.score(periods)
        idx = np.argsort(scores)
        ##tze_periods = periods[idx[-5:]]
        ##tze_scores = scores[idx[-5:]]
        tze_periods = np.array([])
        threshold = 5E-3
        for period in periods[idx][::-1]:
            if (np.abs(tze_periods - period) > threshold).all() or (len(tze_periods) < 1):
                tze_periods = np.append(tze_periods, [period])
        
            if len(tze_periods) >= no_of_periods_specified:
                break
        tze_periods = tze_periods[::-1]    
        ##print(tze_periods)
        ##print(tze_scores)
        
        # Getting the infomation to be returned
        ##No. of observations, 'n' number of periods, and the system's best ave
        combo = nobs,tze_periods,metadata['P']
        returned_list.append(combo)
        ##print(no_of_periods_specified,'no_of_periods_specified')
 
    return returned_list
예제 #12
0
                        bottom=0.15,
                        top=0.9)

    colors = seaborn.color_palette()

    plot_period_comparison(ax[0], ssm_periods, sesar_periods, color=colors[0])
    plot_period_comparison(ax[1], mbls_periods, sesar_periods, color=colors[1])

    ax[0].set_xlabel('supersmoother period (days)')
    ax[0].set_ylabel('Sesar 2010 period (days)')
    ax[1].set_xlabel('multiband period (days)')

    ax[0].set_title("SuperSmoother (g-band)", y=1.04)
    ax[1].set_title("Shared-phase Multiband", y=1.04)

    return fig, ax


if __name__ == '__main__':
    rrlyrae = fetch_rrlyrae()
    lcid = list(rrlyrae.ids)[482]

    fig, ax = plot_example_lightcurve(rrlyrae, lcid)
    fig.savefig('fig07a.pdf')

    fig, ax = plot_periods(ssm_file='S82sims/res_supersmoother_g.npy',
                           mbls_file='S82sims/res_multiband_1_0.npy',
                           rrlyrae=rrlyrae)
    fig.savefig('fig07b.pdf')
    plt.show()
예제 #13
0
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

from gatspy.datasets import fetch_rrlyrae


rrlyrae = fetch_rrlyrae()
rrlyrae_partial = fetch_rrlyrae(partial=True)

data = [rrlyrae.get_lightcurve(lcid)
        for lcid in rrlyrae.ids]
data_partial = [rrlyrae_partial.get_lightcurve(lcid)
                for lcid in rrlyrae.ids]

tminmax = np.array([[t.min(), t.max()] for t,_,_,_ in data])
print(tminmax.min(0), tminmax.max(0))

counts = np.array([[np.sum(filts == f) for f in 'ugriz']
                   for t, y, dy, filts in data])
counts_partial = np.array([[np.sum(filts == f) for f in 'ugriz']
                           for t, y, dy, filts in data_partial])

print(np.mean(counts, 0), np.median(counts, 0))
print(np.mean(counts_partial, 0), np.median(counts_partial, 0))


fig, ax = plt.subplots(2)
sns.violinplot(counts, ax=ax[0], names='ugriz')
sns.violinplot(counts_partial, ax=ax[1], names='ugriz')
예제 #14
0
def test_calc_min_flux_time_cases():
    r"""pytest cases for code/utils.py:
    calc_min_flux_time

    """

    # Define function for testing cases.
    def test_calc_min_flux_time(model,
                                filt,
                                ref_min_flux_time,
                                best_period=None,
                                lwr_time_bound=None,
                                upr_time_bound=None,
                                tol=0.1,
                                maxiter=10):
        r"""Pytest for code/utils.py:
        calc_min_flux_time

        """
        test_min_flux_time = \
            code.utils.calc_min_flux_time(
                model=model, filt=filt, best_period=best_period,
                lwr_time_bound=lwr_time_bound, upr_time_bound=upr_time_bound,
                tol=tol, maxiter=maxiter)
        assert np.isclose(ref_min_flux_time, test_min_flux_time)
        return None

    # Test adapted from
    # https://github.com/astroML/gatspy/blob/master/examples/MultiBand.ipynb
    rrlyrae = gatspy_data.fetch_rrlyrae()
    lcid = rrlyrae.ids[0]
    (times, mags, mags_err, filts) = rrlyrae.get_lightcurve(lcid)
    fluxes_rel = np.empty_like(mags)
    fluxes_rel_err = np.empty_like(mags_err)
    for filt in np.unique(filts):
        tfmask = (filt == filts)
        fluxes_rel[tfmask] = \
            map(lambda mag_1: \
                    bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=np.median(mags[tfmask])),
                mags[tfmask])
        fluxes_rel_err[tfmask] = \
            map(lambda mag_1, mag_2: \
                    abs(1.0 - bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=mag_2)),
                np.add(mags[tfmask], mags_err[tfmask]),
                mags[tfmask])
    model = gatspy_per.LombScargleMultiband(Nterms_base=6, Nterms_band=1)
    best_period = rrlyrae.get_metadata(lcid)['P']
    model.fit(t=times, y=fluxes_rel, dy=fluxes_rel_err, filts=filts)
    min_flux_time_init = \
        code.utils.calc_min_flux_time(
            model=model, filt='z', best_period=best_period, tol=0.1, maxiter=10)
    for (filt, ref_min_flux_time) in \
        zip(['u', 'g', 'r', 'i', 'z'],
            [0.370657590606, 0.366563989108, 0.375194445097, 0.377970590837,
             0.378704402065]):
        time_window_halfwidth = 0.1 * best_period
        test_calc_min_flux_time(
            model=model,
            filt=filt,
            ref_min_flux_time=ref_min_flux_time,
            best_period=best_period,
            lwr_time_bound=min_flux_time_init - time_window_halfwidth,
            upr_time_bound=min_flux_time_init + time_window_halfwidth,
            tol=1e-5,
            maxiter=10)
    # TODO: insert additional test cases here.
    return None
예제 #15
0
                            find_periods,
                            lcids,
                            save_every=save_every,
                            parallel=parallel,
                            client=client)


def gather_results(outfile, ids):
    if not os.path.exists(outfile):
        raise ValueError("Cannot gather results from {0}".format(outfile))
    results = NumpyCache(outfile)
    return np.array([results.get_row(lcid) for lcid in ids])


if __name__ == '__main__':
    rrlyrae = fetch_rrlyrae()
    rrlyrae_partial = fetch_rrlyrae(partial=True)

    parallel = True
    ssm_bands = ['g']

    if parallel:
        # Need some imports on the engine
        from IPython.parallel import Client
        client = Client()
        dview = client.direct_view()
        with dview.sync_imports():
            from gatspy.periodic import (LombScargleMultiband, SuperSmoother,
                                         SuperSmootherMultiband)

        # Make sure necessary data is fetched on all clients.
예제 #16
0
    colors = seaborn.color_palette()

    plot_period_comparison(ax[0], ssm_periods, sesar_periods,
                           color=colors[0])
    plot_period_comparison(ax[1], mbls_periods, sesar_periods,
                           color=colors[1])

    ax[0].set_xlabel('supersmoother period (days)')
    ax[0].set_ylabel('Sesar 2010 period (days)')
    ax[1].set_xlabel('multiband period (days)')

    ax[0].set_title("SuperSmoother (g-band)", y=1.04)
    ax[1].set_title("Shared-phase Multiband", y=1.04)

    return fig, ax


if __name__ == '__main__':
    rrlyrae = fetch_rrlyrae()
    lcid = list(rrlyrae.ids)[482]

    fig, ax = plot_example_lightcurve(rrlyrae, lcid)
    fig.savefig('fig07a.pdf')

    fig, ax = plot_periods(ssm_file='S82sims/res_supersmoother_g.npy',
                           mbls_file='S82sims/res_multiband_1_0.npy',
                           rrlyrae=rrlyrae)
    fig.savefig('fig07b.pdf')
    plt.show()
    
예제 #17
0
 def __init__(self, lsst_file=LSST_FILE):
     self.pointings = self._load_sims(lsst_file)
     self.S82data = fetch_rrlyrae()
예제 #18
0
 def __init__(self, lsst_file=LSST_FILE):
     self.pointings = self._load_sims(lsst_file)
     self.S82data = fetch_rrlyrae()
예제 #19
0
def test_calc_min_flux_time_cases():
    r"""pytest cases for code/utils.py:
    calc_min_flux_time

    """
    # Define function for testing cases.
    def test_calc_min_flux_time(
        model, filt, ref_min_flux_time, best_period=None,
        lwr_time_bound=None, upr_time_bound=None, tol=0.1, maxiter=10):
        r"""Pytest for code/utils.py:
        calc_min_flux_time

        """
        test_min_flux_time = \
            code.utils.calc_min_flux_time(
                model=model, filt=filt, best_period=best_period,
                lwr_time_bound=lwr_time_bound, upr_time_bound=upr_time_bound,
                tol=tol, maxiter=maxiter)
        assert np.isclose(ref_min_flux_time, test_min_flux_time)
        return None
    # Test adapted from
    # https://github.com/astroML/gatspy/blob/master/examples/MultiBand.ipynb
    rrlyrae = gatspy_data.fetch_rrlyrae()
    lcid = rrlyrae.ids[0]
    (times, mags, mags_err, filts) = rrlyrae.get_lightcurve(lcid)
    fluxes_rel = np.empty_like(mags)
    fluxes_rel_err = np.empty_like(mags_err)
    for filt in np.unique(filts):
        tfmask = (filt == filts)
        fluxes_rel[tfmask] = \
            map(lambda mag_1: \
                    bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=np.median(mags[tfmask])),
                mags[tfmask])
        fluxes_rel_err[tfmask] = \
            map(lambda mag_1, mag_2: \
                    abs(1.0 - bss.utils.calc_flux_intg_ratio_from_mags(
                        mag_1=mag_1,
                        mag_2=mag_2)),
                np.add(mags[tfmask], mags_err[tfmask]),
                mags[tfmask])
    model = gatspy_per.LombScargleMultiband(Nterms_base=6, Nterms_band=1)
    best_period = rrlyrae.get_metadata(lcid)['P']
    model.fit(t=times, y=fluxes_rel, dy=fluxes_rel_err, filts=filts)
    min_flux_time_init = \
        code.utils.calc_min_flux_time(
            model=model, filt='z', best_period=best_period, tol=0.1, maxiter=10)
    for (filt, ref_min_flux_time) in \
        zip(['u', 'g', 'r', 'i', 'z'],
            [0.370657590606, 0.366563989108, 0.375194445097, 0.377970590837,
             0.378704402065]):
        time_window_halfwidth = 0.1 * best_period
        test_calc_min_flux_time(
            model=model, filt=filt, ref_min_flux_time=ref_min_flux_time,
            best_period=best_period,
            lwr_time_bound=min_flux_time_init - time_window_halfwidth,
            upr_time_bound=min_flux_time_init + time_window_halfwidth,
            tol=1e-5, maxiter=10)
    # TODO: insert additional test cases here.
    return None