Beispiel #1
0
def _construct_graph_objs():

    graphs = []
    for graph_type in [nx.Graph, nx.MultiGraph, nx.DiGraph, nx.MultiDiGraph]:
        g1 = nx.from_edgelist([("2", "1"), ("3", "1"), ("1", "0")],
                              create_using=graph_type)

        g2 = g1.copy()
        attrs = {
            n: {
                l: i
            }
            for i, (n, l) in enumerate(zip(g2.nodes, string.ascii_lowercase))
        }
        nx.set_node_attributes(g2, attrs)

        g3 = copy.deepcopy(g2)
        attrs = {
            e: {
                l: i
            }
            for i, (e, l) in enumerate(zip(g2.edges, string.ascii_lowercase))
        }
        nx.set_edge_attributes(g3, attrs)

        graphs.extend([(g1, True), (g2, True), (g3, True)])

    graphs.extend([
        # one out edge; these are 'valid' in `nereid`
        (nx.gn_graph(25, seed=42), True),
        # many out edges; these are not 'valid' in `nereid`
        (nx.gnc_graph(25, seed=42), False),
    ])
    return graphs
    def RandomDirectedGNC(self, n, seed=None):
        """
        Returns a random GNC (growing network with copying) digraph with n
        vertices.

        The digraph is constructed by adding vertices with a link to one
        previously added vertex. The vertex to link to is chosen with a
        preferential attachment model, i.e. probability is proportional to
        degree. The new vertex is also linked to all of the previously
        added vertex's successors.

        INPUT:


        -  ``n`` - number of vertices.

        -  ``seed`` - for the random number generator


        EXAMPLE::

            sage: D = digraphs.RandomDirectedGNC(25)
            sage: D.edges(labels=False)
            [(1, 0), (2, 0), (2, 1), (3, 0), (4, 0), (4, 1), (5, 0), (5, 1), (5, 2), (6, 0), (6, 1), (7, 0), (7, 1), (7, 4), (8, 0), (9, 0), (9, 8), (10, 0), (10, 1), (10, 2), (10, 5), (11, 0), (11, 8), (11, 9), (12, 0), (12, 8), (12, 9), (13, 0), (13, 1), (14, 0), (14, 8), (14, 9), (14, 12), (15, 0), (15, 8), (15, 9), (15, 12), (16, 0), (16, 1), (16, 4), (16, 7), (17, 0), (17, 8), (17, 9), (17, 12), (18, 0), (18, 8), (19, 0), (19, 1), (19, 4), (19, 7), (20, 0), (20, 1), (20, 4), (20, 7), (20, 16), (21, 0), (21, 8), (22, 0), (22, 1), (22, 4), (22, 7), (22, 19), (23, 0), (23, 8), (23, 9), (23, 12), (23, 14), (24, 0), (24, 8), (24, 9), (24, 12), (24, 15)]
            sage: D.show()  # long time

        REFERENCE:

        - [1] Krapivsky, P.L. and Redner, S. Network Growth by
          Copying, Phys. Rev. E vol. 71 (2005), p. 036118.
        """
        if seed is None:
            seed = current_randstate().long_seed()
        import networkx
        return DiGraph(networkx.gnc_graph(n, seed=seed))
Beispiel #3
0
 def test_hmc_loss_speed(self):
     print("\nCalculation time test begins")
     data_sizes = [25, 100, 400]
     node_sizes = [50, 200, 400]
     for data_size in data_sizes:
         for node_size in node_sizes:
             true_label = np.random.randint(2, size=(data_size,node_size))
             pred_label = np.random.randint(2, size=(data_size,node_size))
             graph = nx.gnc_graph(node_size)
             label_list = list(range(node_size))
             start_time = time.time()
             cost_list = get_cost_list(graph, 0, label_list)
             cost_list_time = time.time()
             hmc_loss_score(true_label,
                            pred_label,
                            graph,
                            0,
                            label_list,
                            cost_list)
             end_time = time.time()
             whole_calc_time = end_time - start_time
             cost_calc_time = cost_list_time - start_time
             hmc_calc_time = end_time - cost_list_time
             print("Whole calc. time:{0}, Cost list calc. time:{1}, HMC-loss calc. time:{2}, data size:{3}, node size:{4}".format(whole_calc_time, cost_calc_time, hmc_calc_time, data_size, node_size))
     return 0
Beispiel #4
0
    def RandomDirectedGNR(self, n, p, seed=None):
        """
        Returns a random GNR (growing network with redirection) digraph
        with n vertices and redirection probability p.

        The digraph is constructed by adding vertices with a link to one
        previously added vertex. The vertex to link to is chosen uniformly.
        With probability p, the arc is instead redirected to the successor
        vertex. The digraph is always a tree.

        INPUT:

        -  ``n`` - number of vertices.

        -  ``p`` - redirection probability

        -  ``seed`` - for the random number generator.

        EXAMPLE::

            sage: D = digraphs.RandomDirectedGNR(25, .2)
            sage: D.edges(labels=False)
            [(1, 0), (2, 0), (2, 1), (3, 0), (4, 0), (4, 1), (5, 0), (5, 1), (5, 2), (6, 0), (6, 1), (7, 0), (7, 1), (7, 4), (8, 0), (9, 0), (9, 8), (10, 0), (10, 1), (10, 2), (10, 5), (11, 0), (11, 8), (11, 9), (12, 0), (12, 8), (12, 9), (13, 0), (13, 1), (14, 0), (14, 8), (14, 9), (14, 12), (15, 0), (15, 8), (15, 9), (15, 12), (16, 0), (16, 1), (16, 4), (16, 7), (17, 0), (17, 8), (17, 9), (17, 12), (18, 0), (18, 8), (19, 0), (19, 1), (19, 4), (19, 7), (20, 0), (20, 1), (20, 4), (20, 7), (20, 16), (21, 0), (21, 8), (22, 0), (22, 1), (22, 4), (22, 7), (22, 19), (23, 0), (23, 8), (23, 9), (23, 12), (23, 14), (24, 0), (24, 8), (24, 9), (24, 12), (24, 15)]
            sage: D.show()  # long time

        REFERENCE:

        - [1] Krapivsky, P.L. and Redner, S. Organization of Growing
          Random Networks, Phys. Rev. E vol. 63 (2001), p. 066123.
        """
        if seed is None:
            seed = current_randstate().long_seed()
        import networkx
        return DiGraph(networkx.gnc_graph(n, seed=seed))
Beispiel #5
0
    def RandomDirectedGNR(self, n, p, seed=None):
        """
        Returns a random GNR (growing network with redirection) digraph
        with n vertices and redirection probability p.

        The digraph is constructed by adding vertices with a link to one
        previously added vertex. The vertex to link to is chosen uniformly.
        With probability p, the arc is instead redirected to the successor
        vertex. The digraph is always a tree.

        INPUT:

        -  ``n`` - number of vertices.

        -  ``p`` - redirection probability

        -  ``seed`` - for the random number generator.

        EXAMPLE::

            sage: D = digraphs.RandomDirectedGNR(25, .2)
            sage: D.edges(labels=False)
            [(1, 0), (2, 0), (2, 1), (3, 0), (4, 0), (4, 1), (5, 0), (5, 1), (5, 2), (6, 0), (6, 1), (7, 0), (7, 1), (7, 4), (8, 0), (9, 0), (9, 8), (10, 0), (10, 1), (10, 2), (10, 5), (11, 0), (11, 8), (11, 9), (12, 0), (12, 8), (12, 9), (13, 0), (13, 1), (14, 0), (14, 8), (14, 9), (14, 12), (15, 0), (15, 8), (15, 9), (15, 12), (16, 0), (16, 1), (16, 4), (16, 7), (17, 0), (17, 8), (17, 9), (17, 12), (18, 0), (18, 8), (19, 0), (19, 1), (19, 4), (19, 7), (20, 0), (20, 1), (20, 4), (20, 7), (20, 16), (21, 0), (21, 8), (22, 0), (22, 1), (22, 4), (22, 7), (22, 19), (23, 0), (23, 8), (23, 9), (23, 12), (23, 14), (24, 0), (24, 8), (24, 9), (24, 12), (24, 15)]
            sage: D.show()  # long time

        REFERENCE:

        - [1] Krapivsky, P.L. and Redner, S. Organization of Growing
          Random Networks, Phys. Rev. E vol. 63 (2001), p. 066123.
        """
        if seed is None:
            seed = current_randstate().long_seed()
        import networkx
        return DiGraph(networkx.gnc_graph(n, seed=seed))
Beispiel #6
0
    def RandomDirectedGNC(self, n, seed=None):
        """
        Returns a random GNC (growing network with copying) digraph with n
        vertices.

        The digraph is constructed by adding vertices with a link to one
        previously added vertex. The vertex to link to is chosen with a
        preferential attachment model, i.e. probability is proportional to
        degree. The new vertex is also linked to all of the previously
        added vertex's successors.

        INPUT:


        -  ``n`` - number of vertices.

        -  ``seed`` - for the random number generator


        EXAMPLE::

            sage: D = digraphs.RandomDirectedGNC(25)
            sage: D.edges(labels=False)
            [(1, 0), (2, 0), (2, 1), (3, 0), (4, 0), (4, 1), (5, 0), (5, 1), (5, 2), (6, 0), (6, 1), (7, 0), (7, 1), (7, 4), (8, 0), (9, 0), (9, 8), (10, 0), (10, 1), (10, 2), (10, 5), (11, 0), (11, 8), (11, 9), (12, 0), (12, 8), (12, 9), (13, 0), (13, 1), (14, 0), (14, 8), (14, 9), (14, 12), (15, 0), (15, 8), (15, 9), (15, 12), (16, 0), (16, 1), (16, 4), (16, 7), (17, 0), (17, 8), (17, 9), (17, 12), (18, 0), (18, 8), (19, 0), (19, 1), (19, 4), (19, 7), (20, 0), (20, 1), (20, 4), (20, 7), (20, 16), (21, 0), (21, 8), (22, 0), (22, 1), (22, 4), (22, 7), (22, 19), (23, 0), (23, 8), (23, 9), (23, 12), (23, 14), (24, 0), (24, 8), (24, 9), (24, 12), (24, 15)]
            sage: D.show()  # long time

        REFERENCE:

        - [1] Krapivsky, P.L. and Redner, S. Network Growth by
          Copying, Phys. Rev. E vol. 71 (2005), p. 036118.
        """
        if seed is None:
            seed = current_randstate().long_seed()
        import networkx
        return DiGraph(networkx.gnc_graph(n, seed=seed))
Beispiel #7
0
def _construct_graphs():
    graphs = [
        # one out edge; these are 'valid' in `nereid`
        (nx.gn_graph(25, seed=42)),
        # many out edges; these are not 'valid' in `nereid`
        (nx.gnc_graph(25, seed=42)),
    ]

    return graphs
Beispiel #8
0
def test_invalid_graph(contexts):
    context = contexts["default"]

    g = nx.gnc_graph(10)
    data = generate_random_watershed_solve_request_from_graph(
        g,
        context,
    )

    g, err = initialize_graph(data, False, context)

    assert len(err) > 0
Beispiel #9
0
 def graph_sel(graphType, n, p):
     '''
     Funzione che genera e restituisce un grafo del tipo prescelto.
     Viene invocata solo se, nell'inizializzazione del repository,
     non viene direttamente specifica un grafo ma solo un graph type.
     '''
     return {
         'gn': lambda: nx.gn_graph(n),
         'gnr': lambda: nx.gnr_graph(n, p),
         'gnc': lambda: nx.gnc_graph(n),
         'scale_free': lambda: nx.scale_free_graph(n),
         'erdos_renyi': lambda: nx.erdos_renyi_graph(n, p, directed=True),
         'nSCC_graph': lambda: self.nSCC_graph(n)
     }.get(graphType, graphType)()
def create_random_followers_graph(followers_list,fil=None):
    '''Creates a random_followers_graph with nodes the followers_list'''
    if fil==None:
        fil='friendship_graph.graphml'
    n=len(followers_list)
    G=nx.gnc_graph(n)
    F=G.__class__()
    mapping_f={}
    for i,v in enumerate(followers_list):
        mapping_f[i]=v
    for edg in G.edges(data=True):
        F.add_edge(mapping_f[edg[0]],mapping_f[edg[1]],attr_dict=edg[2])
    for i in G.nodes():
        att=G.node[i]
        F.add_node(mapping_f[i], attr_dict=att)
    nx.write_graphml(F,fil)
Beispiel #11
0
def directed_graphs():
    print("Directed graphs")
    print("Growing network")
    D = nx.gn_graph(10)  # the GN graph
    draw_graph(D)
    G = D.to_undirected()  # the undirected version
    draw_graph(G)
    D = nx.gn_graph(10, kernel=lambda x: x**1.5)  # A_k = k^1.5
    draw_graph(D)
    print("Growing network graph")
    D = nx.gnr_graph(n=11, p=0.3)
    draw_graph(D)
    G = D.to_undirected()
    draw_graph(G)
    print("Growing network with copying graph")
    D = nx.gnc_graph(n=7)
    draw_graph(D)
    G = D.to_undirected()
    draw_graph(G)
    print("Scale-free graph")
    G = nx.scale_free_graph(10)
    draw_graph(G)
Beispiel #12
0
def named_validation_responses(client):

    route = API_LATEST + "/network/validate"
    responses = {}
    slow_valid = json.dumps(
        clean_graph_dict(nx.gnr_graph(15000, p=0.05, seed=42)))
    slow_invalid = json.dumps(clean_graph_dict(nx.gnc_graph(15000, seed=42)))

    init_post_requests = [
        ("valid_graph_response_fast",
         get_payload("network_validate_is_valid.json")),
        (
            "invalid_graph_response_fast",
            get_payload("network_validate_is_invalid_cycle.json"),
        ),
        ("valid_graph_response_slow", slow_valid),
        ("invalid_graph_response_slow", slow_invalid),
    ]

    for name, payload in init_post_requests:
        response = client.post(route, data=payload)
        responses[name] = response

    yield responses
Beispiel #13
0
import random
import itertools
import numpy
import scipy
import networkx as nx
import matplotlib.pyplot as plt

N = 10
"""
G = nx.DiGraph()
for u in range(n):
    for v in range(u+1, n):
        if random.random() < 0.8*u/n:
            G.add_edge(u, v)
"""
G = nx.gnc_graph(N)
A = nx.to_scipy_sparse_matrix(G, dtype=float)

Nu = scipy.sparse.linalg.norm(A, ord=0, axis=1)
Nu = (1 / Nu)
Nu[numpy.isinf(Nu)] = 0
A = A.T.multiply(Nu).T

print(A.todense())
eigvals, eigvecs = numpy.linalg.eig(A.todense())
print(eigvals)

plt.figure(figsize=(10, 10))
pos = nx.spring_layout(G)
nx.draw_networkx_labels(G, pos)
nx.draw(G, pos)
Beispiel #14
0
 def test_voterank_centrality_3(self):
     G = nx.gnc_graph(10, seed=7)
     d = nx.voterank(G, 4)
     exact = [3, 6, 8]
     assert exact == d
Beispiel #15
0
        (
            [["a", "b"], ["b", "c"], ["d", "c"], ["c", "e"], ["c", "e"]],
            False,
            ([], [], [["c", "2"]], [["c", "e"]]),
        ),  # duplicate edge
        (
            [["a", "b"], ["b", "c"], ["d", "c"], ["a", "e"]],
            False,
            ([], [], [["a", "2"]], []),
        ),  # multiple out edges, a->b & a->e
    ],
)
def test_validate_network(edgelist, isvalid, result):

    g = nx.from_edgelist(edgelist, create_using=nx.MultiDiGraph)
    assert isvalid == is_valid(g)
    assert result == validate_network(g)


@pytest.mark.parametrize(
    "g, expected",
    [  # multiple out connections
        (nx.gnc_graph(10, seed=42), False),
        # multiple out connections, cycles, duplicated edges
        (nx.random_k_out_graph(10, 2, 1, seed=42), False),
        (nx.gn_graph(10, seed=42), True),
    ],
)
def test_isvalid(g, expected):
    assert expected == is_valid(g)
Beispiel #16
0
# nx.draw(g)		# drawing the Graph
# nx.draw_circular(g)		# to draw the graph in circular form 
# nx.draw_spring(g)		# to draw the graph in spring form 
# plt.show()		# plotting the graph 


# Commands for Labeling and Coloring the Graph
# nx.draw_circular(g, node_color='bisque', with_labels='TRUE')		# to draw the graph with bisque color and nodes marked with with_labels


# Command to show the stats of the Graph
# stats = nx.degree(g)	# this method will give the number of nodes, edges, avg. degree of the graph
# print stats
# print nx.degree(g)		# this methood will display the degree of each node in the graph


# Graph Generators Functions
# g = nx.complete_graph(25)		# this method will make a complete graph with 25 nodes
# nx.draw(g, node_color='bisque', with_labels='TRUE')

g = nx.gnc_graph(7, seed=25)	# creating a random graph with GNC function
# nx.draw(g, node_color='bisque', with_labels='TRUE')

ego_g = nx.ego_graph(g, 3, radius=5)	# creating a ego graph as a sub graph to g, 3 is the center nodes and radius of the graph is 5
nx.draw(ego_g, node_color='bisque', with_labels='TRUE')

plt.show()



Beispiel #17
0
#%%
# Removing nodes
G.remove_node(1)
nx.draw_circular(G, node_color='bisque', with_labels=True)

#%%
# Graph properties
# Show the stats.
sum_stats = nx.info(G)
print(sum_stats)

#%%
# CLoser views
print(nx.degree(G))

#%%
# An automatic graph generator, NO manual inputs needed.
G = nx.complete_graph(25)
nx.draw(G, node_color='bisque', with_labels=True)

#%%
G = nx.gnc_graph(7, seed=25)
nx.draw(G, node_color='bisque', with_labels=True)

#%%
# Ego graph, Social networks use these.
ego_G = nx.ego_graph(G, 3, radius=5)
nx.draw(G, node_color='bisque', with_labels=True)

#%%
                  (8, 16)])
nx.draw(G)

nx.draw_circular(G, node_color='bisque', with_labels=True)
nx.draw_spring(G)

G.remove_node(1)

sum_stats = nx.info(G)
print(sum_stats)
print(nx.degree(G))

G = nx.complete_graph(25)
nx.draw(G, node_color='bisque', with_labels=True)

G = nx.gnc_graph(7, seed=25)  #directed graph
nx.draw(G, node_color='bisque', with_labels=True)

ego_G = nx.ego_graph(G, 3, radius=5)
nx.draw(G, node_color='bisque', with_labels=True)

#=============================================================================

# Social network

# generate a graph object and edgelist
DG = nx.gn_graph(7, seed=25)
#for line in nx.generate_edgelist(DG,data=False):print(line)

# assign attributes to nodes
DG.node[0]['name'] = 'Alice'