예제 #1
0
 def _get_deltacrit(self):
     deltacrit = self.delta_crit(self.z)
     lgdc = np.log10(deltacrit)
     self.f_lgdc_reverse = spline1d(lgdc, self.lgz)
     self.f_lgdc = spline1d(self.lgz, lgdc)
     min_interval_lgdc = np.min(lgdc[1:]-lgdc[:-1])
     self.stp_lgdc  = 2.*min_interval_lgdc
예제 #2
0
    def _get_sigma_M(self):
        """
        """
        sig    = self.sigma_r_0(self.scale)
        self.lgsig  = np.log10(sig)
        self.lgsig_reverse = self.lgsig[::-1]

        self.dlgsig = self.lgsig[2:] - self.lgsig[:-2]
        self.f_lgsig         = spline1d(self.lgmass, self.lgsig)
        self.f_lgsig_reverse = spline1d(self.lgsig_reverse, 
                                        self.lgmass[::-1])
예제 #3
0
파일: signal.py 프로젝트: QRAAT/QRAAT
def compute_bearing_splines(sv):
  ''' Interpolate steering vectors. ''' 
  x = np.arange(-360,360)
  splines = {}
  for (id, G) in sv.steering_vectors.iteritems():
    splines[id] = []
    for i in range(NUM_CHANNELS):
      y = np.array(G)[:,i]; 
      y = np.hstack((y,y))
      I = spline1d(x, np.real(y)) # In-phase
      Q = spline1d(x, np.imag(y)) # Quadrature
      splines[id].append((I, Q)) 
  return splines
예제 #4
0
 def setup_correlation_func_table(self):
     _r, _x = self.correlation_function()
     self.cortbl_rmin = _r[0]
     self.cortbl_rmax = _r[-1]
     # use natural log here because NumSBT returns a 2^n grid.
     _logr = np.log(_r)
     self.correlation_func_table = spline1d(_logr, _x)
예제 #5
0
    def interpolate(self, species, index=0, unit="micron", *args, **kwargs):

        """
        Create an interpolation object for the mass extinction/absorption/
        scattering coefficients.
        
        Additional arguments can be passed to the interpolation object.
        
        The unit of the wavelength for the interpolation can be chosen.
        
        @param species: The dust species (from Dust.dat)
        @type species: string
                
        @keyword index: The index of the kappas in the .opacity/.particle file. 
                        0: extinction, 1: absorption, 2: scattering
                        
                        (default: 0)
        @type index: int
        @keyword unit: The unit of the wavelength. Can be given as u.Unit() 
                       object or as a string representation of those objects.
                       Can range from length, to frequency, and energy
        
                       (default: micron)
        @type unit: str/u.Unit()
                
        @return: The interpolator for the mass extinction/absorption/scattering
                 coefficients.
        @rtype: spline1d 
        
        """

        return spline1d(x=self.getWavelength(species, unit=unit), y=self.getKappas(species, index), *args, **kwargs)
예제 #6
0
 def get_resampler(self, resolution, include_data=False):
     out = SmoothSampler()
     meas = []
     for (t0, t1), interp in zip(self.times, self.interps):
         out.times.append((t0, t1))
         # definite integral generator.
         spi = interp.antiderivative()
         n = max(((t1 - t0) / resolution * 2).round(), 1.)
         res = (t1 - t0) / n
         t = np.arange(n + 1) * res
         y = np.diff(spi(t)) / res  # integrate in each bin.
         # bi-linear extrapolation
         y1 = np.zeros(len(y) + 1)
         y1[:-1] = y / 2
         y1[1:] += y / 2
         y1[0] *= 2
         y1[-1] *= 2
         sp = spline1d(t, y1, k=min(3, len(y1) - 1))
         out.interps.append(sp)
         if include_data:
             meas.append((t + t0, y1))
     if include_data:
         t, y = np.hstack([m[0]
                           for m in meas]), np.hstack([m[1] for m in meas])
         m = Measurements.from_simple(t, y)
         return (out, m)
     return out
예제 #7
0
 def set_massrich(self):
     if self.numnod == 2:
         self.log_richness_mean = interp1d(self.lnMnod, self.lnNnod)
     if self.numnod > 2:
         self.log_richness_mean = spline1d(self.lnMnod,
                                           self.lnNnod,
                                           k=self.numnod - 1)
예제 #8
0
    def interpolate(self, species, index=0, unit='micron', *args, **kwargs):
        """
        Create an interpolation object for the mass extinction/absorption/
        scattering coefficients.
        
        Additional arguments can be passed to the interpolation object.
        
        The unit of the wavelength for the interpolation can be chosen.
        
        @param species: The dust species (from Dust.dat)
        @type species: string
                
        @keyword index: The index of the kappas in the .opacity/.particle file. 
                        0: extinction, 1: absorption, 2: scattering
                        
                        (default: 0)
        @type index: int
        @keyword unit: The unit of the wavelength. Can be given as u.Unit() 
                       object or as a string representation of those objects.
                       Can range from length, to frequency, and energy
        
                       (default: micron)
        @type unit: str/u.Unit()
                
        @return: The interpolator for the mass extinction/absorption/scattering
                 coefficients.
        @rtype: spline1d 
        
        """

        return spline1d(x=self.getWavelength(species,unit=unit),\
                        y=self.getKappas(species,index),*args,**kwargs)
예제 #9
0
def gen_xihm(masswant):
    from scipy.interpolate import InterpolatedUnivariateSpline as spline1d
    if np.isscalar(masswant):
        masswant = np.asarray([
            masswant,
        ])
    else:
        masswant = np.asarray(masswant)

    cp = CosmoParams(set_flat=True)
    h = cp.h
    z = 0.0
    DELTA_HALO = 200.0

    den = Density(cosmo=cp)
    rho_mean = den.rho_mean_z(z=z)
    lin = LinearTheory(cosmo=cp, z=z)

    hs = HaloStat(cosmo=cp, z=z, DELTA_HALO=DELTA_HALO)
    mass = hs.mass

    bias_func = hs.bias_function

    hg = HaloGrowth(cosmo=cp)
    nvir = 100
    mvir = setup_logbin(xmin=mass[0], xmax=mass[-1] * 5., nbin=nvir)
    cvir = np.zeros(nvir)
    m200 = np.zeros(nvir)
    c200 = np.zeros(nvir)
    for i in range(nvir):
        cvir[i] = hg.MAH(mvir[i], z)
        m200[i], c200[i] = den.vir2delta(z, mvir[i], cvir[i], DELTA_HALO)
    lgm200 = np.log10(m200)
    f_cmrelation = spline1d(lgm200, c200)
    c200_func = f_cmrelation(np.log10(mass))

    indxwant = np.searchsorted(mass, masswant)
    c200want = c200_func[indxwant]
    biaswant = bias_func[indxwant]

    radius_hinv = setup_logbin(0.0001, 200.0, 200)
    radius = radius_hinv / h

    xi3d = lin.correlation_func_interp()
    ximm = xi3d(radius)

    xihm_lin = []
    xihm_all = []
    for m, b, c in zip(masswant, biaswant, c200want):
        this_nfw = NFW(m, c, rho_mean, DELTA_HALO=DELTA_HALO)
        halo_profile = this_nfw.profile(radius)
        this_xihm = xi_hm(radius, halo_profile, ximm, b, rho_mean)
        xihm_all.append(this_xihm)
        this_blin = b * ximm
        xihm_lin.append(this_blin)
    xihm_lin = np.asarray(xihm_lin)
    xihm_all = np.asarray(xihm_all)

    return (radius_hinv, radius, xihm_all, xihm_lin)
예제 #10
0
 def setup_sigma_r_table(self, rmin=0.001, rmax=100, nrbin=50):
     _lgr = np.linspace(np.log10(rmin), np.log10(rmax), num=nrbin)
     _r = np.power(10.0, _lgr)
     _sig = self.sigma_r(_r)
     self.sigtbl_rmin = rmin
     self.sigtbl_rmax = rmax
     self.sigtbl_nrbin = nrbin
     self.sigma_r_table = spline1d(_lgr, _sig)
예제 #11
0
 def __init__(self):
     cfg = moby2.user_cfg
     assert 'planet_data' in cfg and 'ESA_models' in cfg['planet_data']
     import os
     full_path = os.path.join(cfg['planet_data']['ESA_models'],
                              self.filename)
     data = moby2.util.StructDB.from_fits_table(full_path)
     x, y = [data[c] for c in self.columns]
     self.valid_freqs = [x[0], x[-1]]
     self.func = spline1d(x, y)
예제 #12
0
파일: position.py 프로젝트: QRAAT/QRAAT
def compute_bearing_spline(l): 
  ''' Interpolate a spline on a bearing likelihood distribuiton. 
    
    Input an aggregated bearing distribution, e.g. the output of 
    `aggregate_spectrum(p)` where p is the output of `_per_site_data.mle()` 
    or `_per_site_data.bartlet()`.
  '''
  bearing_domain = np.arange(-360,360)       
  likelihood_range = np.hstack((l, l))
  return spline1d(bearing_domain, likelihood_range)
def getSpecSpline(spec):
    if spec == 'tt':
        cl = cl_tt
    elif spec == 'ee':
        cl = cl_ee
    elif spec == 'te':
        cl = cl_te
    elif spec == 'eb' or spec == 'tb':
        cl = np.zeros(l_vec.shape)
    return (spline1d(l_vec, cl))
예제 #14
0
파일: kk.py 프로젝트: GiggleLiu/thesis
def matrix_spline_f(x,y,**kwargs):
    '''
    spline over multi-dimensional array - the function version.

    x/y:
        the x/y data, y is an array of matrix.
    \*\*kwargs:
        key word arguments for spline.

    *return*:
        the new list of y.
    '''
    nband=y.shape[-1]
    dtype=y.dtype
    assert(dtype=='complex128' or dtype=='float64')
    fs=ndarray([nband,nband],dtype='O')
    for i in xrange(nband):
        for j in xrange(nband):
            if dtype=='complex128':
                fcr=spline1d(x,y[:,i,j].real,**kwargs)
                fci=spline1d(x,y[:,i,j].imag,**kwargs)
                fs[i,j]=(fcr,fci)
            else:
                fc=spline1d(x,y[:,i,j],**kwargs)
                fs[i,j]=fc
    def mspl(x_new):
        if ndim(x_new)==0:
            ndata=ndarray([nband,nband],dtype=dtype)
        else:
            ndata=ndarray([len(x_new),nband,nband],dtype=dtype)
        for i in xrange(nband):
            for j in xrange(nband):
                if dtype=='complex128':
                    fcr,fci=fs[i,j]
                    ndata[...,i,j]=fcr(x_new)+1j*fci(x_new)
                else:
                    fc=fs[i,j]
                    ndata[...,i,j]=fc(x_new)
        return ndata
    return mspl
예제 #15
0
def outlier_fill(data, ok=None):
    """
    Remove extreme outliers, spline interpolating to fill the gaps.
    """
    import scipy.stats.mstats as ms
    from scipy.interpolate import InterpolatedUnivariateSpline as spline1d
    if ok is None:
        lo, hi = ms.mquantiles(data, (0.03, 0.97))
        lo_bound = lo - (hi - lo) * .5
        hi_bound = hi + (hi - lo) * .5
        ok = (lo_bound <= data) * (data <= hi_bound)
    ## Interpolate
    x = numpy.arange(len(data))
    filler = spline1d(x[ok], data[ok])
    data[~ok] = filler(x[~ok])
    return data
예제 #16
0
파일: kk.py 프로젝트: GiggleLiu/thesis
def kk_smooth(data,which,wlist=None):
    '''
    Kramers-Kronig-relations, even-odd effect avoided,

    Note:
        even input function -> odd ouputput function
        odd input function -> even ouputput function

    data:
        original data, which is defined on wlist.
    which:
        * `i2r` -> imag to real.
        * `r2i` -> real to imag
    wlist:
        provide the wlist instead of an uniform one.
    '''
    nw=len(data)
    if wlist is None:
        wlist=linspace(-1,1,nw*2-1)
        wl_eval=wlist[1::2]
        wl_int=wlist[::2]
    else:
        wl_eval=(wlist[1:]+wlist[:-1])/2
        wl_int=wlist
    if ndim(data)>1:
        is_scalar=False
        nax=ndim(data)-1
    else:
        is_scalar=True
    rl=[]
    for i,w in enumerate(wl_eval):
        cwl,cil=wl_int,data
        if is_scalar:
            r=trapz(cil/(w-cwl),cwl,axis=0)
        else:
            r=trapz(cil/(w-cwl[[slice(None)]+[newaxis]*nax]),cwl,axis=0)
        rl.append(r)
    rl=array(rl)/(pi if which =='r2i' else -pi)
    if is_scalar:
        rfunc=spline1d(wl_eval,rl,ext=0)
    else:
        rfunc=matrix_spline_f(wl_eval,rl,ext=0)
    rl=rfunc(wl_int)
    return rl
예제 #17
0
 def setInnerEps(self,inner_eps):
 
     '''
     Set the inner wind epsilon for the T law. Only relevant when self.inner
     is 1. 
     
     Changes the standard T law as well, in case inner eps is different from
     when the instance of the class was created.
     
     @param inner_eps: the epsilon of the inner wind power law. 
     @type inner_eps: float
     
     '''
     
     self.inner_eps = inner_eps
     
     #-- re-initialise some parameters
     self.r = None
     self.T = None
     self.y = None
     self.dTdr = None
     
     #-- Run the class' own eval() method, with r=self.x, which will not be 
     #   equal to the class' self.r attribute (which is now None), and thus 
     #   it will evaluated properly. Reevaluated if epsilon is different upon
     #   eval call.
     self.T = self.eval(self.x,inner_eps=self.inner_eps,warn=0)
     self.y = self.T
     
     #-- Now also redo the derivative method. Then call diff to set the 
     #   standard derivative of the instance
     if self.interp_dfunc: 
         self.dfunc = spline1d(x=self.x,y=op.diff_central(self.y,self.x),\
                               k=self.order)
     
     #-- Evaluate the derivative with the default grid
     self.dydx = self.diff(self.x,inner_eps=self.inner_eps,warn=0)
     
     #-- Now set r and dTdr.
     self.r = self.x
     self.dTdr = self.dydx
예제 #18
0
    def setInnerEps(self, inner_eps):
        '''
        Set the inner wind epsilon for the T law. Only relevant when self.inner
        is 1. 
        
        Changes the standard T law as well, in case inner eps is different from
        when the instance of the class was created.
        
        @param inner_eps: the epsilon of the inner wind power law. 
        @type inner_eps: float
        
        '''

        self.inner_eps = inner_eps

        #-- re-initialise some parameters
        self.r = None
        self.T = None
        self.y = None
        self.dTdr = None

        #-- Run the class' own eval() method, with r=self.x, which will not be
        #   equal to the class' self.r attribute (which is now None), and thus
        #   it will evaluated properly. Reevaluated if epsilon is different upon
        #   eval call.
        self.T = self.eval(self.x, inner_eps=self.inner_eps, warn=0)
        self.y = self.T

        #-- Now also redo the derivative method. Then call diff to set the
        #   standard derivative of the instance
        if self.interp_dfunc:
            self.dfunc = spline1d(x=self.x,y=op.diff_central(self.y,self.x),\
                                  k=self.order)

        #-- Evaluate the derivative with the default grid
        self.dydx = self.diff(self.x, inner_eps=self.inner_eps, warn=0)

        #-- Now set r and dTdr.
        self.r = self.x
        self.dTdr = self.dydx
예제 #19
0
    plt.plot(l_arr,
             np.sqrt(l_arr_fac *
                     (conv_out_spec_rescaled[:, i]).astype('float')),
             label=est + ' out from ' + str(n) + ' ' + spec + ' map(s)')

    #plt.plot(l_arr, conv_from_noise_spec[:,i]*rescaleConvOut, label=est+ ' out from '+str(n)+ ' '+spec+' noise map(s)')

    #plt.plot(l_arr, np.sqrt(conv_from_unlensed_spec[:,i]*rescaleConvOut), label=est+ ' out from '+str(n)+' unlensed '+spec+' map(s)')
    #plt.plot(l_arr, np.sqrt((conv_from_unlensed_spec[:,i]-conv_out_spec[:,i])*rescaleConvOut), label='from unlensed-total')
    #plt.plot(l_arr, np.sqrt(np.abs(conv_out_spec[:,i]-conv_from_unlensed_spec[:,i])*rescaleConvOut), label='output-unlensed')

Ls_N0 = np.loadtxt(N0_directory + '/planck_N_' + (spec))  #upper(spec)
Ls = (Ls_N0[0, :]).astype(int)
N0dd = Ls_N0[1, :]
N0kk = Ls**4 * N0dd
N0kk_spline = spline1d(Ls, N0kk)
if (subtract_N0):
    #read in and plot N0 corrections to lensing spectra

    N0kk_to_plot = Ls * (Ls + np.ones(Ls.shape)) * N0kk / (2 * pi)

    conv_in_spline = (l_vec, cl_kk)
    conv_in_Ls = conv_in_spline(Ls)

    l_arr_new, ind = np.unique(l_arr, return_index=True)
    ind[1] = 2
    conv_out_spec_new = conv_out_spec[:, 0].reshape(l_arr.shape)[ind]
    conv_out_spline = spline1d(l_arr_new, conv_out_spec_new)
    conv_out_Ls = conv_out_spline(Ls)

    conv_in_plus_noise = Ls * (Ls + np.ones(Ls.shape)) * conv_in_Ls / (
def diffSpectraManual(ls, cs):
    cspl = spline1d(ls, cs)
    dcdl = np.zeros(ls.shape[0])
    for i in range(ls.shape[0]):
        dcdl[i] = (cspl(ls[i] * 1.01) - cspl(ls[i] * 0.99)) / (ls[i] * 0.02)
    return dcdl
예제 #21
0
    def _initialize_mass_function(self):
        """ Find the four fitting parameters for Tinker05 mass function.
        """
        _logDELTA_HALO = log(self.DELTA_HALO)
        x       = np.arange(1.0,10.0,1.0)
        odd     = np.arange(0,9,2)
        even    = np.arange(1,9,2)
        x[odd]  = np.log(200.0*np.power(2.0,(x[odd]-1)/2.0))
        x[even] = np.log(300.0*np.power(2.0,(x[even]-2)/2.0))
        y = np.array([1.858659e-01,
                      1.995973e-01,
                      2.115659e-01,
                      2.184113e-01,
                      2.480968e-01,
                      2.546053e-01,
                      2.600000e-01,
                      2.600000e-01,
                      2.600000e-01,
                      ])
        f1 = spline1d(x, y) 
        a1 = f1(_logDELTA_HALO)
        if(self.DELTA_HALO>=1600):
            a1 = 0.26
        y = np.array([1.466904e+00,
                      1.521782e+00,
                      1.559186e+00,
                      1.614585e+00,
                      1.869936e+00,
                      2.128056e+00,
                      2.301275e+00,
                      2.529241e+00,
                      2.661983e+00,
                      ])
        f2 = spline1d(x, y) 
        a2 = f2(_logDELTA_HALO)
        y = np.array([2.571104e+00, 
                      2.254217e+00, 
                      2.048674e+00, 
                      1.869559e+00, 
                      1.588649e+00, 
                      1.507134e+00, 
                      1.464374e+00, 
                      1.436827e+00, 
                      1.405210e+00, 
                      ])
        f3 = spline1d(x, y) 
        a3 = f3(_logDELTA_HALO)
        y = np.array([1.193958e+00,
                      1.270316e+00,
                      1.335191e+00,
                      1.446266e+00,
                      1.581345e+00,
                      1.795050e+00,
                      1.965613e+00,
                      2.237466e+00,
                      2.439729e+00,
                      ])
        f4 = spline1d(x, y) 
        a4 = f4(_logDELTA_HALO)
        ztemp = self.z > 3.0 and 3.0 or self.z
        a1 = a1*pow(1.0+ztemp, -0.14)
        a2 = a2*pow(1.0+ztemp, -0.06)
        at  = -pow(0.75/log10(self.DELTA_HALO/75.0),1.2)
        at  = pow(10.0,at)
        # Eduardo's buggy version, sigh...
#        at  = -pow(0.75/log(self.DELTA_HALO/75.0),1.2)
#        at  = exp(at)
        a3 = a3*pow(1.0+ztemp, -at)
        self.a1, self.a2, self.a3, self.a4 = (a1,a2,a3,a4)
"""
w=np.loadtxt('wmap_tt_spec.txt')
l_w, c_w=w[:,0], w[:,1]
cw_spl=spline1d(l_w, c_w*2*np.pi/(l_w*(l_w+1)))
"""

if spec == 'tt' or spec == 'ee' or spec == 'te':
    clspl = getSpecSpline(spec)
    #nlspl=getNoiseSpline(spec)
elif spec == 'tb':
    clspl = getSpecSpline('te')
elif spec == 'eb':
    clspl = getSpecSpline('ee')
    #nlspl=getNoiseSpline('ee') ?????

Kspl = spline1d(np.concatenate((np.array([0, 1]), l_vec)),
                np.concatenate((np.array([K[0]]), np.array([K[0]]), K)))

lx = np.arange(-lmax, lmax, delta_l)
ly = np.arange(-lmax, lmax, delta_l)

print lx

lxs, lys = np.meshgrid(lx, ly)

l = np.sqrt(lxs**2 + lys**2)

clgrid = np.zeros(l.shape)
#nlgrid=np.zeros(l.shape)
Kgrid = np.zeros(l.shape)
#c_w_grid=np.zeros(r.shape)
cos_2theta_grid = (lxs**2 - lys**2) / (lxs.astype(float)**2 + lys**2)
예제 #23
0
    def __init__(self, l, func, dfunc=None, order=3, *args, **kwargs):
        '''
        Create an instance of the Opacity() class. Requires a wavelength grid.
        
        The function can also be given as an interpolation object.
        
        The optional args and kwargs give the additional arguments for the 
        opacity function, which are ignored in case func is an interpolation 
        object.
        
        Eval and diff work with the mass extinction coefficient in cm2/g. 
        
        In case func refers to an interpolation object in KappaReader, the
        args/kwargs should always contain an index indicating whether extinction
        (default), absorption or scattering is requested:
            - 0: extinction, 
            - 1: absorption, 
            - 2: scattering

        Note that if func is an interpolator object, the original input x and y
        grids can be passed as additional keywords xin/lin and yin, which would 
        then be arrays. Otherwise, the x and the interpolator(x) are set as 
        xin/lin and yin. xin/lin and yin are ignored if func is a function, even
        if it returns an interpolator (in which case the original grids are 
        known)
        
        Extrapolation is done outside of the "original" (depending on if xin/yin
        are given) wavelength ranges according to a power law ~l^-alpha, with 
        alpha given upon eval() calls.
        
        @param l: The wavelength points (cm)
        @type l: array
        @param func: The function that describes the opacity profile. Can be 
                     given as an interpolation object, in which case lin and yin
                     keywords can be passed as arrays for the original grids.
        @type func: function
        
        @keyword dfunc: Function that describes the derivative of the profile 
                        with respect to x. Can be given as an interpolation 
                        object. If None, a generic central difference is taken & 
                        interpolated with a spline of which the order can be 
                        chosen.
        
                        (default: None)
        @type dfunc: function/interpolation object
        @keyword order: Order of the spline interpolation. Default is cubic.
                        
                        (default: 3)
        @type order: int
                
        @keyword args: Additional parameters passed to the functions when eval
                       or diff are called. 
                       
                       (default: [])
        @type args: tuple
        @keyword kwargs: Additional keywords passed to the functions when eval
                         or diff are called. 
                       
                         (default: {})
        @type kwargs: dict

        '''

        #-- Make sure lin is recognized
        if kwargs.has_key('lin'):
            kwargs['xin'] = kwargs['lin']
            del kwargs['lin']

        #-- Do not name func, dfunc, etc in function call, or *args won't work
        super(Opacity, self).__init__(l, func, dfunc, order, *args, **kwargs)

        #-- Remember the index of the opacities file. If relevant.
        if kwargs.has_key('index'):
            self.index = kwargs['index']
        else:
            self.index = 0

        #-- Set the default alpha. Not used if func is not an interpolator.
        self.alpha = 2.

        #-- If the requested function is not an interpolator of a file, do not
        #   change anything.
        if not self.interp_func:
            self.l = self.x
            self.kappa = self.y
            return

        #-- For Opacity(), in case of an interpolator object as function,
        #   the extrapolation must be re-done for it to be safe.
        #   The eval() method is rewritten here to function with a
        #   power law extrapolation, for which the settings can be chosen.
        #   The diff method must not be rewritten since it is based on the y
        #   profile.
        self.l = None
        self.kappa = None
        self.y = None

        #-- Run the class' own eval() method, with l=self.x, which will not be
        #   equal to the class' self.l attribute, and thus it will evaluated
        #   properly. Evaluated with alpha==2. Reevaluated if alpha is different
        self.kappa = self.eval(self.x, alpha=2.)
        self.y = self.kappa

        #-- Now also redo the derivative method, in case it is an interpolator
        if self.interp_dfunc:
            self.dfunc = spline1d(x=self.x,y=op.diff_central(self.y,self.x),\
                                  k=self.order)

            #-- Evaluate the derivative with the default grid
            self.dydx = self.dfunc(self.x, *self._dargs, **self._dkwargs)

        #-- Now set l, dydl.
        self.l = self.x
        self.dydl = self.dydx
예제 #24
0
    def __init__(self,x,func=interp_file,dfunc=None,order=3,*args,\
                 **kwargs):
    
        '''
        Create an instance of the Profiler() class. Requires a coordinate grid 
        and a function object for the profile. A function for the derivative is
        optional. The functions can also be given as an interpolation object.
        
        The optional args and kwargs give the additional arguments for the 
        two function, which are ignored in case func is an interpolation object.
        
        The default coordinate grid is evaluated for both the function and the
        derivative. They are saved in self.y and self.dydx. Alternatively, new
        evaluations can be attained through eval and diff.
        
        Note that if func is an interpolator object, the original input x and y
        grids can be passed as additional keywords xin and yin, which would then
        be arrays. Otherwise, the x and the interpolator(x) are set as xin and 
        yin. xin and yin are ignored if func is a function, even if it returns
        an interpolator (in which case the original grids are known)
        
        @param x: The default coordinate points, minimum three points. In the 
                  case of an interpolation function, this is the default grid
                  returned by the instance. The original x/y of the 
                  interpolated profile are saved as xori/yori in the object.
        @type x: array
        
        @keyword func: The function that describes the profile with respect to 
                       x. Can be given as an interp1d object. Default is a read
                       function that interpolates data and returns the 
                       interpolator object. If interpolation object, x and 
                       eval(x) are assumed to be the original grids, unless
                       xin and yin are given as keywords with arrays as values
                       for the original grids.
                       
                       (default: interp_file)
        @type func: function/interp1d object
        @keyword dfunc: Function that describes the derivative of the profile 
                        with respect to x. Can be given as an interpolation 
                        object. If None, a generic central difference is taken & 
                        interpolated with a spline of which the order can be 
                        chosen.
        
                        (default: None)
        @type dfunc: function/interpolation object
        @keyword order: Order of the spline interpolation of the derivative. 
                        Default is cubic. Not used for the interpolation if func
                        returns an interpolation object. Use read_order in that
                        case.
                        
                        (default: 3)
        @type order: int
        
        @keyword args: Additional parameters passed to the functions when eval
                       or diff are called. 
                       
                       (default: [])
        @type args: tuple
        @keyword kwargs: Additional keywords passed to the functions when eval
                         or diff are called. 
                       
                         (default: {})
        @type kwargs: dict
        
        '''
        
        #-- Check len of coordinate input. Cannot be less than three for the 
        #   derivative.
        if len(x) < 3:
            raise ValueError('Coordinate grid must have more than 2 elements.')
        
        #-- If the function is given as a string, retrieve it from the local 
        #   child module, or from the Profiler module (as parent). If the latter
        #   case then check if the function comes from one of Profiler's 
        #   attributes, such as the loaded DataIO module.
        #   Can also simply be a constant value, so try making a float first.
        if isinstance(func,str):
            try:
                #-- Check if a constant was given, rather than a function
                kwargs['c'] = float(func)
                func = constant

            except ValueError:
                #-- Note that self.module refers to the child, not Profiler
                if hasattr(sys.modules[self.__module__],func):
                    func = getattr(sys.modules[self.__module__],func)

                #-- Recursively find the function of loaded modules in Profiler
                #   or a function of the Profiler module itself if no '.'         
                else:
                    
                    func = DataIO.read(func=func,module=sys.modules[__name__],\
                                       return_func=1)
        
        #-- set functional args, remember spline order. args/kwargs for 
        #   func and dfunc are saved separately. They are removed if either are
        #   interpolation objects. They are always accessible, the _** variables
        #   are passed to the evaluation.
        self.args = args
        self.kwargs = kwargs
        self._args = self.args
        self._dargs = self.args
        self._dkwargs = self.kwargs
        self._kwargs = self.kwargs
        self.order = order
        
        #-- Grab default xin and yin keys in case they are included, and remove
        #   from the arguments dictionary. None if not available. 
        xin = self.kwargs.pop('xin',None)
        yin = self.kwargs.pop('yin',None)
        
        #-- By default no interpolation, so leave this off.
        self.interp_func = 0
        self.interp_dfunc = 0
        
        #-- Defaults for xori/yori, not used in case of normal functions
        self.xin = np.empty(0)
        self.yin = np.empty(0)
        
        #-- Evaluate the default grid with function. Set x as None first so it
        #   can actually evaluate. Set x once derivative has been evaluated. 
        self.x = None
        if not (isinstance(func,interp1d) or isinstance(func,UnivariateSpline)):
            #-- Evaluate the function, and check what is returned: array or 
            #   interpolation object
            y = func(x,*args,**kwargs)
            
            #-- Interpolation object: so set that as this instance's func. In 
            #   this case, the variable x passed to the class is the default x
            #   grid of this instance. The original x/y-grid is saved as xi, yi
            if isinstance(y,tuple):
                self.func = y[2]
                self.xin = y[0]
                self.yin = y[1]
                self._args = []
                self._kwargs = {}
                self.interp_func = 1
                self.y = self.func(x)
            else: 
                self.func = func
                self.y = y
                
        #-- func is an interpolation object, so just run the normal evaluation.
        #   Set _args/_kwargs to empty, so none are ever passed to the interpol
        else:
            self.func = func
            self._args = []
            self._kwargs = {}
            self.interp_func = 1
            self.y = self.func(x)
            self.yin = yin if not yin is None else self.y
            self.xin = xin if not xin is None else x
                                                    
        #-- Set the derivative function, resorting to default if needed
        if not dfunc is None:
            self.dfunc = dfunc
        elif self.func == constant:
            self.dfunc = zero
        else: 
            #-- Extend array slightly to allow odeint to succeed.
            #   Need better fix for this.
            #x0 = x[0]-(x[1]-x[0])#*0.5
            #xn = x[-1]+(x[-1]-x[-2])#*0.5
            #x_ext = np.hstack([[x0],x,[xn]])
            
            #-- Evaluate the function, and set up an interpolator for 
            #   central difference. The interpolator will extrapolate 
            #   beyond the given x range. This is necessary for odeint to work.
            #   Usually x-range is not exceeded much. 
            self.dfunc = spline1d(x=x,y=op.diff_central(self.y,x),\
                                  k=self.order)
        
        if (isinstance(self.dfunc,interp1d) \
                or isinstance(self.dfunc,UnivariateSpline)):
            self._dargs = []
            self._dkwargs = {}
            self.interp_dfunc = 1
        
        #-- Evaluate the derivative with the default grid
        self.dydx = self.dfunc(x,*self._dargs,**self._dkwargs)
        
        #-- Now set x.
        self.x = x
예제 #25
0
import numpy as np
import matplotlib.pyplot as plt
import scal_power_spectra
from scipy.interpolate import InterpolatedUnivariateSpline as spline1d

l_vec, cl_tt, cl_ee, cl_te, cl_tt_lens, cl_ee_lens, cl_bb_lens, cl_te_lens, cl_kk = scal_power_spectra.spectra(
)
clspl = spline1d(l_vec, cl_tt)
clspl_lens = spline1d(l_vec, cl_tt_lens)
ldcdl_spl = spline1d(l_vec, l_vec * np.gradient(cl_tt))

lmax = 8192
delta_l = 2
n = lmax / delta_l * 2

lx = np.arange(-lmax, lmax, delta_l)
ly = np.arange(-lmax, lmax, delta_l)

lxs, lys = np.meshgrid(lx, ly)

l = np.sqrt(lxs**2 + lys**2)

cos_2theta_grid = (lxs**2 - lys**2) / (lxs.astype(float)**2 + lys**2)
sin_2theta_grid = (2 * lxs * lys) / (lxs.astype(float)**2 + lys**2)
cos_2theta_grid[n / 2, n / 2] = 1
sin_2theta_grid[n / 2, n / 2] = 1

clgrid = np.zeros(l.shape)
clgridlens = np.zeros(l.shape)
ldcdl_grid = np.zeros(l.shape)
예제 #26
0
파일: plot.py 프로젝트: GiggleLiu/thesis
def plot_Fig10(filename,token,zooms):
    '''
    plot err as a function of r-index.
    '''
    lw=1
    ion()
    fig=figure(figsize=(8,4.5))
    ax=subplot(121)
    text(-1.4,2.75,'(a)')
    data=load(filename)
    wl=data[:,0].real
    nw=len(wl)
    gl=data[:,1:5].reshape([nw,2,2])
    fl=data[:,5:9].reshape([nw,2,2])
    sl=data[:,9:13].reshape([nw,2,2])
    al=(gl-swapaxes(gl,1,2).conj())*(1j/2./pi)
    bl=(fl-swapaxes(fl,1,2).conj())*(1j/2./pi)
    si=(sl-swapaxes(sl,1,2).conj())*(-1j/2.)
    a0=(al[:,0,0]+al[:,1,1]).real/2
    az=(al[:,0,0]-al[:,1,1]).real/2
    ax=(al[:,0,1]+al[:,1,0]).real/2
    plot(wl,a0,color='r',lw=lw)
    plot(wl,az,color='b',lw=lw)
    plot(wl,ax,color='k',lw=lw,ls='--')
    xlabel(r'$\omega$',fontsize=16)
    xlim(-1.5,1.5)
    yticks(arange(-1,4))
    ylim(-1,3)
    legend([r'$A_{0}$',r'$A_{z}$',r'$A_{x}$'],fontsize=10)
    axin=axes([0.1,0.65,0.15,0.2])
    xm,ym=0.05,80
    indmin,indmax=searchsorted(wl,[-xm,xm])
    axin.plot(wl[indmin:indmax],a0[indmin:indmax],color='r',lw=lw)
    axin.plot(wl[indmin:indmax],az[indmin:indmax],color='b',lw=lw)
    axin.plot(wl[indmin:indmax],ax[indmin:indmax],color='k',lw=lw,ls='--')
    setp(axin,ylim=(-ym,ym),xlim=(-xm,xm))
    xticks([-xm,xm],fontsize=10)
    yticks([-ym,ym],fontsize=10)

    ax2=subplot(122)
    text(-1.4,2.75,'(b)')
    #plot(wl,sr00,color='r',lw=lw)
    #plot(wl,sr11,color='b',lw=lw)
    #plot(wl,sr01,color='k',lw=lw)
    s0=(si[:,0,0]+si[:,1,1]).real/2
    sz=(si[:,0,0]-si[:,1,1]).real/2
    sx=(si[:,0,1]+si[:,1,0]).real/2
    plot(wl,s0,color='r',lw=lw,ls='-')
    plot(wl,sz,color='b',lw=lw,ls='-')
    plot(wl,sx,color='k',lw=lw,ls='--')
    xlabel(r'$\omega$',fontsize=16)
    xlim(-1.5,1.5)
    yticks([])
    ylim(-1,3)
    #legend([r'Re$[\Sigma_{00}]$',r'Re$[\Sigma_{11}]$',r'Re$[\Sigma_{01/10}]$',\
            #r'Im$[\Sigma_{00}]$',r'Im$[\Sigma_{11}]$',r'Im$[\Sigma_{01/10}]$'],ncol=2,fontsize=10)
    legend([r'Im$[\Sigma_{0}]$',r'Im$[\Sigma_{z}]$',r'Im$[\Sigma_{x}]$'])
    if zooms:
        axin=axes([0.55,0.65,0.15,0.2])
        xm,ym=0.2,2.
        indmin,indmax=searchsorted(wl,[-xm,xm])
        #axin.plot(wl[indmin:indmax],sr00[indmin:indmax],color='r',lw=lw)
        #axin.plot(wl[indmin:indmax],sr11[indmin:indmax],color='b',lw=lw)
        #axin.plot(wl[indmin:indmax],sr10[indmin:indmax],color='k',lw=lw)
        axin.plot(wl[indmin:indmax],s0[indmin:indmax],color='r',lw=lw,ls='--')
        axin.plot(wl[indmin:indmax],sz[indmin:indmax],color='b',lw=lw,ls='--')
        axin.plot(wl[indmin:indmax],sx[indmin:indmax],color='k',lw=lw,ls='--')
        setp(axin,ylim=(-ym,ym),xlim=(-xm,xm))
        xticks([-xm,xm],fontsize=10)
        yticks([-ym,ym],fontsize=10)

    tight_layout(w_pad=0.01)

    cla()
    af=spline1d(wl,al[:,0,0])
    wlist=linspace(-2,2,20000)
    al2=af(wlist)
    gr=(gl+swapaxes(gl.conj(),1,2))/2.
    gr2=kk_fft(-al2,which='i2r')*pi
    plot(wlist,gr2)
    plot(wl,gr[:,0,0])
    pdb.set_trace()
    savefig('spec%s.eps'%token)
    savefig('spec%s.png'%token)
예제 #27
0
 def _get_s_M(self):
     """
     """
     lgs = self.lgsig[1:-1] + self.dlgsig/(self.dlgmass*2.0)
     self.f_lgs = spline1d(self.lgsig_reverse[1:-1], lgs[::-1])
예제 #28
0
    def __call__(self, f):
        if f.type == FT.Calibration and f['cal_type'] == 'focal_plane':
            self.focal_plane = f

        if f.type != FT.Scan:
            return [f]

        if f.type == FT.EndProcessing:
            flush = True
        else:
            flush = False
            self.frame_buffer.append(f)
        self.raw_buffer.append(f[self.enc_name])

        # Figure out what frames we're able to process, given info we have.
        frames_out = []

        # Work in units of seconds.
        raw_t0, raw_t1 = self.raw_buffer[0].t[0], self.raw_buffer[-1].t[-1]
        # Process any frame that ends before raw_t1.
        frame_index = 0
        while len(self.frame_buffer) > 0:
            f = self.frame_buffer[0]
            if not flush and (f['signal'].stop.time / core.G3Units.sec >
                              raw_t1):
                break
            sig = f[self.signal_name]  # f['signal']
            frame_t0 = sig.start.time / core.G3Units.sec
            frame_t1 = sig.stop.time / core.G3Units.sec
            tick_rate = sig.sample_rate / core.G3Units.Hz
            # Figure out what range of samples we will be able to set.
            start_index = np.ceil((raw_t0 - frame_t0) * tick_rate)
            end_index = np.floor((raw_t1 - frame_t0) * tick_rate) + 1
            start_index = max(0, int(start_index))
            end_index = min(int(end_index), sig.n_samples)
            if end_index != sig.n_samples and not flush:
                # Buffer.
                break

            # Otherwise, do the interpolations...
            frames_out.append(self.frame_buffer.pop(0))
            t_raw = np.hstack([r.t for r in self.raw_buffer])
            t_int = frame_t0 + np.arange(start_index, end_index) / tick_rate
            boresight = core.G3TimestreamMap()
            vs = {}
            for k in ['az', 'el', 'corot']:
                interp = spline1d(
                    t_raw, np.hstack([r.data[k] for r in self.raw_buffer]))
                v = np.empty(sig.n_samples)
                v[:start_index] = np.nan
                v[start_index:end_index] = interp(t_int)
                v[end_index:] = np.nan
                vs[k] = v
                boresight[k] = core.G3Timestream(vs[k])

            boresight.start = sig.start
            boresight.stop = sig.stop
            f[self.boresight_name] = boresight  # f['boresight']

            # Compute quaternion.
            q = (  # Sky <-- near (el, az=0)
                coords.q_euler(2, -vs['az'] * np.pi / 180) *
                # ... sky at az=0 <-- near (el=0,az=0)
                coords.q_euler(1, -vs['el'] * np.pi / 180) *
                # ... (1,-xi,eta) <-- (-eta,-xi,1)
                coords.q_euler(1, np.pi / 2) *
                # ... (-eta,-xi,1) <-- (eta,xi,1)
                coords.q_euler(2, np.pi))
            # Note that there's no "TimestreamQuat" class.  So no timestamps.
            f[self.boresight_name + '_q'] = q  # f['boresight_q']

        # Discard raw data we're not using any more.  Out of caution,
        # keep one more frame than we have buffered.
        while len(self.raw_buffer) - len(self.frame_buffer) > 2:
            self.raw_buffer.pop(0)

        return frames_out
예제 #29
0
    def __init__(self,r,func,dfunc=None,order=3,inner=0,inner_eps=0.5,\
                 *args,**kwargs):
    
        '''
        Create an instance of the Temperature() class. Requires a radial grid  
        and a temperature function.
        
        The function can also be given as an interp1d object.
        
        The optional args and kwargs give the additional arguments for the 
        temperature function, which are ignored in case func is an interp1d 
        object.
        
        An additional option concerns the extrapolation to smaller radii, e.g.
        in the inner wind between the stellar surface and the dust condensation
        radius. In this case, the eval/diff methods will differ between inner 
        wind (r<r0) and the rest of the wind (r>r0) in terms of evaluation. 
        
        At r>r0: The given func (or interpolator) is used.
        At r<r0: A Teps power law is used, for which 1 out of Tstar or 
        epsilon can be defined. The default sets epsilon == 0.5 (the optically
        thin case), but inner_epsilon can be passed to the initialisation if 
        needed. r0, T0 must be defined in kwargs either for the
        main wind's Teps law, or as an additional argument if a file is read.
        
        @param r: The radial points (cm)
        @type r: array
        @param func: The function that describes the temperature profile. Can be 
                     given as an interp1d object.
        @type func: function
        
        @keyword dfunc: The function that describes the derivative of the  
                        profile with respect to r. Can be given as an interp1d 
                        object. If None, a generic central difference is taken  
                        and interpolated.
        
                        (default: None)
        @type dfunc: function/interp1d object
        @keyword order: Order of the spline interpolation. Default is cubic.
                        
                        (default: 3)
        @type order: int
        @keyword inner: Applies a power law to the inner region, as a means of
                        extrapolation. Off by default, but can be turned on. 
                        In this case, r0 is taken from kwargs, ie the r0 from 
                        the power law of the wind (if Teps is chosen), or as an 
                        additional keyword if a file is read.
                        
                        (default: 0)
        @type inner: bool
        @keyword inner_eps: The exponent for the power law in the inner wind. 
        
                            (default: 0.5)
        @type inner_eps: float
        
        @keyword args: Additional parameters passed to the functions when eval
                       or diff are called. 
                       
                       (default: [])
        @type args: tuple
        @keyword kwargs: Additional keywords passed to the functions when eval
                         or diff are called. 
                       
                         (default: {})
        @type kwargs: dict
        
        '''

        #-- Do not name func, dfunc, etc in function call, or *args won't work        
        super(Temperature, self).__init__(r,func,dfunc,order,*args,**kwargs)
        
        self.inner = inner
        self.inner_eps = inner_eps

        #-- No extrapolation to the inner wind requested
        if not self.inner: 
            self.r = self.x
            self.T = self.y
            self.dTdr = self.dydx
            return
            
        #-- Alternatively, a power law extrapolation is requested. Extract r0,T0
        self.r0 = kwargs.get('r0')
        self.T0 = kwargs.get('T0')
    
        self.r = None
        self.T = None
        self.y = None
        
        #-- Run the class' own eval() method, with l=self.x, which will not be 
        #   equal to the class' self.r attribute, and thus it will evaluated
        #   properly. Evaluated with inner_eps==0.5. Reevaluated if alpha is
        #   different upon eval call.
        self.T = self.eval(self.x,inner_eps=self.inner_eps)
        self.y = self.T
        
        #-- Now also redo the derivative method. Then call diff to set the 
        #   standard derivative of the instance
        if self.interp_dfunc: 
            self.dfunc = spline1d(x=self.x,y=op.diff_central(self.y,self.x),\
                                  k=self.order)
        
        #-- Evaluate the derivative with the default grid
        self.dydx = self.diff(self.x,inner_eps=0.5)
        
        #-- Now set l, dydl.
        self.r = self.x
        self.dTdr = self.dydx
예제 #30
0
 def _inverse_lgMh(self):
     """ I like natural log """
     self.lgmharr = self._lgMh(self.msarr, check_boundary=False)
     self.log_stellarmass_mean = spline1d(self.lgmharr * self.lg2ln,
                                          self.lgmsarr * self.lg2ln)
예제 #31
0
    def __init__(self,x,func=interp_file,dfunc=None,order=3,*args,\
                 **kwargs):
        '''
        Create an instance of the Profiler() class. Requires a coordinate grid 
        and a function object for the profile. A function for the derivative is
        optional. The functions can also be given as an interpolation object.
        
        The optional args and kwargs give the additional arguments for the 
        two function, which are ignored in case func is an interpolation object.
        
        The default coordinate grid is evaluated for both the function and the
        derivative. They are saved in self.y and self.dydx. Alternatively, new
        evaluations can be attained through eval and diff.
        
        Note that if func is an interpolator object, the original input x and y
        grids can be passed as additional keywords xin and yin, which would then
        be arrays. Otherwise, the x and the interpolator(x) are set as xin and 
        yin. xin and yin are ignored if func is a function, even if it returns
        an interpolator (in which case the original grids are known)
        
        @param x: The default coordinate points, minimum three points. In the 
                  case of an interpolation function, this is the default grid
                  returned by the instance. The original x/y of the 
                  interpolated profile are saved as xori/yori in the object.
        @type x: array
        
        @keyword func: The function that describes the profile with respect to 
                       x. Can be given as an interp1d object. Default is a read
                       function that interpolates data and returns the 
                       interpolator object. If interpolation object, x and 
                       eval(x) are assumed to be the original grids, unless
                       xin and yin are given as keywords with arrays as values
                       for the original grids.
                       
                       (default: interp_file)
        @type func: function/interp1d object
        @keyword dfunc: Function that describes the derivative of the profile 
                        with respect to x. Can be given as an interpolation 
                        object. If None, a generic central difference is taken & 
                        interpolated with a spline of which the order can be 
                        chosen.
        
                        (default: None)
        @type dfunc: function/interpolation object
        @keyword order: Order of the spline interpolation of the derivative. 
                        Default is cubic. Not used for the interpolation if func
                        returns an interpolation object. Use read_order in that
                        case.
                        
                        (default: 3)
        @type order: int
        
        @keyword args: Additional parameters passed to the functions when eval
                       or diff are called. 
                       
                       (default: [])
        @type args: tuple
        @keyword kwargs: Additional keywords passed to the functions when eval
                         or diff are called. 
                       
                         (default: {})
        @type kwargs: dict
        
        '''

        #-- Check len of coordinate input. Cannot be less than three for the
        #   derivative.
        if len(x) < 3:
            raise ValueError('Coordinate grid must have more than 2 elements.')

        #-- If the function is given as a string, retrieve it from the local
        #   child module, or from the Profiler module (as parent). If the latter
        #   case then check if the function comes from one of Profiler's
        #   attributes, such as the loaded DataIO module.
        #   Can also simply be a constant value, so try making a float first.
        if isinstance(func, str):
            try:
                #-- Check if a constant was given, rather than a function
                kwargs['c'] = float(func)
                func = constant

            except ValueError:
                #-- Note that self.module refers to the child, not Profiler
                if hasattr(sys.modules[self.__module__], func):
                    func = getattr(sys.modules[self.__module__], func)

                #-- Recursively find the function of loaded modules in Profiler
                #   or a function of the Profiler module itself if no '.'
                else:

                    func = DataIO.read(func=func,module=sys.modules[__name__],\
                                       return_func=1)

        #-- set functional args, remember spline order. args/kwargs for
        #   func and dfunc are saved separately. They are removed if either are
        #   interpolation objects. They are always accessible, the _** variables
        #   are passed to the evaluation.
        self.args = args
        self.kwargs = kwargs
        self._args = self.args
        self._dargs = self.args
        self._dkwargs = self.kwargs
        self._kwargs = self.kwargs
        self.order = order

        #-- Grab default xin and yin keys in case they are included, and remove
        #   from the arguments dictionary. None if not available.
        xin = self.kwargs.pop('xin', None)
        yin = self.kwargs.pop('yin', None)

        #-- By default no interpolation, so leave this off.
        self.interp_func = 0
        self.interp_dfunc = 0

        #-- Defaults for xori/yori, not used in case of normal functions
        self.xin = np.empty(0)
        self.yin = np.empty(0)

        #-- Evaluate the default grid with function. Set x as None first so it
        #   can actually evaluate. Set x once derivative has been evaluated.
        self.x = None
        if not (isinstance(func, interp1d)
                or isinstance(func, UnivariateSpline)):
            #-- Evaluate the function, and check what is returned: array or
            #   interpolation object
            y = func(x, *args, **kwargs)

            #-- Interpolation object: so set that as this instance's func. In
            #   this case, the variable x passed to the class is the default x
            #   grid of this instance. The original x/y-grid is saved as xi, yi
            if isinstance(y, tuple):
                self.func = y[2]
                self.xin = y[0]
                self.yin = y[1]
                self._args = []
                self._kwargs = {}
                self.interp_func = 1
                self.y = self.func(x)
            else:
                self.func = func
                self.y = y

        #-- func is an interpolation object, so just run the normal evaluation.
        #   Set _args/_kwargs to empty, so none are ever passed to the interpol
        else:
            self.func = func
            self._args = []
            self._kwargs = {}
            self.interp_func = 1
            self.y = self.func(x)
            self.yin = yin if not yin is None else self.y
            self.xin = xin if not xin is None else x

        #-- Set the derivative function, resorting to default if needed
        if not dfunc is None:
            self.dfunc = dfunc
        elif self.func == constant:
            self.dfunc = zero
        else:
            #-- Extend array slightly to allow odeint to succeed.
            #   Need better fix for this.
            #x0 = x[0]-(x[1]-x[0])#*0.5
            #xn = x[-1]+(x[-1]-x[-2])#*0.5
            #x_ext = np.hstack([[x0],x,[xn]])

            #-- Evaluate the function, and set up an interpolator for
            #   central difference. The interpolator will extrapolate
            #   beyond the given x range. This is necessary for odeint to work.
            #   Usually x-range is not exceeded much.
            self.dfunc = spline1d(x=x,y=op.diff_central(self.y,x),\
                                  k=self.order)

        if (isinstance(self.dfunc,interp1d) \
                or isinstance(self.dfunc,UnivariateSpline)):
            self._dargs = []
            self._dkwargs = {}
            self.interp_dfunc = 1

        #-- Evaluate the derivative with the default grid
        self.dydx = self.dfunc(x, *self._dargs, **self._dkwargs)

        #-- Now set x.
        self.x = Data.arrayify(x)
예제 #32
0
    def __init__(self,l,func,dfunc=None,order=3,*args,**kwargs):
    
        '''
        Create an instance of the Opacity() class. Requires a wavelength grid.
        
        The function can also be given as an interpolation object.
        
        The optional args and kwargs give the additional arguments for the 
        opacity function, which are ignored in case func is an interpolation 
        object.
        
        Eval and diff work with the mass extinction coefficient in cm2/g. 
        
        In case func refers to an interpolation object in KappaReader, the
        args/kwargs should always contain an index indicating whether extinction
        (default), absorption or scattering is requested:
            - 0: extinction, 
            - 1: absorption, 
            - 2: scattering

        Note that if func is an interpolator object, the original input x and y
        grids can be passed as additional keywords xin/lin and yin, which would 
        then be arrays. Otherwise, the x and the interpolator(x) are set as 
        xin/lin and yin. xin/lin and yin are ignored if func is a function, even
        if it returns an interpolator (in which case the original grids are 
        known)
        
        Extrapolation is done outside of the "original" (depending on if xin/yin
        are given) wavelength ranges according to a power law ~l^-alpha, with 
        alpha given upon eval() calls.
        
        @param l: The wavelength points (cm)
        @type l: array
        @param func: The function that describes the opacity profile. Can be 
                     given as an interpolation object, in which case lin and yin
                     keywords can be passed as arrays for the original grids.
        @type func: function
        
        @keyword dfunc: Function that describes the derivative of the profile 
                        with respect to x. Can be given as an interpolation 
                        object. If None, a generic central difference is taken & 
                        interpolated with a spline of which the order can be 
                        chosen.
        
                        (default: None)
        @type dfunc: function/interpolation object
        @keyword order: Order of the spline interpolation. Default is cubic.
                        
                        (default: 3)
        @type order: int
                
        @keyword args: Additional parameters passed to the functions when eval
                       or diff are called. 
                       
                       (default: [])
        @type args: tuple
        @keyword kwargs: Additional keywords passed to the functions when eval
                         or diff are called. 
                       
                         (default: {})
        @type kwargs: dict

        '''
        
        #-- Make sure lin is recognized
        if kwargs.has_key('lin'): 
            kwargs['xin'] = kwargs['lin']
            del kwargs['lin']
        
        #-- Do not name func, dfunc, etc in function call, or *args won't work
        super(Opacity, self).__init__(l,func,dfunc,order,*args,**kwargs)
        
        
        #-- Remember the index of the opacities file. If relevant.
        if kwargs.has_key('index'):
            self.index = kwargs['index']
        else:
            self.index = 0
        
        #-- Set the default alpha. Not used if func is not an interpolator.
        self.alpha = 2.
        
        #-- If the requested function is not an interpolator of a file, do not
        #   change anything.
        if not self.interp_func:
            self.l = self.x
            self.kappa = self.y
            return
        
        #-- For Opacity(), in case of an interpolator object as function, 
        #   the extrapolation must be re-done for it to be safe.
        #   The eval() method is rewritten here to function with a
        #   power law extrapolation, for which the settings can be chosen. 
        #   The diff method must not be rewritten since it is based on the y
        #   profile.
        self.l = None
        self.kappa = None
        self.y = None
        
        #-- Run the class' own eval() method, with l=self.x, which will not be 
        #   equal to the class' self.l attribute, and thus it will evaluated
        #   properly. Evaluated with alpha==2. Reevaluated if alpha is different
        self.kappa = self.eval(self.x,alpha=2.)
        self.y = self.kappa
        
        #-- Now also redo the derivative method, in case it is an interpolator
        if self.interp_dfunc: 
            self.dfunc = spline1d(x=self.x,y=op.diff_central(self.y,self.x),\
                                  k=self.order)
        
            #-- Evaluate the derivative with the default grid
            self.dydx = self.dfunc(self.x,*self._dargs,**self._dkwargs)
            
        #-- Now set l, dydl.
        self.l = self.x
        self.dydl = self.dydx
예제 #33
0
def transition_demo(mass=1.e14):
    from scipy.interpolate import InterpolatedUnivariateSpline as spline1d
    radius_hinv, radius, xihm_all, xihm_lin = gen_xihm(mass)
    r = radius_hinv
    lnr = np.log(r)
    n = len(r)
    xihm = np.ravel(xihm_all)
    r0 = 1.0
    r2 = 10.0
    rho_mean = 1.e-12 * 37473017305.5 / 0.702**2
    r1 = get_break(r, xihm)

    i0 = np.searchsorted(r, r0)
    i1 = np.searchsorted(r, r1)
    if abs(r[i1] - r1) > abs(r[i1 + 1] - r1):
        i1 = i1 + 1
    elif abs(r[i1] - r1) > abs(r[i1 - 1] - r1):
        i1 = i1 - 1
    else:
        print("find break index at %4d" % i1)
    i2 = np.searchsorted(r, r2)

    lnr_left_0 = lnr[0:i1]
    lnr_right_0 = lnr[i1:n]

    left = np.hstack([range(i0), [
        i1,
    ]])
    right = np.hstack([[
        i1,
    ], range(i2, n)])

    r_left = r[left]
    lnr_left = np.log(r_left)
    xi_left = xihm[left]
    r_right = r[right]
    lnr_right = np.log(r_right)
    xi_right = xihm[right]

    xibreak0 = xihm[i1]

    fraclist = [-0.30, -0.20, -0.10, 0.0, 0.10, 0.20, 0.30]
    prop = matplotlib.font_manager.FontProperties(size=10)

    rp, delsig0, xirp0, xirpmean0 = DeltaSigmaR(r,
                                                xihm,
                                                rho=rho_mean,
                                                rp_max=30)

    fig = plt.figure(figsize=(12, 6))
    ax1 = fig.add_axes([0.08, 0.5, 0.40, 0.40])
    ax2 = fig.add_axes([0.55, 0.5, 0.40, 0.40])
    ax3 = fig.add_axes([0.08, 0.1, 0.40, 0.40])
    ax4 = fig.add_axes([0.55, 0.1, 0.40, 0.40])
    for frac in fraclist:
        xibreak = xibreak0 * (1. + frac)
        # i0 becomes the index of the break point in the new xi_left array
        xi_left[i0] = xibreak
        # 0 becomes the index of the break point in the new xi_right array
        xi_right[0] = xibreak

        f_left = spline1d(lnr_left, np.log(xi_left))
        xi_left_new = np.exp(f_left(lnr_left_0))
        f_right = spline1d(lnr_right, np.log(xi_right))
        xi_right_new = np.exp(f_right(lnr_right_0))

        xihm_new = np.hstack([xi_left_new, xi_right_new])
        ax1.plot(r, xihm_new, "-", alpha=1.0)

        rp, delsig, xirp, xirpmean = DeltaSigmaR(r,
                                                 xihm_new,
                                                 rho=rho_mean,
                                                 rp_max=30)
        ax2.plot(rp, delsig, "-", label=str(frac * 100.0) + "$\%$")

        ax3.plot(r, xihm_new / xihm, "-", alpha=1.0)

        ax4.plot(rp, delsig / delsig0, "-", alpha=1.0)

    ax1.text(0.02, 0.5, str(mass) + " $M_\odot$")
    ax1.set_xscale("log")
    ax1.set_yscale("log")
    ax1.set_xlim(1e-2, 99)
    ax1.set_ylim(1e-2, 2e5)
    ax1.set_ylabel("$\\xi_{hm}$")
    ax2.legend(loc=1, ncol=2, fancybox=True, shadow=True, prop=prop)
    ax2.set_xscale("log")
    ax2.set_yscale("log")
    ax2.set_xlim(1e-2, 99)
    ax2.set_ylim(5e-1, 2e2)
    ax2.set_ylabel("$\Delta\Sigma(R)$")
    ax3.set_xscale("log")
    ax3.set_xlim(1e-2, 99)
    ax3.set_xlabel("$r$ [h$^{-1}$Mpc]")
    ax4.set_xscale("log")
    ax4.set_xlim(1e-2, 99)
    ax4.set_xlabel("$r$ [h$^{-1}$Mpc]")
    ax3.set_ylim(0.6, 1.4)
    ax4.set_ylim(0.6, 1.4)
    ax3.grid(True)
    ax4.grid(True)
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.show()