See neighbor_graph.
1768
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None,
                               weighting='none'):
  ''''''
  assert ((k is not None) or (epsilon is not None)
          ), "Must provide `k` or `epsilon`"
  assert (_issequence(k) ^ _issequence(epsilon)
          ), "Exactly one of `k` or `epsilon` must be a sequence."
  assert weighting in ('binary','none'), "Invalid weighting param: " + weighting
  is_weighted = weighting == 'none'

  if precomputed:
    D = X
  else:
    D = pairwise_distances(X, metric='euclidean')
  # pre-sort for efficiency
  order = np.argsort(D)[:,1:]

  if k is None:
    k = D.shape[0]

  # generate the sequence of graphs
  # TODO: convert the core of these loops to Cython for speed
  W = np.zeros_like(D)
  I = np.arange(D.shape[0])
  if _issequence(k):
    # varied k, fixed epsilon
    if epsilon is not None:
      D[D > epsilon] = 0
    old_k = 0
    for new_k in k:
      idx = order[:, old_k:new_k]
      dist = D[I, idx.T]
      W[I, idx.T] = dist if is_weighted else 1
      yield Graph.from_adj_matrix(W)
      old_k = new_k
  else:
    # varied epsilon, fixed k
    idx = order[:,:k]
    dist = D[I, idx.T].T
    old_i = np.zeros(D.shape[0], dtype=int)
    for eps in epsilon:
      for i, row in enumerate(dist):
        oi = old_i[i]
        ni = oi + np.searchsorted(row[oi:], eps)
        rr = row[oi:ni]
        W[i, idx[i,oi:ni]] = rr if is_weighted else 1
        old_i[i] = ni
      yield Graph.from_adj_matrix(W)
1149854
def neighbors(self) -> List['Node']:
        
        self._load_neighbors()
        return [edge.source if edge.source != self else edge.target
                for edge in self._neighbors.values()]
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
396496
def neighbors_of( p )
      Set.new.tap do |neighbors|
        i = index_mapping[p]
        (0..index_mapping.size-1).each do |j|
          neighbors.add(points[j]) if adjacency_matrix.lookup(i,j) <= eps
        end
      end
    end
492259
def get_lldp_neighbors(self):
        """"""

        neighbors = {}

        cmd = '<show><lldp><neighbors>all</neighbors></lldp></show>'
        try:
            self.device.op(cmd=cmd)
            lldp_table_xml = xmltodict.parse(self.device.xml_root())
            lldp_table_json = json.dumps(lldp_table_xml['response']['result']['entry'])
            lldp_table = json.loads(lldp_table_json)
        except AttributeError:
            lldp_table = []

        for lldp_item in lldp_table:

            local_int = lldp_item['@name']

            if local_int not in neighbors.keys():
                neighbors[local_int] = []
            try:
                lldp_neighs = lldp_item.get('neighbors').get('entry')
            except AttributeError:
                lldp_neighs = ''
            if isinstance(lldp_neighs, dict):
                lldp_neighs = [lldp_neighs]

            for neighbor in lldp_neighs:
                n = {}
                n['hostname'] = neighbor['system-name']
                n['port'] = neighbor['port-id']
                neighbors[local_int].append(n)
        return neighbors
1331467
def select_neighbors_by_edge_attribute(docgraph, source,
                                       attribute=None, value=None, data=False):
    """"""
    assert isinstance(docgraph, MultiGraph)
    for neighbor_id in docgraph.neighbors_iter(source):
        edges = docgraph[source][neighbor_id].values()

        if attribute is None:
            has_attrib = True # don't filter neighbors
        else:
            has_attrib = any(attribute in edge for edge in edges)

        if has_attrib:
            if value is None:
                has_value = True
            elif isinstance(value, basestring):
                has_value = any(edge.get(attribute) == value
                                for edge in edges)
            else:  # ``value`` is a list/set/dict of values
                has_value = any(edge.get(attribute) == v
                                for edge in edges
                                for v in value)

            if has_value:
                if data:
                    yield (neighbor_id, docgraph.node[neighbor_id])
                else:
                    yield neighbor_id
1032150
def get_root_graph(self,root):
      """"""
      children = self.get_children(root)
      g = Graph()
      nodes = [root]+children
      for node in nodes: g.add_node(node)
      node_ids = [x.id for x in nodes]
      edges = [x for x in self._edges.values() if x.node1.id in node_ids and x.node2.id in node_ids]
      for e in edges: g.add_edge(e)
      return g
1040156
def neighborhood(self, node, degree=4):
    """"""
    assert self.by_name[node.name] == node
    already_visited = frontier = set([node.name])
    for _ in range(degree):
      neighbor_names = set()
      for node_name in frontier:
        outgoing = set(n.name for n in self.by_input[node_name])
        incoming = set(self.by_name[node_name].input)
        neighbor_names |= incoming | outgoing
      frontier = neighbor_names - already_visited
      already_visited |= neighbor_names
    return [self.by_name[name] for name in already_visited]
652411
def _neighbour_pixels(hp, ipix):
        
        neigh_ipix = np.unique(hp.neighbours(ipix).ravel())
        # Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours`
        return neigh_ipix[np.where(neigh_ipix >= 0)]
1181288
def _find_neighbors(self, inst):
        
        dist_vect = []
        for j in range(self._datalen):
            if inst != j:
                locator = [inst, j]
                if inst < j:
                    locator.reverse()
                dist_vect.append(self._distance_array[locator[0]][locator[1]])

        dist_vect = np.array(dist_vect)
        inst_avg_dist = np.average(dist_vect)
        inst_std = np.std(dist_vect) / 2.
        near_threshold = inst_avg_dist - inst_std
        far_threshold = inst_avg_dist + inst_std

        NN_near = []
        NN_far = []
        for j in range(self._datalen):
            if inst != j:
                locator = [inst, j]
                if inst < j:
                    locator.reverse()
                if self._distance_array[locator[0]][locator[1]] < near_threshold:
                    NN_near.append(j)
                elif self._distance_array[locator[0]][locator[1]] > far_threshold:
                    NN_far.append(j)

        return np.array(NN_near), np.array(NN_far)
585453
def neighbors(self, node_id):
        """"""
        node = self.get_node(node_id)
        flattened_nodes_list = []
        for a, b in [self.get_edge(edge_id)['vertices'] for edge_id in node['edges']]:
            flattened_nodes_list.append(a)
            flattened_nodes_list.append(b)
        node_set = set(flattened_nodes_list)
        if node_id in node_set:
            node_set.remove(node_id)
        return [nid for nid in node_set]
202745
def query_neighbors(self, nodes: List[Node]) -> List[Edge]:
        """"""
        return self.session.query(Edge).filter(self._edge_one_node(nodes)).all()
296042
def get_neighbor_in_filter(neigh_ip_address):
    """"""
    core = CORE_MANAGER.get_core_service()
    peer = core.peer_manager.get_by_addr(neigh_ip_address)
    return peer.in_filters
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)
444035
def add_graph(self, other):
        
        self.add_nodes( n for n in other.nodes() if not n in self.nodes() )
        
        for each_node in other.nodes():
            for each_edge in other.neighbors(each_node):
                if (not self.has_edge((each_node, each_edge))):
                    self.add_edge((each_node, each_edge))
592499
def neighbor_difference(self):
        """"""
        differences = np.zeros(self.num_neurons)
        num_neighbors = np.zeros(self.num_neurons)

        distance, _ = self.distance_function(self.weights, self.weights)
        for x, y in self.neighbors():
            differences[x] += distance[x, y]
            num_neighbors[x] += 1

        return differences / num_neighbors
547625
def show_flow(self):
        '''
        
        '''
        for n in self.get_node_list():
            excess = self.get_node_attr(n, 'excess')
            distance = self.get_node_attr(n, 'distance')
            self.set_node_attr(n, 'label', str(excess)+'/'+str(distance))
            for neighbor in self.get_neighbors(n):
                capacity = self.get_edge_attr(n, neighbor, 'capacity')
                flow = self.get_edge_attr(n, neighbor, 'flow')
                if capacity == INF:
                    self.set_edge_attr(n, neighbor, 'label',
                                       'INF'+'/'+str(flow))
                else:
                    self.set_edge_attr(n, neighbor, 'label',
                                       str(capacity)+'/'+str(flow))
                if capacity == flow:
                    self.set_edge_attr(n, neighbor, 'color', 'red')
                elif flow > 0:
                    self.set_edge_attr(n, neighbor, 'color', 'green')
                else:
                    self.set_edge_attr(n, neighbor, 'color', 'black')
        self.display()