예제 #1
0
def test_white_harary_paper():
    # Figure 1b white and harary (2001)
    # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4, 7):
        G.add_edge(0, i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order() - 1)
    for i in range(7, 10):
        G.add_edge(0, i)
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        errmsg = f"Assertion failed in function: {flow_func.__name__}"
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert 3 == len(edge_cut), errmsg
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert not nx.is_connected(H), errmsg
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert {0} == node_cut, errmsg
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert not nx.is_connected(H), errmsg
예제 #2
0
def test_white_harary_paper():
    # Figure 1b white and harary (2001)
    # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4, 7):
        G.add_edge(0, i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order() - 1)
    for i in range(7, 10):
        G.add_edge(0, i)
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(set([0]), node_cut, msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
예제 #3
0
    def process(self, batch, request):

        outputs = gp.Batch()

        gt_graph = nx.Graph()
        mst_graph = nx.Graph()

        for block, block_specs in self.specs.items():
            ground_truth_key = block_specs["ground_truth"][0]
            mst_key = block_specs["mst_pred"][0]
            block_gt_graph = batch[ground_truth_key].to_nx_graph(
            ).to_undirected()
            block_mst_graph = batch[mst_key].to_nx_graph().to_undirected()
            gt_graph = nx.disjoint_union(gt_graph, block_gt_graph)
            mst_graph = nx.disjoint_union(mst_graph, block_mst_graph)

        for node, attrs in gt_graph.nodes.items():
            attrs["id"] = node
        for node, attrs in mst_graph.nodes.items():
            attrs["id"] = node

        outputs[self.gt] = gp.Graph.from_nx_graph(
            gt_graph,
            gp.GraphSpec(roi=gp.Roi((None, ) * 3, (None, ) * 3),
                         directed=False))
        outputs[self.mst] = gp.Graph.from_nx_graph(
            mst_graph,
            gp.GraphSpec(roi=gp.Roi((None, ) * 3, (None, ) * 3),
                         directed=False),
        )
        return outputs
예제 #4
0
def graph_example_1():
    G = nx.convert_node_labels_to_integers(nx.grid_graph([5, 5]),
                                           label_attribute='labels')
    rlabels = nx.get_node_attributes(G, 'labels')
    labels = {v: k for k, v in rlabels.items()}

    for nodes in [(labels[(0, 0)], labels[(1, 0)]),
                  (labels[(0, 4)], labels[(1, 4)]),
                  (labels[(3, 0)], labels[(4, 0)]),
                  (labels[(3, 4)], labels[(4, 4)])]:
        new_node = G.order() + 1
        # Petersen graph is triconnected
        P = nx.petersen_graph()
        G = nx.disjoint_union(G, P)
        # Add two edges between the grid and P
        G.add_edge(new_node + 1, nodes[0])
        G.add_edge(new_node, nodes[1])
        # K5 is 4-connected
        K = nx.complete_graph(5)
        G = nx.disjoint_union(G, K)
        # Add three edges between P and K5
        G.add_edge(new_node + 2, new_node + 11)
        G.add_edge(new_node + 3, new_node + 12)
        G.add_edge(new_node + 4, new_node + 13)
        # Add another K5 sharing a node
        G = nx.disjoint_union(G, K)
        nbrs = G[new_node + 10]
        G.remove_node(new_node + 10)
        for nbr in nbrs:
            G.add_edge(new_node + 17, nbr)
        G.add_edge(new_node + 16, new_node + 5)

    G.name = 'Example graph for connectivity'
    return G
예제 #5
0
    def generate_map(map_size, dim_of_bases, num_bases, buff_size, buff_E,
                     size_connectors):

        main = Map.generate_delaunay_main(map_size)
        full_G = main
        player_pos = {0: 'N', 1: 'S', 2: 'E', 3: 'W'}
        for player in range(num_bases):
            player_base = Map.generate_base(dim_of_bases, dim_of_bases, player,
                                            player_pos[player])
            player_buffer = Map.generate_buffer_zone(buff_size, buff_E, player,
                                                     player_pos[player])
            full_base = nx.disjoint_union(player_base, player_buffer)
            full_G = nx.disjoint_union(full_G, full_base)
        data_nodes = {}
        data_nodes['main'] = []
        data_nodes['base_1'] = []
        data_nodes['base_2'] = []
        data_nodes['base_3'] = []
        data_nodes['base_0'] = []
        data_nodes['buff_1'] = []
        data_nodes['buff_2'] = []
        data_nodes['buff_3'] = []
        data_nodes['buff_0'] = []
        for node in full_G.nodes():
            node_type = full_G.node[node]['type']
            if node_type == 'main':
                data_nodes['main'].append(node)
            for i in range(4):
                if node_type == ('base', i):
                    data_nodes['base_' + str(i)].append(node)
                if node_type == ('buffer', i):
                    data_nodes['buff_' + str(i)].append(node)

        return full_G, data_nodes
예제 #6
0
    def from_cr(cls, cr, HASH):
        _rdkit_config = rdkit_config(reaction_center=cr.ReactingAtomsMN,
                                     reactant_or_product='reactant')
        reaction = HashGraph.from_rdkit(cr.reactants[0], '1',
                                        _rdkit_config).to_networkx()
        for reactant in cr.reactants[1:]:
            g = HashGraph.from_rdkit(reactant, '1', _rdkit_config).\
                to_networkx()
            reaction = nx.disjoint_union(reaction, g)

        _rdkit_config = rdkit_config(reaction_center=cr.ReactingAtomsMN,
                                     reactant_or_product='product')
        for product in cr.products:
            g = HashGraph.from_rdkit(product, '1', _rdkit_config).\
                to_networkx()
            reaction = nx.disjoint_union(reaction, g)

        g = _from_networkx(cls, reaction)
        g.hash = HASH
        if g.nodes.to_pandas()['ReactingCenter'].max() <= 0:
            raise RuntimeError(f'No reacting atoms are found in reactants: '
                               f'{cr.reaction_smarts}')
        if g.nodes.to_pandas()['ReactingCenter'].min() >= 0:
            raise RuntimeError(f'No reacting atoms are found in products: '
                               f'{cr.reaction_smarts}')
        return g
예제 #7
0
    def from_reaction_template(cls, template_smarts):
        template = ReactionTemplate(template_smarts)
        _rdkit_config = rdkit_config(reaction_center=template.ReactingAtomsMN,
                                     reactant_or_product='reactant',
                                     IsSanitized=False,
                                     set_morgan_identifier=False)
        reaction = Graph.from_rdkit(template.reactants[0],
                                    _rdkit_config).to_networkx()
        for reactant in template.reactants[1:]:
            g = Graph.from_rdkit(reactant, _rdkit_config).to_networkx()
            reaction = nx.disjoint_union(reaction, g)

        _rdkit_config = rdkit_config(reaction_center=template.ReactingAtomsMN,
                                     reactant_or_product='product',
                                     IsSanitized=False,
                                     set_morgan_identifier=False)
        for product in template.products:
            g = Graph.from_rdkit(product, _rdkit_config).to_networkx()
            reaction = nx.disjoint_union(reaction, g)

        g = _from_networkx(cls, reaction)
        if g.nodes.to_pandas()['ReactingCenter'].max() <= 0:
            raise RuntimeError(f'No reacting atoms are found in reactants: '
                               f'{template_smarts}')
        if g.nodes.to_pandas()['ReactingCenter'].min() >= 0:
            raise RuntimeError(f'No reacting atoms are found in products: '
                               f'{template_smarts}')
        return g
예제 #8
0
def atlas6():
    """ Return the atlas of all connected graphs of 6 nodes or less.
        Attempt to check for isomorphisms and remove.
    """

    Atlas = graph_atlas_g()[0:208]  # 208
    # remove isolated nodes, only connected graphs are left
    U = nx.Graph()  # graph for union of all graphs in atlas
    for G in Atlas:
        zerodegree = [n for n in G if G.degree(n) == 0]
        for n in zerodegree:
            G.remove_node(n)
        U = nx.disjoint_union(U, G)

    # list of graphs of all connected components
    C = nx.connected_component_subgraphs(U)

    UU = nx.Graph()
    # do quick isomorphic-like check, not a true isomorphism checker
    nlist = []  # list of nonisomorphic graphs
    for G in C:
        # check against all nonisomorphic graphs so far
        if not iso(G, nlist):
            nlist.append(G)
            UU = nx.disjoint_union(UU, G)  # union the nonisomorphic graphs
    return UU
예제 #9
0
파일: local.py 프로젝트: fhaive/VOLTA
def __generate_motifs__(x=208):
    """ 
    Return the atlas of all connected graphs of 5 nodes or less.
    Uses networkx graph atlas, which returns all possible graphs with up to 7 nodes, based on https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_atlas.html

    Parameters:
        x (int): which motifs of the graph atlas are returned
    Returns:
        graph atlas: contains all possible graphs of specified size as shown in the graph atlas
    """

    #uses networkx graph atlas, which returns all possible graphs with up to 6 nodes
    #based on https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_atlas.html
    Atlas = graph_atlas_g()[0:x]
    # remove isolated nodes, only connected graphs are left
    U = nx.Graph()  # graph for union of all graphs in atlas
    for G in Atlas:
        zerodegree = [n for n in G if G.degree(n) == 0]
        for n in zerodegree:
            G.remove_node(n)
        U = nx.disjoint_union(U, G)

    # list of graphs of all connected components
    C = (U.subgraph(c) for c in nx.connected_components(U))

    UU = nx.Graph()
    # do quick isomorphic-like check, not a true isomorphism checker
    nlist = []  # list of nonisomorphic graphs
    for G in C:
        # check against all nonisomorphic graphs so far

        if not __iso__(G, nlist):
            nlist.append(G)
            UU = nx.disjoint_union(UU, G)  # union the nonisomorphic graphs
    return UU
예제 #10
0
def test_white_harary_paper():
    # Figure 1b white and harary (2001)
    # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4,7):
        G.add_edge(0,i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order()-1)
    for i in range(7,10):
        G.add_edge(0,i)
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(set([0]), node_cut, msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
    def _crossover(self, ga, gb):
        gs = []

        ga = nx.convert_node_labels_to_integers(ga)
        gb = nx.convert_node_labels_to_integers(gb)

        edges_a = self._get_valid_edges(ga, max_num=self.n_edges)
        edges_b = self._get_valid_edges(gb, max_num=self.n_edges)
        for ea in edges_a:
            for eb in edges_b:
                if ea is not None and eb is not None:
                    ia, ja = ea
                    ib, jb = eb
                    ibu, jbu = ib + len(ga), jb + len(ga)

                    gu0 = nx.disjoint_union(ga, gb)
                    self._swap_edge(gu0, (ia, ja), (ibu, jbu), mode=0)
                    components = list(nx.connected_components(gu0))
                    gs.extend([
                        nx.subgraph(gu0, component).copy()
                        for component in components
                    ])

                    gu1 = nx.disjoint_union(ga, gb)
                    self._swap_edge(gu1, (ia, ja), (ibu, jbu), mode=1)
                    components = list(nx.connected_components(gu1))
                    gs.extend([
                        nx.subgraph(gu1, component).copy()
                        for component in components
                    ])
        return gs
예제 #12
0
    def _init_graph(self, p1, p2):
        """ Returns an Apex Bridge graph where the first
        cluster is sampled from G(self._n1, P1) and the
        second sampled from G(self._n2, P2).
        """
        # Create a graph with only the apex
        apex_graph = nx.Graph()
        apex_graph.add_node(self._apex)

        # Create a graph with only the bridge
        bridge_graph = nx.Graph()
        bridge_graph.add_node(self._bridge)

        # Create the two cluster graphs
        g1 = nx.erdos_renyi_graph(self._n1, p1)
        g2 = nx.erdos_renyi_graph(self._n2, p2)

        # Create the final graph
        g = nx.disjoint_union(apex_graph, g1)
        g = nx.disjoint_union(g, g2)
        g = nx.disjoint_union(g, bridge_graph)

        # Connect the apex and bridge nodes
        for v in range(1, self._bridge + 1):
            g.add_edge(self._apex, v)

        # Connect the bridge to the two communities
        for v in self._cluster1:
            g.add_edge(self._bridge, v)
        for v in self._cluster2:
            g.add_edge(self._bridge, v)

        return g
예제 #13
0
def graph_example_1():
    G = nx.convert_node_labels_to_integers(nx.grid_graph([5, 5]),
                                           label_attribute='labels')
    rlabels = nx.get_node_attributes(G, 'labels')
    labels = {v: k for k, v in rlabels.items()}

    for nodes in [(labels[(0, 0)], labels[(1, 0)]),
                  (labels[(0, 4)], labels[(1, 4)]),
                  (labels[(3, 0)], labels[(4, 0)]),
                  (labels[(3, 4)], labels[(4, 4)])]:
        new_node = G.order() + 1
        # Petersen graph is triconnected
        P = nx.petersen_graph()
        G = nx.disjoint_union(G, P)
        # Add two edges between the grid and P
        G.add_edge(new_node + 1, nodes[0])
        G.add_edge(new_node, nodes[1])
        # K5 is 4-connected
        K = nx.complete_graph(5)
        G = nx.disjoint_union(G, K)
        # Add three edges between P and K5
        G.add_edge(new_node + 2, new_node + 11)
        G.add_edge(new_node + 3, new_node + 12)
        G.add_edge(new_node + 4, new_node + 13)
        # Add another K5 sharing a node
        G = nx.disjoint_union(G, K)
        nbrs = G[new_node + 10]
        G.remove_node(new_node + 10)
        for nbr in nbrs:
            G.add_edge(new_node + 17, nbr)
        G.add_edge(new_node + 16, new_node + 5)

    G.name = 'Example graph for connectivity'
    return G
def test_union_and_compose():
    K3 = nx.complete_graph(3)
    P3 = nx.path_graph(3)

    G1 = nx.DiGraph()
    G1.add_edge('A', 'B')
    G1.add_edge('A', 'C')
    G1.add_edge('A', 'D')
    G2 = nx.DiGraph()
    G2.add_edge('1', '2')
    G2.add_edge('1', '3')
    G2.add_edge('1', '4')

    G = nx.union(G1, G2)
    H = nx.compose(G1, G2)
    assert_edges_equal(G.edges(), H.edges())
    assert not G.has_edge('A', 1)
    pytest.raises(nx.NetworkXError, nx.union, K3, P3)
    H1 = nx.union(H, G1, rename=('H', 'G1'))
    assert (sorted(H1.nodes()) == [
        'G1A', 'G1B', 'G1C', 'G1D', 'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC',
        'HD'
    ])

    H2 = nx.union(H, G2, rename=("H", ""))
    assert (sorted(H2.nodes()) == [
        '1', '2', '3', '4', 'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'
    ])

    assert not H1.has_edge('NB', 'NA')

    G = nx.compose(G, G)
    assert_edges_equal(G.edges(), H.edges())

    G2 = nx.union(G2, G2, rename=('', 'copy'))
    assert (sorted(G2.nodes()) == [
        '1', '2', '3', '4', 'copy1', 'copy2', 'copy3', 'copy4'
    ])

    assert sorted(G2.neighbors('copy4')) == []
    assert sorted(G2.neighbors('copy1')) == ['copy2', 'copy3', 'copy4']
    assert len(G) == 8
    assert nx.number_of_edges(G) == 6

    E = nx.disjoint_union(G, G)
    assert len(E) == 16
    assert nx.number_of_edges(E) == 12

    E = nx.disjoint_union(G1, G2)
    assert sorted(E.nodes()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

    G = nx.Graph()
    H = nx.Graph()
    G.add_nodes_from([(1, {'a1': 1})])
    H.add_nodes_from([(1, {'b1': 1})])
    R = nx.compose(G, H)
    assert R.nodes == {1: {'a1': 1, 'b1': 1}}
    def _crossover(self, ga, gb):
        gs = []

        ga = nx.convert_node_labels_to_integers(ga)
        edges_a = self._get_valid_edges(ga, max_num=self.n_cycles, n_edges_per_cycle=self.n_edges_per_cycle)
        if edges_a is None:
            return gs
        edges_a = self._get_selected_edges(ga, edges_a, fraction=self.fraction)

        gb = nx.convert_node_labels_to_integers(gb)
        edges_b = self._get_valid_edges(gb, max_num=self.n_cycles, n_edges_per_cycle=self.n_edges_per_cycle)
        if edges_b is None:
            return gs
        edges_b = self._get_selected_edges(gb, edges_b, fraction=self.fraction)

        if edges_a is None or edges_b is None:
            return gs
        for ea in edges_a:
            for eb in edges_b:
                if ea is not None and eb is not None:
                    ia, ja = ea[0]
                    ib, jb = eb[0]
                    ibu, jbu = ib + len(ga), jb + len(ga)

                    ka, la = ea[1]
                    kb, lb = eb[1]
                    kbu, lbu = kb + len(ga), lb + len(ga)

                    gu0 = nx.disjoint_union(ga, gb)
                    self._swap_edge(gu0, (ia, ja), (ibu, jbu), mode=0)
                    self._swap_edge(gu0, (ka, la), (kbu, lbu), mode=0)
                    components = list(nx.connected_components(gu0))
                    gs.extend([nx.subgraph(gu0, component).copy() for component in components])

                    gu0 = nx.disjoint_union(ga, gb)
                    self._swap_edge(gu0, (ia, ja), (ibu, jbu), mode=0)
                    self._swap_edge(gu0, (ka, la), (kbu, lbu), mode=1)
                    components = list(nx.connected_components(gu0))
                    gs.extend([nx.subgraph(gu0, component).copy() for component in components])

                    gu1 = nx.disjoint_union(ga, gb)
                    self._swap_edge(gu1, (ia, ja), (ibu, jbu), mode=1)
                    self._swap_edge(gu1, (ka, la), (kbu, lbu), mode=1)
                    components = list(nx.connected_components(gu1))
                    gs.extend([nx.subgraph(gu1, component).copy() for component in components])

                    gu1 = nx.disjoint_union(ga, gb)
                    self._swap_edge(gu1, (ia, ja), (ibu, jbu), mode=1)
                    self._swap_edge(gu1, (ka, la), (kbu, lbu), mode=0)
                    components = list(nx.connected_components(gu1))
                    gs.extend([nx.subgraph(gu1, component).copy() for component in components])

        return gs
예제 #16
0
def test_white_harary1():
    # Figure 1b white and harary (2001)
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4, 7):
        G.add_edge(0, i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order() - 1)
    for i in range(7, 10):
        G.add_edge(0, i)
    assert_equal(1, approx.node_connectivity(G))
예제 #17
0
def test_white_harary1():
    # Figure 1b white and harary (2001)
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4,7):
        G.add_edge(0,i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order()-1)
    for i in range(7,10):
        G.add_edge(0,i)
    assert_equal(1, approx.node_connectivity(G))
예제 #18
0
def test_white_harary_1():
    # Figure 1b white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (vertex connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4, 7):
        G.add_edge(0, i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order() - 1)
    for i in range(7, 10):
        G.add_edge(0, i)
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(3, nx.edge_connectivity(G))
예제 #19
0
def test_white_harary_1():
    # Figure 1b white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (vertex connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4,7):
        G.add_edge(0,i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order()-1)
    for i in range(7,10):
        G.add_edge(0,i)
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(3, nx.edge_connectivity(G))
예제 #20
0
def test_generate_seq_graph():
    macro_str_A = "A:6:1:A-1."
    macro_str_B = "B:2:4:B-1."

    macros = {"A": MacroString(macro_str_A), "B": MacroString(macro_str_B)}

    seq_graph = generate_seq_graph(["A", "B", "A"], macros,
                                   ["0:1:2-0", "1:2:1-1"])
    graphA = macros["A"].gen_graph()
    graphB = macros["B"].gen_graph()

    ref_graph = nx.disjoint_union(graphA, graphB)
    ref_graph = nx.disjoint_union(ref_graph, graphA)
    ref_graph.add_edges_from([(2, 6), (7, 12)])
    assert nx.is_isomorphic(ref_graph, seq_graph)
예제 #21
0
    def random_pair_stitch(self, num_edges):
        left_nodes = self.left_region.graph.nodes()
        right_nodes = self.right_region.graph.nodes()

        if num_edges > len(left_nodes) * len(right_nodes):
            raise Exception("Too many edges to stitch")

        stitch = []
        while len(stitch) != num_edges:
            edge = (random.choice(list(left_nodes)),
                    random.choice(list(right_nodes)))
            if edge in stitch:
                continue
            stitch.append(edge)

        self.graph.structure = nx.disjoint_union(
            self.left_region.graph.structure,
            self.right_region.graph.structure)

        for (left_node, right_node) in stitch:
            edge = (left_node, right_node)
            self.graph.structure.add_edges_from([edge])
            self.attack_edges.append(edge)

        self.known_honests = self.left_region.known_honests
        self.is_stitched = True
예제 #22
0
파일: rnasubopt.py 프로젝트: bgruening/EDeN
def string_to_networkx(header, sequence, **options):
    # defaults
    energy_range = options.get('energy_range', 10)
    max_num = options.get('max_num', 3)
    max_num_subopts = options.get('max_num_subopts', 100)
    split_components = options.get('split_components', False)
    seq_struct_list, energy_list = rnasubopt_wrapper(sequence, energy_range=energy_range, max_num=max_num, max_num_subopts=max_num_subopts)
    if split_components:
        for seq_struct, energy in zip(seq_struct_list, energy_list):
            G = sequence_dotbracket_to_graph(seq_info=sequence, seq_struct=seq_struct)
            G.graph['info'] = 'RNAsubopt energy=%s max_num=%s' % (energy, max_num)
            if G.number_of_nodes() < 2:
                G = seq_to_networkx(header, sequence, **options)
            G.graph['id'] = header
            G.graph['sequence'] = sequence
            G.graph['structure'] = seq_struct
            yield G
    else:
        G_global = nx.Graph()
        G_global.graph['id'] = header
        G_global.graph['info'] = 'RNAsubopt energy_range=%s max_num=%s' % (energy_range, max_num)
        G_global.graph['sequence'] = sequence
        for seq_struct in seq_struct_list:
            G = sequence_dotbracket_to_graph(seq_info=sequence, seq_struct=seq_struct)
            G_global = nx.disjoint_union(G_global, G)
        if G_global.number_of_nodes() < 2:
            G_global = seq_to_networkx(header, sequence, **options)
        yield G_global
예제 #23
0
    def CreateInd(self,nbClusters, connectInter, connectIntra, pcExc, pcInh, nbNeuronByCluster, interRatio):
        """
        connectInter est la probabilite de connecter deux clusters entre eux
        connectIntra est une liste de probabilite de connection de neurones suivant leur type (pEE,pEI,pII,pIE)
        pcExc et pcInh sont le pourcentage de chaque type de neurones
        interRatio est le ratio de neurones-interface entre deux clusters (>1)
        """

        nbNeuronsInd = nbClusters * nbNeuronByCluster
        
        numNeuron = 0
        nbExc = int(pcExc * nbNeuronByCluster)
        lstNeuronsType = ([1] * nbExc  + [-1]*(nbNeuronByCluster - nbExc)) * nbClusters 
        lstNeuronToCluster = [y for y in range(nbClusters) for x in range(nbNeuronByCluster)]
        lstClusterToNeuron = [range(y*nbNeuronByCluster,(y+1)*nbNeuronByCluster) for y in range(nbClusters) ]
        lstInterfaceNeuron = [[],[],[],[]]  #Liste des neurones de chaque cluster connectes aux neurones d'autres clusters

        gphInd =  nx.MultiDiGraph()

        #Creation des clusters
        for numCluster in range(nbClusters):
            gphCluster = nx.MultiDiGraph()
            matrix = self.CreateConnectionMatrix(pcExc,pcInh,nbNeuronByCluster,connectIntra)
            #Parcourt de la matrice de connexion du cluster
            for ligne in range(nbNeuronByCluster):
                for col in range(nbNeuronByCluster):
                    gphCluster.add_edge(ligne+numNeuron , col+numNeuron,weight=matrix[ligne,col])

            #Permet la numerotation continue entre les clusters
            numNeuron+=nbNeuronByCluster
            #Rajoute le graphe du cluster (gphCluster) au graphe total (gphInd)
            gphInd=nx.disjoint_union(gphInd,gphCluster)
            gphCluster=nx.create_empty_copy(gphCluster)

        #Creation des connexions inter-cluster
        lstClusterConnection = self.CreateClusterConnection(connectInter,nbClusters)
        for numCluster in range(nbClusters):
            pcInter = int(nbNeuronByCluster /  interRatio)   #Nombre de neurones connectes entre deux clusters
            (preNeurones,postNeurones,weights) = self.CreateInterConnectionMatrix(numCluster,nbNeuronByCluster,lstClusterToNeuron,lstClusterConnection,pcInter,lstNeuronsType)
            for n in range(len(preNeurones)):
                gphInd.add_edge(preNeurones[n] , postNeurones[n] ,weight=weights[n])
                
         #Liste caracterisant les connexions inter-cluster
         #ligne 0 : numero de cluster des neurones pre-synaptiques
         #ligne 1 : numero des neurones pre-synaptiques
         #ligne 2 : numero de cluster des neurones post-synaptiques
         #ligne 3 : numero des neurones post-synaptiques
               
            lstInterfaceNeuron[0].extend([numCluster] * len(preNeurones))
            lstInterfaceNeuron[1].extend(preNeurones)       
            lstInterfaceNeuron[2].extend( [lstNeuronToCluster[x] for x in postNeurones] )   
            lstInterfaceNeuron[3].extend(postNeurones)
            
            
        #Stockage des valeurs de sortie dans des proprietes de la classe    
        self.graph = gphInd
        self.lstNeuronsType = lstNeuronsType
        self.lstNeuronToCluster = lstNeuronToCluster
        self.lstClusterToNeuron = lstClusterToNeuron
        self.lstInterfaceNeuron = lstInterfaceNeuron
예제 #24
0
 def _string_to_networkx(self, header=None, sequence=None, constraint=None):
     seq_struct_list, energy_list = self._rnasubopt_wrapper(sequence)
     if self.split_components:
         for seq_struct, energy in zip(seq_struct_list, energy_list):
             graph = sequence_dotbracket_to_graph(header=header,
                                                  seq_info=sequence,
                                                  seq_struct=seq_struct)
             graph.graph['info'] = 'RNAsubopt energy=%s max_num=%s' % \
                 (energy, self.max_num)
             graph.graph['id'] = header
             graph.graph['sequence'] = sequence
             graph.graph['structure'] = seq_struct
             yield graph
     else:
         graph_global = nx.Graph()
         graph_global.graph['id'] = header
         graph_global.graph['info'] = \
             'RNAsubopt energy_range=%s max_num=%s' % \
             (self.energy_range, self.max_num)
         graph_global.graph['sequence'] = sequence
         for seq_struct in seq_struct_list:
             graph = sequence_dotbracket_to_graph(header=header,
                                                  seq_info=sequence,
                                                  seq_struct=seq_struct)
             graph_global = nx.disjoint_union(graph_global, graph)
         yield graph_global
예제 #25
0
    def get_shortest_path(self, tree_1, tree_2, connection_point):
        ''' Given two trees and a connection point, find the shortest path
        from the first node in the forst tree to the last in the second
        Args:
            tree_1: Tree with starting point at node index 0
            tree_2: Tree with ending point as the last node.
            connection_point: The point that connects the two trees
        Returns:
            The path as a Nx3 NumPy array with points 
        '''
        full_tree = nx.disjoint_union(tree_1.tree, tree_2.tree)
        full_nodes = np.append(tree_1.nodes, tree_2.nodes, axis=0)
        connection_idx_tree_1 = len(tree_1.nodes) - 1
        connection_idx_tree_2 = tree_2.nearest_node(connection_point)[0]
        connection_idx_tree_2_full_tree = connection_idx_tree_1 + connection_idx_tree_2 + 1
        full_tree.add_edge(connection_idx_tree_1,
                           connection_idx_tree_2_full_tree,
                           weight=0)

        start_idx = 0
        end_idx = len(tree_1.nodes)

        def dist(a, b):
            a_point = full_nodes[a]
            b_point = full_nodes[b]
            return np.linalg.norm(b_point - a_point)

        path = nx.astar_path(full_tree, start_idx, end_idx, heuristic=dist)
        return np.array([full_nodes[idx] for idx in path])
예제 #26
0
    def connect_clusters_n_times(graphs, number_of_times):
        """
        inserts edges between given graphs to create connected graph
        """
        cpy = copy.deepcopy(graphs)
        if graphs is None or len(graphs) == 0:
            return None

        result_graph = cpy.pop()
        while len(cpy) > 0:
            rand = random.randint(0, len(cpy) - 1)  #select subgraph to add
            subgraph = cpy.pop(rand)
            offset_to_new_nodes = nx.number_of_nodes(result_graph)
            subgraph_number_of_nodes = nx.number_of_nodes(subgraph)
            result_graph = nx.disjoint_union(result_graph, subgraph)
            #connect by random edge connected to graph

            used_edges = []
            current_edge = [-1, -1]
            for i in range(number_of_times):
                while current_edge in used_edges:
                    node_idx_1 = random.randint(0, offset_to_new_nodes - 1)
                    node_idx_2 = offset_to_new_nodes + random.randint(
                        0, subgraph_number_of_nodes - 1)
                result_graph.add_edge(node_idx_1, node_idx_2)
                used_edges.add([node_idx_1, node_idx_2])

        return result_graph
예제 #27
0
    def graph(self, nested=False):
        '''
        generate the graph that will be used for evaluation ( it will be vectorized by eden and then used
        in a machine learning scheme).

        Args:
            nested: bool
                the graph returned here is the union of graph minor and the base graph.
                nested decides wether there edges between nodes in the base graph and their
                representative in the graph minor. these edges have the attribute 'nested'.


        Returns:
            nx.graph
        '''
        g= nx.disjoint_union(self._base_graph, self.abstract_graph())
        node_id= len(g)

        if nested:
            for n,d in g.nodes(data=True):
                if 'contracted' in d and 'edge' not in d:
                    for e in d['contracted']:
                        if 'edge' not in g.node[e]:
                            # we want an edge from n to e
                            g.add_node(node_id,edge=True,label='e')
                            g.add_edge( n, node_id, nesting=True)
                            g.add_edge( node_id, e, nesting=True)
                            #g.add_edge( n, e, nesting=True)
                            node_id+=1

        return g
예제 #28
0
def join_graphs(*graphs):
    graph = graphs[0]
    for g in graphs[1:]:
        graph = nx.disjoint_union(graph, g)

    assert len(graph.nodes) == sum(len(g.nodes) for g in graphs)
    return graph
예제 #29
0
    def connect_clusters_by_overlay(overlay_graph, subgraphs):
        """
        inserts subgraphs as edges between given graphs into overlay
        """
        cpy = copy.deepcopy(subgraphs)
        if subgraphs is None or len(subgraphs) == 0:
            return None

        result_graph = cpy.pop()

        number_overlay_nodes = nx.number_of_nodes(overlay_graph)
        onverlay_node_index = 0
        while len(cpy) > 0:
            rand = random.randint(0, len(cpy) - 1)  # select subgraph to add
            subgraph = cpy.pop(rand)
            offset_to_new_nodes = nx.number_of_nodes(result_graph)
            subgraph_number_of_nodes = nx.number_of_nodes(subgraph)
            result_graph = nx.disjoint_union(result_graph, subgraph)
            # connect by random edge connected to graph
            subgraph_node_idx = offset_to_new_nodes + random.randint(
                0, subgraph_number_of_nodes - 1)
            result_graph.add_edge(onverlay_node_index, subgraph_node_idx)
            onverlay_node_index = (onverlay_node_index +
                                   1) % number_overlay_nodes

        return result_graph
def test_five_clique():
    # Make a graph that can be disconnected less than 4 edges, but no node has
    # degree less than 4.
    G = nx.disjoint_union(nx.complete_graph(5), nx.complete_graph(5))
    paths = [
        # add aux-connections
        (1, 100, 6),
        (2, 100, 7),
        (3, 200, 8),
        (4, 200, 100),
    ]
    G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
    assert min(dict(nx.degree(G)).values()) == 4

    # For k=3 they are the same
    assert fset(nx.k_edge_components(G,
                                     k=3)) == fset(nx.k_edge_subgraphs(G, k=3))

    # For k=4 they are the different
    # the aux nodes are in the same CC as clique 1 but no the same subgraph
    assert fset(nx.k_edge_components(G, k=4)) != fset(
        nx.k_edge_subgraphs(G, k=4))

    # For k=5 they are not the same
    assert fset(nx.k_edge_components(G, k=5)) != fset(
        nx.k_edge_subgraphs(G, k=5))

    # For k=6 they are the same
    assert fset(nx.k_edge_components(G,
                                     k=6)) == fset(nx.k_edge_subgraphs(G, k=6))
    _check_edge_connectivity(G)
예제 #31
0
def disjoint_union_all(graphs):
    """Return the disjoint union of all graphs.

    This operation forces distinct integer node labels starting with 0
    for the first graph in the list and numbering consecutively.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    U : A graph with the same type as the first graph in list

    Notes
    -----
    It is recommended that the graphs be either all directed or all undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    U = graphs.pop(0)
    for H in graphs:
        U = nx.disjoint_union(U, H)
    return U
예제 #32
0
def self_repetition(G, n=1, linknode=0):
    new_graph = nx.null_graph()
    new_graph.add_node(0)
    for i in range(n):
        new_graph = nx.disjoint_union(new_graph, G.copy())
        new_graph.add_edge(0, i * len(G) + linknode + 1)
    return new_graph
예제 #33
0
def generate_synthetic():
    import random
    max_nodes = 200
    min_nodes = 100
    community_num_nodes = 10
    graphs = []
    labels = []
    com_1 = nx.caveman_graph(1, community_num_nodes)
    com_2 = nx.star_graph(community_num_nodes)

    for i in range(500):
        num_nodes = random.randint(min_nodes, max_nodes)
        graph = nx.fast_gnp_random_graph(num_nodes, 0.1)
        graph = nx.disjoint_union(graph, com_1)
        for i in range(num_nodes, graph.number_of_nodes()):
            for j in range(num_nodes):
                if random.random() > 0.9:
                    graph.add_edge(graph.nodes()[i], graph.nodes()[j])
        graphs.append(graph)
        labels.append(1)
        num_nodes = random.randint(min_nodes, max_nodes)
        graph = nx.fast_gnp_random_graph(num_nodes, 0.1)
        for i in range(num_nodes, graph.number_of_nodes()):
            for j in range(num_nodes):
                if random.random() > 0.9:
                    graph.add_edge(graph.nodes[i], graph.nodes[j])
        graphs.append(graph)
        labels.append(0)

    return graphs, labels
예제 #34
0
    def __imul__(self, m):
        """In-place repeat of atoms."""
        if isinstance(m, int):
            m = (m, m, m)

        for x, vec in zip(m, self._cell):
            if x != 1 and not vec.any():
                raise ValueError(
                    'Cannot repeat along undefined lattice vector')

        M = np.product(m)
        n = len(self)

        for name, a in self.arrays.items():
            self.arrays[name] = np.tile(a, (M, ) + (1, ) * (len(a.shape) - 1))
            cgraph = self._graph.copy()

        positions = self.arrays['positions']
        i0 = 0

        for m0 in range(m[0]):
            for m1 in range(m[1]):
                for m2 in range(m[2]):
                    i1 = i0 + n
                    positions[i0:i1] += np.dot((m0, m1, m2), self._cell)
                    i0 = i1
                    if m0 + m1 + m2 != 0:
                        self._graph = nx.disjoint_union(self._graph, cgraph)

        if self.constraints is not None:
            self.constraints = [c.repeat(m, n) for c in self.constraints]

        self._cell = np.array([m[c] * self._cell[c] for c in range(3)])

        return self
예제 #35
0
    def staple_component_to_graph(self, n_nodes_in_subgraph, graph_root_node,
                                  **kwargs):
        """
        Staple a connected component to a graph.

        Args
            - n_nodes_in_subgraph (int): number of nodes in each subgraph
            - graph_root_node (int): node in the base graph that the component should be "stapled" to

        Return
            - cc_node_ids (list): nodes in a connected component
            - cc_root_node (int): node in the connected component (subgraph) to connect with the graph_root_node
        """

        # Create new connected component for the node in base graph
        con_component = self.generate_subgraph(n_nodes_in_subgraph, **kwargs)

        cc_node_ids = list(
            range(len(self.graph.nodes),
                  len(self.graph.nodes) + n_nodes_in_subgraph))

        # Staple the connected component to the base graph
        joined_graph = nx.disjoint_union(self.graph, con_component)
        cc_root_node = random.sample(cc_node_ids, 1)[0]
        joined_graph.add_edge(graph_root_node, cc_root_node)
        self.graph = joined_graph.copy()

        return cc_node_ids, cc_root_node
예제 #36
0
 def _string_to_networkx(self, header=None, sequence=None, constraint=None):
     seq_struct_list, energy_list = self._rnasubopt_wrapper(sequence)
     if self.split_components:
         for seq_struct, energy in zip(seq_struct_list, energy_list):
             graph = sequence_dotbracket_to_graph(header=header,
                                                  seq_info=sequence,
                                                  seq_struct=seq_struct)
             graph.graph['info'] = 'RNAsubopt energy=%s max_num=%s' % \
                 (energy, self.max_num)
             graph.graph['id'] = header
             graph.graph['sequence'] = sequence
             graph.graph['structure'] = seq_struct
             yield graph
     else:
         graph_global = nx.Graph()
         graph_global.graph['id'] = header
         graph_global.graph['info'] = \
             'RNAsubopt energy_range=%s max_num=%s' % \
             (self.energy_range, self.max_num)
         graph_global.graph['sequence'] = sequence
         for seq_struct in seq_struct_list:
             graph = sequence_dotbracket_to_graph(header=header,
                                                  seq_info=sequence,
                                                  seq_struct=seq_struct)
             graph_global = nx.disjoint_union(graph_global, graph)
         yield graph_global
예제 #37
0
    def random_pair_stitch(self, num_edges):
        left_nodes = self.left_region.graph.nodes()
        right_nodes = self.right_region.graph.nodes()

        if num_edges > len(left_nodes) * len(right_nodes):
            raise Exception("Too many edges to stitch")

        stitch = []
        while len(stitch) != num_edges:
            edge = (
                random.choice(left_nodes),
                random.choice(right_nodes)
            )
            if edge in stitch:
                continue
            stitch.append(edge)

        self.graph.structure = nx.disjoint_union(
            self.left_region.graph.structure,
            self.right_region.graph.structure
        )

        for (left_node, right_node) in stitch:
            edge = (left_node,
                len(left_nodes)+right_node
            )
            self.graph.structure.add_edges_from([edge])
            self.attack_edges.append(edge)

        self.known_honests = self.left_region.known_honests
        self.is_stitched = True
예제 #38
0
def _patch_modification(block, modification):
    """
    Applies, in order, modifications to block and returns a new Block.
    Modifications are applied by overlaying the anchor of a modification with
    the block and adding the remaining nodes and edges.
    """
    anchor_idxs = set()
    for mod_idx in modification:
        if not modification.nodes[mod_idx]['PTM_atom']:
            anchor_idxs.add(mod_idx)

    anchor = nx.subgraph(modification, anchor_idxs)
    non_anchor_idxs = set(modification) - anchor_idxs
    non_anchor = nx.subgraph(modification, non_anchor_idxs)

    block = nx.convert_node_labels_to_integers(block)

    ismags = ISMAGS(block, anchor, node_match=_node_equal)
    anchor_block_to_mod = list(ismags.subgraph_isomorphisms_iter())
    if not anchor_block_to_mod:
        LOGGER.error("Modification {} doesn't fit on Block {}",
                     modification.name, block.name)
        raise ValueError("Cannot apply modification to block")
    # This probably can't happen, since atoms in Modifications /should/ have
    # atomnames. Which should be unique. So, nocover.
    elif len(anchor_block_to_mod) > 1:  # pragma: nocover
        LOGGER.error("Modification {} fits on Block {} in {} ways",
                     modification.name, block.name,
                     len(anchor_block_to_mod))  # pragma: nocover
        raise ValueError(
            "Cannot apply modification to block")  # pragma: nocover

    block_to_mod = anchor_block_to_mod[0]
    mod_to_block = {val: key for key, val in block_to_mod.items()}
    # Add the extra modification atoms to the mapping/match. It's important to
    # note that this is under the assumption that when nx.disjoint_union
    # relabels nodes in non_anchor to ints it keeps the same order.
    # The alternative to this assumption is to reimplement disjoint_union where
    # the mapping is also returned
    mod_to_block.update(
        dict(
            zip(non_anchor_idxs,
                range(len(block),
                      len(block) + len(non_anchor_idxs)))))
    result = Block(nx.disjoint_union(block, non_anchor))

    # Mark the modified atoms with the specified modification, so canonicalize
    # modifications has an easier job
    for mod_idx in modification:
        idx = mod_to_block[mod_idx]
        node_mods = result.nodes[idx].get('modifications', [])
        if modification not in node_mods:
            result.nodes[idx]['modifications'] = node_mods + [modification]

    for mod_idx, mod_jdx in modification.edges_between(anchor_idxs,
                                                       non_anchor_idxs):
        idx = mod_to_block[mod_idx]
        jdx = mod_to_block[mod_jdx]
        result.add_edge(idx, jdx)
    return result
예제 #39
0
    def __setup_network_graph(self):
        structure = nx.disjoint_union(
            self.left_region.graph.structure,
            self.right_region.graph.structure
        )

        return sypy.CustomGraph(structure)
예제 #40
0
def plot_clustered_graph(dist_matrix, labels=None):
    plt.close('all')
    plt.figure(1)
    plt.clf()
    n_clusters = max(labels) + 1
    print('n_clusters = {}'.format(n_clusters))
    g_g = nx.Graph()
    for k in range(0, n_clusters):
        class_members = labels == k
        class_dist = dist_matrix[class_members].T[class_members]
        g = nx.from_numpy_matrix(class_dist)
        g_g = nx.disjoint_union(g_g, g)

    # color nodes the same in each connected subgraph
    for g in nx.connected_component_subgraphs(g_g):
        c = [random.random()] * nx.number_of_nodes(g)  # random color...
        nx.draw(g,

                node_size=40,
                node_color=c,
                vmin=0.0,
                vmax=1.0,
                with_labels=False)
    plt.savefig("atlas.png", dpi=75)
    plt.show()
예제 #41
0
파일: all.py 프로젝트: Harshi3030/algos
def disjoint_union_all(graphs):
    """Return the disjoint union of all graphs.

    This operation forces distinct integer node labels starting with 0
    for the first graph in the list and numbering consecutively.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    U : A graph with the same type as the first graph in list

    Raises
    ------
    ValueError
       If `graphs` is an empty list.

    Notes
    -----
    It is recommended that the graphs be either all directed or all undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    if not graphs:
        raise ValueError('cannot apply disjoint_union_all to an empty list')
    graphs = iter(graphs)
    U = next(graphs)
    for H in graphs:
        U = nx.disjoint_union(U, H)
    return U
예제 #42
0
def disjoint_union_all(graphs):
    """Return the disjoint union of all graphs.

    This operation forces distinct integer node labels starting with 0
    for the first graph in the list and numbering consecutively.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    U : A graph with the same type as the first graph in list

    Notes
    -----
    It is recommended that the graphs be either all directed or all undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    graphs = iter(graphs)
    U = next(graphs)
    for H in graphs:
        U = nx.disjoint_union(U, H)
    return U
예제 #43
0
def patternsets2(MotifG1, MotifG2):
    #enumerate all possible permutations of node labels,
    #minimum is sharing one edge, all the way to max is the smaller number of edges, complexity 2^edgenum_max
    #return a set of possibly isomorphic collapses

    patternset = set()
    edgenum_max = min(MotifG1.number_of_edges(), MotifG2.number_of_edges())

    #select L (two+) edges to overlap
    for L in range(1, edgenum_max + 1):
        print L
        L_subsets = list(itertools.combinations(MotifG1.edges(),L))
        L_subsets2 = list(itertools.combinations(MotifG2.edges(),L))
        for subset1 in L_subsets:
            for subset2 in L_subsets2:
                print "already chose these" +str(L)+" edges in Motif2"
                print subset2
                permutations = list(itertools.permutations(subset1))
                i = 0
                for permutation in permutations:
                    print "this permutation is"
                    print permutation
                    print "in this particular order" + str(i)
                    if MotifG1 == MotifG2:
                        print "waring!!!same motif non-relabled"
                        G = nx.disjoint_union(MotifG1, MotifG2)
                    else:
                        G = nx.union(MotifG1, MotifG2)

                    if len(G) != 0:
                        G2 = nx.Graph()
                        G22 = nx.Graph()
                        Motif2merged_nodes = set()
                        for j in range(0, len(permutation)):
                            edge_1 = permutation[j]
                            edge_2 = subset2[j]
                            print "edge 1"
                            print edge_1
                            print "edge 2"
                            print edge_2

                            if edge_2[0] not in Motif2merged_nodes:
                                G1 = merge_nodes(G, edge_1[0], edge_2[0])
                                Motif2merged_nodes.add(edge_2[0])
                            if edge_2[1] not in Motif2merged_nodes:
                                G2 = merge_nodes(G1, edge_1[1], edge_2[1])
                                Motif2merged_nodes.add(edge_2[1])

                            if edge_2[0] not in Motif2merged_nodes:
                                G11 = merge_nodes(G, edge_1[1], edge_2[0])
                            if edge_2[1] not in Motif2merged_nodes:
                                G22 = merge_nodes(G11, edge_1[0], edge_2[1])

                        patternset.add(G2)
                        patternset.add(G22)
                        print G2.nodes()
                    i += 1


    return patternset
예제 #44
0
 def add_community(self, G, community):
     last_community = len(G.nodes())/self._household_size-1
     G=nx.disjoint_union(G, community)
     self.get_node_with_highest_degree(last_community, G)
     for i in range(last_community+1, last_community+len(community.nodes())/self._household_size+1):
         G.add_edge(self.get_random_node(last_community), self.get_random_node(i))
     return G
예제 #45
0
def contraction(graphs=None,
                contraction_attribute='label',
                dont_contract_attribute_symbol=None,
                nesting=False,
                contraction_weight_scaling_factor=1,
                modifiers=modifiers,
                **options):
    '''
    modifiers: list of named tuples, each containing the keys: attribute_in, attribute_out and reduction.
    "attribute_in" identifies the node attribute that is extracted from all contracted nodes.
    "attribute_out" identifies the node attribute that is written in the resulting graph.
    "reduction" is one of the following reduction operations:
    1. histogram,
    2. sum,
    3. average,
    4. categorical,
    5. set_categorical.
    "histogram" returns a sparse vector with numerical hashed keys,
    "sum" and "average" cast the values into floats before computing the sum and average respectively,
    "categorical" returns the concatenation string of the lexicographically sorted list of input attributes,
    "set_categorical" returns the concatenation string of the lexicographically sorted set of input
    attributes.
    contraction_weight_scaling_factor: factor to multiply the weights of the contracted part
    '''
    for g in graphs:
        # check for 'position' attribute and add it if not present
        for i, (n, d) in enumerate(g.nodes_iter(data=True)):
            if d.get('position', None) is None:
                g.node[n]['position'] = i
        # compute contraction
        g_contracted = edge_contraction(graph=g, node_attribute=contraction_attribute,
                                        except_symbol=dont_contract_attribute_symbol)
        info = g_contracted.graph.get('info', '')
        g_contracted.graph['info'] = info + '\n' + serialize_modifiers(modifiers)
        for n, d in g_contracted.nodes_iter(data=True):
            # get list of contracted node ids
            contracted = d.get('contracted', None)
            if contracted is None:
                raise Exception('Empty contraction list for: id %d data: %s' % (n, d))
            for modifier in modifiers:
                modifier_func = contraction_modifer_map[modifier.reduction]
                g_contracted.node[n][modifier.attribute_out] = modifier_func(
                    input_attribute=modifier.attribute_in, graph=g, id_nodes=contracted)
                # rescale the weight of the contracted nodes
                if contraction_weight_scaling_factor != 1:
                    w = d.get('weight', 1)
                    w = w * contraction_weight_scaling_factor
                    g_contracted.node[n]['weight'] = w
        if nesting:  # add nesting edges between the constraction graph and the original graph
            g_nested = nx.disjoint_union(g, g_contracted)
            # rewire contracted graph to the original graph
            for n, d in g_nested.nodes_iter(data=True):
                contracted = d.get('contracted', None)
                if contracted:
                    for m in contracted:
                        g_nested.add_edge(n, m, label='.', len=1, nesting=True)
            yield g_nested
        else:
            yield g_contracted
예제 #46
0
파일: instance8.py 프로젝트: diivanand/mlst
def instance8_1000():
    """
    Returns a 3-element tuple (G,T,leaves) where G is the graph
    T is the optimal solution and leaves is the number of leaves
    in the optimal solution.
    
    The graph is constructed by creating 4 stars with 90 nodes and
    adding 10 random nodes.
    """
    
    #create a star of 4 stars
    starList = []
    
    for _ in range(0,6):
        starList.append(nx.heawood_graph())
    
    T = nx.Graph()
    for star in starList:
        T = nx.disjoint_union(T,star)
        
    T.add_node(84)
    T.add_edges_from([(84,0),(84,14),(84,28),(84,42),(84,56),(84,70)])
    
    #add 10 more nodes with random edges
    T.add_nodes_from(range(85,100))
    for i in range(85,100):
        x = int(random()*5371)%90
        T.add_edge(i,x)
        
    #count the number of leaves
    leaves = list(T.degree(T.nodes()).values()).count(1)
    
    #randomize the label of nodes
    n = range(100)
    new = range(100)

    r.shuffle(new)

    T = nx.relabel_nodes(T,dict(zip(n,new)))
        
    G = nx.Graph()
    G.add_nodes_from(T.nodes())
    G.add_edges_from(T.edges())

    # add random edges
    for i in range(1000):
        x = int(random()*15897)%100
        y = int(random()*17691)%100
        G.add_edge(G.nodes()[x],G.nodes()[y])

    for e in G.edges():
        if e[0] == e[1]:
            G.remove_edge(e[0],e[1])

    G = G.to_undirected()  
    #T = mlst.one_edge_swap(G)  
    
    T = nx.Graph()
    return (G,T)
예제 #47
0
    def test_is_planar_unions(self):
        try:
            from itertools import combinations,product
        except ImportError:
            raise SkipTest('itertools.combinations not found')

        for (G1,G2) in combinations(self.planar,2):
            G=nx.disjoint_union(G1,G2)
            assert_true(planarity.is_planar(G))

        for (G1,G2) in combinations(self.non_planar,2):
            G=nx.disjoint_union(G1,G2)
            assert_false(planarity.is_planar(G))

        for (G1,G2) in product(self.planar,self.non_planar):
            G=nx.disjoint_union(G1,G2)
            assert_false(planarity.is_planar(G))
예제 #48
0
def original_graph():
    romeos_family = nx.complete_graph(5)
    julias_family = nx.complete_graph(5)
    # The families clash <- aw, not good!
    family_fight = nx.disjoint_union(romeos_family, julias_family)
    # ... but Romeo and Julia make love nevertheless
    family_fight.add_edge(0, 9)
    return family_fight
예제 #49
0
def test_spanner_unweighted_disconnected_graph():
    """Test spanner construction on a disconnected graph."""
    G = nx.disjoint_union(nx.complete_graph(10), nx.complete_graph(10))

    spanner = nx.spanner(G, 4, seed=_seed)
    _test_spanner(G, spanner, 4)

    spanner = nx.spanner(G, 10, seed=_seed)
    _test_spanner(G, spanner, 10)
예제 #50
0
    def get_json(self):

        # join together all layers in the network
        H = nx.DiGraph()
        for G in self.layergraphs:
            H = nx.disjoint_union(G, H)

        data = json_graph.node_link_data(H)
        return json.dumps(data)
예제 #51
0
def test_white_harary_2():
    # Figure 8 white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.add_edge(0,4)
    # kappa <= lambda <= delta
    assert_equal(3, min(nx.core_number(G).values()))
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(1, nx.edge_connectivity(G))
예제 #52
0
파일: instance1.py 프로젝트: diivanand/mlst
def instance1_1000():
    #make a star of 4 24-node stars
    A = nx.star_graph(24)
    B = nx.star_graph(24)
    C = nx.star_graph(24)
    D = nx.star_graph(23)
    T = nx.disjoint_union(A,B)
    T = nx.disjoint_union(T,C)
    T = nx.disjoint_union(T,D)
    T.add_node(99)
    T.add_edges_from([(0,99),(25,99),(50,99),(75,99)])
    
    #randomize the labels of nodes    

    # for n in T.nodes():
    #     new = n + int(random()*10000)
    #    while(new in T.nodes()):
    #        new = n + int(random()*10000)
    
    n = range(100)
    new = range(100)

    r.shuffle(new)

    T = nx.relabel_nodes(T,dict(zip(n,new)))

    # T is optimal solution
    # G is the graph

    G = nx.Graph()
    G.add_nodes_from(T.nodes())
    G.add_edges_from(T.edges())

    # add random edges
    for i in range(1000):
        x = int(random()*15897)%100
        y = int(random()*17691)%100
        G.add_edge(G.nodes()[x],G.nodes()[y])

    for e in G.edges():
        if e[0] == e[1]:
            G.remove_edge(e[0],e[1])

    return (G,T)
예제 #53
0
    def pre_vectorizer_graph(self, nested=True, fcorrect=False, base_only=False):
        """

        Parameters
        ----------
        nested: nested minor + base graph
        fcorrect: introduce nodes that aid the forgi abstraction
        base_only: only return the base graph


        Returns
        -------
            nx.graph
        """

        g = nx.disjoint_union(nx.Graph(self._base_graph), self.abstract_graph())
        if base_only:
            g = self.base_graph().copy()
        node_id = len(g)
        delset = []
        if nested:
            for n, d in g.nodes(data=True):
                if 'contracted' in d and 'edge' not in d:
                    for e in d['contracted']:
                        if 'edge' not in g.node[e] and not (g.node[e]['label'] == 'F' and fcorrect):  # think about this

                            # we want an edge from n to e
                            g.add_node(node_id, edge=True, label='e')
                            g.add_edge(n, node_id, nesting=True)
                            g.add_edge(node_id, e, nesting=True)
                            # g.add_edge( n, e, nesting=True)
                            node_id += 1

        if fcorrect:
            for n, d in g.nodes(data=True):
                if d['label'] == "F":
                    down = self.nextnode(g, n)
                    up = self.nextnode(g, n, down_direction=False)
                    delset.append((n, down, up))

            for r, d, u in delset:
                # print g.node[d[0]]
                # we copy the label of the adjacent edge to r
                g.node[r] = g.node[d[0]].copy()
                # print g.node[r]

                # g.node[r]={"label":'-','edge':True}
                # delete neighbors
                g.remove_nodes_from([d[0], u[0]])

                # rewire neighbors of neighbors
                g.add_edge(r, d[1])
                g.add_edge(u[1], r)
                # print r,d,u

        return g
예제 #54
0
def test_disjoint_union_multigraph():
    G = nx.MultiGraph()
    G.add_edge(0, 1, key=0)
    G.add_edge(0, 1, key=1)
    H = nx.MultiGraph()
    H.add_edge(2, 3, key=0)
    H.add_edge(2, 3, key=1)
    GH = nx.disjoint_union(G, H)
    assert_equal(set(GH), set(G) | set(H))
    assert_equal(set(GH.edges(keys=True)), set(G.edges(keys=True)) | set(H.edges(keys=True)))
예제 #55
0
    def test_already_branching(self):
        """Tests that a directed acyclic graph that is already a
        branching produces an isomorphic branching as output.

        """
        T1 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
        T2 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
        G = nx.disjoint_union(T1, T2)
        B = nx.dag_to_branching(G)
        assert_true(nx.is_isomorphic(G, B))
예제 #56
0
파일: instance7.py 프로젝트: diivanand/mlst
def instance7_2000():
    """
    Returns a 3-element tuple (G,T,leaves) where G is the graph
    T is the optimal solution and leaves is the number of leaves
    in the optimal solution.
    
    The graph is constructed by creating 4 stars with 90 nodes and
    adding 10 random nodes.
    """
    
    #create a star of 4 stars
    starList = []
    
    starList.append(nx.star_graph(22))
    starList.append(nx.star_graph(21))
    starList.append(nx.star_graph(21))
    starList.append(nx.star_graph(21))
    
    T = nx.Graph()
    for star in starList:
        T = nx.disjoint_union(T,star)
        
    T.add_node(89)
    T.add_edges_from([(89,0),(89,23),(89,67),(89,45)])
    
    #add 10 more nodes with random edges
    T.add_nodes_from(range(90,101))
    for i in range(90,101):
        x = int(random()*5371)%90
        T.add_edge(i,x)
        
    #count the number of leaves
    leaves = list(T.degree(T.nodes()).values()).count(1)
    
    #randomize the label of nodes
    for n in T.nodes():
        new = n + int(random()*2000)
        while(new in T.nodes()):
            new = n + int(random()*2000)
        T = nx.relabel_nodes(T,{n:new})
        
    G = nx.Graph()
    G.add_nodes_from(T.nodes())
    G.add_edges_from(T.edges())

    #code for 2000 edges
    #add random edges
    while(G.number_of_edges() < 2000):
        x = int(random()*15897)%100
        y = int(random()*17691)%100
        
        G.add_edge(G.nodes()[x],G.nodes()[y])
    T = one_edge_swap(G)

    return (G,T)
예제 #57
0
파일: __init__.py 프로젝트: xypan1232/EDeN
 def _union(self, graphs):
     graph_global = nx.Graph()
     for graph in graphs:
         graph_global = nx.disjoint_union(graph_global, graph)
     for n in graph_global.nodes():
         if self.attribute in graph_global.node[n]:
             graph_global.node[n]['part_id'] = \
                 [graph_global.node[n][self.attribute]]
             graph_global.node[n]['part_name'] = \
                 [graph_global.node[n]['label']]
     return graph_global
    def getRandomG():

        G = nx.Graph()
        H = nx.Graph()
        allAnomNodes = []
        for node in range(30):
            p = CustomData.minval(CustomData.myrand(), 0.09)
            n = int((CustomData.myrand() + CustomData.myrand()) * 10)
            n = CustomData.minval(n)
            tenp = int(p * 10 + 1)
            num_nodes = int(math.ceil(n * tenp / 3))
            recur = tenp
            g = nx.Graph()
            temp = nx.fast_gnp_random_graph(num_nodes, p)
            for j in range(recur):
                g = nx.disjoint_union(g, temp)
            dup = g.copy()
            maxAnomCount = n * math.sqrt(len(g.edges())) * p
            anomCount = 0
            nodes = g.nodes()
            if len(nodes) == 0:
                continue
            numAnomNodes = int(len(nodes) * random.randint(1, 10) / 100)
            numAnomNodes = 1 if numAnomNodes == 0 else numAnomNodes
            anomNodes = random.sample(nodes, numAnomNodes)
            random.shuffle(nodes)
            print "anom_edges:%d recur:%d nodes:%d edges:%d numAnomNodes:%d" % (
                maxAnomCount, recur, len(g.nodes()), len(g.edges()), numAnomNodes)

            for node in nodes:
                for anomNode in anomNodes:
                    if anomCount <= maxAnomCount and not g.has_edge(node, anomNode):
                        dup.add_edge(anomNode, node)
            G = nx.disjoint_union(g, G)
            H = nx.disjoint_union(dup, H)
            allAnomNodes.extend(anomNodes)
        H = CustomGraph(H)
        H.addAnomNodes(allAnomNodes)
        print (len(G.nodes()), len(G.edges()))
        print (len(H.nodes()), len(H.edges()))
        return G, H
예제 #59
0
 def create_community(self, community_size):
     households = []
     for i in range(community_size):
         H =self.create_household()
         households.insert(0, H)
     G = households[0]
     for i in range(1, len(households)):
         G = nx.disjoint_union(G, households[i])
     for i in range(len(households)-1):
         for j in range(i+1, len(households)):
             G.add_edge(self.get_random_node(i), self.get_random_node(j))
     return G