Python numpy.select() Examples

The following are 30 code examples for showing how to use numpy.select(). 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: SpatioTemporalSegmentation   Author: chrischoy   File: transforms.py    License: MIT License 7 votes vote down vote up
def hsv_to_rgb(hsv):
    # Translated from source of colorsys.hsv_to_rgb
    # h,s should be a numpy arrays with values between 0.0 and 1.0
    # v should be a numpy array with values between 0.0 and 255.0
    # hsv_to_rgb returns an array of uints between 0 and 255.
    rgb = np.empty_like(hsv)
    rgb[..., 3:] = hsv[..., 3:]
    h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
    i = (h * 6.0).astype('uint8')
    f = (h * 6.0) - i
    p = v * (1.0 - s)
    q = v * (1.0 - s * f)
    t = v * (1.0 - s * (1.0 - f))
    i = i % 6
    conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5]
    rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v)
    rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t)
    rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p)
    return rgb.astype('uint8') 
Example 2
Project: GSEApy   Author: zqfang   File: algorithm.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def gsea_pval(es, esnull):
    """Compute nominal p-value.

    From article (PNAS):
    estimate nominal p-value for S from esnull by using the positive
    or negative portion of the distribution corresponding to the sign
    of the observed ES(S).
    """

    # to speed up, using numpy function to compute pval in parallel.
    condlist = [ es < 0, es >=0]
    choicelist = [(esnull < es.reshape(len(es),1)).sum(axis=1)/ (esnull < 0).sum(axis=1),
                  (esnull >= es.reshape(len(es),1)).sum(axis=1)/ (esnull >= 0).sum(axis=1)]
    pvals = np.select(condlist, choicelist)

    return pvals 
Example 3
Project: ibis   Author: ibis-project   File: test_operations.py    License: Apache License 2.0 6 votes vote down vote up
def test_searched_case_column(batting, batting_df):
    t = batting
    df = batting_df
    expr = (
        ibis.case()
        .when(t.RBI < 5, 'really bad team')
        .when(t.teamID == 'PH1', 'ph1 team')
        .else_(t.teamID)
        .end()
    )
    result = expr.execute()
    expected = pd.Series(
        np.select(
            [df.RBI < 5, df.teamID == 'PH1'],
            ['really bad team', 'ph1 team'],
            df.teamID,
        )
    )
    tm.assert_series_equal(result, expected) 
Example 4
Project: ibis   Author: ibis-project   File: test_operations.py    License: Apache License 2.0 6 votes vote down vote up
def test_simple_case_column(batting, batting_df):
    t = batting
    df = batting_df
    expr = (
        t.RBI.case()
        .when(5, 'five')
        .when(4, 'four')
        .when(3, 'three')
        .else_('could be good?')
        .end()
    )
    result = expr.execute()
    expected = pd.Series(
        np.select(
            [df.RBI == 5, df.RBI == 4, df.RBI == 3],
            ['five', 'four', 'three'],
            'could be good?',
        )
    )
    tm.assert_series_equal(result, expected) 
Example 5
Project: trax   Author: google   File: lax_numpy_test.py    License: Apache License 2.0 6 votes vote down vote up
def testSelect(self, rng_factory, shapes, dtypes):
    rng = rng_factory()
    n = len(dtypes) - 1
    def args_maker():
      condlist = [rng(shape, onp.bool_) for shape in shapes[:n]]
      choicelist = [rng(shape, dtype)
                    for shape, dtype in zip(shapes[n:-1], dtypes[:n])]
      default = rng(shapes[-1], dtypes[-1])
      return condlist, choicelist, default
    # TODO(phawkins): float32/float64 type mismatches
    def onp_fun(condlist, choicelist, default):
      choicelist = [x if lnp.bfloat16 != lnp.result_type(x)
                    else x.astype(onp.float32) for x in choicelist]
      dtype = lnp.result_type(default, *choicelist)
      return onp.select(condlist,
                        [onp.asarray(x, dtype=dtype) for x in choicelist],
                        onp.asarray(default, dtype=dtype))
    self._CheckAgainstNumpy(onp_fun, lnp.select, args_maker,
                            check_dtypes=False)
    self._CompileAndCheck(lnp.select, args_maker, check_dtypes=True,
                          check_incomplete_shape=True,
                          rtol={onp.float64: 1e-7, onp.complex128: 1e-7}) 
Example 6
Project: smallrnaseq   Author: dmnfarrell   File: mirdeep2.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check_quantifier_results(path):
    """Check quantifier vs results file in case of miscounts"""

    resfile = glob.glob(os.path.join(path,'result*.csv'))[0]
    df = read_results_file(resfile)
    files = glob.glob(os.path.join(path,'miRNAs_expressed_all_samples*.csv'))
    q = pd.read_csv(files[0],sep='\t')
    key='provisional id'
    m=q.merge(df,left_on='#miRNA',right_on=key).drop_duplicates('#miRNA')
    m.sc = m['miRDeep2 score']
    m['err'] = abs(m['read_count']-m['total read count'])
    cols=['#miRNA','total read count','read_count','miRDeep2 score']
    print (m[m.err>400].sort('total read count',ascending=False)[cols])
    m['size'] = np.select([m.sc < 2, m.sc < 3, m.sc < 4], [20,40,50], 80)
    f,ax=plt.subplots(1,1)
    plt.xscale('log')
    plt.yscale('log')
    m.plot(x='total read count',y='read_count', kind='scatter',s=60,alpha=0.6,ax=ax)
    #ax.plot([0, 1], [0, 1], transform=ax.transAxes,color='red',alpha=0.7)
    plt.show()
    return 
Example 7
Project: SpatioTemporalSegmentation   Author: chrischoy   File: transforms.py    License: MIT License 6 votes vote down vote up
def rgb_to_hsv(rgb):
    # Translated from source of colorsys.rgb_to_hsv
    # r,g,b should be a numpy arrays with values between 0 and 255
    # rgb_to_hsv returns an array of floats between 0.0 and 1.0.
    rgb = rgb.astype('float')
    hsv = np.zeros_like(rgb)
    # in case an RGBA array was passed, just copy the A channel
    hsv[..., 3:] = rgb[..., 3:]
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    maxc = np.max(rgb[..., :3], axis=-1)
    minc = np.min(rgb[..., :3], axis=-1)
    hsv[..., 2] = maxc
    mask = maxc != minc
    hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask]
    rc = np.zeros_like(r)
    gc = np.zeros_like(g)
    bc = np.zeros_like(b)
    rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]
    gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]
    bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]
    hsv[..., 0] = np.select([r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc)
    hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0
    return hsv 
Example 8
Project: Conditional_Density_Estimation   Author: freelunchtheorem   File: ArmaJump.py    License: MIT License 6 votes vote down vote up
def simulate_conditional(self, X):
    """ Draws random samples from the conditional distribution

    Args:
      X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)

    Returns:
      Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)
    """
    mean = self.arma_c * (1 - self.arma_a1) + self.arma_a1 * X
    y_ar = self.random_state.normal(loc=mean, scale=self.std, size=X.shape[0])

    mean_jump = mean + self.jump_mean
    y_jump = self.random_state.normal(loc=mean_jump, scale=self.jump_std, size=X.shape[0])

    jump_bernoulli = self.random_state.uniform(size=X.shape[0]) < self.jump_prob

    return X, np.select([jump_bernoulli, np.bitwise_not(jump_bernoulli)], [y_jump, y_ar]) 
Example 9
Project: Carnets   Author: holzschu   File: functional_models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def evaluate(x, y, amplitude, x_0, y_0, a, b, theta):
        """Two dimensional Ellipse model function."""

        xx = x - x_0
        yy = y - y_0
        cost = np.cos(theta)
        sint = np.sin(theta)
        numerator1 = (xx * cost) + (yy * sint)
        numerator2 = -(xx * sint) + (yy * cost)
        in_ellipse = (((numerator1 / a) ** 2 + (numerator2 / b) ** 2) <= 1.)
        result = np.select([in_ellipse], [amplitude])

        if isinstance(amplitude, Quantity):
            return Quantity(result, unit=amplitude.unit, copy=False)
        else:
            return result 
Example 10
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 11
Project: lambda-packs   Author: ryfeus   File: _continuous_distns.py    License: MIT License 5 votes vote down vote up
def _pdf(self, x, c, d):
        u = 2 / (d - c + 1)

        condlist = [x < c, x <= d, x > d]
        choicelist = [u * x / c, u, u * (1 - x) / (1 - d)]
        return np.select(condlist, choicelist) 
Example 12
Project: lambda-packs   Author: ryfeus   File: _continuous_distns.py    License: MIT License 5 votes vote down vote up
def _cdf(self, x, c, d):
        condlist = [x < c, x <= d, x > d]
        choicelist = [x**2 / c / (d - c + 1),
                      (c + 2 * (x - c)) / (d - c + 1),
                      1 - ((1 - x)**2 / (d - c + 1) / (1 - d))]
        return np.select(condlist, choicelist) 
Example 13
Project: lambda-packs   Author: ryfeus   File: _continuous_distns.py    License: MIT License 5 votes vote down vote up
def _ppf(self, q, c, d):
        qc, qd = self._cdf(c, c, d), self._cdf(d, c, d)
        condlist = [q < qc, q <= qd, q > qd]
        choicelist = [np.sqrt(q * c * (1 + d - c)),
                      0.5 * q * (1 + d - c) + 0.5 * c,
                      1 - np.sqrt((1 - q) * (d - c + 1) * (1 - d))]
        return np.select(condlist, choicelist) 
Example 14
Project: lambda-packs   Author: ryfeus   File: _distn_infrastructure.py    License: MIT License 5 votes vote down vote up
def _pmf(self, x):
        return np.select([x == k for k in self.xk],
                         [np.broadcast_arrays(p, x)[0] for p in self.pk], 0) 
Example 15
Project: terrain-erosion-3-ways   Author: dandrino   File: simulation.py    License: MIT License 5 votes vote down vote up
def apply_slippage(terrain, repose_slope, cell_width):
  delta = util.simple_gradient(terrain) / cell_width
  smoothed = util.gaussian_blur(terrain, sigma=1.5)
  should_smooth = np.abs(delta) > repose_slope
  result = np.select([np.abs(delta) > repose_slope], [smoothed], terrain)
  return result 
Example 16
Project: Computable   Author: ktraunmueller   File: test_distributions.py    License: MIT License 5 votes vote down vote up
def test_cdf(self):
        x = numpy.r_[0:36:100j]
        k = numpy.floor(x)
        out = numpy.select([k >= 30,k >= 5],[1.0,(k-5.0+1)/(30-5.0)],0)
        vals = stats.randint.cdf(x,5,30)
        assert_array_almost_equal(vals, out, decimal=12) 
Example 17
Project: ibis   Author: ibis-project   File: generic.py    License: Apache License 2.0 5 votes vote down vote up
def execute_searched_case(op, whens, thens, otherwise, **kwargs):
    if otherwise is None:
        otherwise = np.nan
    raw = np.select(whens, thens, otherwise)
    return wrap_case_result(raw, op.to_expr()) 
Example 18
Project: ibis   Author: ibis-project   File: generic.py    License: Apache License 2.0 5 votes vote down vote up
def execute_simple_case_scalar(op, value, whens, thens, otherwise, **kwargs):
    if otherwise is None:
        otherwise = np.nan
    raw = np.select(np.asarray(whens) == value, thens, otherwise)
    return wrap_case_result(raw, op.to_expr()) 
Example 19
Project: ibis   Author: ibis-project   File: generic.py    License: Apache License 2.0 5 votes vote down vote up
def execute_simple_case_series(op, value, whens, thens, otherwise, **kwargs):
    if otherwise is None:
        otherwise = np.nan
    raw = np.select([value == when for when in whens], thens, otherwise)
    return wrap_case_result(raw, op.to_expr()) 
Example 20
Project: MINERVA   Author: shehzaadzd   File: environment.py    License: Apache License 2.0 5 votes vote down vote up
def get_reward(self):
        reward = (self.current_entities == self.end_entities)

        # set the True and False values to the values of positive and negative rewards.
        condlist = [reward == True, reward == False]
        choicelist = [self.positive_reward, self.negative_reward]
        reward = np.select(condlist, choicelist)  # [B,]
        return reward 
Example 21
Project: addons   Author: tensorflow   File: sparsemax_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_two_dimentional(dtype):
    """check two dimentation sparsemax case."""
    t = np.linspace(-2, 2, test_obs, dtype=dtype)
    z = np.vstack([t, np.zeros(test_obs, dtype=dtype)]).T

    tf_sparsemax_out = sparsemax(z.astype(dtype)).numpy()

    p0_expected = np.select([t < -1, t <= 1, t > 1], [0, (t + 1) / 2, 1])

    test_utils.assert_allclose_according_to_type(p0_expected, tf_sparsemax_out[:, 0])
    test_utils.assert_allclose_according_to_type(
        1 - p0_expected, tf_sparsemax_out[:, 1]
    )
    assert z.shape == tf_sparsemax_out.shape 
Example 22
Project: trax   Author: google   File: array_ops.py    License: Apache License 2.0 5 votes vote down vote up
def select(condlist, choicelist, default=0):  # pylint: disable=missing-docstring
  if len(condlist) != len(choicelist):
    msg = 'condlist must have length equal to choicelist ({} vs {})'
    raise ValueError(msg.format(len(condlist), len(choicelist)))
  if not condlist:
    raise ValueError('condlist must be non-empty')
  choices = _promote_dtype(default, *choicelist)
  choicelist = choices[1:]
  output = choices[0]
  # The traversal is in reverse order so we can return the first value in
  # choicelist where condlist is True.
  for cond, choice in zip(condlist[::-1], choicelist[::-1]):
    output = where(cond, choice, output)
  return output 
Example 23
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 24
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _continuous_distns.py    License: MIT License 5 votes vote down vote up
def _ppf(self, q, c, d):
        qc, qd = self._cdf(c, c, d), self._cdf(d, c, d)
        condlist = [q < qc, q <= qd, q > qd]
        choicelist = [np.sqrt(q * c * (1 + d - c)),
                      0.5 * q * (1 + d - c) + 0.5 * c,
                      1 - np.sqrt((1 - q) * (d - c + 1) * (1 - d))]
        return np.select(condlist, choicelist) 
Example 25
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _distn_infrastructure.py    License: MIT License 5 votes vote down vote up
def _pmf(self, x):
        return np.select([x == k for k in self.xk],
                         [np.broadcast_arrays(p, x)[0] for p in self.pk], 0) 
Example 26
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    License: MIT License 5 votes vote down vote up
def test_cdf(self):
        x = numpy.r_[0:36:100j]
        k = numpy.floor(x)
        out = numpy.select([k >= 30, k >= 5], [1.0, (k-5.0+1)/(30-5.0)], 0)
        vals = stats.randint.cdf(x, 5, 30)
        assert_array_almost_equal(vals, out, decimal=12) 
Example 27
Project: cupy   Author: cupy   File: indexing.py    License: MIT License 5 votes vote down vote up
def take(a, indices, axis=None, out=None):
    """Takes elements of an array at specified indices along an axis.

    This is an implementation of "fancy indexing" at single axis.

    This function does not support ``mode`` option.

    Args:
        a (cupy.ndarray): Array to extract elements.
        indices (int or array-like): Indices of elements that this function
            takes.
        axis (int): The axis along which to select indices. The flattened input
            is used by default.
        out (cupy.ndarray): Output array. If provided, it should be of
            appropriate shape and dtype.

    Returns:
        cupy.ndarray: The result of fancy indexing.

    .. seealso:: :func:`numpy.take`

    """
    # TODO(okuta): check type
    return a.take(indices, axis, out) 
Example 28
Project: s-vae-tf   Author: nicola-decao   File: ive.py    License: MIT License 5 votes vote down vote up
def ive(v, z):
    """Exponentially scaled modified Bessel function of the first kind."""
    output = array_ops.reshape(script_ops.py_func(
        lambda v, z: np.select(condlist=[v == 0, v == 1],
                               choicelist=[scipy.special.i0e(z, dtype=z.dtype),
                                           scipy.special.i1e(z, dtype=z.dtype)],
                               default=scipy.special.ive(v, z, dtype=z.dtype)), [v, z], z.dtype),
        ops.convert_to_tensor(array_ops.shape(z), dtype=dtypes.int32))

    def grad(dy):
        return None, dy * (ive(v - 1, z) - ive(v, z) * (v + z) / z)

    return output, grad 
Example 29
Project: MyGrad   Author: rsokl   File: ops.py    License: MIT License 5 votes vote down vote up
def backward_var(self, grad, index, **kwargs):
        # d arcsin / dx at x = -1, 1 returns 0, not NaN
        a = self.variables[index]
        return np.select([np.abs(a.data) != 1], [grad / np.sqrt(1 - a.data ** 2)]) 
Example 30
Project: MyGrad   Author: rsokl   File: ops.py    License: MIT License 5 votes vote down vote up
def backward_var(self, grad, index, **kwargs):
        # d arccos / dx at x = -1, 1 returns 0, not NaN
        a = self.variables[index]
        return np.select([np.abs(a.data) != 1], [-grad / np.sqrt(1 - a.data ** 2)])