Python numpy.extract() Examples

The following are 30 code examples for showing how to use numpy.extract(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: lambda-packs   Author: ryfeus   File: _continuous_distns.py    License: MIT License 6 votes vote down vote up
def _cdf(self, x, c):
        output = np.zeros(x.shape, dtype=x.dtype)
        val = (1.0+c)/(1.0-c)
        c1 = x < np.pi
        c2 = 1-c1
        xp = np.extract(c1, x)
        xn = np.extract(c2, x)
        if np.any(xn):
            valn = np.extract(c2, np.ones_like(x)*val)
            xn = 2*np.pi - xn
            yn = np.tan(xn/2.0)
            on = 1.0-1.0/np.pi*np.arctan(valn*yn)
            np.place(output, c2, on)
        if np.any(xp):
            valp = np.extract(c1, np.ones_like(x)*val)
            yp = np.tan(xp/2.0)
            op = 1.0/np.pi*np.arctan(valp*yp)
            np.place(output, c1, op)
        return output 
Example 2
Project: Computable   Author: ktraunmueller   File: mstats_basic.py    License: MIT License 6 votes vote down vote up
def skew(a, axis=0, bias=True):
    a, axis = _chk_asarray(a,axis)
    n = a.count(axis)
    m2 = moment(a, 2, axis)
    m3 = moment(a, 3, axis)
    olderr = np.seterr(all='ignore')
    try:
        vals = ma.where(m2 == 0, 0, m3 / m2**1.5)
    finally:
        np.seterr(**olderr)

    if not bias:
        can_correct = (n > 2) & (m2 > 0)
        if can_correct.any():
            m2 = np.extract(can_correct, m2)
            m3 = np.extract(can_correct, m3)
            nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5
            np.place(vals, can_correct, nval)
    return vals 
Example 3
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _continuous_distns.py    License: MIT License 6 votes vote down vote up
def _cdf(self, x, c):
        output = np.zeros(x.shape, dtype=x.dtype)
        val = (1.0+c)/(1.0-c)
        c1 = x < np.pi
        c2 = 1-c1
        xp = np.extract(c1, x)
        xn = np.extract(c2, x)
        if np.any(xn):
            valn = np.extract(c2, np.ones_like(x)*val)
            xn = 2*np.pi - xn
            yn = np.tan(xn/2.0)
            on = 1.0-1.0/np.pi*np.arctan(valn*yn)
            np.place(output, c2, on)
        if np.any(xp):
            valp = np.extract(c1, np.ones_like(x)*val)
            yp = np.tan(xp/2.0)
            op = 1.0/np.pi*np.arctan(valp*yp)
            np.place(output, c1, op)
        return output 
Example 4
Project: IkaLog   Author: hasegaw   File: downie.py    License: Apache License 2.0 6 votes vote down vote up
def _detect_gear_level(self, gear_level_image):
        img_level = matcher.MM_COLOR_BY_HUE(
            hue=(30 - 5, 30 + 5), visibility=(200, 255))(gear_level_image)
        cv2.imshow('level', img_level)
        img_level_hist = np.sum(img_level / 255, axis=0)
        img_level_x = np.extract(img_level_hist > 3, np.arange(1024))

        level_width = np.amax(img_level_x) - np.amin(img_level_x)

        if level_width < 10:
            return 1

        elif level_width < 40:
            return 2

        return 3

    # Sub abilities 
Example 5
Project: Aegean   Author: PaulHancock   File: fits_image.py    License: Academic Free License v3.0 6 votes vote down vote up
def get_background_rms(self):
        """
        Calculate the rms of the image. The rms is calculated from the interqurtile range (IQR), to
        reduce bias from source pixels.

        Returns
        -------
        rms : float
            The image rms.

        Notes
        -----
        The rms value is cached after first calculation.
        """
        # TODO: return a proper background RMS ignoring the sources
        # This is an approximate method suggested by PaulH.
        # I have no idea where this magic 1.34896 number comes from...
        if self._rms is None:
            # Get the pixels values without the NaNs
            data = numpy.extract(self.hdu.data > -9999999, self.hdu.data)
            p25 = scipy.stats.scoreatpercentile(data, 25)
            p75 = scipy.stats.scoreatpercentile(data, 75)
            iqr = p75 - p25
            self._rms = iqr / 1.34896
        return self._rms 
Example 6
Project: pyroomacoustics   Author: LCAV   File: tools_fri_doa_plane.py    License: MIT License 6 votes vote down vote up
def multiband_extract_off_diag(mtx):
    """
    extract off-diagonal entries in mtx
    The output vector is order in a column major manner

    Parameters
    ----------
    mtx: input matrix to extract the off-diagonal entries
    """
    # we transpose the matrix because the function np.extract will first flatten the matrix
    # withe ordering convention 'C' instead of 'F'!!
    Q = mtx.shape[0]
    num_bands = mtx.shape[2]
    extract_cond = np.reshape((1 - np.eye(Q)).T.astype(bool), (-1, 1), order='F')
    return np.column_stack([np.reshape(np.extract(extract_cond, mtx[:, :, band].T),
                                       (-1, 1), order='F')
                            for band in range(num_bands)]) 
Example 7
Project: pyroomacoustics   Author: LCAV   File: tools_fri_doa_plane.py    License: MIT License 6 votes vote down vote up
def mtx_freq2visi(M, p_mic_x, p_mic_y):
    """
    build the matrix that maps the Fourier series to the visibility

    Parameters
    ----------
    M: 
        the Fourier series expansion is limited from -M to M
    p_mic_x: 
        a vector that constains microphones x coordinates
    p_mic_y: 
        a vector that constains microphones y coordinates
    """
    num_mic = p_mic_x.size
    ms = np.reshape(np.arange(-M, M + 1, step=1), (1, -1), order='F')
    p_mic_x_outer = p_mic_x[:, np.newaxis]
    p_mic_y_outer = p_mic_y[:, np.newaxis]
    p_mic_x_inner = p_mic_x[np.newaxis, :]
    p_mic_y_inner = p_mic_y[np.newaxis, :]
    extract_cond = np.reshape((1 - np.eye(num_mic)).astype(bool), (-1, 1), order='C')
    baseline_x = np.extract(extract_cond, p_mic_x_outer - p_mic_x_inner)[:, np.newaxis]
    baseline_y = np.extract(extract_cond, p_mic_y_outer - p_mic_y_inner)[:, np.newaxis]
    baseline_norm = np.sqrt(baseline_x * baseline_x + baseline_y * baseline_y)
    return (-1j) ** ms * sp.special.jv(ms, baseline_norm) * \
           np.exp(1j * ms * np.arctan2(baseline_y, baseline_x)) 
Example 8
Project: pyroomacoustics   Author: LCAV   File: tools_fri_doa_plane.py    License: MIT License 6 votes vote down vote up
def build_mtx_amp(phi_k, p_mic_x, p_mic_y):
    """
    the matrix that maps Diracs' amplitudes to the visibility

    Parameters
    ----------
    phi_k: 
        Diracs' location (azimuth)
    p_mic_x: 
        a vector that contains microphones' x-coordinates
    p_mic_y: 
        a vector that contains microphones' y-coordinates
    """
    xk, yk = polar2cart(1, phi_k[np.newaxis, :])
    num_mic = p_mic_x.size
    p_mic_x_outer = p_mic_x[:, np.newaxis]
    p_mic_y_outer = p_mic_y[:, np.newaxis]
    p_mic_x_inner = p_mic_x[np.newaxis, :]
    p_mic_y_inner = p_mic_y[np.newaxis, :]
    extract_cond = np.reshape((1 - np.eye(num_mic)).astype(bool), (-1, 1), order='C')
    baseline_x = np.extract(extract_cond, p_mic_x_outer - p_mic_x_inner)[:, np.newaxis]
    baseline_y = np.extract(extract_cond, p_mic_y_outer - p_mic_y_inner)[:, np.newaxis]
    return np.exp(-1j * (xk * baseline_x + yk * baseline_y)) 
Example 9
Project: FRIDA   Author: LCAV   File: tools_fri_doa_plane.py    License: MIT License 5 votes vote down vote up
def extract_off_diag(mtx):
    """
    extract off diagonal entries in mtx.
    The output vector is order in a column major manner.
    :param mtx: input matrix to extract the off diagonal entries
    :return:
    """
    # we transpose the matrix because the function np.extract will first flatten the matrix
    # withe ordering convention 'C' instead of 'F'!!
    extract_cond = np.reshape((1 - np.eye(*mtx.shape)).T.astype(bool), (-1, 1), order='F')
    return np.reshape(np.extract(extract_cond, mtx.T), (-1, 1), order='F') 
Example 10
Project: pyscf   Author: pyscf   File: lsofcsr.py    License: Apache License 2.0 5 votes vote down vote up
def lsofcsr(coo3, dtype=float, shape=None, axis=0):
  """
    Generate a list of csr matrices out of a 3-dimensional coo format 
    Args:
      coo3  : must be a tuple (data, (i1,i2,i3)) in analogy to the tuple (data, (rows,cols)) for a common coo format
      shape : a tuple of dimensions if they are known or cannot be guessed correctly from the data
      axis  : index (0,1 or 2) along which to construct the list of sparse arrays
    Returns:
      list of csr matrices
  """
  (d, it) = coo3
  assert len(it)==3
  for ia in it: assert len(d)==len(ia)
  shape = [max(ia)+1 for ia in it] if shape is None else shape
  #print( len(d) )
  #print( shape )
  
  iir = [i for i in range(len(shape)) if i!=axis]
  #print(__name__, iir)
  #print(__name__, type(it), type(it[0]==0))
  #print(__name__, it[0]==0)
  
  lsofcsr = [0] * shape[axis]
  sh = [shape[i] for i in iir]
  for i in range(shape[axis]):
    mask = it[axis]==i
    csrm = csr_matrix( (extract(mask,d), (extract(mask,it[iir[0]]),extract(mask,it[iir[1]]) )), shape=sh, dtype=dtype)
    csrm.eliminate_zeros()
    lsofcsr[i] = csrm
    
  #print(__name__, 'ttot', ttot)
  
  return lsofcsr

#
#
# 
Example 11
Project: recruit   Author: Frank-qlu   File: function_base.py    License: Apache License 2.0 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : ndarray
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N, it will be repeated, and if elements of `a` are to be masked,
        this sequence must be non-empty.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    if not isinstance(arr, np.ndarray):
        raise TypeError("argument 1 must be numpy.ndarray, "
                        "not {name}".format(name=type(arr).__name__))

    return _insert(arr, mask, vals) 
Example 12
Project: mars   Author: mars-project   File: test_indexing_execute.py    License: Apache License 2.0 5 votes vote down vote up
def testExtractExecution(self):
        data = np.arange(12).reshape((3, 4))
        a = tensor(data, chunk_size=2)
        condition = mod(a, 3) == 0

        t = extract(condition, a)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.extract(np.mod(data, 3) == 0, data)
        np.testing.assert_array_equal(res, expected) 
Example 13
Project: lambda-packs   Author: ryfeus   File: function_base.py    License: MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : ndarray
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N, it will be repeated, and if elements of `a` are to be masked,
        this sequence must be non-empty.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    if not isinstance(arr, np.ndarray):
        raise TypeError("argument 1 must be numpy.ndarray, "
                        "not {name}".format(name=type(arr).__name__))

    return _insert(arr, mask, vals) 
Example 14
Project: lambda-packs   Author: ryfeus   File: _util.py    License: MIT License 5 votes vote down vote up
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
    """
    np.where(cond, x, fillvalue) always evaluates x even where cond is False.
    This one only evaluates f(arr1[cond], arr2[cond], ...).
    For example,
    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
    >>> def f(a, b):
        return a*b
    >>> _lazywhere(a > 2, (a, b), f, np.nan)
    array([ nan,  nan,  21.,  32.])

    Notice it assumes that all `arrays` are of the same shape, or can be
    broadcasted together.

    """
    if fillvalue is None:
        if f2 is None:
            raise ValueError("One of (fillvalue, f2) must be given.")
        else:
            fillvalue = np.nan
    else:
        if f2 is not None:
            raise ValueError("Only one of (fillvalue, f2) can be given.")

    arrays = np.broadcast_arrays(*arrays)
    temp = tuple(np.extract(cond, arr) for arr in arrays)
    tcode = np.mintypecode([a.dtype.char for a in arrays])
    out = _valarray(np.shape(arrays[0]), value=fillvalue, typecode=tcode)
    np.place(out, cond, f(*temp))
    if f2 is not None:
        temp = tuple(np.extract(~cond, arr) for arr in arrays)
        np.place(out, ~cond, f2(*temp))

    return out 
Example 15
Project: lambda-packs   Author: ryfeus   File: _util.py    License: MIT License 5 votes vote down vote up
def _lazyselect(condlist, choicelist, arrays, default=0):
    """
    Mimic `np.select(condlist, choicelist)`.

    Notice it assumes that all `arrays` are of the same shape, or can be
    broadcasted together.

    All functions in `choicelist` must accept array arguments in the order
    given in `arrays` and must return an array of the same shape as broadcasted
    `arrays`.

    Examples
    --------
    >>> x = np.arange(6)
    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
    array([  0,   1,   4,   0,  64, 125])

    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
    array([   0.,    1.,    4.,   0.,   64.,  125.])

    >>> a = -np.ones_like(x)
    >>> _lazyselect([x < 3, x > 3],
    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
    ...             (x, a), default=np.nan)
    array([   0.,    1.,    4.,   nan,  -64., -125.])

    """
    arrays = np.broadcast_arrays(*arrays)
    tcode = np.mintypecode([a.dtype.char for a in arrays])
    out = _valarray(np.shape(arrays[0]), value=default, typecode=tcode)
    for index in range(len(condlist)):
        func, cond = choicelist[index], condlist[index]
        if np.all(cond is False):
            continue
        cond, _ = np.broadcast_arrays(cond, arrays[0])
        temp = tuple(np.extract(cond, arr) for arr in arrays)
        np.place(out, cond, func(*temp))
    return out 
Example 16
Project: lambda-packs   Author: ryfeus   File: _continuous_distns.py    License: MIT License 5 votes vote down vote up
def _stats(self, b, moments='mv'):
        mu, mu2, g1, g2 = None, None, None, None
        if 'm' in moments:
            mask = b > 1
            bt = np.extract(mask, b)
            mu = valarray(np.shape(b), value=np.inf)
            np.place(mu, mask, bt / (bt-1.0))
        if 'v' in moments:
            mask = b > 2
            bt = np.extract(mask, b)
            mu2 = valarray(np.shape(b), value=np.inf)
            np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2)
        if 's' in moments:
            mask = b > 3
            bt = np.extract(mask, b)
            g1 = valarray(np.shape(b), value=np.nan)
            vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt))
            np.place(g1, mask, vals)
        if 'k' in moments:
            mask = b > 4
            bt = np.extract(mask, b)
            g2 = valarray(np.shape(b), value=np.nan)
            vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) /
                    np.polyval([1.0, -7.0, 12.0, 0.0], bt))
            np.place(g2, mask, vals)
        return mu, mu2, g1, g2 
Example 17
Project: lambda-packs   Author: ryfeus   File: _distn_infrastructure.py    License: MIT License 5 votes vote down vote up
def argsreduce(cond, *args):
    """Return the sequence of ravel(args[i]) where ravel(condition) is
    True in 1D.

    Examples
    --------
    >>> import numpy as np
    >>> rand = np.random.random_sample
    >>> A = rand((4, 5))
    >>> B = 2
    >>> C = rand((1, 5))
    >>> cond = np.ones(A.shape)
    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
    >>> B1.shape
    (20,)
    >>> cond[2,:] = 0
    >>> [A2, B2, C2] = argsreduce(cond, A, B, C)
    >>> B2.shape
    (15,)

    """
    newargs = np.atleast_1d(*args)
    if not isinstance(newargs, list):
        newargs = [newargs, ]
    expand_arr = (cond == cond)
    return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs] 
Example 18
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: function_base.py    License: MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : ndarray
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N it will be repeated.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    if not isinstance(arr, np.ndarray):
        raise TypeError("argument 1 must be numpy.ndarray, "
                        "not {name}".format(name=type(arr).__name__))

    return _insert(arr, mask, vals) 
Example 19
Project: vnpy_crypto   Author: birforce   File: function_base.py    License: MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : ndarray
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N, it will be repeated, and if elements of `a` are to be masked,
        this sequence must be non-empty.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    if not isinstance(arr, np.ndarray):
        raise TypeError("argument 1 must be numpy.ndarray, "
                        "not {name}".format(name=type(arr).__name__))

    return _insert(arr, mask, vals) 
Example 20
Project: vnpy_crypto   Author: birforce   File: scipy.py    License: MIT License 5 votes vote down vote up
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
    """
    np.where(cond, x, fillvalue) always evaluates x even where cond is False.
    This one only evaluates f(arr1[cond], arr2[cond], ...).
    For example,
    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
    >>> def f(a, b):
        return a*b
    >>> _lazywhere(a > 2, (a, b), f, np.nan)
    array([ nan,  nan,  21.,  32.])
    Notice it assumes that all `arrays` are of the same shape, or can be
    broadcasted together.
    """
    if fillvalue is None:
        if f2 is None:
            raise ValueError("One of (fillvalue, f2) must be given.")
        else:
            fillvalue = np.nan
    else:
        if f2 is not None:
            raise ValueError("Only one of (fillvalue, f2) can be given.")

    arrays = np.broadcast_arrays(*arrays)
    temp = tuple(np.extract(cond, arr) for arr in arrays)
    tcode = np.mintypecode([a.dtype.char for a in arrays])
    out = _valarray(np.shape(arrays[0]), value=fillvalue, typecode=tcode)
    np.place(out, cond, f(*temp))
    if f2 is not None:
        temp = tuple(np.extract(~cond, arr) for arr in arrays)
        np.place(out, ~cond, f2(*temp))

    return out


# Work around for complex chnges in gammaln in 1.0.0.  loggamma introduced in 0.18. 
Example 21
Project: Computable   Author: ktraunmueller   File: function_base.py    License: MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : array_like
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N it will be repeated.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    return _insert(arr, mask, vals) 
Example 22
Project: eht-imaging   Author: achael   File: patch_prior.py    License: GNU General Public License v3.0 5 votes vote down vote up
def im2col(im, patchSize):

    # extract all overlapping patches from the image
    M,N = im.shape
    col_extent = N - patchSize + 1
    row_extent = M - patchSize + 1
    # Get Starting block indices
    start_idx = np.arange(patchSize)[:,None]*N + np.arange(patchSize)
    # Get offsetted indices across the height and width of input array
    offset_idx = np.arange(row_extent)[:,None]*N + np.arange(col_extent)
    # Get all actual indices & index into input array for final output
    Z = np.take (im,start_idx.ravel()[:,None] + offset_idx.ravel())
    return Z 
Example 23
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: function_base.py    License: MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : ndarray
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N, it will be repeated, and if elements of `a` are to be masked,
        this sequence must be non-empty.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    if not isinstance(arr, np.ndarray):
        raise TypeError("argument 1 must be numpy.ndarray, "
                        "not {name}".format(name=type(arr).__name__))

    return _insert(arr, mask, vals) 
Example 24
def visualize_accuracy(a, start=0.01, end=0.5, showlist=None, resolution=100):
    """ Compute the Accuracy in rate
    Args:
        a:              distance matrix like err in compute_distance 
        showlist:       list of joints to be shown
        resolutional:   determine the 
    """
    if showlist is None:
        showlist = range(0, len(Global.joint_list))
    else:
        show_list = showlist

    plt.title("CPM PCKh benchmark on MPII")
    plt.xlabel("Normalized distance")
    plt.ylabel("Accuracy")

    dists = np.linspace(start, end, resolution)
    re = np.zeros((dists.shape[0], a.shape[1]), np.float)
    av = np.zeros((dists.shape[0]), np.float)
    for ridx in range(dists.shape[0]):
        print "[*]\tProcessing Result in normalized distance of", dists[ridx]
        for j in range(a.shape[1]):
            condition = a[:,j] <= dists[ridx]
            re[ridx, j] = len(np.extract(condition, a[:,j]))/float(a.shape[0])
            print "[*]\t", Global.joint_list[j], " Accuracy :\t\t", re[ridx, j]
        av[ridx] = np.average(re[ridx])
        print "[*]\t\tTOTAL Accuracy :\t\t", av[ridx]

    for j in show_list:
        plt.plot(dists, re[:, j], label=Global.joint_list[j], linewidth = 2.0)
    plt.plot(dists, av, label="Average",linewidth = 3.0)
    plt.legend(loc='upper left')
    plt.grid()
    plt.show() 
Example 25
Project: GraphicDesignPatternByPython   Author: Relph1119   File: function_base.py    License: MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """
    Change elements of an array based on conditional and input values.

    Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
    `place` uses the first N elements of `vals`, where N is the number of
    True values in `mask`, while `copyto` uses the elements where `mask`
    is True.

    Note that `extract` does the exact opposite of `place`.

    Parameters
    ----------
    arr : ndarray
        Array to put data into.
    mask : array_like
        Boolean mask array. Must have the same size as `a`.
    vals : 1-D sequence
        Values to put into `a`. Only the first N elements are used, where
        N is the number of True values in `mask`. If `vals` is smaller
        than N, it will be repeated, and if elements of `a` are to be masked,
        this sequence must be non-empty.

    See Also
    --------
    copyto, put, take, extract

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    """
    if not isinstance(arr, np.ndarray):
        raise TypeError("argument 1 must be numpy.ndarray, "
                        "not {name}".format(name=type(arr).__name__))

    return _insert(arr, mask, vals) 
Example 26
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _util.py    License: MIT License 5 votes vote down vote up
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
    """
    np.where(cond, x, fillvalue) always evaluates x even where cond is False.
    This one only evaluates f(arr1[cond], arr2[cond], ...).
    For example,
    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
    >>> def f(a, b):
        return a*b
    >>> _lazywhere(a > 2, (a, b), f, np.nan)
    array([ nan,  nan,  21.,  32.])

    Notice it assumes that all `arrays` are of the same shape, or can be
    broadcasted together.

    """
    if fillvalue is None:
        if f2 is None:
            raise ValueError("One of (fillvalue, f2) must be given.")
        else:
            fillvalue = np.nan
    else:
        if f2 is not None:
            raise ValueError("Only one of (fillvalue, f2) can be given.")

    arrays = np.broadcast_arrays(*arrays)
    temp = tuple(np.extract(cond, arr) for arr in arrays)
    tcode = np.mintypecode([a.dtype.char for a in arrays])
    out = _valarray(np.shape(arrays[0]), value=fillvalue, typecode=tcode)
    np.place(out, cond, f(*temp))
    if f2 is not None:
        temp = tuple(np.extract(~cond, arr) for arr in arrays)
        np.place(out, ~cond, f2(*temp))

    return out 
Example 27
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _util.py    License: MIT License 5 votes vote down vote up
def _lazyselect(condlist, choicelist, arrays, default=0):
    """
    Mimic `np.select(condlist, choicelist)`.

    Notice it assumes that all `arrays` are of the same shape, or can be
    broadcasted together.

    All functions in `choicelist` must accept array arguments in the order
    given in `arrays` and must return an array of the same shape as broadcasted
    `arrays`.

    Examples
    --------
    >>> x = np.arange(6)
    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
    array([  0,   1,   4,   0,  64, 125])

    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
    array([   0.,    1.,    4.,   0.,   64.,  125.])

    >>> a = -np.ones_like(x)
    >>> _lazyselect([x < 3, x > 3],
    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
    ...             (x, a), default=np.nan)
    array([   0.,    1.,    4.,   nan,  -64., -125.])

    """
    arrays = np.broadcast_arrays(*arrays)
    tcode = np.mintypecode([a.dtype.char for a in arrays])
    out = _valarray(np.shape(arrays[0]), value=default, typecode=tcode)
    for index in range(len(condlist)):
        func, cond = choicelist[index], condlist[index]
        if np.all(cond is False):
            continue
        cond, _ = np.broadcast_arrays(cond, arrays[0])
        temp = tuple(np.extract(cond, arr) for arr in arrays)
        np.place(out, cond, func(*temp))
    return out 
Example 28
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _continuous_distns.py    License: MIT License 5 votes vote down vote up
def _stats(self, b, moments='mv'):
        mu, mu2, g1, g2 = None, None, None, None
        if 'm' in moments:
            mask = b > 1
            bt = np.extract(mask, b)
            mu = valarray(np.shape(b), value=np.inf)
            np.place(mu, mask, bt / (bt-1.0))
        if 'v' in moments:
            mask = b > 2
            bt = np.extract(mask, b)
            mu2 = valarray(np.shape(b), value=np.inf)
            np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2)
        if 's' in moments:
            mask = b > 3
            bt = np.extract(mask, b)
            g1 = valarray(np.shape(b), value=np.nan)
            vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt))
            np.place(g1, mask, vals)
        if 'k' in moments:
            mask = b > 4
            bt = np.extract(mask, b)
            g2 = valarray(np.shape(b), value=np.nan)
            vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) /
                    np.polyval([1.0, -7.0, 12.0, 0.0], bt))
            np.place(g2, mask, vals)
        return mu, mu2, g1, g2 
Example 29
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _distn_infrastructure.py    License: MIT License 5 votes vote down vote up
def argsreduce(cond, *args):
    """Return the sequence of ravel(args[i]) where ravel(condition) is
    True in 1D.

    Examples
    --------
    >>> import numpy as np
    >>> rand = np.random.random_sample
    >>> A = rand((4, 5))
    >>> B = 2
    >>> C = rand((1, 5))
    >>> cond = np.ones(A.shape)
    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
    >>> B1.shape
    (20,)
    >>> cond[2,:] = 0
    >>> [A2, B2, C2] = argsreduce(cond, A, B, C)
    >>> B2.shape
    (15,)

    """
    newargs = np.atleast_1d(*args)
    if not isinstance(newargs, list):
        newargs = [newargs, ]
    expand_arr = (cond == cond)
    return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs] 
Example 30
Project: IkaLog   Author: hasegaw   File: objective_tracker.py    License: Apache License 2.0 5 votes vote down vote up
def tower_pos(self, context):
        img = context['engine']['frame'][self.tower_line_top:self.tower_line_top +
                                         self.tower_line_height, self.tower_left:self.tower_left + self.tower_width]
        img2 = cv2.resize(img, (self.tower_width, 100))
        img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        for i in range(2):
            img2[20:40, :, i] = cv2.resize(
                img_hsv[:, :, 0], (self.tower_width, 20))
            img2[40:60, :, i] = cv2.resize(
                img_hsv[:, :, 1], (self.tower_width, 20))
            img2[60:80, :, i] = cv2.resize(
                img_hsv[:, :, 2], (self.tower_width, 20))

        # ゲージのうち信頼できる部分だけでマスクする
        img3 = img & self.ui_tower_mask

        # 白い部分にいまヤグラ/ホコがある
        img3_hsv = cv2.cvtColor(img3, cv2.COLOR_BGR2HSV)
        white_mask_v = cv2.inRange(img3_hsv[:, :, 2], 248, 256)
        x_list = np.arange(self.tower_width)
        tower_x = np.extract(white_mask_v[3, :] > 128, x_list)

        if tower_x.shape[0] == 0:
            return None

        tower_xPos = np.average(tower_x)

        # FixMe: マスクした関係が位置がずれている可能性があるので、適宜補正すべき

        xPos_pct = (tower_xPos - self.tower_width / 2) / \
            (self.tower_width * 0.86 / 2) * 100

        # あきらかにおかしい値が出たらとりあえず排除
        if xPos_pct < -120 or 120 < xPos_pct:
            xPos_pct = None

        return xPos_pct