예제 #1
0
def rand(*args):
    """
    Random values in a given shape.
    
    Create an array of the given shape and propagate it with random samples from a uniform 
        distribution over [0, 1).
    
    :param d0, d1, ..., dn: (*int*) optional. The dimensions of the returned array, should all
        be positive. If no argument is given a single Python float is returned.
        
    :returns: Random values array.
    """
    if len(args) == 0:
        return RandomUtil.rand()
    elif len(args) == 1:
        return NDArray(RandomUtil.rand(args[0]))
    else:
        return NDArray(RandomUtil.rand(args))
예제 #2
0
def inv(a):
    '''
    Compute the (multiplicative) inverse of a matrix.
    
    :param a: (*array_like*) Input array.
    
    :returns: Inverse matrix.
    '''
    r = LinalgUtil.inv(a.asarray())
    return NDArray(r)
예제 #3
0
def percentile(a, q, axis=None):
    '''
    Compute the qth percentile of the data along the specified axis.
    
    :param a: (*array_like*) Input array.
    :param q: (*float*) float in range of [0,100].
        Percentile to compute, which must be between 0 and 100 inclusive.
    :param axis: (*int*) Axis or axes along which the percentiles are computed. The default is 
        to compute the percentile along a flattened version of the array.
    
    :returns: (*float*) qth percentile value.
    '''
    if isinstance(a, list):
        a = NDArray(ArrayUtil.array(x))
    if axis is None:
        r = StatsUtil.percentile(a.asarray(), q)
    else:
        r = StatsUtil.percentile(a.asarray(), q, axis)
        r = NDArray(r)
    return r
예제 #4
0
def ds2uv(d, s):
    '''
    Calculate U/V from wind direction and wind speed.
    
    :param d: (*array_like*) Wind direction.
    :param s: (*array_like*) Wind speed.
    
    :returns: Wind U/V.
    '''
    if isinstance(d, NDArray):
        r = ArrayMath.ds2uv(d.asarray(), s.asarray())
        u = NDArray(r[0])
        v = NDArray(r[1])
        if isinstance(d, DimArray) and isinstance(s, DimArray):
            u = DimArray(u, d.dims, d.fill_value, d.proj)
            v = DimArray(v, d.dims, d.fill_value, d.proj)
        return u, v
    else:
        r = ArrayMath.ds2uv(d, s)
        return r[0], r[1]
예제 #5
0
def count(a, size):
    '''
    Count none-zero points with window size
    
    :param a: (*array_like*) 2-D array.
    :param size: (*int*) Window size.
    
    :returns: (*array_like*) Count result.
    '''
    r = ImageUtil.count(a.asarray(), size)
    return NDArray(r)
예제 #6
0
def uv2ds(u, v):
    '''
    Calculate wind direction and wind speed from U/V.
    
    :param u: (*array_like*) U component of wind field.
    :param v: (*array_like*) V component of wind field.
    
    :returns: Wind direction and wind speed.
    '''
    if isinstance(u, NDArray):
        r = ArrayMath.uv2ds(u.asarray(), v.asarray())
        d = NDArray(r[0])
        s = NDArray(r[1])
        if isinstance(u, DimArray) and isinstance(v, DimArray):
            d = DimArray(d, u.dims, u.fill_value, u.proj)
            s = DimArray(s, u.dims, u.fill_value, u.proj)
        return d, s
    else:
        r = ArrayMath.uv2ds(u, v)
        return r[0], r[1]
예제 #7
0
def polyval(p, x):
    """
    Evaluate a polynomial at specific values.
    
    If p is of length N, this function returns the value:
    
    p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]
    
    If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the 
    composite polynomial p(x(t)) is returned.
    
    :param p: (*array_like*) 1D array of polynomial coefficients (including coefficients equal to zero) 
        from highest degree to the constant term.
    :param x: (*array_like*) A number, an array of numbers, or an instance of poly1d, at which to evaluate 
        p.
        
    :returns: Polynomial value
    """
    if isinstance(x, list):
        x = NDArray(ArrayUtil.array(x))
    return NDArray(ArrayMath.polyVal(p, x.asarray()))
예제 #8
0
def imread(fname):
    '''
    Read RGB(A) data array from image file.
    
    :param fname: (*String*) Image file name.
    
    :returns: (*array*) RGB(A) data array.
    '''
    if not os.path.exists(fname):
        raise IOError(fname)
    r = ImageUtil.imageRead(fname)
    return NDArray(r)
예제 #9
0
def mean(a, size, positive=True):
    '''
    Calculate mean value with window size
    
    :param a: (*array_like*) 2-D array.
    :param size: (*int*) Window size.
    :param positive: (*boolean*) Only calculate the positive value or not.
    
    :returns: (*array_like*) Mean result.
    '''
    r = ImageUtil.mean(a.asarray(), size, positive)
    return NDArray(r)
예제 #10
0
def __getreturn(src, dst):
    if isinstance(src, Graphic):
        src.getShape().setImage(dst)
        return src
    elif isinstance(src, MILayer):
        src.layer.setImage(dst)
        return src
    elif isinstance(src, NDArray):
        r = ImageUtil.imageRead(dst)
        return NDArray(r)
    else:
        return dst
예제 #11
0
def geotiffread(filename):
    '''
    Return data array from a GeoTiff data file.
    
    :param filename: (*string*) The GeoTiff file name.
    
    :returns: (*NDArray*) Readed data array.
    '''
    geotiff = GeoTiff(filename)
    geotiff.read()
    r = geotiff.readArray()
    return NDArray(r)
예제 #12
0
def lstsq(a, b):
    '''
    Compute least-squares solution to equation Ax = b.

    Compute a vector x such that the 2-norm |b - A x| is minimized.
    
    Parameters
    ----------
    a : (M, N) array
        Left hand side matrix (2-D array).
    b : (M,) array
        Right hand side vector.
        
    Returns
    -------
    x : (N,) array
        Least-squares solution. Return shape matches shape of b.
    residues : (0,) or () or (K,) ndarray
        Sums of residues, squared 2-norm for each column in b - a x.
    '''
    r = StatsUtil.multipleLineRegress_OLS(b.asarray(), a.asarray(), True)
    return NDArray(r[0]), NDArray(r[1])
예제 #13
0
def lu(a):
    '''
    Compute pivoted LU decomposition of a matrix.
    
    The decomposition is::
    
        A = P L U
        
    where P is a permutation matrix, L lower triangular with unit
    diagonal elements, and U upper triangular.
    
    Parameters
    ----------
    a : (M, M) array_like
        Array to decompose
    permute_l : bool, optional
        Perform the multiplication P*L  (Default: do not permute)
    overwrite_a : bool, optional
        Whether to overwrite data in a (may improve performance)
    check_finite : bool, optional
        Whether to check that the input matrix contains only finite numbers.
        Disabling may give a performance gain, but may result in problems
        (crashes, non-termination) if the inputs do contain infinities or NaNs.
        
    Returns
    -------
    p : (M, M) ndarray
        Permutation matrix
    l : (M, M) ndarray
        Lower triangular or trapezoidal matrix with unit diagonal.
    u : (M, M) ndarray
        Upper triangular or trapezoidal matrix
    '''
    r = LinalgUtil.lu(a.asarray())
    p = NDArray(r[0])
    l = NDArray(r[1])
    u = NDArray(r[2])
    return p, l, u
예제 #14
0
def mlinregress(y, x):
    '''
    Implements ordinary least squares (OLS) to estimate the parameters of a multiple linear 
    regression model.
    
    :param y: (*array_like*) Y sample data - one dimension array.
    :param x: (*array_like*) X sample data - two dimension array.
    
    :returns: Estimated regression parameters and residuals.
    '''
    if isinstance(x, list):
        x = NDArray(ArrayUtil.array(x))
    if isinstance(y, list):
        y = NDArray(ArrayUtil.array(y))
    r = StatsUtil.multipleLineRegress_OLS(y.asarray(), x.asarray())
    return NDArray(r[0]), NDArray(r[1])
예제 #15
0
def gifread(gif, frame=0):
    '''
    Read RGB(A) data array from a gif image file or a gif decoder object.
    
    :param gif: (*string or GifDecoder*) Gif image file or gif decoder object.
    :param frame: (*int*) Image frame index.
    
    :returns: (*array*) RGB(A) data array.
    '''
    if isinstance(gif, basestring):
        gif = gifopen(gif)
    im = gif.getFrame(frame)
    r = ImageUtil.imageRead(im)
    return NDArray(r)
예제 #16
0
def exponential(scale=1.0, size=None):
    """
    Draw samples from a exponential distribution.
    
    :param scale: (*float*) The scale parameter.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized exponential distribution.    
    """
    dist = ExponentialDistribution(scale)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #17
0
def standard_t(df, size=None):
    """
    Draw samples from a standard Student’s t distribution with df degrees of freedom.
    
    :param df: (*float*) Degrees of freedom, should be > 0.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Student’s t distribution.    
    """
    dist = TDistribution(df)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #18
0
def weibull(a, size=None):
    """
    Draw samples from a Weibull distribution.
    
    :param a: (*float*) Shape parameter of the distribution. Must be nonnegative.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Weibull distribution.    
    """
    dist = WeibullDistribution(a, 1)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #19
0
    def rvs(self, *args, **kwargs):
        '''
        Random variates of given type.

        :param loc: (*float*) location parameter (default=0).
        :param scale: (*float*) scale parameter (default=1).
        :param size: (*int*) Size.
        
        :returns: Probability density function.
        '''
        dist = self._create_distribution(*args)
        size = kwargs.pop('size', 1)
        r = DistributionUtil.rvs(dist, size)
        return NDArray(r)
예제 #20
0
def pareto(a, size=None):
    """
    Draw samples from a Pareto II or Lomax distribution with specified shape.
    
    :param a: (*float*) Shape of the distribution. Should be greater than zero.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Pareto distribution.    
    """
    dist = ParetoDistribution(1, a)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #21
0
def chisquare(df, size=None):
    """
    Draw samples from a chi-square distribution.
    
    :param df: (*float*) Number of degrees of freedom, should be > 0.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized chisquare distribution.    
    """
    dist = ChiSquaredDistribution(df)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #22
0
def normal(loc=0.0, scale=1.0, size=None):
    """
    Draw random samples from a normal (Gaussian) distribution.
    
    :param loc: (*float*) Mean (“centre”) of the distribution.
    :param scale: (*float*) Standard deviation (spread or “width”) of the distribution.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    """
    dist = NormalDistribution(loc, scale)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #23
0
def p2h(press):
    """
    Pressure to height
    
    :param press: (*float*) Pressure - hPa.
    
    :returns: (*float*) Height - meter.
    """
    if isinstance(press, NDArray):
        r = NDArray(ArrayMath.press2Height(press.asarray()))
        if isinstance(press, DimArray):
            r = DimArray(r, press.dims, press.fill_value, press.proj)
        return r
    else:
        return MeteoMath.press2Height(press)
예제 #24
0
def lognormal(mean=0.0, sigma=1.0, size=None):
    """
    Draw samples from the log-normal distribution.
    
    :param mean: (*float*) Mean value of the underlying normal distribution. Default is 0.
    :param sigma: (*float*) Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized log-normal distribution.    
    """
    dist = LogNormalDistribution(loc, scale)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #25
0
def logistic(loc=0.0, scale=1.0, size=None):
    """
    Draw samples from the Logistic distribution.
    
    :param loc: (*float*) Mean (“centre”) of the distribution.
    :param scale: (*float*) Standard deviation (spread or “width”) of the distribution.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Logistic distribution.    
    """
    dist = LogisticDistribution(loc, scale)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #26
0
def laplace(loc=0.0, scale=1.0, size=None):
    """
    Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
    
    :param loc: (*float*) Mean (“centre”) of the distribution.
    :param scale: (*float*) Standard deviation (spread or “width”) of the distribution.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Laplace distribution.    
    """
    dist = LaplaceDistribution(loc, scale)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #27
0
def gamma(shape, scale=1.0, size=None):
    """
    Draw random samples from a Gamma distribution.
    
    :param shape: (*float*) The shape of the gamma distribution. Should be greater than zero.
    :param scale: (*float*) Standard deviation (spread or “width”) of the distribution.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Gamma distribution.    
    """
    dist = GammaDistribution(shape, scale)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #28
0
def f(dfnum, dfden, size=None):
    """
    Draw random samples from a F distribution.
    
    :param dfnum: (*float*) Degrees of freedom in numerator, should be > 0.
    :param dfden: (*float*) Degrees of freedom in denominator, should be > 0.
    :param size: (*int*) Output shape. If size is None (default), a single value is returned.
    
    :returns: (*ndarray or scalar*) Drawn samples from the parameterized Fisher distribution.    
    """
    dist = FDistribution(dfnum, dfden)
    if size is None:
        size = 1
    r = DistributionUtil.rvs(dist, size)
    return NDArray(r)
예제 #29
0
def poisson(lam=1.0, size=None):
    """
    Draw samples from a Poisson distribution.
    
    :param lam: (*float*) Expectation of interval, should be >= 0.
    :param size: (*int or tuple*) Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples 
        are drawn. Default is None, in which case a single value is returned.
        
    :returns: (*float or array*) Drawn samples from the parameterized Poisson distribution.
    """
    if size is None:
        r = RandomUtil.poisson(lam)
    else:
        r = NDArray(RandomUtil.poisson(lam, size))
    return r
예제 #30
0
def h2p(height):
    """
    Height to pressure
    
    :param height: (*float*) Height - meter.
    
    :returns: (*float*) Pressure - hPa.
    """
    if isinstance(height, NDArray):
        r = NDArray(ArrayMath.height2Press(height.asarray()))
        if isinstance(height, DimArray):
            r = DimArray(r, height.dims, height.fill_value, height.proj)
        return r
    else:
        return MeteoMath.height2Press(height)