Example #1
0
def get_spatial_network_friends_from_db():
	cursor = get_database("gowalla", "network")

	network = {}
	squery = {'checkins_count': {'$gt': 0}}
	rquery = {'freq_loc': 1, 'user_id': 1, 'friends': 1}
	for item in cursor.find(squery, rquery):
		user_id = item['user_id']
		lat = float(item['freq_loc']['lat'])
		lng = float(item['freq_loc']['lng'])
		if lat != -1 and lng != -1: 
			network[user_id] = set(item['friends'])

	for user in network.keys():
		friends = [f for f in network[user] if f in network and f != user]
		network[user] = set(friends)

	G = nx.Graph()
	for node, friends in network.items():
		edges = [(node, f) for f in friends]
		G.add_edges_from(edges)

	lcc = set(nx.connected_components(G)[0])
	lcc_network = {}

	for user in lcc:
		friends = [f for f in network[user] if f in lcc] 
		lcc_network[user] = set(friends)
		
	return lcc_network
Example #2
0
def get_spatial_network_friends_from_db():
    cursor = get_database("foursquare", "network")

    network = {}
    for item in cursor.find({}):
        user_id = item['user_id']
        lat = float(item['lat'])
        lng = float(item['lng'])
        if lat != -1 and lng != -1:
            network[user_id] = set(item['friends'])

    for user, friends in network.items():
        selected_friends = [f for f in friends if f in network and f != user]
        network[user] = set(selected_friends)

    G = nx.Graph()
    for node, friends in network.items():
        edges = [(node, f) for f in friends]
        G.add_edges_from(edges)

    lcc = set(nx.connected_components(G)[0])
    lcc_network = {}

    for user in lcc:
        friends = [f for f in network[user] if f in lcc]
        lcc_network[user] = set(friends)

    return lcc_network
Example #3
0
def get_spatial_network_friends_from_db():
    selection = {'user_id': 1, 'avg_location': 1, 'friends': 1}
    cursor = get_database("gowalla", "network")

    network = {}
    for item in cursor.find({}, selection):
        user_id = item['user_id']
        lat = float(item['avg_location'][0])
        lng = float(item['avg_location'][1])
        if lat != -1 and lng != -1: network[user_id] = set(item['friends'])

    for user in network.keys():
        friends = [f for f in network[user] if f in network and f != user]
        network[user] = set(friends)

    G = nx.Graph()
    for node, friends in network.items():
        edges = [(node, f) for f in friends]
        G.add_edges_from(edges)

    lcc = set(nx.connected_components(G)[0])
    lcc_network = {}

    for user in lcc:
        friends = [f for f in network[user] if f in lcc]
        lcc_network[user] = set(friends)

    return lcc_network
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)
def ErdosRenyi(n, p):
    # generate Erdos Renyi graph given (n,p)
    G = nx.erdos_renyi_graph(n=n, p=p, seed=5)

    # Find the giant component
    Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
    G_main = G.subgraph(Gcc[0])

    # compute graph properties
    graph_properties(G, G_main, n, p)

    # draw degree distribution
    draw_degree_hist(G, n, p)

    # draw the giant component
    save_graph(G_main, n, p)
if nx.is_connected(G) is False:
    print("NOT CONNECTED, NEED TO ADD EDGES")

    # at first connect nodes with 0 neighbors
    for i in range(0, n):
        node = None
        neighbors = []
        for a in [n for n in G.neighbors(i)]:
            neighbors.append(a)
        if len(neighbors) == 0:
            node = i

            print("NODE ", node,
                  " HAS 0 neighbours. CONNECTING IT TO THE LONGEST COMPONENT")

            longest_connected_comp = sorted(nx.connected_components(G),
                                            key=len,
                                            reverse=True)[0]
            # a node in longest_connected_comp
            comp_node = next(iter(longest_connected_comp))
            print("SOURCE NODE ", node)
            print("DESTINATION NODE ", comp_node)
            G.add_edge(node, comp_node, weight=randint(1, 1))

    for a in range(
            0, len(sorted(nx.connected_components(G), key=len, reverse=True))):
        print(sorted(nx.connected_components(G), key=len, reverse=True)[a])

    #     attach smaller components to the longest component
    for i in list(
            reversed(
Example #7
0
    s = ""
    for c in denseHash:
        s += "{0:02x}".format(c)
    return s

grid = []
for i in xrange(128):
     kh = knotHash("%s-%d" % (inpt, i))
     gridline = []
     for c in kh:
         gridline.extend([int(c) for c in "{0:04b}".format(int(c, 16))])
     grid.append(gridline)

graph = nx.Graph()
for y in xrange(128):
  for x in xrange(128):
    if grid[y][x]:
      graph.add_node((y,x))
for y in xrange(128):
  for x in xrange(128):
    if y > 0:
      if grid[y][x] and grid[y-1][x]:
        graph.add_edge((y,x), (y-1,x))
    if x > 0:
      if grid[y][x] and grid[y][x-1]:
        graph.add_edge((y,x), (y,x-1))

# part 1
print sum(sum(gridline) for gridline in grid)
print len(list(nx.connected_components(graph)))
#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