Python numpy.choose() Examples

The following are 30 code examples of numpy.choose(). 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: math_util.py    From ronin with GNU General Public License v3.0 6 votes vote down vote up
def adjust_angle_array(angles):
    """
    Resolve ambiguities within a array of angles. It assumes neighboring angles should be close.
    Args:
        angles: an array of angles.

    Return:
        Adjusted angle array.
    """
    new_angle = np.copy(angles)
    angle_diff = angles[1:] - angles[:-1]

    diff_cand = angle_diff[:, None] - np.array([-math.pi * 4, -math.pi * 2, 0, math.pi * 2, math.pi * 4])
    min_id = np.argmin(np.abs(diff_cand), axis=1)

    diffs = np.choose(min_id, diff_cand.T)
    new_angle[1:] = np.cumsum(diffs) + new_angle[0]
    return new_angle 
Example #2
Source File: ClimatologySpark2.py    From incubator-sdap-nexus with Apache License 2.0 6 votes vote down vote up
def combine(a, b):
    '''Combine accumulators by summing.'''
    print >> sys.stderr, 'Combining accumulators . . .'
    if 'urls' in a['_meta'] and 'urls' in b['_meta']:
        a['_meta']['urls'].extend(b['_meta']['urls'])
    if 'mean' in a:
        ntotal = a['count'] + b['count']
        #        mask = N.not_equal(ntotal, 0)
        #        a['mean'] = N.choose(mask, (0, (a['mean'] * a['count'] + b['mean'] * b['count']) / ntotal))
        a['mean'] = (a['mean'] * a['count'] + b['mean'] * b['count']) / ntotal
    if 'min' in a:
        if N.ma.isMaskedArray(a):
            a['min'] = N.ma.minimum(a['min'], b['min'])
        else:
            a['min'] = N.minimum(a['min'], b['min'])
    if 'max' in a:
        if N.ma.isMaskedArray(a):
            a['max'] = N.ma.maximum(a['max'], b['max'])
        else:
            a['max'] = N.maximum(a['max'], b['max'])
    for k in a.keys():
        if k[0] == '_': continue
        if k != 'mean' and k != 'min' and k != 'max':
            a[k] += b[k]  # just sum count and other moments
    return a 
Example #3
Source File: misc.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def zero_if_close(a, tol=1.e-15):
    """set real and/or imaginary part to 0 if their absolute value is smaller than `tol`.

    Parameters
    ----------
    a : ndarray
        numpy array to be rounded
    tol : float
        the threashold which values to consider as '0'.
    """
    if a.dtype == np.complex128 or a.dtype == np.complex64:
        ar = np.choose(np.abs(a.real) < tol, [a.real, np.zeros(a.shape)])
        ai = np.choose(np.abs(a.imag) < tol, [a.imag, np.zeros(a.shape)])
        return ar + 1j * ai
    else:
        return np.choose(np.abs(a) < tol, [a, np.zeros_like(a)]) 
Example #4
Source File: select_item.py    From chainer with MIT License 6 votes vote down vote up
def forward(self, inputs):
        self.retain_inputs((1,))
        x, t = inputs
        self._in_shape = x.shape
        self._in_dtype = x.dtype
        if chainer.is_debug():
            if not ((0 <= t).all() and
                    (t < x.shape[1]).all()):
                msg = 'Each label `t` need to satisfty `0 <= t < x.shape[1]`'
                raise ValueError(msg)

        xp = backend.get_array_module(x)
        if xp is numpy:
            # This code is equivalent to `t.choose(x.T)`, but `numpy.choose`
            # does not work when `x.shape[1] > 32`.
            return x[six.moves.range(t.size), t],
        else:
            y = cuda.elementwise(
                'S t, raw T x',
                'T y',
                'int ind[] = {i, t}; y = x[ind];',
                'getitem_fwd'
            )(t, x)
            return y, 
Example #5
Source File: gdal_merge.py    From CoastSat with GNU General Public License v3.0 6 votes vote down vote up
def raster_copy_with_mask( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n,
                           t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n,
                           m_band ):
    try:
        import numpy as Numeric
    except ImportError:
        import Numeric

    s_band = s_fh.GetRasterBand( s_band_n )
    t_band = t_fh.GetRasterBand( t_band_n )

    data_src = s_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
                                   t_xsize, t_ysize )
    data_mask = m_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
                                    t_xsize, t_ysize )
    data_dst = t_band.ReadAsArray( t_xoff, t_yoff, t_xsize, t_ysize )

    mask_test = Numeric.equal(data_mask, 0)
    to_write = Numeric.choose( mask_test, (data_src, data_dst) )

    t_band.WriteArray( to_write, t_xoff, t_yoff )

    return 0

# ============================================================================= 
Example #6
Source File: gdal_merge.py    From CoastSat with GNU General Public License v3.0 6 votes vote down vote up
def raster_copy_with_nodata( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n,
                             t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n,
                             nodata ):
    try:
        import numpy as Numeric
    except ImportError:
        import Numeric

    s_band = s_fh.GetRasterBand( s_band_n )
    t_band = t_fh.GetRasterBand( t_band_n )

    data_src = s_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
                                   t_xsize, t_ysize )
    data_dst = t_band.ReadAsArray( t_xoff, t_yoff, t_xsize, t_ysize )

    nodata_test = Numeric.equal(data_src,nodata)
    to_write = Numeric.choose( nodata_test, (data_src, data_dst) )

    t_band.WriteArray( to_write, t_xoff, t_yoff )

    return 0

# ============================================================================= 
Example #7
Source File: convert2onnx.py    From centerpose with MIT License 6 votes vote down vote up
def gather_numpy(inputs, dim, index):
    """
    Gathers values along an axis specified by dim.
    For a 3-D tensor the output is specified by:
        out[i][j][k] = input[index[i][j][k]][j][k]  # if dim == 0
        out[i][j][k] = input[i][index[i][j][k]][k]  # if dim == 1
        out[i][j][k] = input[i][j][index[i][j][k]]  # if dim == 2

    :param dim: The axis along which to index
    :param index: A tensor of indices of elements to gather
    :return: tensor of gathered values
    """
    idx_xsection_shape = index.shape[:dim] + index.shape[dim + 1:]
    self_xsection_shape = inputs.shape[:dim] + inputs.shape[dim + 1:]
    if idx_xsection_shape != self_xsection_shape:
        raise ValueError("Except for dimension " + str(dim) +
                         ", all dimensions of index and self should be the same size")
    if index.dtype != np.dtype('int_'):
        raise TypeError("The values of index must be integers")
    data_swaped = np.swapaxes(inputs, 0, dim)
    index_swaped = np.swapaxes(index, 0, dim)
    gathered = np.choose(index_swaped, data_swaped)
    return np.swapaxes(gathered, 0, dim) 
Example #8
Source File: vector_quantization.py    From Python-Machine-Learning-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
def compress_image(img, num_clusters):
    # Convert input image into (num_samples, num_features) 
    # array to run kmeans clustering algorithm 
    X = img.reshape((-1, 1))  

    # Run kmeans on input data
    kmeans = cluster.KMeans(n_clusters=num_clusters, n_init=4, random_state=5)
    kmeans.fit(X)
    centroids = kmeans.cluster_centers_.squeeze()
    labels = kmeans.labels_

    # Assign each value to the nearest centroid and 
    # reshape it to the original image shape
    input_image_compressed = np.choose(labels, centroids).reshape(img.shape)

    return input_image_compressed 
Example #9
Source File: test_multiarray.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_broadcast1(self):
        A = np.choose(self.ind, (self.x2, self.y2))
        assert_equal(A, [[2, 2, 3], [2, 2, 3]]) 
Example #10
Source File: test_numeric.py    From pySINDy with MIT License 5 votes vote down vote up
def clip(self, a, m, M, out=None):
        # use slow-clip
        selector = np.less(a, m) + 2*np.greater(a, M)
        return selector.choose((a, m, M), out=out)

    # Handy functions 
Example #11
Source File: treeanc.py    From treetime with MIT License 5 votes vote down vote up
def preorder_traversal_marginal(self, reconstruct_tip_states=False, sample_from_profile=False, assign_sequence=False):
        self.logger("Preorder: computing marginal profiles...",3)
        # propagate root -->> leaves, reconstruct the internal node sequences
        # provided the upstream message + the message from the complementary subtree
        N_diff = 0
        for node in self.tree.find_clades(order='preorder'):
            if node.up is None: # skip if node is root
                continue
            if hasattr(node, 'branch_state'): del node.branch_state

            # integrate the information coming from parents with the information
            # of all children my multiplying it to the prev computed profile
            node.marginal_outgroup_LH, pre = normalize_profile(np.log(np.maximum(ttconf.TINY_NUMBER, node.up.marginal_profile)) - node.marginal_log_Lx,
                                                               log=True, return_offset=False)
            if node.is_terminal() and (not reconstruct_tip_states): # skip remainder unless leaves are to be reconstructed
                continue

            tmp_msg_from_parent = self.gtr.evolve(node.marginal_outgroup_LH,
                                                 self._branch_length_to_gtr(node), return_log=False)
            node.marginal_profile, pre = normalize_profile(node.marginal_subtree_LH * tmp_msg_from_parent, return_offset=False)
            # choose sequence based maximal marginal LH.
            if assign_sequence:
                seq, prof_vals, idxs = prof2seq(node.marginal_profile, self.gtr,
                                                sample_from_prof=sample_from_profile, normalize=False)

                if self.sequence_reconstruction:
                    N_diff += (seq!=node.cseq).sum()
                else:
                    N_diff += self.data.compressed_length
                #assign new sequence
                node._cseq = seq

        return N_diff 
Example #12
Source File: mask_generator.py    From Neural-Photo-Editor with MIT License 5 votes vote down vote up
def _get_hidden_layer_connectivity(self, layerIdx):
        layer_size = self._hidden_sizes[layerIdx]
        if layerIdx == 0:
            p_vals = self._get_p(T.min(self.layers_connectivity[layerIdx]))
        else:
            p_vals = self._get_p(T.min(self.layers_connectivity_updates[layerIdx-1]))

        # #Implementations of np.choose in theano GPU
        # return T.nonzero(self._mrng.multinomial(pvals=[self._p_vals] * layer_size, dtype=theano.config.floatX))[1].astype(dtype=theano.config.floatX)
        # return T.argmax(self._mrng.multinomial(pvals=[self._p_vals] * layer_size, dtype=theano.config.floatX), axis=1)
        return T.sum(T.cumsum(self._mrng.multinomial(pvals=T.tile(p_vals[::-1][None, :], (layer_size, 1)), dtype=theano.config.floatX), axis=1), axis=1) 
Example #13
Source File: test_numeric.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def test_choose(self):
        choices = [[0, 1, 2],
                   [3, 4, 5],
                   [5, 6, 7]]
        tgt = [5, 1, 5]
        a = [2, 0, 1]

        out = np.choose(a, choices)
        assert_equal(out, tgt) 
Example #14
Source File: test_numeric.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def clip(self, a, m, M, out=None):
        # use slow-clip
        selector = np.less(a, m) + 2*np.greater(a, M)
        return selector.choose((a, m, M), out=out)

    # Handy functions 
Example #15
Source File: test_umath.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def test_mixed(self):
        c = np.array([True, True])
        a = np.array([True, True])
        assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) 
Example #16
Source File: test_multiarray.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_broadcast2(self):
        A = np.choose(self.ind, (self.x, self.y2))
        assert_equal(A, [[2, 2, 3], [2, 2, 3]])


# TODO: test for multidimensional 
Example #17
Source File: test_multiarray.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_all(self):
        a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
        for i in range(a.ndim):
            amax = a.max(i)
            aargmax = a.argmax(i)
            axes = list(range(a.ndim))
            axes.remove(i)
            assert_(all(amax == aargmax.choose(*a.transpose(i,*axes)))) 
Example #18
Source File: owchoropleth.py    From orange3-geo with GNU General Public License v3.0 5 votes vote down vote up
def get_colors_sel(self):
        white_pen = self._make_pen(QColor(Qt.white), 1)
        if self.selection is None:
            pen = [white_pen] * self.n_ids
        else:
            sels = np.max(self.selection)
            if sels == 1:
                orange_pen = self._make_pen(QColor(255, 190, 0, 255), 3)
                pen = np.where(self.selection, orange_pen, white_pen)
            else:
                palette = LimitedDiscretePalette(number_of_colors=sels + 1)
                pens = [white_pen] + [self._make_pen(palette[i], 3)
                                      for i in range(sels)]
                pen = np.choose(self.selection, pens)
        return pen 
Example #19
Source File: pairwise_samplers.py    From botorch with MIT License 5 votes vote down vote up
def forward(self, posterior: Posterior) -> Tensor:
        r"""Draws MC samples from the posterior and make comparisons

        Args:
            posterior: The Posterior to sample from.
                The returned samples are expected to have output dimension of 1.

        Returns:
            Posterior sample pairwise comparisons.
        """
        samples = super().forward(posterior)
        np.random.seed(self.seed)

        s_n = samples.shape[-2]  # candidate number per batch
        if s_n < 2:
            raise RuntimeError("Number of samples < 2, cannot make comparisons")

        # TODO: Don't instantiate a generator
        all_pairs = np.array(list(combinations(range(s_n), 2)))
        if self.max_num_comparisons is None:
            comp_n = len(all_pairs)
        else:
            comp_n = min(self.max_num_comparisons, len(all_pairs))

        comp_pairs = all_pairs[
            np.random.choice(range(len(all_pairs)), comp_n, replace=False)
        ]
        s_comps_size = torch.Size((*samples.shape[:-2], comp_n, 2))
        s_v = samples.view(-1, s_n)

        idx1, idx2 = comp_pairs[:, 0], comp_pairs[:, 1]
        prefs = (s_v[:, idx1] > s_v[:, idx2]).long()
        cpt = comp_pairs.T
        c1 = np.choose(prefs, cpt)
        c2 = np.choose(1 - prefs, cpt)
        s_comps = torch.stack([c1, c2], dim=-1).reshape(s_comps_size)

        return s_comps 
Example #20
Source File: test_numeric.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def clip(self, a, m, M, out=None):
        # use slow-clip
        selector = np.less(a, m) + 2*np.greater(a, M)
        return selector.choose((a, m, M), out=out)

    # Handy functions 
Example #21
Source File: test_numeric.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def test_choose(self):
        choices = [[0, 1, 2],
                   [3, 4, 5],
                   [5, 6, 7]]
        tgt = [5, 1, 5]
        a = [2, 0, 1]

        out = np.choose(a, choices)
        assert_equal(out, tgt) 
Example #22
Source File: test_umath.py    From pySINDy with MIT License 5 votes vote down vote up
def test_mixed(self):
        c = np.array([True, True])
        a = np.array([True, True])
        assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) 
Example #23
Source File: timescan.py    From OpenSarToolkit with MIT License 5 votes vote down vote up
def _zvalue_from_index(arr, ind):
    """private helper function to work around the limitation of np.choose() by employing np.take()
    arr has to be a 3D array
    ind has to be a 2D array containing values for z-indicies to take from arr
    See: http://stackoverflow.com/a/32091712/4169585
    This is faster and more memory efficient than using the ogrid based solution with fancy indexing.
    """
    # get number of columns and rows
    _, nC, nR = arr.shape

    # get linear indices and extract elements with np.take()
    idx = nC * nR * ind + np.arange(nC*nR).reshape((nC,nR))
    return np.take(arr, idx) 
Example #24
Source File: test_numeric.py    From pySINDy with MIT License 5 votes vote down vote up
def test_choose(self):
        choices = [[0, 1, 2],
                   [3, 4, 5],
                   [5, 6, 7]]
        tgt = [5, 1, 5]
        a = [2, 0, 1]

        out = np.choose(a, choices)
        assert_equal(out, tgt) 
Example #25
Source File: gc2d.py    From topoflow with MIT License 5 votes vote down vote up
def ice_sliding( taubX , taubY , xcmpnt , ycmpnt ,
                 THERMAL_TOGGLE=False,
                 FREEZEON_TOGGLE=False,
                 UsChar=Parameters.UsChar,
                 taubChar=Parameters.taubChar ):

    #------------------------------
    # CALCULATE SLIDING VELOCITY
    #------------------------------        
    # Here's the guts of calculating the sliding velocity 
    UsxX = np.choose( np.abs(taubX)<1e-5 , ( UsChar * np.exp(1 - taubChar / taubX) * xcmpnt ,
                                                   UsChar * np.exp(1 - taubChar        ) * xcmpnt ) )
    UsyY = np.choose( np.abs(taubY)<1e-5 , ( UsChar * np.exp(1 - taubChar / taubY) * ycmpnt , 
                                                   UsChar * np.exp(1 - taubChar        ) * ycmpnt ) )

    if (THERMAL_TOGGLE and FREEZEON_TOGGLE):
        
        ##################################################################
        # NOTE!  Many of the vars needed by this segment are undefined,
        #        such as:  Tb_ext, Zb_ext, seaLevel.  (SDP, 9/21/09)
        ################################################################## 
        ## notFrozen  = (Tb_ext > -.5) or (Zb_ext < seaLevel)
        notFrozen  = np.logical_or( Tb_ext > -0.5, Zb_ext < seaLevel )
        notFrozenX = ( notFrozen[1:-1, :-1] + notFrozen[1:-1,1:  ] ) / 2.
        notFrozenY = ( notFrozen[ :-1,1:-1] + notFrozen[1:  ,1:-1] ) / 2.

        UsxX *= notFrozenX
        UsyY *= notFrozenY

    return ( UsxX , UsyY )

#   ice_sliding()
#-------------------------------------------------------------------------------------------------- 
Example #26
Source File: casting.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def int_abs(arr):
    """ Absolute values of array taking care of max negative int values

    Parameters
    ----------
    arr : array-like

    Returns
    -------
    abs_arr : array
        array the same shape as `arr` in which all negative numbers have been
        changed to positive numbers with the magnitude.

    Examples
    --------
    This kind of thing is confusing in base numpy:

    >>> import numpy as np
    >>> np.abs(np.int8(-128))
    -128

    ``int_abs`` fixes that:

    >>> int_abs(np.int8(-128))
    128
    >>> int_abs(np.array([-128, 127], dtype=np.int8))
    array([128, 127], dtype=uint8)
    >>> int_abs(np.array([-128, 127], dtype=np.float32))
    array([ 128.,  127.], dtype=float32)
    """
    arr = np.array(arr, copy=False)
    dt = arr.dtype
    if dt.kind == 'u':
        return arr
    if dt.kind != 'i':
        return np.absolute(arr)
    out = arr.astype(np.dtype(dt.str.replace('i', 'u')))
    return np.choose(arr < 0, (arr, arr * -1), out=out) 
Example #27
Source File: test_umath.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_mixed(self):
        c = np.array([True, True])
        a = np.array([True, True])
        assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) 
Example #28
Source File: test_numeric.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def clip(self, a, m, M, out=None):
        # use slow-clip
        selector = np.less(a, m) + 2*np.greater(a, M)
        return selector.choose((a, m, M), out=out)

    # Handy functions 
Example #29
Source File: test_numeric.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_choose(self):
        choices = [[0, 1, 2],
                   [3, 4, 5],
                   [5, 6, 7]]
        tgt = [5, 1, 5]
        a = [2, 0, 1]

        out = np.choose(a, choices)
        assert_equal(out, tgt) 
Example #30
Source File: test_umath.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_mixed(self):
        c = np.array([True, True])
        a = np.array([True, True])
        assert_equal(np.choose(c, (a, 1)), np.array([1, 1]))