예제 #1
0
def test_subgraph(graph, subgraph, final_set, subgraph_vertices=None):
    """
    Examine whether the planted subgraph pattern was found. For G(k, q), this examination requires knowing the vertices
    that belong to the subgraph, otherwise we look for a specific pattern and do not care whether we found exactly the
    vertices of the planted subgraph.
    """
    if subgraph == "clique":
        return all(
            [graph.has_edge(v1, v2) for v1, v2 in combinations(final_set, 2)])
    elif subgraph == "dag-clique":
        return all([
            any([graph.has_edge(v1, v2),
                 graph.has_edge(v2, v1)])
            for v1, v2 in combinations(final_set, 2)
        ] + [
            nx.is_directed_acyclic_graph(nx.induced_subgraph(graph, final_set))
        ])
    elif subgraph == "k-plex":
        return all([
            d[1] >= len(final_set) - 2
            for d in nx.degree(nx.induced_subgraph(graph, final_set))
        ])
    elif subgraph == "biclique":
        if not nx.is_connected(nx.induced_subgraph(graph, final_set)):
            return False
        try:
            first, second = nx.algorithms.bipartite.basic.sets(
                nx.induced_subgraph(graph, final_set))
            return all(
                [graph.has_edge(v1, v2) for v1, v2 in product(first, second)])
        except nx.exception.NetworkXError:
            return False
    else:  # G(k, q). The only case we have the exact vertices we want and not a subgraph shape.
        return len(subgraph_vertices) == len(
            set(subgraph_vertices).intersection(set(final_set)))
예제 #2
0
def test_subgraph(graph, subgraph, final_set, subgraph_vertices=None):
    if subgraph == "clique":
        return all(
            [graph.has_edge(v1, v2) for v1, v2 in combinations(final_set, 2)])
    elif subgraph == "dag-clique":
        return all([
            any([graph.has_edge(v1, v2),
                 graph.has_edge(v2, v1)])
            for v1, v2 in combinations(final_set, 2)
        ] + [
            nx.is_directed_acyclic_graph(nx.induced_subgraph(graph, final_set))
        ])
    elif subgraph == "k-plex":
        return all([
            d[1] >= len(final_set) - 2
            for d in nx.degree(nx.induced_subgraph(graph, final_set))
        ])
    elif subgraph == "biclique":
        if not nx.is_connected(nx.induced_subgraph(graph, final_set)):
            return False
        try:
            first, second = nx.algorithms.bipartite.basic.sets(
                nx.induced_subgraph(graph, final_set))
            return all(
                [graph.has_edge(v1, v2) for v1, v2 in product(first, second)])
        except nx.exception.NetworkXError:
            return False
    else:  # G(k, q). The only case we have the exact vertices we want and not a subgraph shape.
        return len(subgraph_vertices) == len(
            set(subgraph_vertices).intersection(set(final_set)))
예제 #3
0
    def test_partial_subgraph(self):
        G = self.K3
        H = nx.induced_subgraph(G, 0)
        assert_equal(dict(H.adj), {0: {}})
        assert_not_equal(dict(G.adj), {0: {}})

        H = nx.induced_subgraph(G, [0, 1])
        assert_equal(dict(H.adj), {0: {1: {}}, 1: {0: {}}})
    def test_partial_subgraph(self):
        G = self.K3
        H = nx.induced_subgraph(G, 0)
        assert_equal(dict(H.adj), {0: {}})
        assert_not_equal(dict(G.adj), {0: {}})

        H = nx.induced_subgraph(G, [0, 1])
        assert_equal(dict(H.adj), {0: {1: {}}, 1: {0: {}}})
예제 #5
0
    def test_partial_subgraph(self):
        G = self.K3
        H = nx.induced_subgraph(G, 0)
        assert dict(H.adj) == {0: {}}
        assert dict(G.adj) != {0: {}}

        H = nx.induced_subgraph(G, [0, 1])
        assert dict(H.adj) == {0: {1: {}}, 1: {0: {}}}
예제 #6
0
def R(G, T, e):
    T.remove_edges_from([e])
    components = list(nx.connected_components(T))
    T.add_edges_from([e])
    A = components[0]
    B = components[1]
    G_A = nx.induced_subgraph(G, A)
    G_B = nx.induced_subgraph(G, B)
    return [G_A, G_B]
예제 #7
0
 def test_subgraph(self):
     assert_equal(self.G.subgraph([0, 1, 2, 4]).adj,
                  nx.subgraph(self.G, [0, 1, 2, 4]).adj)
     assert_equal(self.DG.subgraph([0, 1, 2, 4]).adj,
                  nx.subgraph(self.DG, [0, 1, 2, 4]).adj)
     assert_equal(self.G.subgraph([0, 1, 2, 4]).adj,
                  nx.induced_subgraph(self.G, [0, 1, 2, 4]).adj)
     assert_equal(self.DG.subgraph([0, 1, 2, 4]).adj,
                  nx.induced_subgraph(self.DG, [0, 1, 2, 4]).adj)
     # subgraph-subgraph chain is allowed in function interface
     H = nx.induced_subgraph(self.G.subgraph([0, 1, 2, 4]), [0, 1, 4])
     assert_is_not(H._graph, self.G)
     assert_equal(H.adj, self.G.subgraph([0, 1, 4]).adj)
예제 #8
0
 def test_subgraph(self):
     assert_equal(self.G.subgraph([0, 1, 2, 4]).adj,
                  nx.subgraph(self.G, [0, 1, 2, 4]).adj)
     assert_equal(self.DG.subgraph([0, 1, 2, 4]).adj,
                  nx.subgraph(self.DG, [0, 1, 2, 4]).adj)
     assert_equal(self.G.subgraph([0, 1, 2, 4]).adj,
                  nx.induced_subgraph(self.G, [0, 1, 2, 4]).adj)
     assert_equal(self.DG.subgraph([0, 1, 2, 4]).adj,
                  nx.induced_subgraph(self.DG, [0, 1, 2, 4]).adj)
     # subgraph-subgraph chain is allowed in function interface
     H = nx.induced_subgraph(self.G.subgraph([0, 1, 2, 4]), [0, 1, 4])
     assert_is_not(H._graph, self.G)
     assert_equal(H.adj, self.G.subgraph([0, 1, 4]).adj)
예제 #9
0
 def test_subgraph(self):
     assert (self.G.subgraph([0, 1, 2, 4]).adj ==
             nx.subgraph(self.G, [0, 1, 2, 4]).adj)
     assert (self.DG.subgraph([0, 1, 2, 4]).adj ==
             nx.subgraph(self.DG, [0, 1, 2, 4]).adj)
     assert (self.G.subgraph([0, 1, 2, 4]).adj ==
             nx.induced_subgraph(self.G, [0, 1, 2, 4]).adj)
     assert (self.DG.subgraph([0, 1, 2, 4]).adj ==
             nx.induced_subgraph(self.DG, [0, 1, 2, 4]).adj)
     # subgraph-subgraph chain is allowed in function interface
     H = nx.induced_subgraph(self.G.subgraph([0, 1, 2, 4]), [0, 1, 4])
     assert H._graph is not self.G
     assert H.adj == self.G.subgraph([0, 1, 4]).adj
def inspect_remainders(test_scores, test_lbs, eval_scores, eval_lbs, train_scores, train_lbs,
                       graph_size, subgraph_size, graph_indices, key_name, dirname, iteration):
    scores = train_scores + eval_scores + test_scores
    lbs = train_lbs + eval_lbs + test_lbs
    head_path = os.path.join(os.path.dirname(__file__), '..', 'graph_calculations', 'pkl', key_name[0], key_name[1] + '_runs')
    if not os.path.exists(os.path.join("remaining_after_model", key_name[0], dirname)):
        os.mkdir(os.path.join("remaining_after_model", key_name[0], dirname))
    dumping_path = os.path.join("remaining_after_model", key_name[0], dirname, key_name[1] + "_runs")
    for run in range(len(graph_indices)):
        ranks, labels = map(lambda x: x[run * graph_size:(run + 1) * graph_size], [scores, lbs])
        dir_path = os.path.join(head_path, key_name[1] + "_run_" + str(graph_indices[run][1]))
        sorted_vertices = np.argsort(ranks)
        initial_candidates = sorted_vertices[-2*subgraph_size:]
        total_graph = pickle.load(open(os.path.join(dir_path, "gnx.pkl"), "rb"))
        induced_subgraph = nx.induced_subgraph(total_graph, initial_candidates)
        candidate_scores, candidate_labels = map(lambda x: [x[c] for c in initial_candidates], [ranks, labels])
        candidate_dumping_path = os.path.join(dumping_path, key_name[1] + "_run_" + str(graph_indices[run][1]))
        if not os.path.exists(candidate_dumping_path):
            os.mkdir(candidate_dumping_path)
        all_df = pd.DataFrame({"score": ranks, "label": labels}, index=list(range(graph_size)))
        all_df = all_graph_measurements(total_graph, induced_subgraph).join(all_df)
        all_df.to_csv(os.path.join(candidate_dumping_path,
                                   f"all_results_iteration_{iteration}_set_{graph_indices[run][0]}.csv"))
        cand_df = pd.DataFrame({"score": candidate_scores, "label": candidate_labels}, index=initial_candidates)
        cand_df = candidate_graph_measurements(total_graph, induced_subgraph, initial_candidates).join(cand_df)
        cand_df.to_csv(os.path.join(candidate_dumping_path,
                                    f"candidates_results_iteration_{iteration}_set_{graph_indices[run][0]}.csv"))
예제 #11
0
def induced_subgraph(
    G, filter_type, filter_attribute, filter_values, ignore_attrs=False
):
    """
    Create custom induced subgraph.

    Args:
        filter_type: 'node' or 'edge'
        filter_attribute: attribute to filter on
        filter_values: attribute values to evaluate to `True`

    """
    G = nx.MultiDiGraph(G)
    if filter_type == "node":
        nodes = [
            n for n in G.nodes() if G.nodes[n].get(filter_attribute) in filter_values
        ]
        sG = nx.induced_subgraph(G, nodes)
    elif filter_type == "edge":
        sG = nx.MultiDiGraph()
        sG.add_nodes_from(G.nodes(data=not ignore_attrs))
        sG.add_edges_from(
            [
                (e[0], e[1], e[-1])
                for e in G.edges(data=True)
                if e[-1][filter_attribute] in filter_values
            ]
        )
    else:
        raise

    sG.graph["name"] = "_".join(
        [G.graph["name"], filter_type, filter_attribute, str(*filter_values)]
    )
    return sG
예제 #12
0
def rep(g):
    nbar = {
        u: nx.induced_subgraph(g, [v for v in g if v not in g[u]])
        for u in g
    }

    x = {
        u: {v: LpVariable(f'x{u},{v}', cat='Binary')
            for v in nbar[u]}
        for u in g
    }

    lp = LpProblem()
    lp += lpSum([x[u][u] for u in g])

    for v in g:
        lp += lpSum([x[u][v] for u in nbar[v]]) >= 1

    for u in g:
        for v, w in nbar[u].edges:
            lp += x[u][v] + x[u][w] <= x[u][u]

    lp.writeLP('rep.lp')
    PULP_CBC_CMD(msg=0).solve(lp)

    reps = [u for u in g if x[u][u].varValue > 0]
    cols = [None] * g.order()
    for c, v in enumerate(reps):
        cols[v] = c
    for c, r in enumerate(reps):
        for v in [v for v, xi in x[r].items() if xi.varValue > 0]:
            if v not in reps:
                cols[v] = c
    return cols
예제 #13
0
def intermediate_subgraph(graph, source, target):
    paths = nx.all_simple_paths(graph, source, target)
    nodes = set()
    for path in paths:
        for node in path:
            nodes.add(node)
    return nx.induced_subgraph(graph, nodes)
예제 #14
0
    def _algorithm(self, graph, labels):
        # INITIALIZATION - optimal solutions from a version of the paper#
        alpha = 0.8
        beta = 2.3
        eta = 1.2
        eps_4 = 1. / alpha - 1e-8
        t = eps_4 * np.log(self._params['vertices']) / \
            np.log(np.power(self.rho(alpha, beta, eta), 2) / self.tau(alpha, beta))
        t = np.floor(t)
        v_i = [v for v in range(len(labels))]

        # First Stage #
        for _ in range(int(t)):
            s_i = self._choose_s_i(v_i, alpha)
            s_i_tilde = self._get_si_tilde(graph, s_i, eta)
            new_vi = self._get_vi(graph, v_i, s_i, s_i_tilde, beta)
            v_i = new_vi

        # Second Stage #
        g_t = nx.induced_subgraph(graph, v_i)
        k_tilde = self._get_k_tilde(g_t, alpha, beta, eta, t)

        # Third Stage - From K' to K* using the rule they said at the bottom of the paper #
        k_tag = self._get_k_tag(k_tilde, graph)
        k_star = self._get_k_star(k_tag, graph)

        print(
            f"After the final stage, {len([v for v in k_star if labels[v]])} clique vertices "
            f"out of {len(k_star)} vertices are left")
        return [1 if v in k_star else 0 for v in graph]
예제 #15
0
    def test_restricted_induced_subgraph_chains(self):
        """ Test subgraph chains that both restrict and show nodes/edges.

        A restricted_view subgraph should allow induced subgraphs using
        G.subgraph that automagically without a chain (meaning the result
        is a subgraph view of the original graph not a subgraph-of-subgraph.
        """
        hide_nodes = [3, 4, 5]
        hide_edges = [(6, 7)]
        RG = nx.restricted_view(self.G, hide_nodes, hide_edges)
        nodes = [4, 5, 6, 7, 8]
        SG = nx.induced_subgraph(RG, nodes)
        SSG = RG.subgraph(nodes)
        assert_is(SSG.root_graph, SSG._graph)
        assert_is_not(SG.root_graph, SG._graph)
        assert_edges_equal(SG.edges, SSG.edges)
        # should be same as morphing the graph
        CG = self.G.copy()
        CG.remove_nodes_from(hide_nodes)
        CG.remove_edges_from(hide_edges)
        assert_edges_equal(CG.edges(nodes), SSG.edges)
        CG.remove_nodes_from([0, 1, 2, 3])
        assert_edges_equal(CG.edges, SSG.edges)
        # switch order: subgraph first, then restricted view
        SSSG = self.G.subgraph(nodes)
        RSG = nx.restricted_view(SSSG, hide_nodes, hide_edges)
        assert_is_not(RSG.root_graph, RSG._graph)
        assert_edges_equal(RSG.edges, CG.edges)
예제 #16
0
    def test_restricted_induced_subgraph_chains(self):
        """ Test subgraph chains that both restrict and show nodes/edges.

        A restricted_view subgraph should allow induced subgraphs using
        G.subgraph that automagically without a chain (meaning the result
        is a subgraph view of the original graph not a subgraph-of-subgraph.
        """
        hide_nodes = [3, 4, 5]
        hide_edges = [(6, 7)]
        RG = nx.restricted_view(self.G, hide_nodes, hide_edges)
        nodes = [4, 5, 6, 7, 8]
        SG = nx.induced_subgraph(RG, nodes)
        SSG = RG.subgraph(nodes)
        assert RG._graph is self.G
        assert SSG._graph is self.G
        assert SG._graph is RG
        assert_edges_equal(SG.edges, SSG.edges)
        # should be same as morphing the graph
        CG = self.G.copy()
        CG.remove_nodes_from(hide_nodes)
        CG.remove_edges_from(hide_edges)
        assert_edges_equal(CG.edges(nodes), SSG.edges)
        CG.remove_nodes_from([0, 1, 2, 3])
        assert_edges_equal(CG.edges, SSG.edges)
        # switch order: subgraph first, then restricted view
        SSSG = self.G.subgraph(nodes)
        RSG = nx.restricted_view(SSSG, hide_nodes, hide_edges)
        assert RSG._graph is not self.G
        assert_edges_equal(RSG.edges, CG.edges)
예제 #17
0
 def _get_k_star(self, k_tag, graph):
     if len(k_tag) <= self.k:
         return k_tag
     g_k_tag = nx.induced_subgraph(graph, k_tag)
     vertices = [v for v in g_k_tag]
     degrees = [g_k_tag.degree(v) for v in vertices]
     vertices_order = [vertices[v] for v in np.argsort(degrees)]
     return vertices_order[-self.k:]
예제 #18
0
 def test_subgraph_of_subgraph(self):
     for G in [self.G, self.DG, self.DMG, self.MG]:
         SG = nx.induced_subgraph(G, [4, 5, 6])
         assert_equal(list(SG), [4, 5, 6])
         SSG = SG.subgraph([6, 7])
         assert_equal(list(SSG), [6])
         # subgraph-subgraph chain is short-cut in base class method
         assert_is(SSG._graph, G)
예제 #19
0
 def subtree(self, G, k):
     H = copy.deepcopy(G)
     path_to_parent = [(j, k) for j in H if G.has_edge(j, k) and j <= k]
     H.remove_edges_from(path_to_parent)
     conn_comp = nx.connected_components(H)
     node = list(filter(lambda x: k in x, conn_comp))[0]
     node_sorted = sorted(node)
     subtree = nx.induced_subgraph(H, node_sorted)
     return subtree
예제 #20
0
def cut_edges(G, T, e):
    T.remove_edges_from([e])
    components = list(nx.connected_components(T))
    T.add_edges_from([e])
    A = components[0]
    B = components[1]
    G_A = nx.induced_subgraph(G, A)
    G_B = nx.induced_subgraph(G, B)
    edges_of_G = list(G.edges())
    for x in list(G_A.edges()):
        if x in edges_of_G:
            edges_of_G.remove(x)
        if (x[1], x[0]) in edges_of_G:
            edges_of_G.remove((x[1], x[0]))
    for x in list(G_B.edges()):
        if x in edges_of_G:
            edges_of_G.remove(x)
        if (x[1], x[0]) in edges_of_G:
            edges_of_G.remove((x[1], x[0]))
    return edges_of_G
예제 #21
0
 def test_subgraph_of_subgraph(self):
     SGv = nx.subgraph(self.G, range(3, 7))
     SDGv = nx.subgraph(self.DG, range(3, 7))
     SMGv = nx.subgraph(self.MG, range(3, 7))
     SMDGv = nx.subgraph(self.MDG, range(3, 7))
     for G in self.graphs + [SGv, SDGv, SMGv, SMDGv]:
         SG = nx.induced_subgraph(G, [4, 5, 6])
         assert list(SG) == [4, 5, 6]
         SSG = SG.subgraph([6, 7])
         assert list(SSG) == [6]
         # subgraph-subgraph chain is short-cut in base class method
         assert SSG._graph is G
예제 #22
0
 def test_subgraph_of_subgraph(self):
     SGv = nx.subgraph(self.G, range(3, 7))
     SDGv = nx.subgraph(self.DG, range(3, 7))
     SMGv = nx.subgraph(self.MG, range(3, 7))
     SMDGv = nx.subgraph(self.MDG, range(3, 7))
     for G in self.graphs + [SGv, SDGv, SMGv, SMDGv]:
         SG = nx.induced_subgraph(G, [4, 5, 6])
         assert_equal(list(SG), [4, 5, 6])
         SSG = SG.subgraph([6, 7])
         assert_equal(list(SSG), [6])
         # subgraph-subgraph chain is short-cut in base class method
         assert_is(SSG._graph, G)
예제 #23
0
def directed_induced_subgraph(graph, source: str, target: str):
    """
    Induced subgraph on edges along shortest paths between source
    and target. networkx.exception.NetworkXNoPath if no path
    """
    try:
        shortest_paths = all_shortest_paths(graph, source, target)
        edges = edges_on_paths(shortest_paths)
        subgraph = graph.edge_subgraph(edges)
    except NetworkXNoPath:
        raise
    if source == target:
        subgraph = nx.induced_subgraph(graph, source)
    return subgraph
예제 #24
0
    def test_subgraph_order(self):
        G = self.G
        G_sub = G.subgraph([1, 2, 3])
        assert_equals(list(G.nodes), list(G_sub.nodes))
        assert_equals(list(G.edges), list(G_sub.edges))
        assert_equals(list(G.pred[3]), list(G_sub.pred[3]))
        assert_equals([2, 1], list(G_sub.pred[3]))
        assert_equals([], list(G_sub.succ[3]))

        G_sub = nx.induced_subgraph(G, [1, 2, 3])
        assert_equals(list(G.nodes), list(G_sub.nodes))
        assert_equals(list(G.edges), list(G_sub.edges))
        assert_equals(list(G.pred[3]), list(G_sub.pred[3]))
        assert_equals([2, 1], list(G_sub.pred[3]))
        assert_equals([], list(G_sub.succ[3]))
예제 #25
0
    def test_subgraph_order(self):
        G = self.G
        G_sub = G.subgraph([1, 2, 3])
        assert list(G.nodes) == list(G_sub.nodes)
        assert list(G.edges) == list(G_sub.edges)
        assert list(G.pred[3]) == list(G_sub.pred[3])
        assert [2, 1] == list(G_sub.pred[3])
        assert [] == list(G_sub.succ[3])

        G_sub = nx.induced_subgraph(G, [1, 2, 3])
        assert list(G.nodes) == list(G_sub.nodes)
        assert list(G.edges) == list(G_sub.edges)
        assert list(G.pred[3]) == list(G_sub.pred[3])
        assert [2, 1] == list(G_sub.pred[3])
        assert [] == list(G_sub.succ[3])
def all_license_subgraphs(g, licenses, quota=1, proportion=0):
    """Takes a graph and returns the subgraphs induced by different 
    licenses types.
    
    Parameters:
    g: either a gt.Graph or a nx.Graph
    licenses: list of keys to be used for the return dict
    quota: an int for the minimum number of licenses of a given type to appear
        in that licenses subgraph
    proportion: a float for the proportion of licenses on the domain that should
        be the given license type
    
    Returns:
    a dict mapping string license names to subgraphs
    """
    if isinstance(g, gt.Graph):
        subgraph_by_license = dict()
        for license in licenses:
            nodes = g.new_vp('bool')
            for v in g.vertices():
                cc_licenses = g.vp['cc_licenses'][v]
                if isinstance(cc_licenses, dict):
                    total_licenses = sum(cc_licenses.values())
                    if (license in cc_licenses and
                            cc_licenses[license] >= proportion * total_licenses
                            and cc_licenses[license] >= quota):
                        nodes[v] = True
                else:
                    nodes[v] = False
            subgraph_by_license[license] = gt.GraphView(g, vfilt=nodes)
        return subgraph_by_license
    elif isinstance(g, nx.Graph):
        subgraph_by_license = dict()
        for license in licenses:
            nodes = set()
            for v, data in g.nodes(data=True):
                cc_licenses = data['cc_licenses']
                if isinstance(cc_licenses, dict):
                    total_licenses = sum(cc_licenses.values())
                    if (license in cc_licenses and
                            cc_licenses[license] >= proportion * total_licenses
                            and cc_licenses[license] >= quota):
                        nodes.add(v)
            subgraph_by_license[license] = nx.induced_subgraph(g, nodes)
        return subgraph_by_license
    else:
        raise TypeError('graph format not recognized, must be nx or gt')
예제 #27
0
def measure_paths(row,
                  vocab,
                  node_from,
                  node_to,
                  avoiding,
                  avoiding_property=1):

    graph = nx.Graph()

    def l(j):
        return vocab.inverse_lookup(j)

    only_using_nodes = [
        l(i[0]) for i in row["kb_nodes"] if l(i[avoiding_property]) != avoiding
    ] + [node_from, node_to]

    for i in row["kb_nodes"]:
        graph.add_node(l(i[0]), attr_dict={"body": [l(j) for j in i]})

    for id_a, connections in enumerate(
            row["kb_adjacency"][:row["kb_nodes_len"]]):
        for id_b, connected in enumerate(connections[:row["kb_nodes_len"]]):
            if connected:
                node_a = row["kb_nodes"][id_a]
                node_b = row["kb_nodes"][id_b]
                edge = (l(node_a[0]), l(node_b[0]))
                graph.add_edge(*edge)

    induced_subgraph = nx.induced_subgraph(graph, only_using_nodes)

    try:
        shortest_path_avoiding = len(
            nx.shortest_path(induced_subgraph, node_from, node_to)) - 2
    except:
        shortest_path_avoiding = None
        pass

    try:
        shortest_path = len(nx.shortest_path(graph, node_from, node_to)) - 2
    except:
        shortest_path = None
        pass

    return {
        "shortest_path": shortest_path,
        "shortest_path_avoiding": shortest_path_avoiding,
    }
def restrict_graph_by_property(g, prop):
    """Takes a DiGraph and returns the induced subgraph view for nodes that have
    the given property.

    Parameters:
    g: networkx DiGraph
    prop: boolean function that takes in (node, data)

    Returns:
    a networkx subgraph view for the induced subgraph
    """
    if not isinstance(g, nx.Graph):
        raise TypeError('not a networkx graph')
    subgraph_nodes = []
    for node_id, data in g.nodes(data=True):
        if prop(node_id, data):
            subgraph_nodes.append(node_id)
    return nx.induced_subgraph(g, subgraph_nodes)
예제 #29
0
def remove_edges_map(graph,tree,edge_list):
    '''This is the map that produces a partition from a tree and a list of edges
    
    :graph: the graph to be partitioned
    :tree: a chosen spanning tree on the graph
    :edge_list: a list of edges of the tree
    
    returns list of subgraphs induced by the components of the forest
    obtained by removing 'edge_list edges from  tree
    
    these correspond to the 'districts'

    '''
    tree.remove_edges_from(edge_list)
    components = list(nx.connected_components(tree.to_undirected()))
    tree.add_edges_from(edge_list)
    subgraphs = [nx.induced_subgraph(graph, subtree) for subtree in components]
    #This is expensive - TODO in case of error
    return subgraphs
예제 #30
0
    def _parse_loops_from_graph(self, graph):
        """
        Return all Loop instances that can be extracted from a graph.

        :param graph:   The graph to analyze.

        :return:        A list of all the Loop instances that were found in the graph.
        """
        outtop = []
        outall = []
        for subg in ( networkx.induced_subgraph(graph, nodes).copy() for nodes in networkx.strongly_connected_components(graph)):
            if len(subg.nodes()) == 1:
                if len(list(subg.successors(list(subg.nodes())[0]))) == 0:
                    continue
            thisloop, allloops = self._parse_loop_graph(subg, graph)
            if thisloop is not None:
                outall += allloops
                outtop.append(thisloop)
        return outtop, outall
예제 #31
0
def main():
    """ Reads in a graph and prints an approximate TSP tour """

    graph_file_path = sys.argv[1]

    input_graph = nx.read_weighted_edgelist(graph_file_path)

    # Compute an MST for G
    mst = nx.minimum_spanning_tree(input_graph)

    # Compute the subgraph in G induced by odd-degree vertices of the MST
    # Find a minimum-weight matching in this graph

    odd_verts = list(filter(lambda v: mst.degree(v) % 2 == 1, list(mst.nodes)))
    odd_induced_graph = nx.induced_subgraph(input_graph, odd_verts).copy()

    # Need to flip the edge weights since networkx only has a max-weight matching function
    orig_edges = list(odd_induced_graph.edges.items())
    max_weight = max(orig_edges,
                     key=lambda pair: pair[1]['weight'])[1]['weight']

    # subtract the max edge weight from every edge
    flipped_edges = list(map(lambda pair: \
            (pair[0][0], pair[0][1], max_weight - pair[1]['weight']), orig_edges))
    odd_induced_graph.add_weighted_edges_from(flipped_edges)
    matching = nx.max_weight_matching(odd_induced_graph, maxcardinality=True)

    # Union the MST with the matching to get an Eulerian multigraph
    # We can forget the weights at this point

    augmented_mst = nx.MultiGraph()
    augmented_mst.add_edges_from(mst.edges)
    augmented_mst.add_edges_from(matching)

    # Compute an Eulerian circuit of the augmented MST and shortcut if necessary
    tour_nodes = [u for u, v in nx.eulerian_circuit(augmented_mst)]
    final_tour = []
    for node in tour_nodes:
        if node not in final_tour:
            final_tour.append(node)
    final_tour.append(final_tour[0])

    print("Approximate TSP Tour:", final_tour)
예제 #32
0
파일: graph.py 프로젝트: eculicny/snowshu
    def get_connected_subgraphs(self) -> tuple:
        """ Generates the set of (weakly) connected components of the object's graph

            Returns:
                tuple of connected subgraphs of the original processing graph
        """

        if not isinstance(self.graph, networkx.Graph):
            raise ValueError('Graph must be built before SnowShuGraph can get graphs from it.')

        dags = [networkx.induced_subgraph(self.graph, bunch)
                for bunch in networkx.weakly_connected_components(self.graph)]

        # set the views flag
        for dag in dags:
            dag.contains_views = False
            for relation in dag.nodes:
                dag.contains_views = any((dag.contains_views, relation.is_view,))

        return tuple(dags)
def children(H_nodes, G):
    #returns the list of all children of subgraph H in graph G
    #In the tree described in the comments above
    N = neighbors(H_nodes, G)

    #input H as a list of nodes
    admissable_additions = []
    for n in N:
        H_nodes.add(n)
        candidate_child = nx.induced_subgraph(G, H_nodes)
        H_nodes.remove(n)
        P = parent(candidate_child)
        if P == H_nodes:
            admissable_additions.append(n)
    admissable_children = []
    for n in admissable_additions:
        H_nodes.add(n)
        admissable_children.append(copy.deepcopy(H_nodes))
        H_nodes.remove(n)
    return admissable_children
예제 #34
0
def run_dgp(sz, p, sg_sz, subgraph, write=False, writer=None):
    """
    An implementation of the algorithm of Dekel, Gurel-Gurevich and Peres for clique recovery
    using degree-based measurements.
    """
    graphs, all_labels = graphs_loader(sz, p, sg_sz, subgraph)
    remaining_subgraph_vertices = []

    start_time = time.time()
    for graph, labels in zip(graphs, all_labels):
        alpha, beta, eta = 0.8, 2.3, 1.2
        eps_4 = 1. / alpha - 1e-8
        t = eps_4 * np.log(sz) / np.log(
            np.power(dgp_rho(alpha, beta, eta, sg_sz / np.sqrt(sz)), 2) /
            dgp_tau(alpha, beta))
        t = np.floor(t)
        v_i = [v for v in range(len(labels))]
        # First Stage #
        for _ in range(int(t)):
            s_i = dgp_choose_s_i(v_i, alpha)
            s_i_tilde = dgp_get_si_tilde(graph, s_i, eta)
            new_vi = dgp_get_vi(graph, v_i, s_i, s_i_tilde, beta)
            v_i = new_vi
        # Second Stage #
        g_t = nx.induced_subgraph(graph, v_i)
        k_tilde = dgp_get_k_tilde(g_t, alpha, beta, eta, t,
                                  sg_sz / np.sqrt(sz), sg_sz)
        # INCLUDING the third, extension stage #
        k_tag = dgp_get_k_tag(k_tilde, graph)
        k_star = dgp_get_k_star(k_tag, graph, sg_sz)
        remaining_subgraph_vertices.append(
            len([v for v in k_star if labels[v]]))
    total_time = time.time() - start_time
    if write:
        assert writer is not None
        writer.writerow([
            str(val) for val in
            [sz, sg_sz,
             np.round(np.mean(remaining_subgraph_vertices), 4)]
        ])
    return total_time, np.mean(remaining_subgraph_vertices)
예제 #35
0
 def test_full_graph(self):
     G = self.K3
     H = nx.induced_subgraph(G, [0, 1, 2, 5])
     assert_equal(H.name, G.name)
     self.graphs_equal(H, G)
     self.same_attrdict(H, G)
예제 #36
0
 def test_subgraph_toundirected(self):
     SG = nx.induced_subgraph(self.G, [4, 5, 6])
     SSG = SG.to_undirected()
     assert_equal(list(SSG), [4, 5, 6])
     assert_equal(sorted(SSG.edges), [(4, 5), (5, 6)])