Beispiel #1
0
def test_dartmouth_basic(bands=['J']):
    dar = Dartmouth_Isochrone(bands)
    _basic_ic_checks(dar)

    assert np.isclose(dar.radius(1., 9.5, 0.0), 0.95409593462955189)
    assert np.isclose(dar.radius(1.01, 9.72, 0.02), 1.0435559519926865)
    assert np.isclose(dar.radius(1.21, 9.38, 0.11), 1.2762022494652547)
    assert np.isclose(dar.radius(0.61, 9.89, -0.22), 0.5964945760402941)
Beispiel #2
0
def obs_to_starmodel(obs, iso=None):
    """ Given an Observation, return a StarModel object """

    if iso is None:
        iso = Dartmouth_Isochrone()

    mags = obs_to_mags(obs)
    parallax = (obs.tgas_source.parallax, obs.tgas_source.parallax_error)

    model = StarModel(iso, use_emcee=True, parallax=parallax, **mags)
    model.set_bounds(mass=(0.01, 20),
                     feh=(-1, 1),
                     distance=(0, 300),
                     AV=(0, 1))

    return model
Beispiel #3
0
def isochrones(name):
    dar = Dartmouth_Isochrone()
    Teff, logg, feh, vsini, vmag = parameters(name)
    model = StarModel(
        dar,
        Teff=Teff,
        feh=feh,
        logg=logg,
        V=vmag,
    )
    outfn = os.path.join(OUTPUTDIR, '{}_isochrones.hdf'.format(name))
    print "performing isochrones analysis on {}".format(name)
    model.fit(overwrite=True)
    columns = 'Teff logg feh mass radius age distance'.split()
    print "performing isochrones analysis on {}".format(name)
    print model.samples[columns].quantile([0.15, 0.5, 0.85]).T.to_string()
    model.save_hdf(outfn)
Beispiel #4
0
def get_ichrone(models, bands=None, default=False, **kwargs):
    """Gets Isochrone Object by name, or type, with the right bands

	If `default` is `True`, then will set bands
	to be the union of bands and default_bands
	"""
    if isinstance(models, Isochrone):
        return models

    def actual(bands, ictype):
        if bands is None:
            return list(ictype.default_bands)
        elif default:
            return list(set(bands).union(set(ictype.default_bands)))
        else:
            return bands

    if type(models) is type(type):
        ichrone = models(actual(bands, models))
    elif models == 'dartmouth':
        from isochrones.dartmouth import Dartmouth_Isochrone
        ichrone = Dartmouth_Isochrone(bands=actual(bands, Dartmouth_Isochrone),
                                      **kwargs)
    elif models == 'dartmouthfast':
        from isochrones.dartmouth import Dartmouth_FastIsochrone
        ichrone = Dartmouth_FastIsochrone(bands=actual(
            bands, Dartmouth_FastIsochrone),
                                          **kwargs)
    elif models == 'mist':
        from isochrones.mist import MIST_Isochrone
        ichrone = MIST_Isochrone(bands=actual(bands, MIST_Isochrone), **kwargs)
    elif models == 'padova':
        from isochrones.padova import Padova_Isochrone
        ichrone = Padova_Isochrone(bands=actual(bands, Padova_Isochrone),
                                   **kwargs)
    elif models == 'basti':
        from isochrones.basti import Basti_Isochrone
        ichrone = Basti_Isochrone(bands=actual(bands, Basti_Isochrone),
                                  **kwargs)
    else:
        raise ValueError('Unknown stellar models: {}'.format(models))
    return ichrone
Beispiel #5
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_mcmc(**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()
Beispiel #6
0
import tempfile
import os, shutil, glob
import logging

import numpy as np
from isochrones.dartmouth import Dartmouth_Isochrone
from isochrones.mist import MIST_Isochrone
from isochrones import StarModel, get_ichrone

DAR = Dartmouth_Isochrone()
MIST = MIST_Isochrone()

def test_dartmouth_basic(bands=['z', 'B', 'W3', 'LSST_r', 'J', 'UK_J']):
    dar = Dartmouth_Isochrone(bands)
    _basic_ic_checks(dar)
    print('{} ({})'.format(dar.radius(1., 9.5, 0.0), 0.95409593462955189))
    assert np.isclose(dar.radius(1., 9.5, 0.0), 0.95409593462955189) 
    assert np.isclose(dar.radius(1.01, 9.72, 0.02), 1.0435559519926865)
    assert np.isclose(dar.radius(1.21, 9.38, 0.11), 1.2762022494652547)
    assert np.isclose(dar.radius(0.61, 9.89, -0.22), 0.5964945760402941)

def test_mist_basic(bands=['G','B','V','J','H','K','W1','W2','W3']):
    ic = MIST_Isochrone(bands)
    _basic_ic_checks(ic)
    print('{} ({})'.format(ic.radius(1.0, 9.5, 0.0), 0.9764494078461442))
    assert np.isclose(ic.radius(1.0, 9.5, 0.0), 0.9764494078461442)
    assert np.isclose(ic.radius(1.01, 9.72, 0.02), 1.0671791635014685)
    assert np.isclose(ic.radius(1.21, 9.38, 0.11), 1.2836469028034225)
    assert np.isclose(ic.radius(0.61, 9.89, -0.22), 0.59475269177846402)
def get_isochrone_params(stars, modeldir, overwrite=False):
    """Fill out parameter table with values obtained from isochrone package

    Args:
        stars (pd.DataFrame): parameter table
        modeldir (str): directory to save fitted models
        overwrite (bool, optional): whether to use existing models or overwrite
    Returns:
        stars (pd.DataFrame): updated parameter table
    """
    dar = Dartmouth_Isochrone()

    num_stars = len(stars)
    current_star = 1

    for idx, row in stars.iterrows():
        print("Getting isochrone parameters for star {0} of {1}".format(
            current_star, num_stars))
        current_star += 1

        # get known stellar properties
        lib_props = {}
        for p in library.Library.STAR_PROPS:
            if not np.isnan(row[p]):
                # (value, uncertainty)
                lib_props[p] = (row[p], row['u_' + p])
        # if all properties are known, we don't need to use the model
        if len(lib_props) == 6:
            continue

        if modeldir is None:
            model = StarModel(dar, **lib_props)
            model.fit(overwrite=True, verbose=False)
        else:
            # check if fitting has already been done
            modelfile = os.path.join(modeldir,
                                     "{0}_model.h5".format(row['cps_name']))
            if os.path.exists(modelfile) and not overwrite:
                model = StarModel.load_hdf(modelfile)
            # otherwise perform the fit
            else:
                model = StarModel(dar, **lib_props)
                model.fit(overwrite=True, verbose=False)
                model.save_hdf(modelfile)

        N_SIGMA = 2
        MAX_PERCENTILE = 0.95
        MIN_PERCENTILE = 0.05
        # fill out unknown parameters
        for p in library.Library.STAR_PROPS:
            value = model.samples[p].quantile(0.5)
            upper_bound = model.samples[p].quantile(MAX_PERCENTILE)
            lower_bound = model.samples[p].quantile(MIN_PERCENTILE)

            # If a property is already known, check for model consistency
            if p in lib_props:
                # check if 2-sigma bounds fail to overlap
                if (row[p] + N_SIGMA * row['u_'+p]) < lower_bound \
                        or (row[p] - N_SIGMA * row['u_'+p]) > upper_bound:
                    warningstr = "Warning: Inconisistent {0} for star {1}\n"\
                        .format(p, row['cps_name'])
                    warningstr += "\tLibrary values: {0:.2f} +/- {1:.2f}\n"\
                        .format(row[p], row['u_'+p])
                    warningstr += "\tModel values: {0:.2f}, ".format(value)
                    warningstr += "{0:d}-sigma = ({1:.2f}, {2:.2f})\n".format(
                        N_SIGMA, lower_bound, upper_bound)

                    print(warningstr)
                    # Save error messages to file
                    errpath = os.path.join(modeldir, 'errors.txt')
                    with open(errpath, 'a') as f:
                        f.write(warningstr)
            # Insert the unknown values if we don't already know them
            else:
                stars.loc[idx, p] = np.around(value, 2)
                stars.loc[idx, 'u_'+p] = \
                    np.around((upper_bound - lower_bound) / 2, 2)
    return stars
Beispiel #8
0
# useful links:
# http://slittlefair.staff.shef.ac.uk/teaching/phy241/resources/plotting_isochrones.html
# https://isochrones.readthedocs.io/en/latest/
# https://isochrones.readthedocs.io/en/latest/_modules/isochrones/isochrone.html

#catalog_name = "./isochronetest_ngc7062.csv"
#df = pd.read_csv(catalog_name)

#g = df['phot_g_mean_mag']
#bp = df['phot_bp_mean_mag']
#rp = df['phot_rp_mean_mag']

#padoviso = Padova_Isochrone(bands=['B','V'])
#padoviso = Padova_Isochrone()
#mist = MIST_Isochrone()
iso = Dartmouth_Isochrone(bands=['B', 'V'])

#sys.exit(0)

#print(padoviso.bands)

#print(mist.radius(1.0, 9.7, 0.0)) #M/Msun, log10(age), Fe/H
#print(mist.bands)

#mass, age, feh, distance, AV = (0.95, 9.61, -0.2, 200, 0.2)
#print(mist.mag['g'](mass, age, feh, distance, AV))
#print(iso.bands)

#model = iso.isochrone(9.235) # log10 of the age
#print(type(model))
Beispiel #9
0
def test_dartmouth_basic(bands=['z', 'B', 'W3', 'LSST_r', 'J', 'UK_J']):
    dar = Dartmouth_Isochrone(bands)
    _basic_ic_checks(dar)
Beispiel #10
0
from __future__ import print_function, division

import pandas as pd
import numpy as np
import logging
from scipy.stats import poisson
from numba import jit

from isochrones.dartmouth import Dartmouth_Isochrone

from .utils import draw_powerlaw 
from .utils import get_duration, get_a, get_delta, get_pgeom

dar = Dartmouth_Isochrone()
#because
dar.radius(1,9.8,0.0)

R_EARTH = 0.009171 # in solar units

# Some default ranges
P_RANGE = (50, 300) 
R_RANGE = (0.75, 20)


def sim_binaries(stars, fB=0.5, gamma=0.3, 
              qmin=0.1, minmass=None, band='Kepler', ic=dar):
    """
    Generates binary companions to stars


import numpy as np
import emcee
from tqdm import tqdm

# Package
from comoving_rv.log import logger
from comoving_rv.db import Session, Base, db_connect
from comoving_rv.db.model import (Run, Observation, TGASSource, SimbadInfo,
                                  GroupToObservations, SpectralLineInfo,
                                  SpectralLineMeasurement, RVMeasurement)

from isochrones import StarModel
# from isochrones.mist import MIST_Isochrone
# iso = MIST_Isochrone() # interpolation issues with MIST isochrones
from isochrones.dartmouth import Dartmouth_Isochrone
iso = Dartmouth_Isochrone()


def main():
    # TODO: bad, hard-coded...
    # base_path = '/Volumes/ProjectData/gaia-comoving-followup/'
    base_path = '../../data/'
    db_path = path.join(base_path, 'db.sqlite')
    engine = db_connect(db_path)
    session = Session()

    chain_path = path.abspath('./isochrone_chains')
    os.makedirs(chain_path, exist_ok=True)

    # Check out the bottom of "Color-magnitude diagram.ipynb":
    interesting_group_ids = [1500, 1229, 1515]
from isochrones.dartmouth import Dartmouth_Isochrone
from isochrones.utils import addmags
import numpy as np
import pandas as pd

file = open('/tigress/np5/true_params.txt','a')


for n in range(6000,7000,1):
    index = str(n)

    file.write('test: ' + index + '\n')

    dar = Dartmouth_Isochrone()

    array = np.random.rand(2) + 0.5
    if array[0] > array[1]:
        M1 = array[1]
        M2 = array[0]
    else:
        M1 = array[0]
        M2 = array[1]

    feh1,feh2 = 0.7*np.random.rand(2) - 0.5

    random1, random2 = np.random.rand(2)
    age_low, age_high = dar.agerange(M1,feh1)
    age_low = max(age_low, dar.minage)
    age_high = min(age_high, dar.maxage)
    age_low = 10**age_low
    age_high = 10**age_high
def main():
    args = _parser()
    path = os.path.expanduser('~/.SWEETCat/')
    _sc = os.path.join(path, 'sweetcat.csv')
    if os.path.isdir(path):
        if not os.path.isfile(_sc):
            print('Downloading SWEET-Cat...')
            _download_sweetcat(_sc)
    else:
        os.mkdir(path)
        print('%s Created' % path)
        print('Downloading SWEET-Cat...')
        _download_sweetcat(_sc)

    df = _read_sweetcat(_sc)
    if args.sweetcat:
        df = df[df.source == True]

    df['x'] = df[args.x]
    df['y'] = df[args.y]

    if (args.x == 'age') or (args.y == 'age') or (args.z == 'age'):
        from isochrones.dartmouth import Dartmouth_Isochrone
        dar = Dartmouth_Isochrone()
        age = np.zeros(df.shape[0])
        for i, (mass, feh) in enumerate(df[['mass', 'feh']].values):
            tmp = dar.agerange(mass, feh)
            age[i] = (10**(tmp[0]-9) + 10**(tmp[1]-9))/2
        df['age'] = pd.Series(age)

    if args.z:
        if args.iz:
            z = 1/df[args.z].values
        else:
            z = df[args.z].values
        color = df[args.z].values
        u = z[~np.isnan(z)]
        size = (z-u.min())/(u.max()-u.min())*100
        size[np.argmin(size)] = 10  # Be sure to show the "smallest" point
        plt.scatter(df['x'], df['y'], c=color, s=size)  #, cmap=cm.viridis)
    else:
        plt.scatter(df['x'], df['y'], s=40)


    labels = {'teff':      r'$T_\mathrm{eff}$ [K]',
              'tefferr':   r'$\sigma T_\mathrm{eff}$ [K]',
              'logg':      r'$\log(g)$ [cgs]',
              'loggerr':   r'$\sigma \log(g)$ [cgs]',
              'logglc':    r'$\log(g)$ [cgs]',
              'logglcerr': r'$\sigma \log(g)$ [cgs]',
              'feh':        '[Fe/H]',
              'feherr':    r'$\sigma$ [Fe/H]',
              'vt':        r'$\xi_\mathrm{micro}$ [km/s]',
              'vterr':     r'$\sigma\xi_\mathrm{micro}$ [km/s]',
              'lum':       r'$L_\odot$',
              'mass':      r'$M_\odot$',
              'masserr':   r'$\sigma M_\odot$',
              'radius':    r'$R_\odot$',
              'radiuserr': r'$\sigma R_\odot$',
              'age':       r'Age $[Gyr]$',
              'par':       r'$\pi$ [mas]',
              'parerr':    r'$\sigma \pi$ [mas]',
              'vmag':       'V magnitude',
              'vmagerr':   r'$\sigma$ V magnitude'}

    plt.xlabel(labels[args.x])
    plt.ylabel(labels[args.y])
    if args.z:
        cbar = plt.colorbar()
        cbar.set_label(labels[args.z])
    if args.s:
        sun = {'teff': 5777,
               'tefferr': 1,
               'logg': 4.44,
               'loggerr': 0.01,
               'feh': 0.00,
               'feherr': 0.01,
               'vt': 1.00,
               'vterr': 0.01,
               'lum': 1,
               'mass': 1,
               'masserr': 0.01,
               'radius': 1,
               'radiuserr': 0.01,
               'age': 4.567}
        plt.scatter(sun[args.x], sun[args.y], marker='*', s=200, alpha=0.8)
    if args.ix:
        plt.xlim(plt.xlim()[::-1])
    if args.iy:
        plt.ylim(plt.ylim()[::-1])

    if args.lx:
        plt.xscale('log')
        df['x'] = np.log(df['x'])
    if args.ly:
        y1, y2 = plt.ylim()
        plt.yscale('log')
        plt.ylim(max(y1, 0.01), y2)
        df['y'] = np.log(df['y'])

    if args.l:
        p = np.polyfit(df['x'], df['y'], deg=1)
        print('  y=%.3f*x+%.3f' % (p[0], p[1]))
        x1, x2 = df.x.min(), df.x.max()
        yfit = np.poly1d(p)([x1, x2])
        if args.lx and args.ly:
            plt.plot(np.exp([x1, x2]), np.exp(yfit), '-k')
        elif args.lx and not args.ly:
            plt.plot(np.exp([x1, x2]), yfit, '-k')
        elif not args.lx and args.ly:
            plt.plot([x1, x2], np.exp(yfit), '-k')
        else:
            plt.plot([x1, x2], yfit, '-k')

    plt.tight_layout()
    plt.show()
Beispiel #14
0
def iso_age(teff, logg, feh):
    dar = Dartmouth_Isochrone()
    mod = StarModel(dar, Teff=(teff, 80), Logg=(logg, 0.10), Feh=(feh, 0.1))
    logage, _, _ = mod.maxlike()
    age = np.exp(logage)
    return age