create a new graph by extracting a subgraph given a list of edges
339512
public static int nvgraphExtractSubgraphByEdge(
        nvgraphHandle handle, 
        nvgraphGraphDescr descrG, 
        nvgraphGraphDescr subdescrG, 
        Pointer subedges, 
        long numedges)
    {
        return checkResult(nvgraphExtractSubgraphByEdgeNative(handle, descrG, subdescrG, subedges, numedges));
    }
163003
def create_graph(grid):
    
    try:
        import numpy as np
    except ImportError:
        print(
            "NumPY is not installed. segraph needs NumPY to function. Please use 'pip install numpy' to install numpy.")
        exit(0)
    print("Creating a graph using segmented grid..")
    # get an array of unique labels
    try:
        vertices = np.unique(grid)

        # get number of vertices
        num_vertices = len(vertices)

        # map these unique labels to [1,...,N], where N is the number of labels (vertices)
        mapping = dict(zip(vertices, np.arange(num_vertices)))
        mapped_grid = np.array([mapping[x] for x in grid.flat]).reshape(grid.shape)

        # create edges, going left to right and top to bottom
        l2r = np.c_[mapped_grid[:, :-1].ravel(), mapped_grid[:, 1:].ravel()]
        t2b = np.c_[mapped_grid[:-1, :].ravel(), mapped_grid[1:, :].ravel()]

        # stack for entire graph
        edges = np.vstack([l2r, t2b])
        edges = edges[edges[:, 0] != edges[:, 1], :]
        edges = np.sort(edges, axis=1)

        # create a edge map, a hashmap
        edge_map = edges[:, 0] + num_vertices * edges[:, 1]

        # filter unique connections as edges
        edges = np.unique(edge_map)

        # reverse map and form edges as pairs
        edges = [[vertices[edge % num_vertices],
                  vertices[edge // num_vertices]] for edge in edges]
    except:
        print("Invalid argument supplied !")
        return None

    return vertices, edges
257603
def new_graph(self, name, data=None, **attr):
        
        self._init_graph(name, 'Graph')
        g = Graph(self, name, data, **attr)
        self._graph_objs[name] = g
        return g
989325
def B(u, v, dfs_data):
    """Bu(v) = {wx | w is in S*(v)}"""
    if a(v, dfs_data) != u:
        return None

    return list(set([edge_id for w in S_star(v, dfs_data) for edge_id in dfs_data['graph'].get_node(w)['edges']]))
1042205
def _adjacency_to_edges(adjacency):
    """"""
    edges = set()
    for u in adjacency:
        for v in adjacency[u]:
            try:
                edge = (u, v) if u <= v else (v, u)
            except TypeError:
                # Py3 does not allow sorting of unlike types
                if (v, u) in edges:
                    continue
                edge = (u, v)

            edges.add(edge)
    return edges
17136
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
    

    node_orig = 1

    if directed:
        graph = Dot(graph_type='digraph')
    else:
        graph = Dot(graph_type='graph')

    for row in matrix:
        if not directed:
            skip = matrix.index(row)
            r = row[skip:]
        else:
            skip = 0
            r = row
        node_dest = skip + 1

        for e in r:
            if e:
                graph.add_edge(
                    Edge(
                        node_prefix + node_orig,
                        node_prefix + node_dest))
            node_dest += 1
        node_orig += 1

    return graph
1048639
def find_minimum_spanning_tree_as_subgraph(graph):
    """"""
    edge_list = find_minimum_spanning_tree(graph)
    subgraph = get_subgraph_from_edge_list(graph, edge_list)

    return subgraph
394034
def as_graph(self) -> Digraph:  # pragma: no cover
        """"""
        if Digraph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Digraph()

        subgraphs = [Digraph(graph_attr={'rank': 'same'}), Digraph(graph_attr={'rank': 'same'})]
        nodes = [{}, {}]  # type: List[Dict[Union[TLeft, TRight], str]]
        edges = []  # type: List [Tuple[str, str]]
        node_id = 0
        for (tail_part, tail), head_set in self.items():
            if tail not in nodes[tail_part]:
                name = 'node{:d}'.format(node_id)
                nodes[tail_part][tail] = name
                subgraphs[tail_part].node(name, label=str(tail))
                node_id += 1
            for head_part, head in head_set:
                if head not in nodes[head_part]:
                    name = 'node{:d}'.format(node_id)
                    nodes[head_part][head] = name
                    subgraphs[head_part].node(name, label=str(head))
                    node_id += 1
                edges.append((nodes[tail_part][tail], nodes[head_part][head]))
        graph.subgraph(subgraphs[0])
        graph.subgraph(subgraphs[1])
        for tail_node, head_node in edges:
            graph.edge(tail_node, head_node)
        return graph
229407
def connected_subgraphs(self, directed=True, ordered=False):
    '''
    '''
    num_ccs, labels = self.connected_components(directed=directed)
    # check the trivial case first
    if num_ccs == 1:
      yield self
      raise StopIteration
    if ordered:
      # sort by descending size (num vertices)
      order = np.argsort(np.bincount(labels))[::-1]
    else:
      order = range(num_ccs)

    # don't use self.subgraph() here, because we can reuse adj
    adj = self.matrix('dense', 'csr', 'csc')
    for c in order:
      mask = labels == c
      sub_adj = adj[mask][:,mask]
      yield self.__class__.from_adj_matrix(sub_adj)
462167
def edges
      result = []
      c = edge_class
      each_edge { |u,v| result << c.new(u,v) }
      result
    end
823928
def from_edge_pairs(pairs, num_vertices=None, symmetric=False, weights=None):
  '''
  '''
  if not symmetric:
    if weights is None:
      return EdgePairGraph(pairs, num_vertices=num_vertices)
    row, col = np.asarray(pairs).T
    row, weights = np.broadcast_arrays(row, weights)
    shape = None if num_vertices is None else (num_vertices, num_vertices)
    adj = ss.coo_matrix((weights, (row, col)), shape=shape)
    return SparseAdjacencyMatrixGraph(adj)
  # symmetric case
  G = SymmEdgePairGraph(pairs, num_vertices=num_vertices)
  if weights is None:
    return G
  # Convert to sparse adj graph with provided edge weights
  s = G.matrix('coo').astype(float)
  # shenanigans to assign edge weights in the right order
  flat_idx = np.ravel_multi_index(s.nonzero(), s.shape)
  r, c = np.transpose(pairs)
  rc_idx = np.ravel_multi_index((r,c), s.shape)
  cr_idx = np.ravel_multi_index((c,r), s.shape)
  order = np.argsort(flat_idx)
  flat_idx = flat_idx[order]
  s.data[order[np.searchsorted(flat_idx, rc_idx)]] = weights
  s.data[order[np.searchsorted(flat_idx, cr_idx)]] = weights
  return SparseAdjacencyMatrixGraph(s)
1166417
def new_edge(self, node_a, node_b, cost=1):
        """"""

        # Verify that both nodes exist in the graph
        try:
            self.nodes[node_a]
        except KeyError:
            raise NonexistentNodeError(node_a)
        try:
            self.nodes[node_b]
        except KeyError:
            raise NonexistentNodeError(node_b)

        # Create the new edge
        edge_id = self.generate_edge_id()

        edge = {'id': edge_id,
                'vertices': (node_a, node_b),
                'cost': cost,
                'data': {}
        }

        self.edges[edge_id] = edge
        self.nodes[node_a]['edges'].append(edge_id)

        self._num_edges += 1

        return edge_id
1071560
def tsp_gurobi(edges):
    
    from gurobipy import Model, GRB, quicksum

    edges = populate_edge_weights(edges)
    incoming, outgoing, nodes = node_to_edge(edges)
    idx = dict((n, i) for i, n in enumerate(nodes))
    nedges = len(edges)
    n = len(nodes)

    m = Model()

    def step(x): return "u_{0}".format(x)
    # Create variables
    vars = {}
    for i, (a, b, w) in enumerate(edges):
        vars[i] = m.addVar(obj=w, vtype=GRB.BINARY, name=str(i))
    for u in nodes[1:]:
        u = step(u)
        vars[u] = m.addVar(obj=0, vtype=GRB.INTEGER, name=u)
    m.update()

    # Bounds for step variables
    for u in nodes[1:]:
        u = step(u)
        vars[u].lb = 1
        vars[u].ub = n - 1

    # Add degree constraint
    for v in nodes:
        incoming_edges = incoming[v]
        outgoing_edges = outgoing[v]
        m.addConstr(quicksum(vars[x] for x in incoming_edges) == 1)
        m.addConstr(quicksum(vars[x] for x in outgoing_edges) == 1)

    # Subtour elimination
    edge_store = dict(((idx[a], idx[b]), i)
                      for i, (a, b, w) in enumerate(edges))

    # Given a list of edges, finds the shortest subtour
    def subtour(s_edges):
        visited = [False] * n
        cycles = []
        lengths = []
        selected = [[] for i in range(n)]
        for x, y in s_edges:
            selected[x].append(y)
        while True:
            current = visited.index(False)
            thiscycle = [current]
            while True:
                visited[current] = True
                neighbors = [x for x in selected[current] if not visited[x]]
                if len(neighbors) == 0:
                    break
                current = neighbors[0]
                thiscycle.append(current)
            cycles.append(thiscycle)
            lengths.append(len(thiscycle))
            if sum(lengths) == n:
                break
        return cycles[lengths.index(min(lengths))]

    def subtourelim(model, where):
        if where != GRB.callback.MIPSOL:
            return
        selected = []
        # make a list of edges selected in the solution
        sol = model.cbGetSolution([model._vars[i] for i in range(nedges)])
        selected = [edges[i] for i, x in enumerate(sol) if x > .5]
        selected = [(idx[a], idx[b]) for a, b, w in selected]
        # find the shortest cycle in the selected edge list
        tour = subtour(selected)
        if len(tour) == n:
            return
        # add a subtour elimination constraint
        c = tour
        incident = [edge_store[a, b] for a, b in pairwise(c + [c[0]])]
        model.cbLazy(quicksum(model._vars[x]
                              for x in incident) <= len(tour) - 1)

    m.update()

    m._vars = vars
    m.params.LazyConstraints = 1
    m.optimize(subtourelim)

    selected = [v.varName for v in m.getVars() if v.x > .5]
    selected = [int(x) for x in selected if x[:2] != "u_"]
    results = sorted(x for i, x in enumerate(edges) if i in selected) \
        if selected else None
    return results
1292740
def get_graph_tool_from_adjacency(adjacency, directed=None):
    """"""
    import graph_tool as gt
    adjacency_edge_list = adjacency
    if not directed:
        from scipy.sparse import tril
        adjacency_edge_list = tril(adjacency)
    g = gt.Graph(directed=directed)
    g.add_vertex(adjacency.shape[0])  # this adds adjacency.shap[0] vertices
    g.add_edge_list(np.transpose(adjacency_edge_list.nonzero()))
    weights = g.new_edge_property('double')
    for e in g.edges():
        # graph_tool uses the following convention,
        # which is opposite to the rest of scanpy
        weights[e] = adjacency[int(e.source()), int(e.target())]
    g.edge_properties['weight'] = weights
    return g
383279
def graph_simplify(G):
    
    spurs = []
    path_nodes = []
    for k, d in G.degree().iteritems():
        if d == 1:
            spurs.append(k)
        elif d == 2:
            path_nodes.append(k)

    logging.debug("Remove {0} spurs.".format(len(spurs)))
    G.remove_nodes_from(spurs)

    SG = G.subgraph(path_nodes)
    cc = nx.connected_components(SG)
    for c in cc:
        if len(c) == 1:
            continue
        c = set(c)
        neighbors = set()
        for x in c:
            neighbors |= set(G.neighbors(x))
        neighbors -= c
        newtag = list(c)[0] + "*"
        for n in neighbors:
            G.add_edge(newtag, n)
        G.remove_nodes_from(c)
    logging.debug("Contract {0} path nodes into {1} nodes.".\
                    format(len(path_nodes), len(cc)))
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
611598
def run(self, graph):
        
        if not self:
            log.debug('no seeding, returning graph: %s', graph)
            return graph

        subgraphs = []

        for seed in self:
            seed_method, seed_data = seed[SEED_METHOD], seed[SEED_DATA]

            log.debug('seeding with %s: %s', seed_method, seed_data)
            subgraph = get_subgraph(graph, seed_method=seed_method, seed_data=seed_data)

            if subgraph is None:
                log.debug('seed returned empty graph: %s', seed)
                continue

            subgraphs.append(subgraph)

        if not subgraphs:
            log.debug('no subgraphs returned')
            return

        return union(subgraphs)