def questionOne():
    """ QUESTION ONE: Create a random graph with
    N = 10000 and p = 0.0005 and analyze its properties.
    """
    N = 10000  # number of nodes
    p = 0.0005  #probability of linking

    # building the Graph
    G = nx.gnp_random_graph(N, p)

    # compute de the number of connected componentes
    cc = nx.connected_components(G)  #connected components
    ncc = nx.number_connected_components(G)  #number of connected components
    print("Number of connected components:", ncc)

    # the size of the giant component
    sortedComponents = sorted(
        cc, key=len,
        reverse=True)  # sort components in descending order (length)
    gc = G.subgraph(sortedComponents[0])  #the giant component
    print("Size of the giant component:", gc.number_of_nodes())

    # the average distance in the giant component
    ad = nx.average_shortest_path_length(gc)
    print("Average distance in the giant component:", ad)
Example #2
0
    def _compute_component_scores(self):
        components = self._components.items()

        # for each component, compute all necessary scores
        for idx, _component in components:
            component_graph = nx.subgraph(self._graph, _component)
            component_score = {
                'total_pop':
                sum(self._graph.nodes[node]['pop'] for node in _component),
                'components':
                nx.number_connected_components(component_graph),
            }

            self._component_scores[idx] = component_score
Example #3
0
        if line.endswith("\\\n"):  # continuation line, buffer, goto next
            oldline = line.strip("\\\n")
            continue

        (headname, tails) = line.split(":")

        # head
        numfind = re.compile("^\d+")  # re to find the number of this word
        head = numfind.findall(headname)[0]  # get the number

        G.add_node(head)

        for tail in tails.split():
            if head == tail:
                print("skipping self loop", head, tail, file=sys.stderr)
            G.add_edge(head, tail)

    return G


if __name__ == '__main__':
    G = roget_graph()
    print("Loaded roget_dat.txt containing 1022 categories.")
    print("digraph has %d nodes with %d edges"
          % (nx.number_of_nodes(G), nx.number_of_edges(G)))
    UG = G.to_undirected()
    print(nx.number_connected_components(UG), "connected components")

    nx.draw_circular(UG)
    plt.show()
Example #4
0
        numfind = re.compile(r"^\d+")  # re to find the number of this word
        head = numfind.findall(headname)[0]  # get the number

        G.add_node(head)

        for tail in tails.split():
            if head == tail:
                print("skipping self loop", head, tail, file=sys.stderr)
            G.add_edge(head, tail)

    return G


G = roget_graph()
print("Loaded roget_dat.txt containing 1022 categories.")
print(
    f"digraph has {nx.number_of_nodes(G)} nodes with {nx.number_of_edges(G)} edges"
)
UG = G.to_undirected()
print(nx.number_connected_components(UG), "connected components")

options = {
    "node_color": "black",
    "node_size": 1,
    "edge_color": "gray",
    "linewidths": 0,
    "width": 0.1,
}
nx.draw_circular(UG, **options)
plt.show()
import gowalla

from networkx import nx

network = gowalla.get_spatial_friendship_network()
locations = gowalla.get_users_locations()

edges = set()

for user, friends in network.items():
	l_user = locations[user]
	for friend in friends:
		l_friend = locations[friend]
		dist = gowalla.calc_spatial_dist(l_user, l_friend)
		if dist < 160:
			if (user, friend) not in edges and (friend, user) not in edges:
				edges.add((user, friend))

G = nx.Graph()

for a, b in edges:
	G.add_edge(a, b)

print nx.number_connected_components(G)
#codigo em python 3

#pacote para fazer graficos
import matplotlib.pyplot as plt
#pacote para caracterizacao de redes
from networkx import nx

M = 100  # numero de vertices
p = 0.01 # probabilidade de conexao em um par aleatorio

#geracao da rede de Erdos Renyi, tambem chamada de binomial
grafo = nx.binomial_graph(M, p)

#escreve na tela informacoes gerais do grafo
print(nx.info(grafo))

#cria uma visualizacao do grafo
nx.draw(grafo,nodesize = 0.5)
#salva a visualizacao em um arquivo
plt.savefig('fig_erdos_renyi_v1a.png',dpi = 300, bbox_inches='tight') 

#calcula o numero de componentes
nc = nx.number_connected_components(grafo)
print(nc) #escreve na tela

#calcula o tamanho (numero de vertices) da maior componente
largest_cc = max(nx.connected_components(grafo), key=len)
sc = len(largest_cc)
print(sc) #escreve na tela