def test_pl(filename=os.path.join(TMP,'test_pl.h5')):
    mass = (0.83,0.03)
    radius = (0.91,0.03)
    period = 289.8622
    rprs = 0.02
    starmodel_file = resource_filename('vespa','tests/test_starmodel_single.h5')
    starmodel = StarModel.load_hdf(starmodel_file)
    pop = PlanetPopulation(period=period, rprs=rprs,
                       starmodel=starmodel, n=100, MAfn=MAfn)

    pop.save_hdf(filename, overwrite=True)
    pop2 = PlanetPopulation.load_hdf(filename)
    assert type(pop2)==PlanetPopulation
    os.remove(filename)
Example #2
0
    def __init__(self, koi, recalc=False,
                 use_JRowe=True, trsig_kws=None,
                 tag=None, starmodel_mcmc_kws=None,
                 **kwargs):

        koi = koiname(koi)

        #if saved popset exists, load
        folder = os.path.join(KOI_FPPDIR,koi)
        if tag is not None:
            folder += '_{}'.format(tag)

        if not os.path.exists(folder):
            os.makedirs(folder)

        if trsig_kws is None:
            trsig_kws = {}

        #first check if pickled signal is there to be loaded
        trsigfile = os.path.join(folder,'trsig.pkl')
        if os.path.exists(trsigfile):
            trsig = pickle.load(open(trsigfile,'rb'))
        else:
            if use_JRowe:
                trsig = JRowe_KeplerTransitSignal(koi, **trsig_kws)
            else:
                trsig = KeplerTransitSignal(koi, **trsig_kws)

        popsetfile = os.path.join(folder,'popset.h5')
        if os.path.exists(popsetfile) and not recalc:
            popset = PopulationSet(popsetfile, **kwargs)

        else:
            koinum = koiname(koi, koinum=True)
            kepid = ku.DATA.ix[koi,'kepid']

            if 'mass' not in kwargs:
                kwargs['mass'] = koi_propdist(koi, 'mass')
            if 'radius' not in kwargs:
                kwargs['radius'] = koi_propdist(koi, 'radius')
            if 'feh' not in kwargs:
                kwargs['feh'] = koi_propdist(koi, 'feh')
            if 'age' not in kwargs:
                try:
                    kwargs['age'] = koi_propdist(koi, 'age')
                except:
                    kwargs['age'] = (9.7,0.1) #default age
            if 'Teff' not in kwargs:
                kwargs['Teff'] = kicu.DATA.ix[kepid,'teff']
            if 'logg' not in kwargs:
                kwargs['logg'] = kicu.DATA.ix[kepid,'logg']
            if 'rprs' not in kwargs:
                if use_JRowe:
                    kwargs['rprs'] = trsig.rowefit.ix['RD1','val']
                else:
                    kwargs['rprs'] = ku.DATA.ix[koi,'koi_ror']
                    
            #if stellar properties are determined spectroscopically,
            # fit stellar model
            if 'starmodel' not in kwargs:
                if re.match('SPE', kicu.DATA.ix[kepid, 'teff_prov']):
                    logging.info('Spectroscopically determined stellar properties.')
                    #first, see if there already is a starmodel to load

                    #fit star model
                    Teff = kicu.DATA.ix[kepid, 'teff']
                    e_Teff = kicu.DATA.ix[kepid, 'teff_err1']
                    logg = kicu.DATA.ix[kepid, 'logg']
                    e_logg = kicu.DATA.ix[kepid, 'logg_err1']
                    feh = kicu.DATA.ix[kepid, 'feh']
                    e_feh = kicu.DATA.ix[kepid, 'feh_err1']
                    logging.info('fitting StarModel (Teff=({},{}), logg=({},{}), feh=({},{}))...'.format(Teff, e_Teff, logg, e_logg, feh, e_feh))

                    dar = Dartmouth_Isochrone()
                    starmodel = StarModel(dar, Teff=(Teff, e_Teff),
                                          logg=(logg, e_logg),
                                          feh=(feh, e_feh))
                    if starmodel_mcmc_kws is None:
                        starmodel_mcmc_kws = {}
                    starmodel.fit(**starmodel_mcmc_kws)
                    logging.info('Done.')
                    kwargs['starmodel'] = starmodel
                


            if 'mags' not in kwargs:
                kwargs['mags'] = ku.KICmags(koi)
            if 'ra' not in kwargs:
                kwargs['ra'], kwargs['dec'] = ku.radec(koi)
            if 'period' not in kwargs:
                kwargs['period'] = ku.DATA.ix[koi,'koi_period']

            if 'pl_kws' not in kwargs:
                kwargs['pl_kws'] = {}

            if 'fp_specific' not in kwargs['pl_kws']:
                rp = kwargs['radius'].mu * kwargs['rprs'] * RSUN/REARTH
                kwargs['pl_kws']['fp_specific'] = fp_fressin(rp)

            #trilegal_filename = os.path.join(folder,'starfield.h5')
            trilegal_filename = kepler_starfield_file(koi)
            popset = PopulationSet(trilegal_filename=trilegal_filename,
                                   **kwargs)
            #popset.save_hdf('{}/popset.h5'.format(folder), overwrite=True)


        lhoodcachefile = os.path.join(folder,'lhoodcache.dat')
        self.koi = koi
        FPPCalculation.__init__(self, trsig, popset,
                                folder=folder)
        self.save()
        self.apply_default_constraints()
Example #3
0
#rank = comm.Get_rank()

for n in range(100,200,1):
    if n < 10:
        i = '0' + str(n)
    else:
        i = str(n)

    #same system case
    df = pd.read_csv('df_binary_test{}.csv'.format(i))

    dar = Dartmouth_Isochrone()
    t = ObservationTree.from_df(df, name='test{}'.format(i))
    t.define_models(dar)

    mod = StarModel(dar, obs=t)
    mod.fit_multinest(n_live_points=1000,
                        basename='test{}_bound'.format(i))

    #if rank == 0:
    f1 = open('evidence_bound2.txt','a')
    evi = mod.evidence
    evi = str(evi)
    f1.write('case{}: '.format(i) + evi + '\n')

    #mod.corner(['mass_0_0','mass_0_1','distance_0','AV_0'])
    fig = mod.corner_physical(props=['mass', 'distance', 'AV'])
    fig.savefig('test{}_bound_corner_physical.png'.format(i))
    plt.close(fig)
    fig = mod.corner_observed()
    fig.savefig('test{}_bound_corner_observed.png'.format(i))
        return '0' + str(n)
    else:
        return str(n)

n = sys.argv[1]
i = get_index(n)

df = pd.read_csv('/tigress/np5/dataFrame/df_triplet_test{}.csv'.format(i))

#-------------------------------------------------------------------------------
#triplet0 - all in same system
dar = Dartmouth_Isochrone()
t = ObservationTree.from_df(df, name='test{}'.format(i))
t.define_models(dar)

mod = StarModel(dar, obs=t)
mod.fit_multinest(n_live_points=1000,
                    basename='/tigress/np5/chains/test{}_triplet0'.format(i))

#if rank == 0:
f1 = open('/tigress/np5/evidence_triplet0.txt','a')
evi = mod.evidence
evi = str(evi)
f1.write('case{}: '.format(i) + evi + '\n')
f1.close()

fig = mod.corner_physical(props=['mass', 'distance', 'AV'])
fig.savefig('/tigress/np5/figures/test{}_triplet0_corner_physical.png'.format(i))
plt.close(fig)
fig = mod.corner_observed()
fig.savefig('/tigress/np5/figures/test{}_triplet0_corner_observed.png'.format(i))
Example #5
0
from isochrones.dartmouth import Dartmouth_Isochrone
from isochrones.starmodel import StarModel
from isochrones.observation import ObservationTree
import numpy as np

df_data = pd.DataFrame()

for i in range(6000,7000,1):
    df = pd.read_csv('/tigress/np5/dataFrame/df_binary_test{}.csv'.format(i))

    dar = Dartmouth_Isochrone()
    t = ObservationTree.from_df(df, name='test{}'.format(i))

    t.define_models(dar, index=[0,1])

    mod = StarModel(dar, obs=t)
    mod.fit_multinest(n_live_points=1000,
                        basename='/tigress/np5/chains/test{}_unassociated'.format(i))

    M1 = mod.samples.mass_0_0.median()
    M2 = mod.samples.mass_1_0.median()
    distance1 = mod.samples.distance_0.median()
    distance2 = mod.samples.distance_1.median()

    index = 'case'+str(i)
    df_data = df_data.append(pd.DataFrame({'M1_fit':M1,
                    'M2_fit':M2,
                    'distance1_fit':distance1,
                    'distance2_fit':distance2},index=[index]))

df_data.to_csv(path_or_buf='/tigress/np5/df_fit_params.csv')
        row['mag'] = unresolved[b]
        row['e_mag'] = mag_unc[inst]
        df = df.append(pd.DataFrame(row, index=[i]))
        i += 1

for inst in ['RAO']:  #Resolved observations
    for b in bands[inst]:
        mags = [resolved_1[b], resolved_2[b]]
        pas = [0, PA]
        seps = [0., separation]
        for mag,sep,pa in zip(mags,seps,pas):
            row = {}
            row['name'] = inst
            row['band'] = b
            row['resolution'] = resolution[inst]
            row['relative'] = relative[inst]
            row['separation'] = sep
            row['pa'] = pa
            row['mag'] = mag
            row['e_mag'] = mag_unc[inst]
            df = df.append(pd.DataFrame(row, index=[i]))
            i += 1

t = ObservationTree.from_df(df, name='test-binary')
t.define_models(dar, index=[0,1])
t.add_limit(logg=(3.0,None))
t.print_ascii()

mod = StarModel(dar, obs=t)
mod.save_hdf('mod.h5', overwrite=True)
Example #7
0
    def __init__(self, koi, recalc=False, use_JRowe=True, trsig_kws=None, tag=None, starmodel_mcmc_kws=None, **kwargs):

        koi = koiname(koi)

        # if saved popset exists, load
        folder = os.path.join(KOI_FPPDIR, koi)
        if tag is not None:
            folder += "_{}".format(tag)

        if not os.path.exists(folder):
            os.makedirs(folder)

        if trsig_kws is None:
            trsig_kws = {}

        # first check if pickled signal is there to be loaded
        trsigfile = os.path.join(folder, "trsig.pkl")
        if os.path.exists(trsigfile):
            trsig = pickle.load(open(trsigfile, "rb"))
        else:
            if use_JRowe:
                trsig = JRowe_KeplerTransitSignal(koi, **trsig_kws)
            else:
                trsig = KeplerTransitSignal(koi, **trsig_kws)

        popsetfile = os.path.join(folder, "popset.h5")
        if os.path.exists(popsetfile) and not recalc:
            popset = PopulationSet(popsetfile, **kwargs)

        else:
            koinum = koiname(koi, koinum=True)
            kepid = KOIDATA.ix[koi, "kepid"]

            if "mass" not in kwargs:
                kwargs["mass"] = koi_propdist(koi, "mass")
            if "radius" not in kwargs:
                kwargs["radius"] = koi_propdist(koi, "radius")
            if "feh" not in kwargs:
                kwargs["feh"] = koi_propdist(koi, "feh")
            if "age" not in kwargs:
                try:
                    kwargs["age"] = koi_propdist(koi, "age")
                except:
                    kwargs["age"] = (9.7, 0.1)  # default age
            if "Teff" not in kwargs:
                kwargs["Teff"] = kicu.DATA.ix[kepid, "teff"]
            if "logg" not in kwargs:
                kwargs["logg"] = kicu.DATA.ix[kepid, "logg"]
            if "rprs" not in kwargs:
                if use_JRowe:
                    kwargs["rprs"] = trsig.rowefit.ix["RD1", "val"]
                else:
                    kwargs["rprs"] = KOIDATA.ix[koi, "koi_ror"]

            # if stellar properties are determined spectroscopically,
            # fit stellar model
            if "starmodel" not in kwargs:
                if re.match("SPE", kicu.DATA.ix[kepid, "teff_prov"]):
                    logging.info("Spectroscopically determined stellar properties.")
                    # first, see if there already is a starmodel to load

                    # fit star model
                    Teff = kicu.DATA.ix[kepid, "teff"]
                    e_Teff = kicu.DATA.ix[kepid, "teff_err1"]
                    logg = kicu.DATA.ix[kepid, "logg"]
                    e_logg = kicu.DATA.ix[kepid, "logg_err1"]
                    feh = kicu.DATA.ix[kepid, "feh"]
                    e_feh = kicu.DATA.ix[kepid, "feh_err1"]
                    logging.info(
                        "fitting StarModel (Teff=({},{}), logg=({},{}), feh=({},{}))...".format(
                            Teff, e_Teff, logg, e_logg, feh, e_feh
                        )
                    )

                    dar = Dartmouth_Isochrone()
                    starmodel = StarModel(dar, Teff=(Teff, e_Teff), logg=(logg, e_logg), feh=(feh, e_feh))
                    if starmodel_mcmc_kws is None:
                        starmodel_mcmc_kws = {}
                    starmodel.fit(**starmodel_mcmc_kws)
                    logging.info("Done.")
                    kwargs["starmodel"] = starmodel

            if "mags" not in kwargs:
                kwargs["mags"] = ku.KICmags(koi)
            if "ra" not in kwargs:
                kwargs["ra"], kwargs["dec"] = ku.radec(koi)
            if "period" not in kwargs:
                kwargs["period"] = KOIDATA.ix[koi, "koi_period"]

            if "pl_kws" not in kwargs:
                kwargs["pl_kws"] = {}

            if "fp_specific" not in kwargs["pl_kws"]:
                rp = kwargs["radius"].mu * kwargs["rprs"] * RSUN / REARTH
                kwargs["pl_kws"]["fp_specific"] = fp_fressin(rp)

            # trilegal_filename = os.path.join(folder,'starfield.h5')
            trilegal_filename = kepler_starfield_file(koi)
            popset = PopulationSet(trilegal_filename=trilegal_filename, **kwargs)
            # popset.save_hdf('{}/popset.h5'.format(folder), overwrite=True)

        lhoodcachefile = os.path.join(folder, "lhoodcache.dat")
        self.koi = koi
        FPPCalculation.__init__(self, trsig, popset, folder=folder)
        self.save()
        self.apply_default_constraints()
Example #8
0
        return '0' + str(n)
    else:
        return str(n)

n = sys.argv[1]
i = get_index(n)

df = pd.read_csv('/tigress/np5/dataFrame/df_quad_test{}.csv'.format(i))

#-------------------------------------------------------------------------------
#quad0 - all in same system
dar = Dartmouth_Isochrone()
t = ObservationTree.from_df(df, name='test{}'.format(i))
t.define_models(dar)

mod = StarModel(dar, obs=t)
mod.fit_multinest(n_live_points=1000,
                    basename='/tigress/np5/chains/test{}_quad0'.format(i))

if rank == 0:
    f1 = open('/tigress/np5/evidence_quad0.txt','a')
    evi = mod.evidence
    evi = str(evi)
    f1.write('case{}: '.format(i) + evi + '\n')
    f1.close()

    fig = mod.corner_physical(props=['mass', 'distance', 'AV'])
    fig.savefig('/tigress/np5/figures/test{}_quad0_corner_physical.png'.format(i))
    plt.close(fig)
    fig = mod.corner_observed()
    fig.savefig('/tigress/np5/figures/test{}_quad0_corner_observed.png'.format(i))
Example #9
0
import pandas as pd
from isochrones.dartmouth import Dartmouth_Isochrone
from isochrones.observation import ObservationTree
from isochrones.starmodel import StarModel
from datetime import datetime


df = pd.read_csv('df.csv')

dar = Dartmouth_Isochrone()

t = ObservationTree.from_df(df, name='test-triplet')
t.define_models(dar, index=[0,0,1])
t.add_limit(logg=(3.0,None))

mod = StarModel(dar, obs=t)
startTime = datetime.now()
mod.fit_multinest(n_live_points=1000)
time = datetime.now() - startTime
evi = mod.evidence

print 'evidence = {}'.format(evi)
print 'total time = {}'.format(time)