Ejemplo n.º 1
0
    def __init__(self,m_ini,age,feh,m_act,logL,Teff,logg,mags,tri=None,
                 minage=None, maxage=None, ext_table=False):
        """Warning: if tri object not provided, this will be very slow to be created.
        """

        self.minage = age.min()
        self.maxage = age.max()
        self.minmass = m_act.min()
        self.maxmass = m_act.max()
        self.minfeh = feh.min()
        self.maxfeh = feh.max()

        self.ext_table = ext_table

        if minage is not None:
            logging.warning("minage and maxage keywords are deprecated." + \
                          "Use instead the .set_bounds(age=(lo, hi)) attribute of StarModel.")
            self.minage = minage
        if maxage is not None:
            logging.warning("minage and maxage keywords are deprecated." + \
                          "Use instead the .set_bounds(age=(lo, hi)) attribute of StarModel.")
            self.maxage = maxage

        L = 10**logL

        if tri is None:
            points = np.zeros((len(m_ini),3))
            points[:,0] = m_ini
            points[:,1] = age
            points[:,2] = feh
            fn = interpnd(points,m_act)
            self.tri = fn.tri
        else:
            self.tri = tri
            self.mass = interpnd(self.tri,m_act)

        self._data = {'mass':m_act,
                    'logL':logL,
                    'logg':logg,
                    'logTeff':np.log10(Teff),
                    'mags':mags}
        self._props = ['mass', 'logL', 'logg', 'logTeff']

        self.bands = mags.keys()

        self._mag = {band:interpnd(self.tri,mags[band]) for band in self.bands}

        d = {}
        for b in self._mag.keys():
            d[b] = self._mag_fn(b)

        self.mag = d
Ejemplo n.º 2
0
def build_interpfn(ks=None,nz=100,return_vals=False,filename='cosi_pdf_grid.h5',
                   kmax=300, save=False):
    """
    """
    if ks is None:
        ks = np.concatenate((np.logspace(-2,0,100),np.linspace(1.1,kmax+1,300)))

    nk = len(ks)
    zs = np.linspace(0,0.9999,nz)
    vals = np.zeros(nk*nz)
    allks = vals*0
    allzs = vals*0
    i=0
    for k in ks:
        for z in zs:
            vals[i] = cosi_pdf(z,k)
            allks[i] = k
            allzs[i] = z
            i += 1
    pts = np.array([allzs,allks]).T
    if save:
        df = pd.DataFrame({'z':allzs, 'k':allks, 'val': vals})
        df.to_hdf(filename,'grid')
    if return_vals:
        return pts,vals
    else:
        return interpnd(pts,vals)
Ejemplo n.º 3
0
 def _prop(self, prop, *args):
     if prop not in self._props:
         raise ValueError('Cannot call this function with {}.'.format(prop))
     attr = '_{}'.format(prop)
     if not hasattr(self, attr):
         setattr(self, attr, interpnd(self.tri, self._data[prop]))
     fn = getattr(self, attr)
     return fn(*args)
Ejemplo n.º 4
0
def cosi_pdf_fn(filename=resource_filename('obliquity','data/cosi_pdf_grid.h5'),
                recalc=False,**kwargs):
    if recalc:
        return build_interpfn(**kwargs)
    else:
        df = pd.read_hdf(filename,'grid')
        pts = np.array([df['z'],df['k']]).T
        vals = np.array(df['val'])
        return interpnd(pts,vals)
Ejemplo n.º 5
0
 def func(*x):
     x = np.atleast_1d(x).squeeze()
     values = interpnd(points=self.grid.coord_vectors,
                       values=inp.data.reshape(self.grid.shape,
                                               order=self.order),
                       method='nearest',
                       xi=x,
                       fill_value=None)  # Allow points outside
     return values[0] if values.shape == (1,) else values
Ejemplo n.º 6
0
    def __init__(self,age,m_ini,m_act,logL,Teff,logg,mags,fehs=None):
        self.minage = age.min()
        self.maxage = age.max()
        self.minmass = m_act.min()
        self.maxmass = m_act.max()
        
        self.bands = []
        for band in mags:
            self.bands.append(band)
        L = 10**logL
        #R = sqrt(G*m_act*MSUN/10**logg)/RSUN

        if fehs is None:
            points = array([m_ini,age]).T
            self.is3d = False
        else:
            points = array([m_ini,age,fehs]).T
            self.is3d = True

        if self.is3d:
            self.feh = lambda m,age,feh: feh
        else:
            self.feh = lambda m,age: self.isofeh

        self.M = interpnd(points,m_act)
        self.tri = self.M.tri
        #self.R = interpnd(points,R)
        self.logL = interpnd(self.tri,logL)
        self.logg = interpnd(self.tri,logg)
        self.logTe = interpnd(self.tri,log10(Teff))
        def Teff_fn(*pts):
            return 10**self.logTe(*pts)
        #self.Teff = lambda *pts: 10**self.logTe(*pts)
        self.Teff = Teff_fn
        def R_fn(*pts):
            return sqrt(G*self.M(*pts)*MSUN/10**self.logg(*pts))/RSUN
        #self.R = lambda *pts: sqrt(G*self.M(*pts)*MSUN/10**self.logg(*pts))/RSUN
        self.R = R_fn

        self.mag = {}
        for band in self.bands:
            self.mag[band] = interpnd(self.tri,mags[band])
Ejemplo n.º 7
0
def write_tri(filename=os.path.join(ISOCHRONES, 'dartmouth.tri')):
    df = DartmouthModelGrid(['g']).df
    N = len(df)
    pts = np.zeros((N, 3))
    pts[:, 0] = np.array(df['MMo'])
    pts[:, 1] = np.array(df['age'])
    pts[:, 2] = np.array(df['feh'])
    gmags = np.array(df['g'])

    gfn = interpnd(pts, gmags)

    with open(filename, 'wb') as f:
        pickle.dump(gfn.tri, f)
Ejemplo n.º 8
0
def write_tri(df=MASTERDF,outfile=TRI_FILE):
        N = len(df)
        pts = np.zeros((N,3))
        pts[:,0] = np.array(df['M_ini'])
        pts[:,1] = np.array(df['age'])
        pts[:,2] = np.array(df['feh'])
        Jmags = np.array(df['J'])

        Jfn = interpnd(pts,Jmags)

        f = open(outfile,'wb')
        pickle.dump(Jfn.tri,f)
        f.close()
Ejemplo n.º 9
0
def write_tri(filename=os.path.join(ISOCHRONES,'yapsi.tri')):
    df = YAPSIModelGrid(['V']).df
    N = len(df)
    pts = np.zeros((N,3))
    pts[:,0] = np.array(df['mass'])
    pts[:,1] = np.array(df['age'])
    pts[:,2] = np.array(df['feh'])
    mags = np.array(df['V'])

    fn = interpnd(pts,mags)

    with open(filename,'wb') as f:
        pickle.dump(fn.tri,f)
Ejemplo n.º 10
0
def write_tri(df=MASTERDF, outfile=TRI_FILE):
    N = len(df)
    pts = np.zeros((N, 3))
    pts[:, 0] = np.array(df['M_ini'])
    pts[:, 1] = np.array(df['age'])
    pts[:, 2] = np.array(df['feh'])
    Jmags = np.array(df['J'])

    Jfn = interpnd(pts, Jmags)

    f = open(outfile, 'wb')
    pickle.dump(Jfn.tri, f)
    f.close()
Ejemplo n.º 11
0
def write_tri(df=MASTERDF, outfile=TRI_FILE):
    N = len(df)
    pts = np.zeros((N, 3))
    pts[:, 0] = np.array(df['mini'])
    pts[:, 1] = np.array(df['logage'])
    pts[:, 2] = np.array(df['feh'])

    Rs = np.array(df['radius'])

    Rfn = interpnd(pts, Rs)

    f = open(outfile, 'wb')
    pickle.dump(Rfn.tri, f)
    f.close()
Ejemplo n.º 12
0
def write_tri(df=MASTERDF,outfile=TRI_FILE):
    N = len(df)
    pts = np.zeros((N,3))
    pts[:,0] = np.array(df['mini'])
    pts[:,1] = np.array(df['logage'])
    pts[:,2] = np.array(df['feh'])

    Rs = np.array(df['radius'])
    
    Rfn = interpnd(pts,Rs)
    
    f = open(outfile,'wb')
    pickle.dump(Rfn.tri,f)
    f.close()
Ejemplo n.º 13
0
    def __init__(self,
                 m_ini,
                 age,
                 feh,
                 m_act,
                 logL,
                 Teff,
                 logg,
                 mags,
                 tri=None):
        """Warning: if tri object not provided, this will be very slow to be created.
        """

        self.minage = age.min()
        self.maxage = age.max()
        self.minmass = m_act.min()
        self.maxmass = m_act.max()
        self.minfeh = feh.min()
        self.maxfeh = feh.max()

        L = 10**logL

        if tri is None:
            points = np.zeros((len(m_ini), 2))
            points[:, 0] = m_ini
            points[:, 1] = age
            self.mass = interpnd(points, m_act)
            self.tri = self.mass.tri
        else:
            self.tri = tri
            self.mass = interpnd(self.tri, m_act)

        self.logL = interpnd(self.tri, logL)
        self.logg = interpnd(self.tri, logg)
        self.logTeff = interpnd(self.tri, np.log10(Teff))

        def Teff_fn(*pts):
            return 10**self.logTeff(*pts)

        self.Teff = Teff_fn

        def R_fn(*pts):
            return np.sqrt(
                G * self.mass(*pts) * MSUN / 10**self.logg(*pts)) / RSUN

        self.radius = R_fn

        self.bands = []
        for band in mags.keys():
            self.bands.append(band)

        self.mag = {
            band: interpnd(self.tri, mags[band])
            for band in self.bands
        }
Ejemplo n.º 14
0
def write_tri(df=MASTERDF, outfile=TRI_FILE):
    """Writes the Delanuay triangulation of the models to file.  Takes a few minutes, so beware.

    Typically no need to do this unless you can't download the .tri file for some reason...
    """
    N = len(df)
    pts = np.zeros((N, 3))
    pts[:, 0] = np.array(df['M/Mo'])
    pts[:, 1] = np.log10(np.array(df['age']) * 1e9)
    pts[:, 2] = np.array(df['feh'])
    Jmags = np.array(df['J'])

    Jfn = interpnd(pts, Jmags)

    f = open(outfile, 'wb')
    pickle.dump(Jfn.tri, f)
    f.close()
Ejemplo n.º 15
0
def write_tri(df=MASTERDF, outfile=TRI_FILE):
    """Writes the Delanuay triangulation of the models to file.  Takes a few minutes, so beware.

    Typically no need to do this unless you can't download the .tri file for some reason...
    """
    N = len(df)
    pts = np.zeros((N,3))
    pts[:,0] = np.array(df['M/Mo'])
    pts[:,1] = np.log10(np.array(df['age'])*1e9)
    pts[:,2] = np.array(df['feh'])
    Jmags = np.array(df['J'])

    Jfn = interpnd(pts,Jmags)

    f = open(outfile,'wb')
    pickle.dump(Jfn.tri,f)
    f.close()
Ejemplo n.º 16
0
def read_Pdelta(root=MAIN_PATH+'matter_power/',**kwargs):
    """This is an interpolation in k and z, for array P_delta(k,z) output by CAMB.
    Input parameters for this function are the root where the power spectra arrays are stored, plus kwargs.
    This returns result in [cm^3 comoving]. It takes z, and k[1/Mpc comoving].
    Note1: Array of redshifts corresponding to the grid P must be stored in the location root/zs.txt.
    Note2: This also relies on particular file naming (regulated by CAMB), which can be adjusted in the function."""

    
    zs = np.loadtxt('%s/zs.txt' % root)
    all_Pdeltas = []
    for i,z in enumerate(zs):
        ks,Ps = np.loadtxt('%s/_matterpower_%i.dat' % (root,i),unpack=True)
        ks *= h0 
        Ps *= (Mpc_in_cm/h0)**3
        all_Pdeltas.append(Ps)
    all_Pdeltas = np.array(all_Pdeltas).T
    Zs,Ks = np.meshgrid(zs,ks)
    points = np.array([Zs.ravel(),Ks.ravel()]).T
    return interpnd(points,all_Pdeltas.ravel(),**kwargs)
Ejemplo n.º 17
0
    def __init__(self,m_ini,age,feh,m_act,logL,Teff,logg,mags,tri=None,
                 minage=None, maxage=None):
        """Warning: if tri object not provided, this will be very slow to be created.
        """

        self.minage = age.min()
        self.maxage = age.max()
        self.minmass = m_act.min()
        self.maxmass = m_act.max()
        self.minfeh = feh.min()
        self.maxfeh = feh.max()

        if minage is not None:
            self.minage = minage
        if maxage is not None:
            self.maxage = maxage

        L = 10**logL

        if tri is None:
            points = np.zeros((len(m_ini),3))
            points[:,0] = m_ini
            points[:,1] = age
            points[:,2] = feh
            self.mass = interpnd(points,m_act)
            self.tri = self.mass.tri
        else:
            self.tri = tri
            self.mass = interpnd(self.tri,m_act)

        self.logL = interpnd(self.tri,logL)
        self.logg = interpnd(self.tri,logg)
        self.logTeff = interpnd(self.tri,np.log10(Teff))

        def Teff_fn(*pts):
            return 10**self.logTeff(*pts)
        self.Teff = Teff_fn
        
        def R_fn(*pts):
            return np.sqrt(G*self.mass(*pts)*MSUN/10**self.logg(*pts))/RSUN
        self.radius = R_fn

        self.bands = []
        for band in mags.keys():
            self.bands.append(band)

        self.mag = {band:interpnd(self.tri,mags[band]) for band in self.bands}       
Ejemplo n.º 18
0
class ObservedThePlot(ThePlot):
    f_mv_sat = fits['f(mv_sat)']

    po = np.load(files['p_obs'])

    po_ms_z = po['ho'].sum(axis=2) / po['ha'].sum(axis=2)
    po_ms_z = np.where(np.isnan(po_ms_z), 0, po_ms_z)
    po_ms_i = interpnd(
        ((po['ms'][1:] + po['ms'][:-1]) / 2, (po['z'][1:] + po['z'][:-1]) / 2),
        po_ms_z,
        bounds_error=False,
        fill_value=0)

    def __init__(self, z, ms, mv):
        self.dms = ms[1] - ms[0]
        self.z = z
        self.po_ms = self.po_ms_i(np.array((ms, [self.z] * len(ms))).T)

        mv = mv.reshape((-1, 1))
        pars = self.f_mv_sat.best_values.copy()
        pars['x0'] = mv + pars['x0']
        self.f = np.power(10, self.f_mv_sat.model.func(mv, **pars))

    def p_mv0_mv(self, f_mv):
        ret = f_mv * self.f
        ret = ret / ret.sum()
        return np.where(np.isnan(ret), 0, ret)

    def fn(self, mv, p, f_mv):
        p_mv0_mv = self.p_mv0_mv(f_mv.ravel())
        fn = ((p_mv0_mv / p_mv0_mv.sum(axis=1, keepdims=True))[:, :,
                                                               np.newaxis] *
              (p / p.sum(axis=1, keepdims=True))[np.newaxis, :, :] *
              self.po_ms[np.newaxis, np.newaxis, :])
        return np.nansum(fn, axis=(1, 2)).reshape(mv.shape)

    def N(self, mv, a, N12, p, f):
        return self.fn(mv, p, f) * super(ObservedThePlot, self).N(
            mv, a, N12, p, f)
Ejemplo n.º 19
0
                                else:
                                    print(
                                        '{} is not a symlink. Not removing file. Please run this again with symlinked files'
                                        .format(fin[izip]))
                        else:
                            print('LUT is okay for :', fin, '. Doing nothing.')
                            sys.exit(1)
                    else:
                        npt = len(zzn)
                        coordn = np.hstack((np.array(xxn).reshape(npt, 1),
                                            np.array(yyn).reshape(npt, 1)))
                        noise = np.array(zzn).reshape(npt, 1)
                        print(
                            'Start 2D interpolation on noiseLut. This may take a while....'
                        )
                        interpfn2 = interpnd(coordn, noise)
                        noiseIntrp = interpfn2(fullX, fullY)
                        prevNoise = noiseToRead
                        if inps.oc:
                            ocfile = os.path.join(
                                odir, 'IW{0}'.format(swath),
                                'noise-iw' + str(swath) + '.cal')
                            write2flt(noiseIntrp, ylist, xlist, ocfile)
                            write2xml(noiseIntrp, ylist[0], xlist[0], 1, 1,
                                      ocfile)
                            print('Writing noise calibration file to ', ocfile)

                #### Radio Calibration
                if radioToRead != prevRadio:
                    ### Locate radiometric calibration xml file
                    if radioToRead.startswith('/vsizip'):  # read from zip file
Ejemplo n.º 20
0
    
import pickle

from .isochrone import Isochrone

#DATADIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
DATADIR = os.getenv('ISOCHRONES',
                    os.path.expanduser(os.path.join('~','.isochrones')))
if not os.path.exists(DATADIR):
    os.mkdir(DATADIR)

MASTERFILE = '{}/dartmouth.h5'.format(DATADIR)
TRI_FILE = '{}/dartmouth.tri'.format(DATADIR)

MAXAGES = np.load(resource_filename('isochrones','data/dartmouth_maxages.npz'))
MAXAGE = interpnd(MAXAGES['points'], MAXAGES['maxages'])


def _download_h5():
    """
    Downloads HDF5 file containing Dartmouth grids from Zenodo.
    """
    #url = 'http://zenodo.org/record/12800/files/dartmouth.h5'
    url = 'http://zenodo.org/record/15843/files/dartmouth.h5'
    import urllib
    print('Downloading Dartmouth stellar model data (should happen only once)...')
    if os.path.exists(MASTERFILE):
        os.remove(MASTERFILE)
    urllib.urlretrieve(url,MASTERFILE)

def _download_tri():
Ejemplo n.º 21
0
    import numpy as np
    from scipy.optimize import newton
    from scipy.interpolate import LinearNDInterpolator as interpnd
except ImportError:
    np, newton, interpnd = (None, None, None)
    on_rtd = True
    
if not on_rtd:
    DATAFOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))

    Es = np.load(os.path.join(DATAFOLDER,'Etable.npy'))
    eccs = np.load(os.path.join(DATAFOLDER,'Etable_eccs.npy'))
    Ms = np.load(os.path.join(DATAFOLDER,'Etable_Ms.npy'))
    ECCS,MS = np.meshgrid(eccs,Ms)
    points = np.array([MS.ravel(),ECCS.ravel()]).T
    EFN = interpnd(points,Es.ravel())
else:
    DATAFOLDER, Es, eccs, Ms, ECCS, MS = (None, None, None, None, None, None)
    points, EFN = (None, None) 
    
def Efn(Ms,eccs):
    """
    Returns Eccentric anomaly, interpolated from pre-computed grid of M, ecc

    Instantaneous solution of Kepler's equation!

    Works for ``-2*np.pi < Ms < 2*np.pi`` and ``eccs <= 0.97``
    
    :param Ms: (``float`` or array-like)
        Mean anomaly
Ejemplo n.º 22
0
if not on_rtd:
    import pandas as pd
else:
    pd = None

import pickle

from ..isochrone import Isochrone, FastIsochrone
from ..config import ISOCHRONES

TRI_FILE = '{}/dartmouth.tri'.format(ISOCHRONES)

if not on_rtd:
    MAXAGES = np.load(
        resource_filename('isochrones', 'data/dartmouth_maxages.npz'))
    MAXAGE = interpnd(MAXAGES['points'], MAXAGES['maxages'])

from .grid import DartmouthModelGrid

TRI = None


class Dartmouth_Isochrone(Isochrone):
    """Dotter (2008) Stellar Models, at solar a/Fe and He abundances.

    :param bands: (optional)
        List of desired photometric bands.  Default list of bands is
        ``['B','V','g','r','i','z','J','H','K','W1','W2','W3','Kepler']``.

    Model grids are obtained from `here <http://stellar.dartmouth.edu/models/>`_
    """
Ejemplo n.º 23
0
p.plot(V[jj] - I[jj], I[jj], '-', lw=2, label='age = 5 Gyr, feh=-1.5')
jj = (a == 5) * (feh == -2.5)
p.plot(V[jj] - I[jj], I[jj], '-', lw=2, label='age = 5 Gyr, feh=-2.5')
jj = (a == 5) * (feh == -2.0)
p.plot(V[jj] - I[jj], I[jj], '-', lw=2, label='age = 5 Gyr, feh=-2.0')

jj = (a == 12) * (feh == -2.0)
p.plot(V[jj] - I[jj], I[jj], '-', lw=2, label='age = 12 Gyr, feh=-2.0')
jj = (a == 12) * (feh == -2.5)
p.plot(V[jj] - I[jj], I[jj], '-', lw=2, label='age = 12 Gyr, feh=-2.5')
jj = (a == 12) * (feh == -1.5)
p.plot(V[jj] - I[jj], I[jj], '-', lw=2, label='age = 12 Gyr, feh=-1.5')

#tri = np.load('asd.tri.npy')

iV = interpnd(pts, V[j])
iI = interpnd(iV.tri, I[j])

np.save('asd.tri', iV.tri)

FEH = -2.5
AGE = 5.0
ms = np.arange(1, 300, 0.1)  ## actually eep
for feh in [-1.75, -2.25]:
    p.plot(iV(ms, AGE, feh) - iI(ms, AGE, feh),
           iI(ms, AGE, feh),
           'k:',
           label='age = {:.2f} Gyr, feh={:.2f}'.format(AGE, feh))
FEH = -2.5
AGE = 12.0
ms = np.arange(1, 300, 0.1)  ## actually eep
Ejemplo n.º 24
0
    def __init__(self,u1=0.394,u2=0.261,pmin=0.007,pmax=2,nps=200,nzs=200,zmax=None):
        self.u1 = u1
        self.u2 = u2
        self.pmin = pmin
        self.pmax = pmax
        if zmax is None:
            zmax = 1+pmax
        self.zmax = zmax
        self.nps = nps

        ps = np.logspace(np.log10(pmin),np.log10(pmax),nps)
        if pmax < 0.5:
            zs = np.concatenate([np.array([0]),ps-1e-10,ps,np.arange(pmax,1-pmax,0.01),
                              np.arange(1-pmax,zmax,0.005)])
        elif pmax < 1:
            zs = np.concatenate([np.array([0]),ps-1e-10,ps,np.arange(1-pmax,zmax,0.005)])
        else:
            zs = np.concatenate([np.array([0]),ps-1e-10,ps,np.arange(pmax,zmax,0.005)])

        self.nzs = np.size(zs)
        #zs = linspace(0,zmax,nzs)
        #zs = concatenate([zs,ps,ps+1e-10])

        mu0s = np.zeros((np.size(ps),np.size(zs)))
        lambdads = np.zeros((np.size(ps),np.size(zs)))
        etads = np.zeros((np.size(ps),np.size(zs)))
        fs = np.zeros((np.size(ps),np.size(zs)))
        for i,p0 in enumerate(ps):
            f,res = occultquad(zs,u1,u2,p0,return_components=True)
            mu0s[i,:] = res[0]
            lambdads[i,:] = res[1]
            etads[i,:] = res[2]
            fs[i,:] = f
        P,Z = np.meshgrid(ps,zs)
        points = np.array([P.ravel(),Z.ravel()]).T
        self.mu0 = interpnd(points,mu0s.T.ravel())
        
        ##need to make two interpolation functions for lambdad 
        ## b/c it's strongly discontinuous at z=p
        mask = (Z<P)
        pointmask = points[:,1] < points[:,0]

        w1 = np.where(mask)
        w2 = np.where(~mask)
        wp1 = np.where(pointmask)
        wp2 = np.where(~pointmask)

        self.lambdad1 = interpnd(points[wp1],lambdads.T[w1].ravel())
        self.lambdad2 = interpnd(points[wp2],lambdads.T[w2].ravel())
        def lambdad(p,z):
            #where p and z are exactly equal, this will return nan....
            p = np.atleast_1d(p)
            z = np.atleast_1d(z)
            l1 = self.lambdad1(p,z)
            l2 = self.lambdad2(p,z)
            bad1 = np.isnan(l1)
            l1[np.where(bad1)]=0
            l2[np.where(~bad1)]=0
            return l1*~bad1 + l2*bad1
        self.lambdad = lambdad
        
        #self.lambdad = interpnd(points,lambdads.T.ravel())
        self.etad = interpnd(points,etads.T.ravel())        
        self.fn = interpnd(points,fs.T.ravel())
Ejemplo n.º 25
0
if not on_rtd:
    import astropy.constants as const
    AU = const.au.cgs.value
    RSUN = const.R_sun.cgs.value
    MSUN = const.M_sun.cgs.value
    REARTH = const.R_earth.cgs.value
    MEARTH = const.M_earth.cgs.value
    G = const.G.cgs.value
    DAY = 86400.

    DATAFOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))

    LDDATA = np.recfromtxt('{}/keplerld.dat'.format(DATAFOLDER),names=True)
    LDOK = ((LDDATA.teff < 10000) & (LDDATA.logg > 2.0) & (LDDATA.feh > -2))
    LDPOINTS = np.array([LDDATA.teff[LDOK],LDDATA.logg[LDOK]]).T
    U1FN = interpnd(LDPOINTS,LDDATA.u1[LDOK])
    U2FN = interpnd(LDPOINTS,LDDATA.u2[LDOK])
else:
    const, AU, RSUN, MSUN = (None, None, None, None)
    REARTH, MEARTH, DAY = (None, None, None)
    DATAFOLDER = None
    LDDATA, LDOK, LDPOINTS, U1FN, U2FN = (None, None, None, None, None)
    

def ldcoeffs(teff,logg=4.5,feh=0):
    """
    Returns limb-darkening coefficients in Kepler band.
    """
    teffs = np.atleast_1d(teff)
    loggs = np.atleast_1d(logg)
Ejemplo n.º 26
0
    import astropy.constants as const
    AU = const.au.cgs.value
    RSUN = const.R_sun.cgs.value
    MSUN = const.M_sun.cgs.value
    REARTH = const.R_earth.cgs.value
    MEARTH = const.M_earth.cgs.value
    G = const.G.cgs.value
    DAY = 86400.

    DATAFOLDER = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'data'))

    LDDATA = np.recfromtxt('{}/keplerld.dat'.format(DATAFOLDER), names=True)
    LDOK = ((LDDATA.teff < 10000) & (LDDATA.logg > 2.0) & (LDDATA.feh > -2))
    LDPOINTS = np.array([LDDATA.teff[LDOK], LDDATA.logg[LDOK]]).T
    U1FN = interpnd(LDPOINTS, LDDATA.u1[LDOK])
    U2FN = interpnd(LDPOINTS, LDDATA.u2[LDOK])
else:
    const, AU, RSUN, MSUN = (None, None, None, None)
    REARTH, MEARTH, DAY = (None, None, None)
    DATAFOLDER = None
    LDDATA, LDOK, LDPOINTS, U1FN, U2FN = (None, None, None, None, None)

MAXSLOPE = 30


def ldcoeffs(teff, logg=4.5, feh=0):
    """
    Returns limb-darkening coefficients in Kepler band.
    """
    teffs = np.atleast_1d(teff)
Ejemplo n.º 27
0
    def __init__(self,
                 u1=0.394,
                 u2=0.261,
                 pmin=0.007,
                 pmax=2,
                 nps=200,
                 nzs=200,
                 zmax=None):
        self.u1 = u1
        self.u2 = u2
        self.pmin = pmin
        self.pmax = pmax
        if zmax is None:
            zmax = 1 + pmax
        self.zmax = zmax
        self.nps = nps

        ps = np.logspace(np.log10(pmin), np.log10(pmax), nps)
        if pmax < 0.5:
            zs = np.concatenate([
                np.array([0]), ps - 1e-10, ps,
                np.arange(pmax, 1 - pmax, 0.01),
                np.arange(1 - pmax, zmax, 0.005)
            ])
        elif pmax < 1:
            zs = np.concatenate([
                np.array([0]), ps - 1e-10, ps,
                np.arange(1 - pmax, zmax, 0.005)
            ])
        else:
            zs = np.concatenate(
                [np.array([0]), ps - 1e-10, ps,
                 np.arange(pmax, zmax, 0.005)])

        self.nzs = np.size(zs)
        #zs = linspace(0,zmax,nzs)
        #zs = concatenate([zs,ps,ps+1e-10])

        mu0s = np.zeros((np.size(ps), np.size(zs)))
        lambdads = np.zeros((np.size(ps), np.size(zs)))
        etads = np.zeros((np.size(ps), np.size(zs)))
        fs = np.zeros((np.size(ps), np.size(zs)))
        for i, p0 in enumerate(ps):
            f, res = occultquad(zs, u1, u2, p0, return_components=True)
            mu0s[i, :] = res[0]
            lambdads[i, :] = res[1]
            etads[i, :] = res[2]
            fs[i, :] = f
        P, Z = np.meshgrid(ps, zs)
        points = np.array([P.ravel(), Z.ravel()]).T
        self.mu0 = interpnd(points, mu0s.T.ravel())

        ##need to make two interpolation functions for lambdad
        ## b/c it's strongly discontinuous at z=p
        mask = (Z < P)
        pointmask = points[:, 1] < points[:, 0]

        w1 = np.where(mask)
        w2 = np.where(~mask)
        wp1 = np.where(pointmask)
        wp2 = np.where(~pointmask)

        self.lambdad1 = interpnd(points[wp1], lambdads.T[w1].ravel())
        self.lambdad2 = interpnd(points[wp2], lambdads.T[w2].ravel())

        def lambdad(p, z):
            #where p and z are exactly equal, this will return nan....
            p = np.atleast_1d(p)
            z = np.atleast_1d(z)
            l1 = self.lambdad1(p, z)
            l2 = self.lambdad2(p, z)
            bad1 = np.isnan(l1)
            l1[np.where(bad1)] = 0
            l2[np.where(~bad1)] = 0
            return l1 * ~bad1 + l2 * bad1

        self.lambdad = lambdad

        #self.lambdad = interpnd(points,lambdads.T.ravel())
        self.etad = interpnd(points, etads.T.ravel())
        self.fn = interpnd(points, fs.T.ravel())
Ejemplo n.º 28
0
        def foo(*args, **kwargs):
            pass

        return foo


if not on_rtd:
    DATAFOLDER = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'data'))

    Es = np.load(os.path.join(DATAFOLDER, 'Etable.npy'))
    eccs = np.load(os.path.join(DATAFOLDER, 'Etable_eccs.npy'))
    Ms = np.load(os.path.join(DATAFOLDER, 'Etable_Ms.npy'))
    ECCS, MS = np.meshgrid(eccs, Ms)
    points = np.array([MS.ravel(), ECCS.ravel()]).T
    EFN = interpnd(points, Es.ravel())
else:
    DATAFOLDER, Es, eccs, Ms, ECCS, MS = (None, None, None, None, None, None)
    points, EFN = (None, None)


def Efn(Ms, eccs):
    """
    Returns Eccentric anomaly, interpolated from pre-computed grid of M, ecc

    Instantaneous solution of Kepler's equation!

    Works for ``-2*np.pi < Ms < 2*np.pi`` and ``eccs <= 0.97``
    
    :param Ms: (``float`` or array-like)
        Mean anomaly