Python scipy.interpolate.InterpolatedUnivariateSpline() Examples

The following are 30 code examples of scipy.interpolate.InterpolatedUnivariateSpline(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.interpolate , or try the search function .
Example #1
Source File: vehicle.py    From CO2MPAS-TA with European Union Public License 1.1 6 votes vote down vote up
def define_slope_model(distances, elevations):
    """
    Returns the angle slope model [rad].

    :param distances:
        Cumulative distance vector [m].
    :type distances: numpy.array

    :param elevations:
        Elevation vector [m].
    :type elevations: numpy.array

    :return:
        Angle slope model [rad].
    :rtype: function
    """
    from scipy.interpolate import InterpolatedUnivariateSpline as Spl
    i = np.append([0], np.where(np.diff(distances) > dfl.EPS)[0] + 1)
    func = Spl(distances[i], elevations[i]).derivative()
    return lambda d: np.arctan(func(d)) 
Example #2
Source File: vehicle.py    From CO2MPAS-TA with European Union Public License 1.1 6 votes vote down vote up
def calculate_accelerations(times, velocities):
    """
    Calculates the acceleration from velocity time series [m/s2].

    :param times:
        Time vector [s].
    :type times: numpy.array

    :param velocities:
        Velocity vector [km/h].
    :type velocities: numpy.array

    :return:
        Acceleration vector [m/s2].
    :rtype: numpy.array
    """
    from scipy.interpolate import InterpolatedUnivariateSpline as Spl
    acc = Spl(times, velocities / 3.6).derivative()(times)
    b = (velocities[:-1] == 0) & (velocities[1:] == velocities[:-1])
    acc[:-1][b] = 0
    if b[-1]:
        acc[-1] = 0
    return acc 
Example #3
Source File: BrownCompleteness.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def calc_fdmag(self, dMag, smin, smax):
        """Calculates probability density of dMag by integrating over projected
        separation
        
        Args:
            dMag (float ndarray):
                Planet delta magnitude(s)
            smin (float ndarray):
                Value of minimum projected separation (AU) from instrument
            smax (float ndarray):
                Value of maximum projected separation (AU) from instrument
        
        Returns:
            float:
                Value of probability density
        
        """
        
        f = np.zeros(len(smin))
        for k, dm in enumerate(dMag):
            f[k] = interpolate.InterpolatedUnivariateSpline(self.xnew,self.EVPOCpdf(self.xnew,dm),ext=1).integral(smin[k],smax[k])
            
        return f 
Example #4
Source File: zhist.py    From nbodykit with GNU General Public License v3.0 6 votes vote down vote up
def interpolate(self, z, ext='zeros'):
        """ Interpoalte dndz as a function of redshift. 

            The interpolation acts as a band pass filter, removing small scale
            fluctuations in the estimator.

            Parameters
            ----------
            z : array_like
                redshift
            ext : 'extrapolate', 'zeros', 'raise', 'const'
                how to deal with values out of bound.

            Returns
            -------
            n : n(z)
        """
        nofz = InterpolatedUnivariateSpline(self.bin_centers, self.nbar, ext=ext)
        return nofz(z) 
Example #5
Source File: load_dataset.py    From Conditional_Density_Estimation with MIT License 6 votes vote down vote up
def _make_riskneutral_df(time_horizon):
  cols_of_interest = ['bakshiSkew', 'bakshiKurt', 'SVIX',]
  riskteural_measures = load_time_series_csv(RISKNEUTRAL_CSV, delimiter=';')
  riskteural_measures = riskteural_measures[['daystomaturity'] + cols_of_interest]
  riskteural_measures = riskteural_measures.dropna()
  interpolated_df = pd.DataFrame()
  for date in list(set(riskteural_measures.index)):
    # filter all row for respective date
    riskneutral_measures_per_day = riskteural_measures.ix[date]

    # filer out all option-implied measures with computed based on a maturity of less than 7 days
    riskneutral_measures_per_day = riskneutral_measures_per_day[riskneutral_measures_per_day['daystomaturity'] > 7]

    # interpolate / extrapolate to get estimate for desired time_horizon
    interpolated_values = [InterpolatedUnivariateSpline(np.array(riskneutral_measures_per_day['daystomaturity']),
                                 np.asarray(riskneutral_measures_per_day[col_of_interest]),
                                 k=1)(time_horizon) for col_of_interest in cols_of_interest]

    # create df with estimated option-implied risk measures
    update_dict = dict(zip(cols_of_interest, interpolated_values))
    update_dict.update({'daystomaturity': time_horizon})
    interpolated_df = interpolated_df.append(pd.DataFrame(update_dict, index=[date]))
  del interpolated_df['daystomaturity']
  return interpolated_df 
Example #6
Source File: interpolate.py    From BAG_framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, scale_list, values, method='spline', extrapolate=False):
        # error checking
        if len(values.shape) != 1:
            raise ValueError('This class only works for 1D data.')
        elif len(scale_list) != 1:
            raise ValueError('input and output dimension mismatch.')

        if method == 'linear':
            k = 1
        elif method == 'spline':
            k = 3
        else:
            raise ValueError('Unsuppoorted interpolation method: %s' % method)

        offset, scale = scale_list[0]
        num_pts = values.shape[0]
        points = np.linspace(offset, (num_pts - 1) * scale + offset, num_pts)  # type: np.multiarray.ndarray

        DiffFunction.__init__(self, [(points[0], points[-1])], delta_list=None)

        ext = 0 if extrapolate else 2
        self.fun = interp.InterpolatedUnivariateSpline(points, values, k=k, ext=ext) 
Example #7
Source File: utils.py    From neuroglia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_interpolator(t,y):
    """ creates a cubic spline interpolator

    Parameters
    ---------
    y : array-like of floats

    Returns
    ---------
    interpolator function that accepts a list of times

    """
    interpolator = interpolate.InterpolatedUnivariateSpline(t, y)
    return interpolator 
Example #8
Source File: foundation.py    From Virtual-Makeup with Apache License 2.0 5 votes vote down vote up
def univariate_plot(lx=[],ly=[]):
    unew = np.arange(lx[0], lx[-1]+1, 1)
    f2 = InterpolatedUnivariateSpline(lx, ly)
    return unew,f2(unew) 
Example #9
Source File: KeplerLike1.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dist_albedo(self, p):
        """Probability density function for albedo
        
        Args:
            p (float ndarray):
                Albedo value(s)
        
        Returns:
            float ndarray:
                Albedo probability density
                
        """
        
        # if called for the first time, define distribution for albedo
        if self.dist_albedo_built is None:
            pgen = self.gen_albedo(int(1e6))
            pr = self.prange
            hp, pedges = np.histogram(pgen, bins=2000, range=(pr[0], pr[1]), density=True)
            pedges = 0.5*(pedges[1:] + pedges[:-1])
            pedges = np.hstack((pr[0], pedges, pr[1]))
            hp = np.hstack((0., hp, 0.))
            self.dist_albedo_built = interpolate.InterpolatedUnivariateSpline(pedges, 
                    hp, k=1, ext=1)
        
        f = self.dist_albedo_built(p)
        
        return f 
Example #10
Source File: nfw_param.py    From lenstronomy with MIT License 5 votes vote down vote up
def c_rho0(self, rho0):
        """
        computes the concentration given a comoving overdensity rho0 (inverse of function rho0_c)
        :param rho0: density normalization in h^2/Mpc^3 (comoving)
        :return: concentration parameter c
        """
        if not hasattr(self, '_c_rho0_interp'):
            c_array = np.linspace(0.1, 10, 100)
            rho0_array = self.rho0_c(c_array)
            from scipy import interpolate
            self._c_rho0_interp = interpolate.InterpolatedUnivariateSpline(rho0_array, c_array, w=None, bbox=[None, None], k=3)
        return self._c_rho0_interp(rho0) 
Example #11
Source File: NaturalBreaksClustering.py    From pax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def startup(self):
        self.min_split_goodness = InterpolatedUnivariateSpline(*self.config['split_goodness_threshold'], k=1)
        self.dt = self.config['sample_duration'] 
Example #12
Source File: anscombe.py    From hypers with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _anscombe_inverse_exact_unbiased(fsignal: ListOrArray):
    """
    Calculate exact inverse Anscombe transformation

    Parameters
    ----------
    fsignal : ListOrArray
        Forward Anscombe-transformed noisy signal

    Returns
    -------
    signal : MixedArray
        Inverse Anscombe-transformed signal
    """
    if isinstance(fsignal, list):
        fsignal = convert_nparray(fsignal)

    mat_dict = loadmat(os.path.join(resource_dir, 'anscombe_vectors.mat'))
    Efz = mat_dict['Efz']
    Ez = mat_dict['Ez']
    asymptotic = (fsignal / 2) ** 2 - 1 / 8  # asymptotically unbiased inverse [3]
    signal = InterpolatedUnivariateSpline(Efz, Ez, k=1)(fsignal)  # exact unbiased inverse [1,2]
    # for large values use asymptotically unbiased inverse instead
    # of linear extrapolation of exact unbiased inverse outside of pre-computed domain
    outside_exact_inverse_domain = fsignal > np.max(Efz)
    signal[outside_exact_inverse_domain] = asymptotic[outside_exact_inverse_domain]
    outside_exact_inverse_domain = fsignal < 2 * np.sqrt(3 / 8)  # min(Efz(:));
    signal[outside_exact_inverse_domain] = 0

    return signal 
Example #13
Source File: pp_manident.py    From photometrypipeline with GNU General Public License v3.0 5 votes vote down vote up
def extrapolate(self, time):
        """fit path with spline, identify nearest source"""

        x, y, t = [], [], []
        for i in range(len(self.files)):
            if self.target_index[i] is not None:
                t.append(self.mjd[i])
                x.append(self.ldac[i][self.target_index[i]]['XWIN_IMAGE'])
                y.append(self.ldac[i][self.target_index[i]]['YWIN_IMAGE'])

        k = min([len(t), 3])-1

        if k >= 1:
            # extrapolate position
            fx = InterpolatedUnivariateSpline(numpy.array(t), numpy.array(x),
                                              k=k)
            fy = InterpolatedUnivariateSpline(numpy.array(t), numpy.array(y),
                                              k=k)

            # identify closest source
            residuals = numpy.sqrt((self.ldac[self.index]['XWIN_IMAGE'] -
                                    fx(time))**2 +
                                   (self.ldac[self.index]['YWIN_IMAGE'] -
                                    fy(time))**2)
            return numpy.argmin(residuals)
        else:
            return None

# -------------------------------------------------------------------- 
Example #14
Source File: models.py    From xrayutilities with GNU General Public License v2.0 5 votes vote down vote up
def convolute_resolution(self, x, y):
        """
        convolve simulation result with a resolution function

        Parameters
        ----------
        x :     array-like
            x-values of the simulation, units of x also decide about the unit
            of the resolution_width parameter
        y :     array-like
            y-values of the simulation

        Returns
        -------
        array-like
            convoluted y-data with same shape as y
        """
        if self.resolution_width == 0:
            return y
        else:
            dx = numpy.mean(numpy.gradient(x))
            nres = int(20 * numpy.abs(self.resolution_width / dx))
            xres = startdelta(-10*self.resolution_width, dx, nres + 1)
            # the following works only exactly for equally spaced data points
            if self.resolution_type == 'Gauss':
                fres = NormGauss1d
            else:
                fres = NormLorentz1d
            resf = fres(xres, numpy.mean(xres), self.resolution_width)
            resf /= numpy.sum(resf)  # proper normalization for discrete conv.
            # pad y to avoid edge effects
            interp = interpolate.InterpolatedUnivariateSpline(x, y, k=1)
            nextmin = numpy.ceil(nres/2.)
            nextpos = numpy.floor(nres/2.)
            xext = numpy.concatenate(
                (startdelta(x[0]-dx, -dx, nextmin)[-1::-1],
                 x,
                 startdelta(x[-1]+dx, dx, nextpos)))
            ypad = numpy.asarray(interp(xext))
            return numpy.convolve(ypad, resf, mode='valid') 
Example #15
Source File: powdermodel.py    From xrayutilities with GNU General Public License v2.0 5 votes vote down vote up
def set_background(self, btype, **kwargs):
        """
        define background as spline or polynomial function

        Parameters
        ----------
        btype :     {polynomial', 'spline'}
            background type; Depending on this
            value the expected keyword arguments differ.
        kwargs :    dict
            optional keyword arguments
        x :     array-like, optional
            x-values (twotheta) of the background points (if btype='spline')
        y :     array-like, optional
            intensity values of the background (if btype='spline')
        p :     array-like, optional
            polynomial coefficients from the highest degree to the constant
            term. len of p decides about the degree of the polynomial (if
            btype='polynomial')
        """
        if btype == 'spline':
            self._bckg_spline = interpolate.InterpolatedUnivariateSpline(
                kwargs.get('x'), kwargs.get('y'), ext=0)
        elif btype == 'polynomial':
            self._bckg_pol = list(kwargs.get('p'))
        else:
            raise ValueError("btype must be either 'spline' or 'polynomial'")
        self._bckg_type = btype 
Example #16
Source File: torque_converter.py    From CO2MPAS-TA with European Union Public License 1.1 5 votes vote down vote up
def define_k_factor_curve(stand_still_torque_ratio=1.0, lockup_speed_ratio=0.0):
    """
    Defines k factor curve.

    :param stand_still_torque_ratio:
        Torque ratio when speed ratio==0.

        .. note:: The ratios are defined as follows:

           - Torque ratio = `gear box torque` / `engine torque`.
           - Speed ratio = `gear box speed` / `engine speed`.
    :type stand_still_torque_ratio: float

    :param lockup_speed_ratio:
        Minimum speed ratio where torque ratio==1.

        ..note::
            torque ratio==1 for speed ratio > lockup_speed_ratio.
    :type lockup_speed_ratio: float

    :return:
        k factor curve.
    :rtype: callable
    """
    from scipy.interpolate import InterpolatedUnivariateSpline
    if lockup_speed_ratio == 0:
        x = [0, 1]
        y = [1, 1]
    elif lockup_speed_ratio == 1:
        x = [0, 1]
        y = [stand_still_torque_ratio, 1]
    else:
        x = [0, lockup_speed_ratio, 1]
        y = [stand_still_torque_ratio, 1, 1]

    return InterpolatedUnivariateSpline(x, y, k=1) 
Example #17
Source File: thermal.py    From CO2MPAS-TA with European Union Public License 1.1 5 votes vote down vote up
def _derivative(times, temp):
    import scipy.misc as sci_misc
    import scipy.interpolate as sci_itp
    par = dfl.functions.calculate_engine_temperature_derivatives
    func = sci_itp.InterpolatedUnivariateSpline(times, temp, k=1)
    return sci_misc.derivative(func, times, dx=par.dx, order=par.order) 
Example #18
Source File: gspv.py    From CO2MPAS-TA with European Union Public License 1.1 5 votes vote down vote up
def _fit_cloud(self):
        from scipy.interpolate import InterpolatedUnivariateSpline as spl

        def _line(n, m, i):
            x = np.mean(m[i]) if m[i] else None
            k_p = n - 1
            while k_p > 0 and k_p not in self:
                k_p -= 1
            x_up = self[k_p][not i](0) if k_p >= 0 else x

            if x is None or x > x_up:
                x = x_up
            return spl([0, 1], [x] * 2, k=1)

        self.clear()
        self.update(copy.deepcopy(self.cloud))

        for k, v in sorted(self.items()):
            v[0] = _line(k, v, 0)

            if len(v[1][0]) > 2:
                v[1] = _gspv_interpolate_cloud(*v[1])
            elif v[1][1]:
                v[1] = spl([0, 1], [np.mean(v[1][1])] * 2, k=1)
            else:
                v[1] = self[k - 1][0] 
Example #19
Source File: cmv.py    From CO2MPAS-TA with European Union Public License 1.1 5 votes vote down vote up
def _interp(r, y, nr):
    from scipy.interpolate import InterpolatedUnivariateSpline as Spline
    n = len(r)
    if n == 0:
        return np.nan * nr
    elif n == 1:
        return (y / r) * nr
    else:
        return Spline(r, y / r, k=1)(nr) * nr


# noinspection PyPep8Naming 
Example #20
Source File: phaseplane.py    From compneuro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, xname, yname, nullc_array, x_relative_scale=1):
        self.xname = xname
        self.yname = yname
        self.array = nullc_array
        # ensure monotonicity
        if not isincreasing(nullc_array[:,0]):
            raise AssertionError("x axis '%s' values must be monotonically increasing" % xname)
        self.spline = InterpolatedUnivariateSpline(nullc_array[:,0],
                                                   nullc_array[:,1])
        # store these precomputed values in advance for efficiency
        self.x_relative_scale_fac = x_relative_scale
        self.x_relative_scale_fac_2 = self.x_relative_scale_fac**2
        self.x_relative_scale_fac_3 = self.x_relative_scale_fac**3 
Example #21
Source File: DulzPlavchan.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dist_sma(self, a):
        """Probability density function for semi-major axis.

        Note that this is a marginalized distribution.

        Args:
            a (float ndarray):
                Semi-major axis value(s)

        Returns:
            float ndarray:
                Semi-major axis probability density

        """

        # if called for the first time, define distribution for albedo
        if self.dist_sma_built is None:
            agen, _ = self.gen_sma_radius(int(1e6))
            ar = self.arange.to('AU').value
            ap, aedges = np.histogram(agen.to('AU').value, bins=2000, range=(ar[0], ar[1]), density=True)
            aedges = 0.5*(aedges[1:] + aedges[:-1])
            aedges = np.hstack((ar[0], aedges, ar[1]))
            ap = np.hstack((0., ap, 0.))
            self.dist_sma_built = interpolate.InterpolatedUnivariateSpline(aedges, ap, k=1, ext=1)

        f = self.dist_sma_built(a)

        return f 
Example #22
Source File: DulzPlavchan.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dist_radius(self, Rp):
        """Probability density function for planetary radius.

        Note that this is a marginalized distribution.

        Args:
            Rp (float ndarray):
                Planetary radius value(s)

        Returns:
            float ndarray:
                Planetary radius probability density

        """

        # if called for the first time, define distribution for albedo
        if self.dist_radius_built is None:
            _, Rgen = self.gen_sma_radius(int(1e6))
            Rpr = self.Rprange.to('earthRad').value
            Rpp, Rpedges = np.histogram(Rgen.to('earthRad').value, bins=2000, range=(Rpr[0], Rpr[1]), density=True)
            Rpedges = 0.5*(Rpedges[1:] + Rpedges[:-1])
            Rpedges = np.hstack((Rpr[0], Rpedges, Rpr[1]))
            Rpp = np.hstack((0., Rpp, 0.))
            self.dist_radius_built = interpolate.InterpolatedUnivariateSpline(Rpedges, Rpp, k=1, ext=1)

        f = self.dist_radius_built(Rp)

        return f 
Example #23
Source File: DulzPlavchan.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dist_albedo(self, p):
        """Probability density function for albedo

        Args:
            p (float ndarray):
                Albedo value(s)

        Returns:
            float ndarray:
                Albedo probability density

        """

        # if called for the first time, define distribution for albedo
        if self.dist_albedo_built is None:
            pgen = self.gen_albedo(int(1e6))
            pr = self.prange
            hp, pedges = np.histogram(pgen, bins=2000, range=(pr[0], pr[1]), density=True)
            pedges = 0.5*(pedges[1:] + pedges[:-1])
            pedges = np.hstack((pr[0], pedges, pr[1]))
            hp = np.hstack((0., hp, 0.))
            self.dist_albedo_built = interpolate.InterpolatedUnivariateSpline(pedges,
                                                                              hp, k=1, ext=1)

        f = self.dist_albedo_built(p)

        return f 
Example #24
Source File: quaternion_time_series.py    From quaternion with MIT License 5 votes vote down vote up
def minimal_rotation(R, t, iterations=2):
    """Adjust frame so that there is no rotation about z' axis

    The output of this function is a frame that rotates the z axis onto the same z' axis as the
    input frame, but with minimal rotation about that axis.  This is done by pre-composing the input
    rotation with a rotation about the z axis through an angle gamma, where

        dgamma/dt = 2*(dR/dt * z * R.conjugate()).w

    This ensures that the angular velocity has no component along the z' axis.

    Note that this condition becomes easier to impose the closer the input rotation is to a
    minimally rotating frame, which means that repeated application of this function improves its
    accuracy.  By default, this function is iterated twice, though a few more iterations may be
    called for.

    Parameters
    ==========
    R: quaternion array
        Time series describing rotation
    t: float array
        Corresponding times at which R is measured
    iterations: int [defaults to 2]
        Repeat the minimization to refine the result

    """
    from scipy.interpolate import InterpolatedUnivariateSpline as spline
    if iterations == 0:
        return R
    R = quaternion.as_float_array(R)
    Rdot = np.empty_like(R)
    for i in range(4):
        Rdot[:, i] = spline(t, R[:, i]).derivative()(t)
    R = quaternion.from_float_array(R)
    Rdot = quaternion.from_float_array(Rdot)
    halfgammadot = quaternion.as_float_array(Rdot * quaternion.z * np.conjugate(R))[:, 0]
    halfgamma = spline(t, halfgammadot).antiderivative()(t)
    Rgamma = np.exp(quaternion.z * halfgamma)
    return minimal_rotation(R * Rgamma, t, iterations=iterations-1) 
Example #25
Source File: quaternion_time_series.py    From quaternion with MIT License 5 votes vote down vote up
def angular_velocity(R, t):
    from scipy.interpolate import InterpolatedUnivariateSpline as spline
    R = quaternion.as_float_array(R)
    Rdot = np.empty_like(R)
    for i in range(4):
        Rdot[:, i] = spline(t, R[:, i]).derivative()(t)
    R = quaternion.from_float_array(R)
    Rdot = quaternion.from_float_array(Rdot)
    return quaternion.as_float_array(2*Rdot/R)[:, 1:] 
Example #26
Source File: helper.py    From fftoptionlib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def spline_fitting(x_data, y_data, order):
    return InterpolatedUnivariateSpline(x_data, y_data, k=order) 
Example #27
Source File: core.py    From BAG_framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, xvec, yvec, xtol, order=3, ext=3):
        self._xvec = xvec
        self._yvec = yvec
        self._xtol = xtol
        self._order = order
        self._ext = ext
        self._fun = interp.InterpolatedUnivariateSpline(xvec, yvec, k=order, ext=ext) 
Example #28
Source File: core.py    From BAG_framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ext(self):
        """interpolation extension mode.  See documentation for InterpolatedUnivariateSpline."""
        return self._ext 
Example #29
Source File: linear.py    From nbodykit with GNU General Public License v3.0 5 votes vote down vote up
def sigma_r(self, r, kmin=1e-5, kmax=1e1):
        r"""
        The mass fluctuation within a sphere of radius ``r``, in
        units of :math:`h^{-1} Mpc` at ``redshift``.

        This returns :math:`\sigma`, where

        .. math::

            \sigma^2 = \int_0^\infty \frac{k^3 P(k,z)}{2\pi^2} W^2_T(kr) \frac{dk}{k},

        where :math:`W_T(x) = 3/x^3 (\mathrm{sin}x - x\mathrm{cos}x)` is
        a top-hat filter in Fourier space.

        The value of this function with ``r=8`` returns
        :attr:`sigma8`, within numerical precision.

        Parameters
        ----------
        r : float, array_like
            the scale to compute the mass fluctation over, in units of
            :math:`h^{-1} Mpc`
        kmin : float, optional
            the lower bound for the integral, in units of :math:`\mathrm{Mpc/h}`
        kmax : float, optional
            the upper bound for the integral, in units of :math:`\mathrm{Mpc/h}`
        """
        import mcfit
        from scipy.interpolate import InterpolatedUnivariateSpline as spline

        k = numpy.logspace(numpy.log10(kmin), numpy.log10(kmax), 1024)
        Pk = self(k)
        R, sigmasq = mcfit.TophatVar(k, lowring=True)(Pk, extrap=True)

        return spline(R, sigmasq)(r)**0.5 
Example #30
Source File: zeldovich.py    From nbodykit with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, k):
        r"""
        Return the Zel'dovich power in :math:`h^{-3} \mathrm{Mpc}^3 at
        :attr:`redshift` and ``k``, where ``k`` is in units of
        :math:`h \mathrm{Mpc}^{-1}`.

        Parameters
        ----------
        k : float, array_like
            the wavenumbers to evaluate the power at
        """
        def Pzel_at_k(ki):

            # return the low-k approximation
            if ki < self._k0_low:
                return self._low_k_approx(ki)

            # do the full integral
            Pzel = 0.0
            for n in range(0, self.nmax + 1):

                I = ZeldovichPowerIntegral(self._r, n)
                if n > 0:
                    f = (ki*self._Y)**n * numpy.exp(-0.5*ki**2 * (self._X + self._Y))
                else:
                    f = numpy.exp(-0.5*ki**2 * (self._X + self._Y)) - numpy.exp(-ki**2*self._sigmasq)

                kk, this_Pzel = I(f, extrap=False)
                Pzel += spline(kk, this_Pzel)(ki)

            return Pzel

        return vectorize_if_needed(Pzel_at_k, k)