Python numpy.select() Examples

The following are 30 code examples of numpy.select(). 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 numpy , or try the search function .
Example #1
Source File: transforms.py    From SpatioTemporalSegmentation with 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
Source File: lax_numpy_test.py    From trax with 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 #3
Source File: transforms.py    From SpatioTemporalSegmentation with 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 #4
Source File: algorithm.py    From GSEApy with 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 #5
Source File: ArmaJump.py    From Conditional_Density_Estimation with 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 #6
Source File: functional_models.py    From Carnets with 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 #7
Source File: mirdeep2.py    From smallrnaseq with 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 #8
Source File: test_operations.py    From ibis with 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 #9
Source File: test_operations.py    From ibis with 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 #10
Source File: _continuous_distns.py    From Splunking-Crime with GNU Affero General Public License v3.0 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 #11
Source File: environment.py    From CPL with MIT License 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 #12
Source File: _continuous_distns.py    From Splunking-Crime with GNU Affero General Public License v3.0 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
Source File: _continuous_distns.py    From Splunking-Crime with GNU Affero General Public License v3.0 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 #14
Source File: _util.py    From Splunking-Crime with GNU Affero General Public License v3.0 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 #15
Source File: numpy_wrapper.py    From autograd with MIT License 5 votes vote down vote up
def select(condlist, choicelist, default=0):
    raw_array = _np.select(list(condlist), list(choicelist), default=default)
    return array(list(raw_array.ravel())).reshape(raw_array.shape) 
Example #16
Source File: molecular_metrics.py    From MolGAN with MIT License 5 votes vote down vote up
def constant_bump(x, x_low, x_high, decay=0.025):
        return np.select(condlist=[x <= x_low, x >= x_high],
                         choicelist=[np.exp(- (x - x_low) ** 2 / decay),
                                     np.exp(- (x - x_high) ** 2 / decay)],
                         default=np.ones_like(x)) 
Example #17
Source File: pandas.py    From PyMove with MIT License 5 votes vote down vote up
def tail(self, n=5):
        """
        Return the last n rows.

        This function returns the last n rows for the object
        based on position. It is useful for quickly testing if
        your object has the right type of data in it.

        Parameters
        ----------
        n : int, default 5.
            Number of rows to select.

        Returns
        -------
        same type as caller
            The last n rows of the caller object.

        References
        ----------
        https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.tail.html

        """

        operation = begin_operation('tail')
        tail_ = self._data.tail(n)
        self.last_operation = end_operation(operation)

        return tail_ 
Example #18
Source File: pandas.py    From PyMove with MIT License 5 votes vote down vote up
def head(self, n=5):
        """
        Return the first n rows.

        This function returns the first n rows for the object
        based on position. It is useful for quickly testing if
        your object has the right type of data in it.

        Parameters
        ----------
        n : int, default 5.
            Number of rows to select.

        Returns
        -------
        same type as caller
            The first n rows of the caller object.

        References
        ----------
        https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html

        """

        operation = begin_operation('head')
        head_ = self._data.head(n)
        self.last_operation = end_operation(operation)

        return head_ 
Example #19
Source File: _distn_infrastructure.py    From Splunking-Crime with GNU Affero General Public License v3.0 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 #20
Source File: molecular_metrics.py    From graph-nvp with MIT License 5 votes vote down vote up
def constant_bump(x, x_low, x_high, decay=0.025):
        return np.select(condlist=[x <= x_low, x >= x_high],
                         choicelist=[np.exp(- (x - x_low) ** 2 / decay),
                                     np.exp(- (x - x_high) ** 2 / decay)],
                         default=np.ones_like(x)) 
Example #21
Source File: ops.py    From MyGrad with MIT License 5 votes vote down vote up
def backward_var(self, grad, index, **kwargs):
        # d arccsc / dx at x = -1, 1 returns 0, not NaN
        a = self.variables[index]
        return np.select(
            [np.abs(a.data) != 1], [-grad / (np.abs(a.data) * np.sqrt(a.data ** 2 - 1))]
        ) 
Example #22
Source File: RSI Pattern Recognition backtest.py    From quant-trading with Apache License 2.0 5 votes vote down vote up
def signal_generation(df,method,n=14):
    
    df['rsi']=0.0
    df['rsi'][n:]=method(df['Close'],n=14)
    
    df['positions']=np.select([df['rsi']<30,df['rsi']>70], \
                              [1,-1],default=0)
    df['signals']=df['positions'].diff()
    
    return df[n:]


# In[5]:

#plotting 
Example #23
Source File: Pair trading backtest.py    From quant-trading with Apache License 2.0 5 votes vote down vote up
def signal_generation(df1,df2,method):
    
    
    signals=method(df1,df2)

    signals['signals1']=0
    
    #as z statistics cannot exceed both upper and lower bounds at the same time
    #this line holds
    signals['signals1']=np.select([signals['z']>signals['z upper limit'], \
                                   signals['z']<signals['z lower limit']], \
                                   [-1,1],default=0)
    
    #signals only imply holding
    #we take the first order difference to obtain the execution signal
    signals['positions1']=signals['signals1'].diff()
    signals['signals2']=-signals['signals1']
    signals['positions2']=signals['signals2'].diff()
    
    #fix initial positions issue
    if signals['signals1'].iloc[0]!=0:
        signals['positions1'].iloc[0]=signals['signals1'].iloc[0]
        signals['positions2'].iloc[0]=signals['signals2'].iloc[0]        
    
    return signals


# In[3]:


#position visualization 
Example #24
Source File: runtime.py    From dm_control with Apache License 2.0 5 votes vote down vote up
def _get_default_action(action_spec):
  """Generates an action to apply to the environment if there is no agent.

  * For action dimensions that are closed intervals this will be the midpoint.
  * For left-open or right-open intervals this will be the maximum or the
    minimum respectively.
  * For unbounded intervals this will be zero.

  Args:
    action_spec: An instance of `BoundedArraySpec` or a list or tuple
      containing these.

  Returns:
    A numpy array of actions if `action_spec` is a single `BoundedArraySpec`, or
    a tuple of such arrays if `action_spec` is a list or tuple.
  """
  if isinstance(action_spec, (list, tuple)):
    return tuple(_get_default_action(spec) for spec in action_spec)
  elif isinstance(action_spec, collections.MutableMapping):
    # Clones the Mapping, preserving type and key order.
    result = copy.copy(action_spec)

    for key, value in six.iteritems(action_spec):
      result[key] = _get_default_action(value)

    return result

  minimum = np.broadcast_to(action_spec.minimum, action_spec.shape)
  maximum = np.broadcast_to(action_spec.maximum, action_spec.shape)
  left_bounded = np.isfinite(minimum)
  right_bounded = np.isfinite(maximum)
  action = np.select(
      condlist=[left_bounded & right_bounded, left_bounded, right_bounded],
      choicelist=[0.5 * (minimum + maximum), minimum, maximum],
      default=0.)
  action = action.astype(action_spec.dtype, copy=False)
  action.flags.writeable = False
  return action 
Example #25
Source File: functional_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def evaluate(x, y, amplitude, x_0, y_0, R_0):
        """Two dimensional Disk model function"""

        rr = (x - x_0) ** 2 + (y - y_0) ** 2
        result = np.select([rr <= R_0 ** 2], [amplitude])

        if isinstance(amplitude, Quantity):
            return Quantity(result, unit=amplitude.unit, copy=False)
        else:
            return result 
Example #26
Source File: functional_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def evaluate(x, y, amplitude, x_0, y_0, r_in, width):
        """Two dimensional Ring model function."""

        rr = (x - x_0) ** 2 + (y - y_0) ** 2
        r_range = np.logical_and(rr >= r_in ** 2, rr <= (r_in + width) ** 2)
        result = np.select([r_range], [amplitude])

        if isinstance(amplitude, Quantity):
            return Quantity(result, unit=amplitude.unit, copy=False)
        else:
            return result 
Example #27
Source File: functional_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def evaluate(x, amplitude, x_0, width):
        """One dimensional Box model function"""

        inside = np.logical_and(x >= x_0 - width / 2., x <= x_0 + width / 2.)
        return np.select([inside], [amplitude], 0) 
Example #28
Source File: functional_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def evaluate(x, y, amplitude, x_0, y_0, x_width, y_width):
        """Two dimensional Box model function"""

        x_range = np.logical_and(x >= x_0 - x_width / 2.,
                                 x <= x_0 + x_width / 2.)
        y_range = np.logical_and(y >= y_0 - y_width / 2.,
                                 y <= y_0 + y_width / 2.)

        result = np.select([np.logical_and(x_range, y_range)], [amplitude], 0)

        if isinstance(amplitude, Quantity):
            return Quantity(result, unit=amplitude.unit, copy=False)
        else:
            return result 
Example #29
Source File: functional_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def evaluate(x, y, amplitude, x_0, y_0, R_0, slope):
        """Two dimensional Trapezoid Disk model function"""

        r = np.sqrt((x - x_0) ** 2 + (y - y_0) ** 2)
        range_1 = r <= R_0
        range_2 = np.logical_and(r > R_0, r <= R_0 + amplitude / slope)
        val_1 = amplitude
        val_2 = amplitude + slope * (R_0 - r)
        result = np.select([range_1, range_2], [val_1, val_2])

        if isinstance(amplitude, Quantity):
            return Quantity(result, unit=amplitude.unit, copy=False)
        else:
            return result 
Example #30
Source File: test_quantity_non_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_select(self):
        q = self.q
        out = np.select([q < 0.55 * u.m, q > 1. * u.m],
                        [q, q.to(u.cm)], default=-1. * u.km)
        expected = np.select([q.value < 0.55, q.value > 1],
                             [q.value, q.value], default=-1000) * u.m
        assert np.all(out == expected)