示例#1
0
def jaccard(network1, network2, d="directed"):
    """Returns Jaccard similarity coefficient and
    distance of two different networks of the same
    sets of nodes.

    Parameters
    ----------
    network1 : first network edge list
    network2 : second network edge list
    d : directed or undirected
        type of graph

    Returns
    -------
    j : float
        Jaccard similarity coefficient
    jd : float
        Jaccard distance
    """
    if d == "directed":
        g1 = nx.read_weighted_edgelist(network1, create_using=nx.DiGraph())
        g2 = nx.read_weighted_edgelist(network2, create_using=nx.DiGraph())
    elif d == "undirected":
        g1 = nx.read_weighted_edgelist(network1)
        g2 = nx.read_weighted_edgelist(network2)

    union = nx.compose(g1, g2)
    inter = nx.intersection(g1, g2)

    j = float(inter.number_of_edges()) / float(union.number_of_edges())
    jd = 1 - j

    return j, jd
示例#2
0
    def equivalent_permutations(self):
        """Return the permutations generating equivalent diagrams.

        Returns:
            (list): Vertices permutations as dictionnaries.

        """
        perm_vertices = [
            vertex for vertex, degrees in enumerate(self.unsort_io_degrees)
            if not self.graph.nodes[vertex]['operator']
            and self.unsort_io_degrees.count(degrees) >= 2
        ]
        permutations = []
        op_nm = nx.algorithms.isomorphism.categorical_node_match(
            'operator', False)
        for permutation in itertools.permutations(perm_vertices):
            permuted_graph = nx.relabel_nodes(
                self.graph,
                dict(list(zip(perm_vertices, permutation))),
                copy=True)
            # Check for a permutation that leaves the graph unchanged
            # (only way to keep the edge list of the same length)
            # (is_isomorphic could maybe be replaced by something faster here)
            if nx.is_isomorphic(self.graph,
                                nx.intersection(self.graph, permuted_graph),
                                node_match=op_nm):
                permutations.append(dict(list(zip(perm_vertices,
                                                  permutation))))
        return permutations
示例#3
0
def intersection_all(graphs):
    """Return a new graph that contains only the edges that exist in
    all graphs.

    All supplied graphs must have the same node set.

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

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

    Notes
    -----
    Attributes from the graph, nodes, and edges are not copied to the new
    graph.
    """
    graphs = iter(graphs)
    R = next(graphs)
    for H in graphs:
        R = nx.intersection(R, H)
    return R
示例#4
0
def plot_predicted_graph(G,H=None,name=None,node_shape="o",node_size=1000,font_size=14,node_color="white"):
    if H is None : return matrix_to_graph(G,name=None,node_shape="o",node_size=1000,font_size=14,node_color="white")
    G = nx.Graph(G)
    H = nx.Graph(H)
    I = nx.intersection(G, H)
    U = nx.compose(G, H)
    edge_color=[]
    edge_style=[]
    for edge in U.edges() :
        if edge in I.edges() :
            edge_color.append("black")
            edge_style.append("solid")
        elif edge in H.edges() :
            edge_color.append("black")
            edge_style.append("dotted")
        else :
            edge_color.append("red")
            edge_style.append("solid")
    labels = {}
    if name is not None :
        for i in range(len(name)) :
            labels[i] = str(name[i])
    else :
        labels = None
    nx.draw(U,labels=labels,with_labels=True,node_shape=node_shape,font_size=font_size,node_size=node_size,node_color=node_color,edge_color=edge_color,style=edge_style)
    plt.show()
示例#5
0
def intersection_all(graphs):
    """Return a new graph that contains only the edges that exist in
    all graphs.

    All supplied graphs must have the same node set.

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

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

    Notes
    -----
    Attributes from the graph, nodes, and edges are not copied to the new
    graph.
    """
    graphs = iter(graphs)
    R = next(graphs)
    for H in graphs:
        R = nx.intersection(R, H)
    return R
示例#6
0
def jaccard(network1, network2, d="directed"):
    """Returns Jaccard similarity coefficient and
    distance of two different networks of the same
    sets of nodes.

    Parameters
    ----------
    network1 : first network edge list
    network2 : second network edge list
    d : directed or undirected
        type of graph

    Returns
    -------
    j : float
        Jaccard similarity coefficient
    jd : float
        Jaccard distance
    """
    if d == "directed":
        g1 = nx.read_weighted_edgelist(network1, create_using=nx.DiGraph())
        g2 = nx.read_weighted_edgelist(network2, create_using=nx.DiGraph())
    elif d == "undirected":
        g1 = nx.read_weighted_edgelist(network1)
        g2 = nx.read_weighted_edgelist(network2)

    union = nx.compose(g1, g2)
    inter = nx.intersection(g1, g2)

    j = float(inter.number_of_edges()) / float(union.number_of_edges())
    jd = 1 - j

    return j, jd
示例#7
0
文件: all.py 项目: Harshi3030/algos
def intersection_all(graphs):
    """Return a new graph that contains only the edges that exist in
    all graphs.

    All supplied graphs must have the same node set.

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

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

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

    Notes
    -----
    Attributes from the graph, nodes, and edges are not copied to the new
    graph.
    """
    if not graphs:
        raise ValueError('cannot apply intersection_all to an empty list')
    graphs = iter(graphs)
    R = next(graphs)
    for H in graphs:
        R = nx.intersection(R, H)
    return R
示例#8
0
def NodeIntersection(G_one, G_two):
    print()
    G1 = nx.DiGraph(G_one)
    G2 = nx.DiGraph(G_two)
    G1_Node_Removal = list()
    G2_Node_Removal = list()

    #Loop through G1's nodes and remove G1 nodes that are not found anywhere within G2
    for key in G1:
        if (key not in G2):
            #print(key, "is not in G2 so remove from G1")
            G1_Node_Removal.append(key)
    G1.remove_nodes_from(G1_Node_Removal)

    #Loop through G2's nodes and remove G2 nodes that are not found anywhere within G1
    for key in G2:
        if (key not in G1):
            #print(key, "is not in G1, so remove from G2")
            G2_Node_Removal.append(key)
    G2.remove_nodes_from(G2_Node_Removal)

    #print("{} nodes, {} edges".format(len(G1), nx.number_of_edges(G1)))
    #print("{} nodes, {} edges".format(len(G2), nx.number_of_edges(G2)))

    I = nx.intersection(G1, G2)
    print(type(I))
    print(nx.info(I))
示例#9
0
def intersection_all(graphs):
    """Return a new graph that contains only the edges that exist in
    all graphs.

    All supplied graphs must have the same node set.

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

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

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

    Notes
    -----
    Attributes from the graph, nodes, and edges are not copied to the new
    graph.
    """
    if not graphs:
        raise ValueError('cannot apply intersection_all to an empty list')
    graphs = iter(graphs)
    R = next(graphs)
    for H in graphs:
        R = nx.intersection(R, H)
    return R
def test_intersection(testgraph):
    """
    Test the Intersection of the two graphs are same
    """

    a = nx.intersection(testgraph[0], testgraph[1])
    b = sg.graph_operations.intersection(testgraph[2], testgraph[3])
    graph_equals(a, b)
    def intersection(self, other_kg):
        """ Returns the intersection of the knowledge graph and other_kg

        :param other_kg: The other knowledge graph
        :type other_kg: :class:`.KnowledgeGraph`
        """
        # Returns a KnowledgeGraph containing only edges that exist in both self and other_kg
        return KnowledgeGraph(nx.intersection(self.net, other_kg.net))
def test_intersection(testgraph):
    """
    Test the Intersection of the two graphs are same
    """

    a = nx.intersection(testgraph[0], testgraph[1])
    b = sg.digraph_operations.intersection(testgraph[2], testgraph[3])
    digraph_equals(a, b)
示例#13
0
def network_intersection(G, H):
    Gnodes = set(list(G.nodes()))
    Hnodes = set(list(H.nodes()))
    cmnnodes = list(Gnodes & Hnodes)
    Gnew = G.subgraph(cmnnodes)
    Hnew = H.subgraph(cmnnodes)
    newnet = nx.intersection(Gnew, Hnew)
    return newnet
示例#14
0
def main():
    print("Processing Aqualung Wiki")
    Aq = Aqualung()
    print("Processing Ian Anderson Wiki")
    IanA = Ian()

    print("Generating Similarity rankings for Aqualung")
    As = nx.simrank_similarity(Aq)
    A = [[As[u][v] for v in sorted(As[u])] for u in sorted(As)]
    sim_array = array(A)

    print("Generating Similarity rankings for Ian Anderson")
    Ia = nx.simrank_similarity(Aq)
    IanAr = [[Ia[u][v] for v in sorted(Ia[u])] for u in sorted(Ia)]
    Ian_array = array(IanAr)

    AqL = list(Aq.nodes)
    IanAL = list(IanA.nodes)

    print("\nSimilarities for Aqualung")
    for x in range(len(sim_array)):
        for y in range(len(sim_array[x])):
            if x == y:
                break
            elif sim_array[x][y] >= 0.01:
                print(AqL[x], " | ", AqL[y], " | ", sim_array[x][y])

    print("\nSimilarities for Ian Anderson")
    for x in range(len(Ian_array)):
        for y in range(len(Ian_array[x])):
            if x == y:
                break
            elif Ian_array[x][y] >= 0.01:
                print(IanAL[x], " | ", IanAL[y], " | ", Ian_array[x][y])

    #removing nodes for networkx.difference
    for node in AqL:
        if (node in IanAL):
            continue
        else:
            Aq.remove_node(node)

    for node in IanAL:
        if (node in AqL):
            continue
        else:
            IanA.remove_node(node)
    print("\nComputing Difference")

    D = nx.difference(Aq, IanA)
    D.remove_nodes_from(list(nx.isolates(D)))
    print(nx.info(D))

    #Computing Intersection
    print("\nIntersection")
    I = nx.intersection(Aq, IanA)
    I.remove_nodes_from(list(nx.isolates(I)))
    print(nx.info(I))
示例#15
0
    def generate_output_matrix(self):
        M1 = self.input_matrix[:, 0:3]
        M2 = self.input_matrix[:, 4:7]

        G1 = nx.from_numpy_matrix(M1, create_using=nx.DiGraph())
        G2 = nx.from_numpy_matrix(M2, create_using=nx.DiGraph())
        OG = nx.intersection(G1, G2)
        output_matrix = nx.to_numpy_array(OG, dtype=int)

        output_matrix[output_matrix != 0] = 2
        return output_matrix
示例#16
0
 def intersect(self, g1, g2):
     g1_copy = g1.copy()
     g1_copy.remove_nodes_from(n for n in g1 if not n in g2)
     intersection = nx.MultiDiGraph()
     try:
         intersection = nx.intersection(g1_copy, g2)
     except:
         traceback.print_exc()
     g1_copy_2 = g1.copy()
     g1_copy_2.remove_nodes_from(n for n in g1 if not n in intersection)
     return g1_copy_2
示例#17
0
def main():
    print("Generating Aq")
    Aq = Aqualung()
    print("Generating IanA")
    IanA = Ian()
    print("Computing similarity")
    nx.write_edgelist(Aq, "aq.edgelist")
    #As = nx.simrank_similarity(Aq,max_iterations=5)
    #print("Done with simrank")

    G1 = nx.DiGraph()
    G1.add_nodes_from([1, 2, 3, 4, 5])
    G1.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 5)])

    #s = nx.simrank_similarity(G1)
    #A = [[s[u][v] for v in sorted(s[u])] for u in sorted(s)]
    #sim_array = array(A)
    #print(sim_array)
    #AqL = list(Aq.nodes)
    #IanAL = list(IanA.nodes)

    #for node in AqL:
    #   for node2 in AqL:
    #       print("Checking",node," ",node2)
    #       sim_val = nx.simrank_similarity(Aq,source=node,target=node2)
    #       if sim_val >= 0.01:
    #           print(node, node2, sim_val)

    #removing nodes for networkx.difference
    AqL = list(Aq.nodes)
    IanAL = list(IanA.nodes)

    for node in AqL:
        if (node in IanAL):
            continue
        else:
            Aq.remove_node(node)

    for node in IanAL:
        if (node in AqL):
            continue
        else:
            IanA.remove_node(node)
    print("\nComputing Difference")

    D = nx.difference(Aq, IanA)
    D.remove_nodes_from(list(nx.isolates(D)))
    print(nx.info(D))

    #Computing Intersection
    print("\nIntersection")
    I = nx.intersection(Aq, IanA)
    I.remove_nodes_from(list(nx.isolates(I)))
    print(nx.info(I))
示例#18
0
def test_intersection():
    G = nx.Graph()
    H = nx.Graph()
    G.add_nodes_from([1, 2, 3, 4])
    G.add_edge(1, 2)
    G.add_edge(2, 3)
    H.add_nodes_from([1, 2, 3, 4])
    H.add_edge(2, 3)
    H.add_edge(3, 4)
    I = nx.intersection(G, H)
    assert set(I.nodes()) == {1, 2, 3, 4}
    assert sorted(I.edges()) == [(2, 3)]
示例#19
0
    def compute_recons_accuracy(self, path):
        ### Compute reconstruction error
        G = self.G
        G_recons = self.read_networks_as_graph(path)
        G_recons.add_nodes_from(G.nodes)
        H = nx.intersection(G, G_recons)
        recons_accuracy = len(H.edges) / len(G.edges)

        print('# edges of original ntwk=', len(G.edges))
        print('# edges of reconstructed ntwk=', len(G_recons.edges))
        print('reconstruction accuracy=', recons_accuracy)
        return H, recons_accuracy
示例#20
0
def test_intersection():
    G = nx.Graph()
    H = nx.Graph()
    G.add_nodes_from([1, 2, 3, 4])
    G.add_edge(1, 2)
    G.add_edge(2, 3)
    H.add_nodes_from([1, 2, 3, 4])
    H.add_edge(2, 3)
    H.add_edge(3, 4)
    I = nx.intersection(G, H)
    assert_equal(set(I.nodes()), set([1, 2, 3, 4]))
    assert_equal(sorted(I.edges()), [(2, 3)])
示例#21
0
def test_intersection():
    G=nx.Graph()
    H=nx.Graph()
    G.add_nodes_from([1,2,3,4])
    G.add_edge(1,2)
    G.add_edge(2,3)
    H.add_nodes_from([1,2,3,4])
    H.add_edge(2,3)
    H.add_edge(3,4)
    I=nx.intersection(G,H)
    assert_equal( set(I.nodes()) , set([1,2,3,4]) )    
    assert_equal( sorted(I.edges()) , [(2,3)] )    
示例#22
0
def test_intersection_node_sets_different():
    G = nx.Graph()
    H = nx.Graph()
    G.add_nodes_from([1, 2, 3, 4, 7])
    G.add_edge(1, 2)
    G.add_edge(2, 3)
    H.add_nodes_from([1, 2, 3, 4, 5, 6])
    H.add_edge(2, 3)
    H.add_edge(3, 4)
    H.add_edge(5, 6)
    I = nx.intersection(G, H)
    assert set(I.nodes()) == {1, 2, 3, 4}
    assert sorted(I.edges()) == [(2, 3)]
示例#23
0
def test_intersection_multigraph_attributes():
    g = nx.MultiGraph()
    g.add_edge(0, 1, key=0)
    g.add_edge(0, 1, key=1)
    g.add_edge(0, 1, key=2)
    h = nx.MultiGraph()
    h.add_edge(0, 1, key=0)
    h.add_edge(0, 1, key=3)
    gh = nx.intersection(g, h)
    assert set(gh.nodes()) == set(g.nodes())
    assert set(gh.nodes()) == set(h.nodes())
    assert sorted(gh.edges()) == [(0, 1)]
    assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
示例#24
0
def test_intersection_multigraph_attributes():
    g = nx.MultiGraph()
    g.add_edge(0, 1, key=0)
    g.add_edge(0, 1, key=1)
    g.add_edge(0, 1, key=2)
    h = nx.MultiGraph()
    h.add_edge(0, 1, key=0)
    h.add_edge(0, 1, key=3)
    gh = nx.intersection(g, h)
    assert_equal( set(gh.nodes()) , set(g.nodes()) )
    assert_equal( set(gh.nodes()) , set(h.nodes()) )
    assert_equal( sorted(gh.edges()) , [(0,1)] )
    assert_equal( sorted(gh.edges(keys=True)) , [(0,1,0)] )
示例#25
0
def get_labels_networkx_edge(list_nx_graph, fill=['number']):
    """
    get a dict of labels for groups in data (networkx graph edge version)

    @type list_nx_graph: list[networkx graph]
    @rtype: dict[str, str]

    :param list_nx_graph: data to get label for (list of graphs)
    :param fill: ["number"|"logic"|"percent"]
    :return: labels: a dict of labels for different graphs on edge
    """

    N = len(list_nx_graph)

    sets_data = list_nx_graph.copy(
    )  # Add union nodes to all graphs to all networkx set operators
    s_all = nx.compose_all(
        sets_data)  # simple union of all graph nodes and edges (compose)
    for i in range(len(sets_data)):
        sets_data[i].add_nodes_from(s_all.nodes)

    # bin(3) --> '0b11', so bin(3).split('0b')[-1] will remove "0b"
    set_collections = {}
    for n in range(1, 2**N):
        key = bin(n).split('0b')[-1].zfill(N)
        value = s_all
        sets_for_intersection = [
            sets_data[i] for i in range(N) if key[i] == '1'
        ]
        sets_for_difference = [sets_data[i] for i in range(N) if key[i] == '0']
        for s in sets_for_intersection:
            value = nx.intersection(value, s)
        for s in sets_for_difference:
            value = nx.difference(value, s)
        set_collections[key] = value

    labels = {k: "" for k in set_collections}
    if "logic" in fill:
        for k in set_collections:
            labels[k] = k + ": "
    if "number" in fill:
        for k in set_collections:
            labels[k] += str(set_collections[k].number_of_edges())
    if "percent" in fill:
        data_size = len(s_all)
        for k in set_collections:
            labels[k] += "(%.1f%%)" % (
                100.0 * set_collections[k].number_of_edges() / data_size)

    return labels
示例#26
0
def test_intersection_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph["name"] = "g"

    h = g.copy()
    h.graph["name"] = "h"
    h.graph["attr"] = "attr"
    h.nodes[0]["x"] = 7
    gh = nx.intersection(g, h)

    assert set(gh.nodes()) == set(g.nodes())
    assert set(gh.nodes()) == set(h.nodes())
    assert sorted(gh.edges()) == sorted(g.edges())
示例#27
0
def join2(source, target, joinBy):
    '''
    returns a graph of a single 'or' condition
    which may contain inner 'and' conditions
    '''
    conn = sqlite3.connect('data.db')
    cur = conn.cursor()
    G = nx.Graph()

    for i in range(len(joinBy)):
        graphs = []

        if source == target:
            return join1(source, target, joinBy)

        if joinBy[i]['value'] == []:
            conn.row_factory = lambda cursor, row: row[0]
            cur = conn.cursor()
            li = list(
                cur.execute(f'''
                                  SELECT DISTINCT {joinBy[i]["attr"]}
                                  FROM T
                                  '''))
            conn.row_factory = lambda cursor, row: row
            cur = conn.cursor()
        else:
            li = joinBy[i]['value']

        for val in li:
            x = nx.Graph()
            query = f'''SELECT {source}, {target}
                        FROM T
                        WHERE {joinBy[i]["attr"]} = ?
                        '''
            print(val)
            s = cur.execute(query, [val]).fetchall()
            print(s)
            x.add_edges_from(s)

            graphs.append(x)

        if i == 0:
            G = nx.compose_all(graphs)
        else:
            G = nx.intersection(G, nx.compose_all(graphs))

    return G
示例#28
0
def get_stats(previous, current, result_file, weeks):
    vertices_intersection = set(previous.G.nodes()).intersection(
        current.G.nodes())
    G1 = previous.G.subgraph(vertices_intersection)
    G2 = current.G.subgraph(vertices_intersection)

    H = nx.intersection(G1, G2)

    number_of_edges = len(H.edges())
    if len(previous.G.edges()) == 0:
        percent_of_edges = 0.0
    else:
        percent_of_edges = float(number_of_edges) / float(
            len(previous.G.edges())) * 100.0
    number_of_missing_edges = len(previous.G.edges()) - number_of_edges
    write_stats(result_file, previous, current, vertices_intersection,
                percent_of_edges, number_of_missing_edges, weeks)
示例#29
0
def join1(source, target, joinBy):
    '''
    returns a graph of a single 'or' condition
    which may contain inner 'and' conditions
    '''
    conn = sqlite3.connect('data.db')
    conn.row_factory = lambda cursor, row: row[0]
    cur = conn.cursor()
    G = nx.Graph()

    for i in range(len(joinBy)):
        graphs = []

        if joinBy[i]['conditionType'] == 'categorical':
            if joinBy[i]['value'] == []:
                li = list(
                    cur.execute(f'''
                                      SELECT DISTINCT {joinBy[i]["attr"]}
                                      FROM T
                                      '''))
            else:
                li = joinBy[i]['value']
            for val in li:
                graphs.append(
                    nx.complete_graph(
                        list(
                            cur.execute(
                                f'''
                                    SELECT {source}
                                    FROM T
                                    WHERE {joinBy[i]["attr"]} = ?
                                    ''', [val]).fetchall())))
                print(f'{val} is complete-networked')

        if i == 0:
            G = nx.compose_all(graphs)
        else:
            temp = nx.compose_all(graphs)
            G.add_nodes_from(temp.nodes)
            temp.add_nodes_from(G.nodes)
            G = nx.intersection(G, temp)

    return G
示例#30
0
def test_intersection_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph['name'] = 'g'

    h = g.copy()
    h.graph['name'] = 'h'
    h.graph['attr'] = 'attr'
    h.nodes[0]['x'] = 7

    gh = nx.intersection(g, h)
    assert_equal(set(gh.nodes()), set(g.nodes()))
    assert_equal(set(gh.nodes()), set(h.nodes()))
    assert_equal(sorted(gh.edges()), sorted(g.edges()))

    h.remove_node(0)
    assert_raises(nx.NetworkXError, nx.intersection, g, h)
示例#31
0
def test_intersection_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph["name"] = "g"

    h = g.copy()
    h.graph["name"] = "Tests"
    h.graph["attr"] = "attr"
    h.nodes[0]["x"] = 7

    gh = nx.intersection(g, h)
    assert set(gh.nodes()) == set(g.nodes())
    assert set(gh.nodes()) == set(h.nodes())
    assert sorted(gh.edges()) == sorted(g.edges())

    h.remove_node(0)
    pytest.raises(nx.NetworkXError, nx.intersection, g, h)
示例#32
0
def test_intersection_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph["name"] = "g"

    h = g.copy()
    h.graph["name"] = "h"
    h.graph["attr"] = "attr"
    h.node[0]["x"] = 7

    gh = nx.intersection(g, h)
    assert_equal(set(gh.nodes()), set(g.nodes()))
    assert_equal(set(gh.nodes()), set(h.nodes()))
    assert_equal(sorted(gh.edges()), sorted(g.edges()))

    h.remove_node(0)
    assert_raises(nx.NetworkXError, nx.intersection, g, h)
示例#33
0
def test_intersection_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph['name'] = 'g'

    h = g.copy()
    h.graph['name'] = 'h'
    h.graph['attr'] = 'attr'
    h.node[0]['x'] = 7

    gh = nx.intersection(g, h)
    assert_equal( set(gh.nodes()) , set(g.nodes()) )
    assert_equal( set(gh.nodes()) , set(h.nodes()) )
    assert_equal( sorted(gh.edges()) , sorted(g.edges()) )

    h.remove_node(0)
    assert_raises(nx.NetworkXError, nx.intersection, g, h)
示例#34
0
文件: trees.py 项目: mpasko/sao_trees
def crossover(t1, t2, graph):
    # here we get from |V-1| edges (when two graphs are identical) 
    # to minimum 1 common edge
    edges = nx.compose(t1,t2).edges()
    shuffle(edges)
    # we select the largest resulting subgraph

    g = nx.Graph()
    g.add_nodes_from(t1.nodes())
    for edge in edges:
        if g.size()  == t1.order() - 1:
            break
        if not nx.has_path(g, edge[0], edge[1]):
            g.add_edge(edge[0], edge[1])
    
    if uniform(0,1) <= 0.25:        
        if nx.intersection(t1,t2).size() ==  t1.size():
            mutation(g, graph)

    return g
示例#35
0
def get_local_filtration(points, filtration_matrix, filtration_steps, m,
                         nodes):
    G = nx.Graph()
    positions = {}
    for i, pt in enumerate(points):
        positions[i] = pt
    #positions.append(pt)
    H = make_k_community(m, nodes, points)
    G_ex = nx.Graph()
    G_ex.add_nodes_from(range(len(points)))
    G_ex.add_edges_from(itertools.combinations(H, 2))
    filtration = []
    for k, step in enumerate(filtration_steps):
        A = np.array(filtration_matrix <= step, int)
        for i in range(len(A)):
            A[i, i] = 0
        G = nx.to_networkx_graph(A)
        R = nx.intersection(G, G_ex)
        #H = nx.ego_graph(G,nodes,radius=m)
        filtration.append(R)
    return filtration
示例#36
0
def bayesnet_compare_plot(bayesmodel_true, bayesmodel_predicted, ax, pos):
    nx.draw_networkx_nodes(bayesmodel_true,
                           ax=ax,
                           pos=pos,
                           node_size=800,
                           node_color='g',
                           alpha=0.6)
    nx.draw_networkx_labels(bayesmodel_true,
                            ax=ax,
                            pos=pos,
                            font_size=16,
                            font_weight='bold')
    nx.draw_networkx_edges(nx.intersection(bayesmodel_true,
                                           bayesmodel_predicted),
                           ax=ax,
                           pos=pos,
                           width=4,
                           edge_color='k',
                           style='solid',
                           alpha=0.6,
                           arrowsize=25)
    nx.draw_networkx_edges(nx.difference(bayesmodel_true,
                                         bayesmodel_predicted),
                           ax=ax,
                           pos=pos,
                           width=4,
                           edge_color='r',
                           style='dashed',
                           alpha=0.6,
                           arrowsize=25)
    nx.draw_networkx_edges(nx.difference(bayesmodel_predicted,
                                         bayesmodel_true),
                           ax=ax,
                           pos=pos,
                           width=4,
                           edge_color='b',
                           style='dashed',
                           alpha=0.6,
                           arrowsize=25)
示例#37
0
 def _calc_tp_misorient(self, true_graph, pred_graph, satisfied_cs):
     true_edges = nx.edges(
         nx.intersection(true_graph.to_undirected(),
                         pred_graph.to_undirected()))
     tp_mis = 0
     for u, v in true_edges:
         if true_graph.has_edge(u, v) and true_graph.has_edge(v, u):
             assert not satisfied_cs, "True graph with CS is DAG"
             if not (pred_graph.has_edge(u, v)
                     and pred_graph.has_edge(v, u)):
                 tp_mis += 1
             continue
         if pred_graph.has_edge(u, v) and pred_graph.has_edge(v, u):
             if satisfied_cs:
                 tp_mis += 0.5
             else:
                 tp_mis += 1
             continue
         if true_graph.has_edge(u, v) and not pred_graph.has_edge(u, v):
             tp_mis += 1
             continue
         if true_graph.has_edge(v, u) and not pred_graph.has_edge(v, u):
             tp_mis += 1
     return tp_mis
示例#38
0
def intersection_all(graphs):
    """Return a new graph that contains only the edges that exist in
    all graphs.

    All supplied graphs must have the same node set.

    Parameters
    ----------
    graphs_list : list
       Multiple NetworkX graphs.  Graphs must have the same node sets.

    Returns
    -------
    R : A new graph with the same type as the first graph

    Notes
    -----
    Attributes from the graph, nodes, and edges are not copied to the new
    graph.
    """
    R = graphs.pop(0)
    for H in graphs:
        R = nx.intersection(R, H)
    return R
示例#39
0
文件: all.py 项目: pengyu/networkx
def intersection_all(graphs):
    """Return a new graph that contains only the edges that exist in
    all graphs.

    All supplied graphs must have the same node set.

    Parameters
    ----------
    graphs_list : list
       Multiple NetworkX graphs.  Graphs must have the same node sets.

    Returns
    -------
    R : A new graph with the same type as the first graph

    Notes
    -----
    Attributes from the graph, nodes, and edges are not copied to the new
    graph.
    """
    R = graphs.pop(0)
    for H in graphs:
        R = nx.intersection(R, H)
    return R
示例#40
0
 def _calc_tp(self, true_graph, pred_graph):
     return nx.number_of_edges(nx.intersection(true_graph, pred_graph))
示例#41
0
def test_mixed_type_intersection():
    G = nx.Graph()
    H = nx.MultiGraph()
    U = nx.intersection(G,H)
示例#42
0
def similarityoftwograph(A,B):
	inter=nx.intersection(A,B)
	union=nx.union(A,B)
	return nx.number_of_nodes(inter)/nx.number_of_nodes(union)
#[(1, 'c'), (3, 'c'), (1, 'b'), (3, 'b'), (2, 'a'), (3, 'a'), (4, 'd'), (1, 'd'), (2, 'b'), (4, 'b'), (2, 'c'), (4, 'c'), (1, 'a'), (4, 'a'), (2, 'd'), (3, 'd')]
GH3.edges()
#[((1, 'c'), (1, 'd')), ((1, 'c'), (1, 'b')), ((1, 'c'), (2, 'c')), ((3, 'c'), (4, 'c')), ((3, 'c'), (2, 'c')), ((3, 'c'), (3, 'b')), ((3, 'c'), (3, 'd')), ((1,'b'), (1, 'a')), ((1, 'b'), (2, 'b')), ((3, 'b'), (3, 'a')), ((3, 'b'), (2, 'b')), ((3, 'b'), (4, 'b')), ((2, 'a'), (3, 'a')), ((2, 'a'), (1, 'a')), ((2, 'a'),(2, 'b')), ((3, 'a'), (4, 'a')), ((4, 'd'), (4, 'c')), ((4, 'd'), (3, 'd')), ((1, 'd'), (2, 'd')), ((2, 'b'), (2, 'c')), ((4, 'b'), (4, 'c')), ((4, 'b'), (4, 'a')), ((2, 'c'), (2, 'd')), ((2, 'd'), (3, 'd'))]

""" Complement """
#Graphe complementaire
G1=nx.complement(G)
G1.nodes()
G1.edges()

""" Intersection de graphes """
# Les noeuds de H et G doivent etre les memes
H.clear()
H.add_nodes_from([1,2,3,4])
H.add_edge(1,2)
GH4=nx.intersection(G,H)
GH4.nodes()
#[1,2,3,4]
GH4.edges()
#[(1,2)]

""" Difference de graphes """
# Les noeuds de H et G doivent etre les memes
GH5=nx.difference(G,H)
GH5.nodes()
# [1,2,3,4]
GH5.edges()
# [((2,3),(3,4)]
# Retourne un graphe avec des aretes qui existent dans G mais pas dans H

""" Difference symetrique de graphes """