r"""
    Compute the average adjacency degree for each node.

    The average adjacency degree is the average of the degrees of a node and
    its neighbors.

    Parameters
    ----------
    G: Graph
        Graph on which the statistic is extracted
166322
def compute_avg_adj_deg(G):
    
    """
    return np.sum(np.dot(G.A, G.A), axis=1) / (np.sum(G.A, axis=1) + 1.)
769321
def average_colors(c1, c2):
    '''  '''
    r = int((c1[0] + c2[0])/2)
    g = int((c1[1] + c2[1])/2)
    b = int((c1[2] + c2[2])/2)

    return (r, g, b)
1165325
def _compute_edges(self):
        
        nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes(
            self._nodes, self._degree
        )
        edge1 = _curve_mod.Curve(nodes1, self._degree, _copy=False)
        edge2 = _curve_mod.Curve(nodes2, self._degree, _copy=False)
        edge3 = _curve_mod.Curve(nodes3, self._degree, _copy=False)
        return edge1, edge2, edge3
108447
def neighborhood_subgraph(self, start_idx, radius=1, weighted=True,
                            directed=True, return_mask=False):
    ''''''
    adj = self.matrix('dense', 'csr', 'csc')
    dist = ssc.dijkstra(adj, directed=directed, indices=start_idx,
                        unweighted=(not weighted), limit=radius)
    mask = np.isfinite(dist)
    sub_adj = adj[mask][:,mask]
    g = self.__class__.from_adj_matrix(sub_adj)
    if return_mask:
      return g, mask
    return g
537650
function degree(x) {

    var i = Number.NEGATIVE_INFINITY;

    for (var k in x) {
      if (!FIELD['empty'](x[k]))
        i = Math.max(k, i);
    }
    return i;
  }
145604
def paga_adjacency(
        adata,
        adjacency='connectivities',
        adjacency_tree='connectivities_tree',
        as_heatmap=True,
        color_map=None,
        show=None,
        save=None):
    
    connectivity = adata.uns[adjacency].toarray()
    connectivity_select = adata.uns[adjacency_tree]
    if as_heatmap:
        matrix(connectivity, color_map=color_map, show=False)
        for i in range(connectivity_select.shape[0]):
            neighbors = connectivity_select[i].nonzero()[1]
            pl.scatter([i for j in neighbors], neighbors, color='black', s=1)
    # as a stripplot
    else:
        pl.figure()
        for i, cs in enumerate(connectivity):
            x = [i for j, d in enumerate(cs) if i != j]
            y = [c for j, c in enumerate(cs) if i != j]
            pl.scatter(x, y, color='gray', s=1)
            neighbors = connectivity_select[i].nonzero()[1]
            pl.scatter([i for j in neighbors],
                       cs[neighbors], color='black', s=1)
    utils.savefig_or_show('paga_connectivity', show=show, save=save)
335080
def get_top_hubs(graph, *, n: Optional[int] = 15) -> List[Tuple[BaseEntity, int]]:
    
    return Counter(dict(graph.degree())).most_common(n=n)
108707
def calculate_average_diameter(self, **kwargs):
        
        self.average_diameter = find_average_diameter(
            self.elements, self.coordinates, **kwargs)
        return self.average_diameter
930996
def get_igraph_from_adjacency(adjacency, directed=None):
    """"""
    import igraph as ig
    sources, targets = adjacency.nonzero()
    weights = adjacency[sources, targets]
    if isinstance(weights, np.matrix):
        weights = weights.A1
    g = ig.Graph(directed=directed)
    g.add_vertices(adjacency.shape[0])  # this adds adjacency.shap[0] vertices
    g.add_edges(list(zip(sources, targets)))
    try:
        g.es['weight'] = weights
    except:
        pass
    if g.vcount() != adjacency.shape[0]:
        logg.warn('The constructed graph has only {} nodes. '
                  'Your adjacency matrix contained redundant nodes.'
                  .format(g.vcount()))
    return g
798219
static int[] rank(final int[][] g) {
        final int ord = g.length;

        final int[] count = new int[ord + 1];
        final int[] rank = new int[ord];

        // frequency of each degree
        for (int v = 0; v < ord; v++)
            count[g[v].length + 1]++;
        // cumulated counts
        for (int i = 0; count[i] < ord; i++)
            count[i + 1] += count[i];
        // store sorted position of each vertex
        for (int v = 0; v < ord; v++)
            rank[v] = count[g[v].length]++;

        return rank;
    }
247389
def calculate_epsilon_effective(rho, epsilon, seed_degree, neighbor_degrees, mean_degree):
    
    # Calculate a weighted neighborhood degree average.
    # neighborhood_degree = rho*seed_degree + (1-rho)*neighbor_degrees.mean()
    neighborhood_degree = neighbor_degrees.mean()

    # Calculate the seed neighborhood normalized effective epsilon.
    epsilon_effective = (epsilon*np.log(1 + seed_degree))/np.log(1 + neighborhood_degree)

    # Calculate the maximum epsilon for at least one push on a neighboring node.
    # Also the minimum epsilon for a push on all the neighboring nodes.
    epsilon_effective_maximum = np.max(1/(seed_degree*neighbor_degrees))
    epsilon_effective_minimum = np.min(1/(seed_degree*neighbor_degrees))

    # print(epsilon_effective, epsilon_effective_maximum, epsilon_effective_minimum)

    # The maximum epsilon is absolute, whereas we regularize for the minimum.
    if epsilon_effective > epsilon_effective_maximum:
        epsilon_effective = epsilon_effective_maximum
    elif epsilon_effective < epsilon_effective_minimum:
        epsilon_effective = (epsilon_effective_minimum + epsilon_effective)/2

    return epsilon_effective
717404
def degree(self, kind='out', weighted=True):
    '''
    '''
    if kind == 'out':
      axis = 1
      adj = self.matrix('dense', 'csc')
    else:
      axis = 0
      adj = self.matrix('dense', 'csr')

    if not weighted and self.is_weighted():
      # With recent numpy and a dense matrix, could do:
      # d = np.count_nonzero(adj, axis=axis)
      d = (adj!=0).sum(axis=axis)
    else:
      d = adj.sum(axis=axis)
    return np.asarray(d).ravel()
933648
int[][] findNeighborIndices() {

		// looking at a typical protein case, number of neighbours are from ~10 to ~50, with an average of ~30
		int initialCapacity = 60;

		int[][] nbsIndices = new int[atomCoords.length][];

		for (int k=0; k<atomCoords.length; k++) {
			double radius = radii[k] + probe + probe;

			List<Integer> thisNbIndices = new ArrayList<>(initialCapacity);

			for (int i = 0; i < atomCoords.length; i++) {
				if (i == k) continue;

				double dist = atomCoords[i].distance(atomCoords[k]);

				if (dist < radius + radii[i]) {
					thisNbIndices.add(i);
				}
			}

			int[] indicesArray = new int[thisNbIndices.size()];
			for (int i=0;i<thisNbIndices.size();i++) indicesArray[i] = thisNbIndices.get(i);
			nbsIndices[k] = indicesArray;
		}
		return nbsIndices;
	}
362295
def get_input_nodes(G: nx.DiGraph) -> List[str]:
    
    return [n for n, d in G.in_degree() if d == 0]
1156004
def _get_upper_bound(self):
        """

        if self.lap_type == 'normalized':
            return 2  # Equal iff the graph is bipartite.
        elif self.lap_type == 'combinatorial':
            bounds = []
            # Equal for full graphs.
            bounds += [self.n_vertices * np.max(self.W)]
            # Gershgorin circle theorem. Equal for regular bipartite graphs.
            # Special case of the below bound.
            bounds += [2 * np.max(self.dw)]
            # Anderson, Morley, Eigenvalues of the Laplacian of a graph.
            # Equal for regular bipartite graphs.
            if self.n_edges > 0:
                sources, targets, _ = self.get_edge_list()
                bounds += [np.max(self.dw[sources] + self.dw[targets])]
            # Merris, A note on Laplacian graph eigenvalues.
            if not self.is_directed():
                W = self.W
            else:
                W = utils.symmetrize(self.W, method='average')
            m = W.dot(self.dw) / self.dw  # Mean degree of adjacent vertices.
            bounds += [np.max(self.dw + m)]
            # Good review: On upper bounds for Laplacian graph eigenvalues.
            return min(bounds)
        else:
            raise ValueError('Unknown Laplacian type '
                             '{}'.format(self.lap_type))
586248
def group_and_sort_nodes(self):
        
        if self.node_grouping and not self.node_order:
            if self.group_order == "alphabetically":
                self.nodes = [
                    n
                    for n, d in sorted(
                        self.graph.nodes(data=True),
                        key=lambda x: x[1][self.node_grouping],
                    )
                ]

            elif self.group_order == "default":
                grp = [
                    d[self.node_grouping]
                    for _, d in self.graph.nodes(data=True)
                ]
                grp_name = list(unique_everseen(grp))
                nodes = []
                for key in grp_name:
                    nodes.extend(
                        [
                            n
                            for n, d in self.graph.nodes(data=True)
                            if key in d.values()
                        ]
                    )
                self.nodes = nodes

        elif self.node_order and not self.node_grouping:
            self.nodes = [
                n
                for n, _ in sorted(
                    self.graph.nodes(data=True),
                    key=lambda x: x[1][self.node_order],
                )
            ]

        elif self.node_grouping and self.node_order:
            if self.group_order == "alphabetically":
                self.nodes = [
                    n
                    for n, d in sorted(
                        self.graph.nodes(data=True),
                        key=lambda x: (
                            x[1][self.node_grouping],
                            x[1][self.node_order],
                        ),
                    )
                ]
            elif self.group_order == "default":
                grp = [
                    d[self.node_grouping]
                    for _, d in self.graph.nodes(data=True)
                ]
                grp_name = list(unique_everseen(grp))
                nodes = []
                for key in grp_name:
                    nodes.extend(
                        [
                            n
                            for n, d in sorted(
                                self.graph.nodes(data=True),
                                key=lambda x: x[1][self.node_order],
                            )
                            if key in d.values()
                        ]
                    )
                self.nodes = nodes
957826
def degree(self, vertex):
        
        try:
            return len(self.vertices[vertex])
        except KeyError:
            raise GraphInsertError("Vertex %s doesn't exist." % (vertex,))