Python networkx.subgraph() Examples

The following are 30 code examples of networkx.subgraph(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def hub_dominance(graph, communities, **kwargs):
    """Hub dominance.

    The hub dominance of a community is defined as the ratio of the degree of its most connected node w.r.t. the theoretically maximal degree within the community.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.hub_dominance(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: max([x[1] for x in
                                                      list(nx.degree(nx.subgraph(graph, coms)))]) / (len(coms) - 1),
                             **kwargs) 
Example #2
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def avg_distance(graph, communities, **kwargs):
    """Average distance.

    The average distance of a community is defined average path length across all possible pair of nodes composing it.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.avg_distance(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: nx.average_shortest_path_length(nx.subgraph(graph, coms)), **kwargs) 
Example #3
Source File: __init__.py    From EDeN with MIT License 6 votes vote down vote up
def _max_common_subgraph(GA, GB, pairings):
    matches = dict([(i, j) for i, j in enumerate(pairings)])
    node_ids = []
    for i, j in GA.edges():
        ii = matches[i]
        jj = matches[j]
        li = GA.node[i]['label']
        lii = GB.node[ii]['label']
        lj = GA.node[j]['label']
        ljj = GB.node[jj]['label']
        if ((ii, jj) in GB.edges() or (jj, ii) in GB.edges()) and li == lii and lj == ljj:
            node_ids.append(ii)
            node_ids.append(jj)
    G = nx.subgraph(GB, node_ids)
    cc = nx.connected_components(G)
    return cc, G 
Example #4
Source File: test_isomorphvf2.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_multiple():
    # Verify that we can use the graph matcher multiple times
    edges = [('A','B'),('B','A'),('B','C')]
    for g1,g2 in [(nx.Graph(),nx.Graph()), (nx.DiGraph(),nx.DiGraph())]:
        g1.add_edges_from(edges)
        g2.add_edges_from(edges)
        g3 = nx.subgraph(g2, ['A','B'])
        if not g1.is_directed():
            gmA = iso.GraphMatcher(g1,g2)
            gmB = iso.GraphMatcher(g1,g3)
        else:
            gmA = iso.DiGraphMatcher(g1,g2)
            gmB = iso.DiGraphMatcher(g1,g3)
        assert_true(gmA.is_isomorphic())
        g2.remove_node('C')
        assert_true(gmA.subgraph_is_isomorphic())
        assert_true(gmB.subgraph_is_isomorphic())
#        for m in [gmB.mapping, gmB.mapping]:
#            assert_true(m['A'] == 'A')
#            assert_true(m['B'] == 'B')
#            assert_true('C' not in m) 
Example #5
Source File: test_isomorphvf2.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multiple():
    # Verify that we can use the graph matcher multiple times
    edges = [('A', 'B'), ('B', 'A'), ('B', 'C')]
    for g1, g2 in [(nx.Graph(), nx.Graph()), (nx.DiGraph(), nx.DiGraph())]:
        g1.add_edges_from(edges)
        g2.add_edges_from(edges)
        g3 = nx.subgraph(g2, ['A', 'B'])
        if not g1.is_directed():
            gmA = iso.GraphMatcher(g1, g2)
            gmB = iso.GraphMatcher(g1, g3)
        else:
            gmA = iso.DiGraphMatcher(g1, g2)
            gmB = iso.DiGraphMatcher(g1, g3)
        assert_true(gmA.is_isomorphic())
        g2.remove_node('C')
        if not g1.is_directed():
            gmA = iso.GraphMatcher(g1, g2)
        else:
            gmA = iso.DiGraphMatcher(g1, g2)
        assert_true(gmA.subgraph_is_isomorphic())
        assert_true(gmB.subgraph_is_isomorphic())
#        for m in [gmB.mapping, gmB.mapping]:
#            assert_true(m['A'] == 'A')
#            assert_true(m['B'] == 'B')
#            assert_true('C' not in m) 
Example #6
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def avg_transitivity(graph, communities, **kwargs):
    """Average transitivity.

    The average transitivity of a community is defined the as the average clustering coefficient of its nodes w.r.t. their connection within the community itself.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.avg_transitivity(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: nx.average_clustering(nx.subgraph(graph, coms)),
                             **kwargs) 
Example #7
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def scaled_density(graph, communities, **kwargs):
    """Scaled density.

    The scaled density of a community is defined as the ratio of the community density w.r.t. the complete graph density.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.scaled_density(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: nx.density(nx.subgraph(graph, coms)) / nx.density(graph), **kwargs) 
Example #8
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __quality_indexes(graph, communities, scoring_function, summary=True):
    """

    :param graph: NetworkX/igraph graph
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-communitys ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    """

    graph = convert_graph_formats(graph, nx.Graph)
    values = []
    for com in communities.communities:
        community = nx.subgraph(graph, com)
        if scoring_function in [pq.PartitionQuality.average_internal_degree, pq.PartitionQuality.internal_edge_density,
                                pq.PartitionQuality.triangle_participation_ratio, pq.PartitionQuality.edges_inside,
                                pq.PartitionQuality.fraction_over_median_degree]:
            values.append(scoring_function(community))
        else:
            values.append(scoring_function(graph, community))

    if summary:
        return FitnessResult(min=min(values), max=max(values), score=np.mean(values), std=np.std(values))
    return values 
Example #9
Source File: vis_utils.py    From nucleus7 with Mozilla Public License 2.0 6 votes vote down vote up
def _draw_click_instructions(subplot: plt_axes.Subplot,
                             doubleclick=True, singleclck=True):
    instruction_texts = list()
    instruction_texts.append("Interactive instructions:")
    if singleclck:
        instruction_texts.append(
            "Click once on nucleotide to see its information")
    if doubleclick:
        instruction_texts.append(
            "Make double clock on nucleotide to cut the subgraph with its "
            "incoming and outgoing nucleotides in new figure")

    instruction_text = "\n".join(instruction_texts)
    subplot.annotate(
        instruction_text, (0.5, 0.01), xycoords="figure fraction",
        ha="center", va="bottom", ma="left",
        bbox=dict(facecolor='white', edgecolor='blue', pad=5.0)) 
Example #10
Source File: vis_utils.py    From nucleus7 with Mozilla Public License 2.0 6 votes vote down vote up
def _create_subgraph_plot(event, dna_helix_graph: nx.DiGraph):
    mouseevent = event.mouseevent
    if not mouseevent.dblclick or mouseevent.button != 1:
        return

    logger = logging.getLogger(__name__)
    nucleotide_name = event.artist.get_label().split(":")[-1]
    nucleotide = _get_nucleotide_by_name(nucleotide_name, dna_helix_graph)
    logger.info("Create subgraph plot for %s", nucleotide_name)
    figure, subplot = _create_figure_with_subplot()
    figure.suptitle("Subgraph of nucleotide {}".format(nucleotide_name))

    nucleotide_with_neighbors_subgraph = _get_nucleotide_subgraph(
        dna_helix_graph, nucleotide)
    draw_dna_helix_on_subplot(
        nucleotide_with_neighbors_subgraph, subplot, verbosity=1)
    _draw_click_instructions(subplot, doubleclick=False)
    plt.draw()
    logger.info("Done!") 
Example #11
Source File: dag.py    From sos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def regenerate_target(self, target: BaseTarget):
        if target in self._all_output_files:
            for node in self._all_output_files[target]:
                if node._status == 'completed':
                    if isinstance(target, sos_step):
                        if env.config['error_mode'] == 'ignore':
                            raise RuntimeError(
                                f'Target {target} that was failed to generate is needed to continue.'
                            )
                        else:
                            raise RuntimeError(
                                f'Completed target {target} is being re-executed. Please report this bug to SoS developers.'
                            )
                    else:
                        env.logger.info(
                            f'Re-running {node._node_id} to generate {target}')
                        node._status = None
            return True
        else:
            return False

    # def subgraph_from(self, targets: sos_targets):
    #     '''Trim DAG to keep only nodes that produce targets'''
    #     if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
    #         env.log_to_file('DAG', 'create subgraph')
    #     # first, find all nodes with targets
    #     subnodes = []
    #     for node in self.nodes():
    #         if node._output_targets.valid() and any(
    #                 x in node._output_targets for x in targets):
    #             subnodes.append(node)
    #     #
    #     ancestors = set()
    #     for node in subnodes:
    #         ancestors |= nx.ancestors(self, node)
    #     return SoS_DAG(nx.subgraph(self, subnodes + list(ancestors))) 
Example #12
Source File: test_graphviews.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subgraph_edgesubgraph_toundirected(self):
        G = self.G.copy()
        SG = G.subgraph([4, 5, 6])
        SSG = SG.edge_subgraph([(4, 5), (5, 4)])
        USSG = SSG.to_undirected()
        assert_equal(list(USSG), [4, 5])
        assert_equal(sorted(USSG.edges), [(4, 5)]) 
Example #13
Source File: test_graphviews.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_copy_disubgraph(self):
        G = self.DG.copy()
        SG = G.subgraph([4, 5, 6])
        CSG = SG.copy(as_view=True)
        DCSG = SG.copy(as_view=False)
        assert_true(hasattr(CSG, '_graph'))  # is a view
        assert_false(hasattr(DCSG, '_graph'))  # not a view 
Example #14
Source File: test_graphviews.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_copy_multidisubgraph(self):
        G = self.MDG.copy()
        SG = G.subgraph([4, 5, 6])
        CSG = SG.copy(as_view=True)
        DCSG = SG.copy(as_view=False)
        assert_true(hasattr(CSG, '_graph'))  # is a view
        assert_false(hasattr(DCSG, '_graph'))  # not a view 
Example #15
Source File: __init__.py    From EDeN with MIT License 5 votes vote down vote up
def max_common_subgraph(GA, GB, pairings):
    cc, G = _max_common_subgraph(GA, GB, pairings)
    len_ccs = [(len(ci), ci) for ci in cc]
    if not len_ccs:
        return None
    n_cc, max_cc_ids = max(len_ccs)
    max_cc = nx.subgraph(G, max_cc_ids)
    return max_cc 
Example #16
Source File: test_graphviews.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_copy_multisubgraph(self):
        G = self.MG.copy()
        SG = G.subgraph([4, 5, 6])
        CSG = SG.copy(as_view=True)
        DCSG = SG.copy(as_view=False)
        assert_true(hasattr(CSG, '_graph'))  # is a view
        assert_false(hasattr(DCSG, '_graph'))  # not a view 
Example #17
Source File: test_graphviews.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subclass(self):
        class MyGraph(nx.DiGraph):
            def my_method(self):
                return "me"
            def to_directed_class(self):
                return MyGraph()

        for origG in self.graphs:
            G = MyGraph(origG)
            SG = G.subgraph([4, 5, 6])
            H = SG.copy()
            assert_equal(SG.my_method(), "me")
            assert_equal(H.my_method(), "me")
            assert_false(3 in H or 3 in SG) 
Example #18
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #19
Source File: test_isomorphvf2.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subgraph(self):
        # A is the subgraph
        # B is the full graph
        head, tail = os.path.split(__file__)
        subgraph = self.create_graph(os.path.join(head, 'si2_b06_m200.A99'))
        graph = self.create_graph(os.path.join(head, 'si2_b06_m200.B99'))
        gm = iso.GraphMatcher(graph, subgraph)
        assert_true(gm.subgraph_is_isomorphic()) 
Example #20
Source File: test_isomorphvf2.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_subgraph(self):
        # A is the subgraph
        # B is the full graph
        head, tail = os.path.split(__file__)
        subgraph = self.create_graph(os.path.join(head, 'si2_b06_m200.A99'))
        graph = self.create_graph(os.path.join(head, 'si2_b06_m200.B99'))
        gm = iso.GraphMatcher(graph, subgraph)
        assert_true(gm.subgraph_is_isomorphic()) 
Example #21
Source File: refex.py    From RolX with GNU General Public License v3.0 5 votes vote down vote up
def inducer(graph, node):
    nebs = nx.neighbors(graph, node)
    sub_nodes = nebs + [node]
    sub_g = nx.subgraph(graph, sub_nodes)
    out_counts = np.sum(map(lambda x: len(nx.neighbors(graph,x)), sub_nodes))
    return sub_g, out_counts, nebs 
Example #22
Source File: refex.py    From RolX with GNU General Public License v3.0 5 votes vote down vote up
def create_features(self):
        state_printer("Basic node level feature extraction and induced subgraph creation started.")
        self.basic_stat_extractor()
        state_printer("Recursion started.")
        self.do_recursions()
        state_printer("Binary feature quantization started.")
        self.binarize()
        state_printer("Saving the raw features.")
        self.dump_to_disk()
        state_printer("The number of extracted features is: " + str(self.new_features.shape[1]) + ".") 
Example #23
Source File: test_graphviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_copy_multidisubgraph(self):
        G = self.MDG.copy()
        SG = G.subgraph([4, 5, 6])
        CSG = SG.copy(as_view=True)
        DCSG = SG.copy(as_view=False)
        assert_equal(CSG.__class__.__name__, 'MultiDiGraphView')
        assert_equal(DCSG.__class__.__name__, 'MultiDiGraph') 
Example #24
Source File: test_isomorphvf2.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_subgraph(self):
        g1 = nx.Graph()
        g2 = nx.Graph()
        g1.add_edges_from(self.g1edges)
        g2.add_edges_from(self.g2edges)
        g3 = g2.subgraph([1, 2, 3, 4])
        gm = iso.GraphMatcher(g1, g3)
        assert_true(gm.subgraph_is_isomorphic()) 
Example #25
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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) 
Example #26
Source File: test_graphviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_copy_multisubgraph(self):
        G = self.MGv.copy()
        SG = G.subgraph([4, 5, 6])
        CSG = SG.copy(as_view=True)
        DCSG = SG.copy(as_view=False)
        assert_equal(CSG.__class__.__name__, 'MultiGraphView')
        assert_equal(DCSG.__class__.__name__, 'MultiGraph') 
Example #27
Source File: test_graphviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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) 
Example #28
Source File: test_graphviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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) 
Example #29
Source File: test_graphviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_reverse_subgraph_toundirected(self):
        G = self.DG.reverse(copy=False)
        SG = G.subgraph([4, 5, 6])
        SSG = SG.to_undirected()
        assert_equal(list(SSG), [4, 5, 6])
        assert_equal(sorted(SSG.edges), [(4, 5), (5, 6)]) 
Example #30
Source File: test_graphviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_subgraph_edgesubgraph_toundirected(self):
        G = self.G.copy()
        SG = G.subgraph([4, 5, 6])
        SSG = SG.edge_subgraph([(4, 5), (5, 4)])
        USSG = SSG.to_undirected()
        assert_equal(list(USSG), [4, 5])
        assert_equal(sorted(USSG.edges), [(4, 5)])