numpy.nonzero

Here are the examples of the python api numpy.nonzero taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

162 Examples 7

Example 1

Project: tvb-library Source File: region_boundaries.py
def find_boundary_triangles(cortex):
    """ 
    Identify triangles that cross a parcellation boundary 
    """
    tb01 = numpy.nonzero(cortex.region_mapping[cortex.triangles][:, 0] - 
                         cortex.region_mapping[cortex.triangles][:, 1])

    tb12 = numpy.nonzero(cortex.region_mapping[cortex.triangles][:, 1] - 
                         cortex.region_mapping[cortex.triangles][:, 2])

    tb20 = numpy.nonzero(cortex.region_mapping[cortex.triangles][:, 2] - 
                         cortex.region_mapping[cortex.triangles][:, 0])

    return numpy.unique(numpy.hstack((tb01, tb12, tb20)))

Example 2

Project: HPGL-GUI Source File: statistics_window.py
    def makeCuts(self):
        self.localMin = float(self.xMin.text())
        self.localMax = float(self.xMax.text())

        self.cutValues = self.clearValues[numpy.nonzero(self.clearValues >= self.localMin)]
        self.cutValues = self.cutValues[numpy.nonzero(self.cutValues <= self.localMax)]
        self.cutClearValues = self.cutValues[numpy.nonzero(self.cutValues != self.undefValue)]

        self.max = '%.2f' % numpy.max(self.cutClearValues)
        self.mean = '%.2f' % numpy.mean(self.cutClearValues)
        self.min = '%.2f' % numpy.min(self.cutClearValues)
        self.median = '%.2f' % numpy.median(self.cutClearValues)
        self.variance = '%.2f' % numpy.var(self.cutClearValues)
        self.defPoints = numpy.size(self.cutClearValues)

Example 3

Project: misvm Source File: nsk.py
Function: compute_separator
    def _compute_separator(self, K):

        self._sv = np.nonzero(self._alphas.flat > self.sv_cutoff)
        self._sv_alphas = self._alphas[self._sv]
        self._sv_bags = [self._bags[i] for i in self._sv[0]]
        self._sv_y = self._y[self._sv]

        n = len(self._sv_bags)
        if n == 0:
            self._b = 0.0
            self._bag_predictions = np.zeros(len(self._bags))
        else:
            _sv_all_K = K[self._sv]
            _sv_K = _sv_all_K.T[self._sv].T
            e = np.matrix(np.ones((n, 1)))
            D = spdiag(self._sv_y)
            self._b = float(e.T * D * e - self._sv_alphas.T * D * _sv_K * e) / n
            self._bag_predictions = np.array(self._b
                                             + self._sv_alphas.T * D * _sv_all_K).reshape((-1,))

Example 4

Project: APGL Source File: CsArrayGraph.py
Function: getalldiredges
    def getAllDirEdges(self):
        """
        Returns the set of directed edges of the current graph as a matrix in which each
        row corresponds to an edge. For an undirected graph, there is an edge from
        v1 to v2 and from v2 to v1 if v2!=v1.

        :returns: A matrix with 2 columns, and each row corresponding to an edge.
        """
        (rows, cols) = numpy.nonzero(self.W)
        edges = numpy.c_[rows, cols]

        return edges

Example 5

Project: ilastik-0.5 Source File: synapseDetectionFilter.py
    def objectsSlow3d(self, cc):
        #returns a dictionary, where the key is the point "intensity" (i.e. connected component number)
        #and the value is a list of point coordinates [[x], [y], [z]]
        objs = {}

        nzindex = numpy.nonzero(cc)
        for i in range(len(nzindex[0])):
            value = cc[nzindex[0][i], nzindex[1][i], nzindex[2][i]]
            if value > 0:
                if value not in objs:
                    objs[value] = [[], [], []]
                objs[value][0].append(nzindex[0][i])
                objs[value][1].append(nzindex[1][i])
                objs[value][2].append(nzindex[2][i])
                
        return objs

Example 6

Project: blockcanvas Source File: selection_reduction_context.py
Function: set_context_undefined
    def set_context_undefined ( self, name, value ):
        """ Sets the value of a currently undefined item.
        """
        mask = self.context.context_selection
        if mask is None:
            super( SelectionReductionContext, self ).set_context_undefined(
                                                                   name, value )
        else:
            data = self.context.get_context_undefined( name, value )
            if data is not Undefined:
                put( data, nonzero( mask ), value )
                self.context.set_context_undefined( name, data )

Example 7

Project: tracer Source File: flat_surface.py
Function: select_rays
    def select_rays(self, idxs):
        """
        Inform the geometry manager that only the given rays are to be used,
        so that internal data size is kept small.
        
        Arguments: 
        idxs - an index array stating which rays of the working bundle
            are active.
        """
        self._idxs = idxs # For slicing ray bundles etc.
        self._backside = N.nonzero(self._backside[idxs])[0]
        
        v = self._working_bundle.get_vertices()[:,idxs]
        d = self._working_bundle.get_directions()[:,idxs]
        p = self._params[idxs]
        del self._params
        
        # Global coordinates on the surface:
        self._global = v + p[None,:]*d

Example 8

Project: robothon Source File: arrayfns.py
def zmin_zmax(z, ireg):
    z = asarray(z, dtype=float)
    ireg = asarray(ireg, dtype=int)
    if z.shape != ireg.shape or z.ndim != 2:
        raise ValueError, "z and ireg must be the same shape and 2-d"
    ix, iy = nx.nonzero(ireg)
    # Now, add more indices
    x1m = ix - 1
    y1m = iy-1
    i1 = x1m>=0
    i2 = y1m>=0
    i3 = i1 & i2
    nix = nx.r_[ix, x1m[i1], x1m[i1], ix[i2] ]
    niy = nx.r_[iy, iy[i1],  y1m[i3], y1m[i2]]
    # remove any negative indices
    zres = z[nix,niy]
    return zres.min().item(), zres.max().item()

Example 9

Project: ilastik-0.5 Source File: classificationMgr.py
    def getTrainingMatrixRefForImage(self, dataItemImage):
        prop = dataItemImage.module["Classification"]
        if len(prop["trainingF"]) == 0 and prop["featureM"] is not None:
            tempF = []
            tempL = []
    
            tempd =  dataItemImage.overlayMgr["Classification/Labels"][:, :, :, :, 0].ravel()
            indices = numpy.nonzero(tempd)[0]
            tempL = dataItemImage.overlayMgr["Classification/Labels"][:,:,:,:,0].ravel()[indices]
            tempL.shape += (1,)
                                   
            prop["trainingIndices"] = indices
            prop["trainingL"] = tempL
            if len(indices) > 0:
                prop["trainingF"] = self.getTrainingMforIndForImage(indices, dataItemImage)
            else:
                self.clearFeaturesAndTrainingForImage(dataItemImage)
        return prop["trainingL"], prop["trainingF"], prop["trainingIndices"]

Example 10

Project: imagen Source File: audio.py
Function: set_matrix_dimensions
    def set_matrix_dimensions(self, bounds, xdensity, ydensity):
        super(ModulatedLogSpectrogram, self).set_matrix_dimensions(bounds, xdensity, ydensity)

        self._modulation_start_index = nonzero(self.frequency_spacing >= self.lower_freq_bound)[0][0]
        self._modulation_end_index = nonzero(self.frequency_spacing >= self.upper_freq_bound)[0][0]

        self._modulation = self.modulation_function(self._modulation_end_index-self._modulation_start_index)
        self._modulation = reshape(self._modulation, [-1,1])

Example 11

Project: qgisSpaceSyntaxToolkit Source File: flow_matrix.py
Function: width
    def width(self,L):
        m=0
        for i,row in enumerate(L):
            w=0
            x,y = np.nonzero(row)
            if len(y) > 0:
                v = y-i
                w=v.max()-v.min()+1
                m = max(w,m)
        return m

Example 12

Project: 3D-R2N2 Source File: binvox_rw.py
Function: dense_to_sparse
def dense_to_sparse(voxel_data, dtype=np.int):
    """ From dense representation to sparse (coordinate) representation.
    No coordinate reordering.
    """
    if voxel_data.ndim != 3:
        raise ValueError('voxel_data is wrong shape; should be 3D array.')
    return np.asarray(np.nonzero(voxel_data), dtype)

Example 13

Project: blockcanvas Source File: reduction_context.py
Function: set_context_undefined
    def set_context_undefined ( self, name, value ):
        """ Sets the value of a currently undefined item.
        """
        mask = self._mask
        if mask is None:
            super( ReductionContext, self ).set_context_undefined( name, value )
        else:
            data = self.context.get_context_undefined( name, value )
            if data is not Undefined:
                put( data, nonzero( mask ), value )
                self.context.set_context_undefined( name, data )

Example 14

Project: blockcanvas Source File: selection_reduction_context.py
Function: set_context_data
    def set_context_data ( self, name, value ):
        """ Sets the value of a specified item.
        """
        data = self.context.get_context_data( name )
        mask = self.context.context_selection
        if mask is not None:
            put( data, nonzero( mask ), value )
            self.context.set_context_data( name, data )

Example 15

Project: chaco Source File: subdivision_cells.py
def arg_find_runs(int_array, order='ascending'):
    """
    This function is like find_runs(), but it returns a list of tuples
    indicating the start and end indices of runs in the input *int_array*.
    """
    if len(int_array) == 0:
        return []
    assert len(int_array.shape)==1, "find_runs() requires a 1D integer array."
    if order == 'ascending':
        increment = 1
    elif order == 'descending':
        increment = -1
    else:
        increment = 0
    rshifted = right_shift(int_array, int_array[0]-increment)
    start_indices = concatenate([[0], nonzero(int_array - (rshifted+increment))[0]])
    end_indices = left_shift(start_indices, len(int_array))
    return zip(start_indices, end_indices)

Example 16

Project: AbTextSumm Source File: algorithms.py
Function: jaccard
def jaccard(v1, v2):
    '''
    Due to the idiosyncracies of my code the jaccard index is a bit 
    altered. The theory is the same but the implementation might be a bit 
    weird. I do not have two vectors containing the words of both docuements
    but instead I have two equally sized vectors. The columns of the vectors 
    are the same and represent the words in the whole corpus. If an entry
    is 1 then the word is present in the docuement. If it is 0 then it is not present.
    SO first we find the indices of the words in each docuements and then jaccard is 
    calculated based on the indices.
    '''  

    indices1 = numpy.nonzero(v1)[0].tolist()
    indices2 = numpy.nonzero(v2)[0].tolist()
    inter = len(set(indices1) & set(indices2))
    un = len(set(indices1) | set(indices2))
    dist = 1 - inter/float(un)
    return dist

Example 17

Project: amen Source File: audio.py
    def _create_zero_indexes(self):
        """
        Create zero crossing indexes.
        We use these in synthesis, and it is easier to make them here.
        """
        zero_indexes = []
        for channel_index in range(self.num_channels):
            channel = self.raw_samples[channel_index]
            zero_crossings = librosa.zero_crossings(channel)
            zero_index = np.nonzero(zero_crossings)[0]
            zero_indexes.append(zero_index)
        return zero_indexes

Example 18

Project: chempy Source File: _equilibrium.py
def _solve_equilibrium_coord(c0, stoich, K, activity_product=None):
    from scipy.optimize import brentq
    mask, = np.nonzero(stoich)
    stoich_m = stoich[mask]
    c0_m = c0[mask]
    lower, upper = _get_rc_interval(stoich_m, c0_m)
    # span = upper - lower
    return brentq(
        equilibrium_residual,
        lower,  # + delta_frac*span,
        upper,  # - delta_frac*span,
        (c0_m, stoich_m, K, activity_product)
    )

Example 19

Project: tensorflow-wavenet Source File: audio_reader.py
Function: trim_silence
def trim_silence(audio, threshold):
    '''Removes silence at the beginning and end of a sample.'''
    energy = librosa.feature.rmse(audio)
    frames = np.nonzero(energy > threshold)
    indices = librosa.core.frames_to_samples(frames)[1]

    # Note: indices can be an empty array, if the whole audio was silence.
    return audio[indices[0]:indices[-1]] if indices.size else audio[0:0]

Example 20

Project: scikit-learn Source File: base.py
Function: get_indices
    def get_indices(self, i):
        """Row and column indices of the i'th bicluster.

        Only works if ``rows_`` and ``columns_`` attributes exist.

        Returns
        -------
        row_ind : np.array, dtype=np.intp
            Indices of rows in the dataset that belong to the bicluster.
        col_ind : np.array, dtype=np.intp
            Indices of columns in the dataset that belong to the bicluster.

        """
        rows = self.rows_[i]
        columns = self.columns_[i]
        return np.nonzero(rows)[0], np.nonzero(columns)[0]

Example 21

Project: hedge Source File: __init__.py
    def map_if(self, expr):
        bool_crit = self.rec(expr.condition)
        then = self.rec(expr.then)
        else_ = self.rec(expr.else_)

        true_indices = np.nonzero(bool_crit)
        false_indices = np.nonzero(~bool_crit)

        result = self.discr.volume_empty(
                kind=self.discr.compute_kind)

        if isinstance(then, np.ndarray):
            then = then[true_indices]
        if isinstance(else_, np.ndarray):
            else_ = else_[false_indices]

        result[true_indices] = then
        result[false_indices] = else_
        return result

Example 22

Project: APGL Source File: DenseGraph.py
    def neighbourOf(self, vertexIndex):
        """
        Return an array of the indices of vertices than have an edge going to the input
        vertex.

        :param vertexIndex: the index of a vertex.
        :type vertexIndex: :class:`int`
        """
        Parameter.checkIndex(vertexIndex, 0, self.vList.getNumVertices())
        nonZeroIndices =  numpy.nonzero(self.W[:, vertexIndex])
        neighbourIndices = nonZeroIndices[0]

        return neighbourIndices

Example 23

Project: APGL Source File: SparseGraph.py
Function: getalldiredges
    def getAllDirEdges(self):
        """
        Returns the set of directed edges of the current graph as a matrix in which each
        row corresponds to an edge. For an undirected graph, there is an edge from
        v1 to v2 and from v2 to v1 if v2!=v1. 

        :returns: A matrix with 2 columns, and each row corresponding to an edge.
        """
        (rows, cols) = numpy.nonzero(self.W)
        edges = numpy.c_[rows, cols]

        return edges

Example 24

Project: GPy Source File: visualize.py
    def modify_edges(self):
        self.line_handle = []
        if not self.connect==None:
            self.I, self.J = np.nonzero(self.connect)
            for rod, i, j in zip(self.rods, self.I, self.J):
                rod.pos, rod.axis = self.pos_axis(i, j)

Example 25

Project: polar2grid Source File: mirs2swath.py
    def filter_by_frequency(self, item, arr, freq):
        freq_var = self[FREQ_VAR]
        freq_idx = numpy.nonzero(freq_var[:] == freq)[0]
        if freq_idx:
            freq_idx = freq_idx[0]
        else:
            LOG.error("Frequency %f for variable %s does not exist" % (freq, item))
            raise ValueError("Frequency %f for variable %s does not exist" % (freq, item))

        freq_dim_idx = self[item].dimensions.index(freq_var.dimensions[0])
        idx_obj = [slice(x) for x in arr.shape]
        idx_obj[freq_dim_idx] = freq_idx
        return arr[idx_obj]

Example 26

Project: qgisSpaceSyntaxToolkit Source File: test_branchings.py
def G2():
    # Now we shift all the weights by -10.
    # Should not affect optimal arborescence, but does affect optimal branching.
    G = nx.DiGraph()
    Garr = G_array.copy()
    Garr[np.nonzero(Garr)] -= 10
    G = nx.from_numpy_matrix(Garr, create_using=G)
    G = nx.MultiDiGraph(G)
    return G

Example 27

Project: deepchem Source File: datasets.py
def sparsify_features(X):
  """Extracts a sparse feature representation from dense feature array."""
  n_samples = len(X)
  X_sparse = []
  for i in range(n_samples):
    nonzero_inds = np.nonzero(X[i])[0]
    nonzero_vals = X[i][nonzero_inds]
    X_sparse.append((nonzero_inds, nonzero_vals))
  X_sparse = np.array(X_sparse, dtype=object)
  return X_sparse

Example 28

Project: blockcanvas Source File: reduction_context.py
Function: set_context_data
    def set_context_data ( self, name, value ):
        """ Sets the value of a specified item.
        """
        mask = self._mask
        if mask is not None:
            data = self.context.get_context_data( name )
            put( data, nonzero( mask ), value )
            self.context.set_context_data( name, data )
        else:
            self.context.set_context_data( name, value )

Example 29

Project: pebl Source File: base.py
    def _all_changes(self):
        net = self.evaluator.network
        changes = []

        # edge removals
        changes.extend((None, edge) for edge in net.edges)

        # edge reversals
        reverse = lambda edge: (edge[1], edge[0])
        changes.extend((reverse(edge), edge) for edge in net.edges)

        # edge additions
        nz = N.nonzero(invert(net.edges.adjacency_matrix))
        changes.extend( ((src,dest), None) for src,dest in zip(*nz) )

        return changes

Example 30

Project: sherpa Source File: optfcts.py
Function: set_limits
def _set_limits(x, xmin, xmax):
    below = numpy.nonzero(x < xmin)
    if below.size > 0:
        return 1

    above = numpy.nonzero(x > xmax)
    if above.size > 0:
        return 1

    return 0

Example 31

Project: chaco Source File: base.py
Function: arg_find_runs
def arg_find_runs(int_array, order='ascending'):
    """
    Like find_runs(), but returns a list of tuples indicating the start and
    end indices of runs in the input *int_array*.
    """
    n_points = len(int_array)
    if n_points == 0:
        return []
    indices = nonzero(diff(int_array) - delta.get(order, 0))[0] + 1
    result = empty(shape=(len(indices) + 1, 2), dtype=indices.dtype)
    result[0, 0] = 0
    result[-1, 1] = n_points
    result[1:, 0] = indices
    result[:-1, 1] = indices
    return result

Example 32

Project: tvb-library Source File: region_boundaries.py
def find_region_neighbours(region_adjacency):
    """
    """
    #NOTE: 'should only be doing 1 hemisphere here and then flipping, for symmetry.
    number_of_regions = region_adjacency.shape[0]
    xxx = numpy.nonzero(region_adjacency + region_adjacency.T)
    neighbours = {}
    for key in xrange(number_of_regions):
        #Assign 
        neighbours[key] = list(xxx[1][xxx[0]==key])
#        # Extend neighbours to include "colourbar neighbours"
#        neighbours[key].append(numpy.mod(key+1, number_of_regions))
#        neighbours[key].append(numpy.mod(key-1, number_of_regions))
    return neighbours

Example 33

Project: CostSensitiveClassification Source File: bagging.py
def _create_stacking_set(estimators, estimators_features, estimators_weight, X, combination):
    """Private function used to create the stacking training set."""
    n_samples = X.shape[0]

    valid_estimators = np.nonzero(estimators_weight)[0]
    n_valid_estimators = valid_estimators.shape[0]
    X_stacking = np.zeros((n_samples, n_valid_estimators))

    for e in range(n_valid_estimators):
        if combination in ['stacking', 'stacking_bmr']:
            X_stacking[:, e] = estimators[valid_estimators[e]].predict(X[:, estimators_features[valid_estimators[e]]])
        elif combination in ['stacking_proba', 'stacking_proba_bmr']:
            X_stacking[:, e] = estimators[valid_estimators[e]].predict_proba(X[:, estimators_features[valid_estimators[e]]])[:, 1]

    return X_stacking

Example 34

Project: scikit-image Source File: watershed.py
def _compute_neighbors(image, structure, offset):
    """Compute neighborhood as an array of linear offsets into the image.

    These are sorted according to Euclidean distance from the center (given
    by `offset`), ensuring that immediate neighbors are visited first.
    """
    structure[tuple(offset)] = 0  # ignore the center; it's not a neighbor
    locations = np.transpose(np.nonzero(structure))
    sqdistances = np.sum((locations - offset)**2, axis=1)
    neighborhood = (np.ravel_multi_index(locations.T, image.shape) -
                    np.ravel_multi_index(offset, image.shape)).astype(np.int32)
    sorted_neighborhood = neighborhood[np.argsort(sqdistances)]
    return sorted_neighborhood

Example 35

Project: misvm Source File: svm.py
Function: compute_separator
    def _compute_separator(self, K):

        self._sv = np.nonzero(self._alphas.flat > self.sv_cutoff)
        self._sv_alphas = self._alphas[self._sv]
        self._sv_X = self._X[self._sv]
        self._sv_y = self._y[self._sv]

        n = len(self._sv_X)
        if n == 0:
            self._b = 0.0
            self._predictions = np.zeros(len(self._X))
        else:
            _sv_all_K = K[self._sv]
            _sv_K = _sv_all_K.T[self._sv].T
            e = np.matrix(np.ones((n, 1)))
            D = spdiag(self._sv_y)
            self._b = float(e.T * D * e - self._sv_alphas.T * D * _sv_K * e) / n
            self._predictions = np.array(self._b
                                         + self._sv_alphas.T * D * _sv_all_K).reshape((-1,))

Example 36

Project: tracer Source File: flat_surface.py
Function: select_rays
    def select_rays(self, idxs):
        """
        Inform the geometry manager that only the given rays are to be used,
        so that internal data size is kept small.
        
        Arguments: 
        idxs - an index array stating which rays of the working bundle
            are active.
        """
        self._idxs = idxs
        self._backside = N.nonzero(self._backside[idxs])[0]
        self._global = self._global[:,idxs].copy()

Example 37

Project: robothon Source File: test_old_ma.py
Function: test_testmaput
    def test_testMaPut(self):
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
        i = numpy.nonzero(m)[0]
        put(ym, i, zm)
        assert all(take(ym, i, axis=0) == zm)

Example 38

Project: HPGL-GUI Source File: cube_list.py
    def definedValues(self, index=0):
        '''Returns values of cube without undefined'''
        allValues = self.allValues(index)
        undefined = self.undefValue(index)

        # nonzero return indexes of defined values, but we need values
        return allValues[numpy.nonzero(allValues != undefined)]

Example 39

Project: robothon Source File: functions.py
Function: non_zero
def nonzero(a):
    res = np.nonzero(a)
    if len(res) == 1:
        return res[0]
    else:
        raise ValueError, "Input argument must be 1d"

Example 40

Project: activepapers-python Source File: storage.py
Function: read_line
    def readline(self, size=None):
        self._check_if_open()
        remaining = len(self._ds) - self._position
        if remaining == 0:
            return self._convert('')
        for l in range(min(100, remaining), remaining+100, 100):
            data = self._ds[self._position:self._position+l]
            eols = np.nonzero(data == 10)[0]
            if len(eols) > 0:
                n = eols[0]+1
                self._position += n
                return self._convert(data[:n].tostring())
        self._position = len(self._ds)
        return self._convert(data.tostring())

Example 41

Project: qutip Source File: test_sparse.py
def test_sp_bandwidth():
    "Sparse: Bandwidth"
    for kk in range(10):
        A = sp.rand(100, 100, density=0.1, format='csr')
        ans1 = sp_bandwidth(A)
        A = A.toarray()
        i, j = np.nonzero(A)
        ans2 = ((j-i).max()+(i-j).max()+1, (i-j).max(), (j-i).max())
        assert_equal(ans1, ans2)

    for kk in range(10):
        A = sp.rand(100, 100, density=0.1, format='csc')
        ans1 = sp_bandwidth(A)
        A = A.toarray()
        i, j = np.nonzero(A)
        ans2 = ((j-i).max()+(i-j).max()+1, (i-j).max(), (j-i).max())
        assert_equal(ans1, ans2)

Example 42

Project: binvox-rw-py Source File: binvox_rw.py
Function: dense_to_sparse
def dense_to_sparse(voxel_data, dtype=np.int):
    """ From dense representation to sparse (coordinate) representation.
    No coordinate reordering.
    """
    if voxel_data.ndim!=3:
        raise ValueError('voxel_data is wrong shape; should be 3D array.')
    return np.asarray(np.nonzero(voxel_data), dtype)

Example 43

Project: hedge Source File: __init__.py
Function: map_if_positive
    def map_if_positive(self, expr):
        crit = self.rec(expr.criterion)
        bool_crit = crit > 0
        then = self.rec(expr.then)
        else_ = self.rec(expr.else_)

        true_indices = np.nonzero(bool_crit)
        false_indices = np.nonzero(~bool_crit)

        result = np.empty_like(crit)

        if isinstance(then, np.ndarray):
            then = then[true_indices]
        if isinstance(else_, np.ndarray):
            else_ = else_[false_indices]

        result[true_indices] = then
        result[false_indices] = else_
        return result

Example 44

Project: APGL Source File: DenseGraph.py
    def neighbours(self, vertexIndex):
        """
        Return an array of the indices of the neighbours of the given vertex.
        
        :param vertexIndex: the index of a vertex.
        :type vertexIndex: :class:`int`
        """
        Parameter.checkIndex(vertexIndex, 0, self.vList.getNumVertices())
        nonZeroIndices =  numpy.nonzero(self.W[vertexIndex, :])
        neighbourIndices = nonZeroIndices[0]
        
        return neighbourIndices

Example 45

Project: trackpy Source File: find.py
def percentile_threshold(image, percentile):
    """Find grayscale threshold based on distribution in image."""

    not_black = image[np.nonzero(image)]
    if len(not_black) == 0:
        return np.nan
    return np.percentile(not_black, percentile)

Example 46

Project: ncpol2sdpa Source File: chordal_extension.py
def find_variable_cliques(variables, objective=0, inequalities=None,
                          equalities=None, momentinequalities=None,
                          momentequalities=None):
    if objective == 0 and inequalities is None and equalities is None:
        raise Exception("There is nothing to extract the chordal structure " +
                        "from!")
    clique_set = generate_clique(variables, objective, inequalities,
                                 equalities, momentinequalities,
                                 momentequalities)
    variable_sets = []
    for clique in clique_set:
        variable_sets.append([variables[i] for i in np.nonzero(clique)[0]])
    return variable_sets

Example 47

Project: scikit-image Source File: peak.py
def _get_high_intensity_peaks(image, mask, num_peaks):
    """
    Return the highest intensity peak coordinates.
    """
    # get coordinates of peaks
    coord = np.nonzero(mask)
    # select num_peaks peaks
    if len(coord[0]) > num_peaks:
        intensities = image[coord]
        idx_maxsort = np.argsort(intensities)
        coord = np.transpose(coord)[idx_maxsort][-num_peaks:]
    else:
        coord = np.column_stack(coord)
    return coord

Example 48

Project: GPy Source File: visualize.py
Function: draw_edges
    def draw_edges(self):
        self.line_handle = []
        if not self.connect==None:
            x = []
            y = []
            z = []
            self.I, self.J = np.nonzero(self.connect)
            for i, j in zip(self.I, self.J):
                x.append(self.vals[i, 0])
                x.append(self.vals[j, 0])
                x.append(np.NaN)
                y.append(self.vals[i, 1])
                y.append(self.vals[j, 1])
                y.append(np.NaN)
                z.append(self.vals[i, 2])
                z.append(self.vals[j, 2])
                z.append(np.NaN)
            self.line_handle = self.axes.plot(np.array(x), np.array(y), np.array(z), '-', color=self.color)

Example 49

Project: deep_nets_iclr04 Source File: stitchparts.py
def plot_maximas_on_image(distribution):
    # imgname = '/Users/ajain/Projects/MODEC/cropped-images/12-oclock-high-special-edition-00171221_00141.png'
    # im = plt.imread(imgname)
    plt.imshow(distribution)
    rows, cols = numpy.nonzero(distribution)
    xs = []
    ys = []
    ss = []
    for idx in range(0, rows.shape[0]):
        y = rows[idx] 
        x = cols[idx] 
        score = distribution[y, x]
        xs.append(x)
        ys.append(y)
        ss.append(score)
    # plt.scatter(xs, ys, c=ss, cmap=cm.coolwarm, s=5)
    plt.show()

Example 50

Project: audfprint Source File: audfprint_match.py
    def _calculate_time_ranges(self, hits, id, mode):
        """Given the id and mode, return the actual time support."""
        match_times = sorted(hits[row, 3]
                             for row in np.nonzero(hits[:, 0]==id)[0]
                             if mode - self.window <= hits[row, 1]
                             and hits[row, 1] <= mode + self.window)
        min_time = match_times[int(len(match_times)*self.time_quantile)]
        max_time = match_times[int(len(match_times)*(1.0 - self.time_quantile)) - 1]
        return min_time, max_time
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4