Esempio n. 1
0
    def test_navigable_small_world(self):
        G = nx.navigable_small_world_graph(5, p=1, q=0)
        gg = nx.grid_2d_graph(5, 5).to_directed()
        assert_true(nx.is_isomorphic(G, gg))

        G = nx.navigable_small_world_graph(5, p=1, q=0, dim=3)
        gg = nx.grid_graph([5, 5, 5]).to_directed()
        assert_true(nx.is_isomorphic(G, gg))

        G = nx.navigable_small_world_graph(5, p=1, q=0, dim=1)
        gg = nx.grid_graph([5]).to_directed()
        assert_true(nx.is_isomorphic(G, gg))
Esempio n. 2
0
    def test_navigable_small_world(self):
        G = nx.navigable_small_world_graph(5, p=1, q=0, seed=42)
        gg = nx.grid_2d_graph(5, 5).to_directed()
        assert nx.is_isomorphic(G, gg)

        G = nx.navigable_small_world_graph(5, p=1, q=0, dim=3)
        gg = nx.grid_graph([5, 5, 5]).to_directed()
        assert nx.is_isomorphic(G, gg)

        G = nx.navigable_small_world_graph(5, p=1, q=0, dim=1)
        gg = nx.grid_graph([5]).to_directed()
        assert nx.is_isomorphic(G, gg)
Esempio n. 3
0
def adjmat(
        size,
        p=1,
        q=1,
        r=2,
        dim=2,
        inhib=0.15,
        show=True):  #CHANGE SO THAT HIGHEST OUT-DEGREE NEURONS ARE INHIBITORY
    directed_sw = nx.navigable_small_world_graph(
        size, p, q, r, dim
    )  #A navigable small-world graph is a directed grid with additional long-range connections that are chosen randomly.
    #nx.draw_circular(directed_sw)
    aspl = nx.average_shortest_path_length(directed_sw)
    acc = nx.average_clustering(directed_sw)
    print("Average shortest path length: " + str(aspl))
    print("Average clustering coefficient: " + str(acc))
    aij = nx.to_numpy_matrix(directed_sw)
    #ADDING INHIBTORY NEURONS
    if dim == 1:
        ind = [j for j in range(size)]
        inh = random.sample(ind, k=math.ceil(
            inhib *
            size))  #CHANGE SO THAT HIGHEST OUT-DEGREE NEURONS ARE INHIBITORY
    elif dim == 2:
        ind = [j for j in range(size**2)]
        inh = random.sample(ind, k=math.ceil(
            inhib * size**
            2))  #CHANGE SO THAT HIGHEST OUT-DEGREE NEURONS ARE INHIBITORY
    for i in inh:
        aij[i, :] *= -1
    if show:
        #        plt.figure()
        plt.matshow(aij)
        plt.show()
    return aij, aspl, acc  #Returns the graph adjacency matrix as a NumPy matrix.
Esempio n. 4
0
def gen_lattice_graph(nodes):
    dim = 2
    n = int(nodes**(1.0 / dim))
    p = 2  # short range connection diameter
    short_connection_count = 2 * p * (p + 1)
    connections_per_node = 50
    q = connections_per_node - short_connection_count  # long range connection count
    return nx.navigable_small_world_graph(n, p, q, 2, dim)
Esempio n. 5
0
def gen_lattice_graph(nodes):
  dim = 2
  n = int(nodes ** (1.0/dim))
  p = 2 # short range connection diameter
  short_connection_count = 2 * p * (p + 1)
  connections_per_node = 50
  q = connections_per_node - short_connection_count # long range connection count
  return nx.navigable_small_world_graph(n, p, q, 2, dim)
Esempio n. 6
0
 def __init__(self,
              n=DEFAULT_N,
              p=DEFAULT_P,
              q=DEFAULT_Q,
              r=DEFAULT_R,
              dim=DEFAULT_DIM,
              seed=None):
     self.G = nx.navigable_small_world_graph(n, p, q, r, dim, seed)
     self.pos = None
Esempio n. 7
0
def makeRandomDiGraph():
    g = nx.navigable_small_world_graph(8,1,1,11,2, 42)
    g = nx.convert_node_labels_to_integers(g, 0)

    pos = nx.spectral_layout(g)
    for n,nbrs in g.adjacency_iter():
        g.node[n]['x'] = pos[n][0]
        g.node[n]['y'] = pos[n][1]
        #g.node[n]['name'] = n #str(n)
        for nbr,eattr in nbrs.items():
            eattr['weight'] = np.linalg.norm(pos[nbr]-pos[n],2) 
    
    return (g,pos)
Esempio n. 8
0
def make_small_worlds():
    #for N in [10,20,30,40,50]:
    for N in [3, 10,20,30,40,50]:
        G = nx.navigable_small_world_graph(N, p=1, q=1, r=2, dim=2, seed=None).to_undirected()
        G = nx.relabel_nodes(G, mapping)
        
        R = random.sample(G.nodes(), N)
        name = 'smallworld-{0}-0'.format(N)
        write_graph(G, name, mapping((0,0)), mapping((N-1,N-1)), R)

        R = random.sample(G.nodes(), (N*N)/2)
        name = 'smallworld-{0}-1'.format(N)
        write_graph(G, name, mapping((0,0)), mapping((N-1,N-1)),R)
Esempio n. 9
0
def make_small_worlds():
    #for N in [10,20,30,40,50]:
    for N in [3, 10, 20, 30, 40, 50]:
        G = nx.navigable_small_world_graph(N, p=1, q=1, r=2, dim=2,
                                           seed=None).to_undirected()
        G = nx.relabel_nodes(G, mapping)

        R = random.sample(G.nodes(), N)
        name = 'smallworld-{0}-0'.format(N)
        write_graph(G, name, mapping((0, 0)), mapping((N - 1, N - 1)), R)

        R = random.sample(G.nodes(), (N * N) / 2)
        name = 'smallworld-{0}-1'.format(N)
        write_graph(G, name, mapping((0, 0)), mapping((N - 1, N - 1)), R)
Esempio n. 10
0
 def SM(self, r: int):
     sm = nx.navigable_small_world_graph(32, 1, 1, r)
     dic = {}
     enum = 0
     for i in range(0, 32):
         for j in range(0, 32):
             dic[(i, j)] = enum
             enum += 1
     g = nx.DiGraph()
     #print(len(sm.nodes()))
     g.add_nodes_from(range(0, 1024))
     for e in sm.edges():
         g.add_edge(dic[e[0]], dic[e[1]])
     return g
Esempio n. 11
0
   def graphGenerator():
	if args.graph_type == "erdos_renyi":
	    return networkx.erdos_renyi_graph(args.graph_size,args.graph_p)
	if args.graph_type == "balanced_tree":
	    ndim = int(np.ceil(np.log(args.graph_size)/np.log(args.graph_degree)))
	    return networkx.balanced_tree(args.graph_degree,ndim)
	if args.graph_type == "cicular_ladder":
	    ndim = int(np.ceil(args.graph_size*0.5))
	    return  networkx.circular_ladder_graph(ndim)
	if args.graph_type == "cycle":
	    return  networkx.cycle_graph(args.graph_size)
	if args.graph_type == 'grid_2d':
	    ndim = int(np.ceil(np.sqrt(args.graph_size)))
            return networkx.grid_2d_graph(ndim,ndim)
	if args.graph_type == 'lollipop':
	    ndim = int(np.ceil(args.graph_size*0.5))
	    return networkx.lollipop_graph(ndim,ndim)
	if args.graph_type =='expander':
	    ndim = int(np.ceil(np.sqrt(args.graph_size)))
	    return networkx.margulis_gabber_galil_graph(ndim)
	if args.graph_type =="hypercube":
	    ndim = int(np.ceil(np.log(args.graph_size)/np.log(2.0)))
	    return networkx.hypercube_graph(ndim)
	if args.graph_type =="star":
	    ndim = args.graph_size-1
	    return networkx.star_graph(ndim)
	if args.graph_type =='barabasi_albert':
	    return networkx.barabasi_albert_graph(args.graph_size,args.graph_degree)
	if args.graph_type =='watts_strogatz':
	    return networkx.connected_watts_strogatz_graph(args.graph_size,args.graph_degree,args.graph_p)
	if args.graph_type =='regular':
	    return networkx.random_regular_graph(args.graph_degree,args.graph_size)
	if args.graph_type =='powerlaw_tree':
	    return networkx.random_powerlaw_tree(args.graph_size)
	if args.graph_type =='small_world':
	    ndim = int(np.ceil(np.sqrt(args.graph_size)))
	    return networkx.navigable_small_world_graph(ndim)
	if args.graph_type =='geant':
	    return topologies.GEANT()
	if args.graph_type =='dtelekom':
	    return topologies.Dtelekom()
	if args.graph_type =='abilene':
	    return topologies.Abilene()
	if args.graph_type =='servicenetwork':
	    return topologies.ServiceNetwork()
Esempio n. 12
0
def adjmat(size, p=1, q=1, r=2, dim=2, show=True):  #default is p=1 and r=2
    directed_sw = nx.navigable_small_world_graph(
        size, p, q, r, dim
    )  #A navigable small-world graph is a directed grid with additional long-range connections that are chosen randomly.
    nx.draw_circular(directed_sw)
    aspl = nx.average_shortest_path_length(directed_sw)
    acc = nx.average_clustering(directed_sw)
    print("Average shortest path length: " + str(aspl))
    print("Average clustering coefficient: " + str(acc))
    aij = nx.to_numpy_matrix(directed_sw)
    #ADDING INHIBTORY NEURONS
    ind = [j for j in range(size**2)]
    inh = random.sample(ind, k=math.ceil(
        0.15 * size**2))  #15% OF NEURONS ARE INHIBITORY
    for i in inh:
        aij[i, :] *= -1
    if show:
        plt.matshow(aij)
    return aij  #Returns the graph adjacency matrix as a NumPy matrix.
Esempio n. 13
0
def geometric_graphs():
    print("Random geometric graphs")
    G = nx.random_geometric_graph(20, 0.1)
    draw_graph(G)
    n = 20
    p = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
    G = nx.random_geometric_graph(n, 0.2, pos=p)
    draw_graph(G)
    print("Geographical threshold graph")
    n = 10
    w = {i: random.expovariate(1.0) for i in range(n)}
    G = nx.geographical_threshold_graph(n, 30, weight=w)
    draw_graph(G)
    print("Waxman graph")
    G = nx.waxman_graph(27)
    draw_graph(G)
    print("Navigable small world graph")
    G = nx.navigable_small_world_graph(7)
    draw_graph(G)
Esempio n. 14
0
def navigable_small_world_graph(n):
    g_aux = nx.navigable_small_world_graph(n,1,5, 1.0)
    g = nx.Graph()

    index = {}
    
    for idx, v in enumerate(g_aux.nodes()):
        (x,y) = v
        g.add_node(idx)
        g.node[idx]["x"] = x
        g.node[idx]["y"] = y
        index[v] = idx
    
    for v in g_aux.nodes():
        for w in g_aux.edge[v]:
            idv = index[v]
            idw = index[w]
            g.add_edge(idv, idw, cost=1)#distance(g, idv, idw))
    
    return g
def generate_world_graph(n=6, p=1, q=4, r=2):
    """
    Uses nx.navigable_small_world_graph to generate a directed grid with additional
    long range connections that are chosen randomly. For each node, each out edge is
    assigned a probability such that the sum of all probabilities <= 1.0 (where the
    remainder is the probability of staying in the node). Nodes are also assigned unique
    random place names and given data attributes for use in the Graph.
    """
    G = nx.navigable_small_world_graph(n, p=p, q=q, r=r, dim=2)
    for node in G.nodes():
        # Assign probabilities to all edges such that probabilities are <= 1
        # TODO: ensure there isn't an edge to self
        dist = np.random.dirichlet(np.ones(G.out_degree(node) + 1), size=1)[0]
        for i, edge in enumerate(G.out_edges(node)):
            G.edges[edge]["weight"] = dist[i]
            G.edges[edge]["distance"] = np.linalg.norm(
                np.asarray(edge[0]) - np.asarray(edge[1])
            )

        # Assign the travel distribution to the node for selection
        G.nodes[node]["prob"] = np.cumsum(dist)

    G.name = "Navigable Small World"
    return G
Esempio n. 16
0
# Set how many episodes you want?
episodes = 10000

# Set the epsilon for e-greedy action selection.
epsilon = 0.1

# Set the step size for updating action-value function.
alpha = 0.1

# Select which graph you want? Also set the source U and target V
# G = nx.convert_node_labels_to_integers(nx.grid_2d_graph(N, N))
# U = 0
# V = (N*N - 1)

G = nx.convert_node_labels_to_integers(nx.navigable_small_world_graph(N))
U = 0
V = (N*N - 1)

################################################################################
def clear_render():
    plt.clf()
    nx.draw_networkx(G, pos=pos)
    plt.draw()


def is_valid(g):  # returns a boolean. g is any subgraph of G.
    # If not a simple path, then g is "not valid".
    if not nx.is_simple_path(G, list(g.nodes)):
        return False
Esempio n. 17
0
for i in range(default_no_entities):
    G = nx.scale_free_graph(default_size,
                            alpha=0.01,
                            beta=0.84,
                            gamma=0.15,
                            create_using=nx.Graph)
    makedir(path_output_data_type + 'entity_' + str(i))
    save_graph(path_output_data_type + 'entity_' + str(i) + '/' + 'J_ij.csv',
               G)

    #Random Small World Graph
    #path_output_data_type = path_output_data + 'small_world/'
    #makedir(path_output_data_type)

    #for i in range(default_no_entities):
    G = nx.navigable_small_world_graph(np.sqrt(default_size).astype(np.int8))
#    makedir(path_output_data_type + 'entity_' + str(i))
#    save_graph(path_output_data_type + 'entity_' + str(i) + '/' + 'J_ij.csv', G)

# Random Intersection Graph
path_output_data_type = path_output_data + 'intersection/'
makedir(path_output_data_type)

for i in range(default_no_entities):
    G = nx.k_random_intersection_graph(default_size, 10, 2)
    makedir(path_output_data_type + 'entity_' + str(i))
    save_graph(path_output_data_type + 'entity_' + str(i) + '/' + 'J_ij.csv',
               G)

# Social Graph
path_output_data = path_input + 'social/'
Esempio n. 18
0
def gen_laplacian(data_num=DATA_NUM, opt=27, cache=False):
    label = None

    if cache:
        print('Loading cached graph')
        graph = pk.load(open('tmp/g.pk', 'rb'))
    else:
        print('Generating graph opt {}'.format(opt))

        if 1 == opt:
            graph = gen_rand_graph(data_num=data_num)
        if 2 == opt:
            top_num = random.randint(1, data_num)
            bottom_num = data_num - top_num
            graph = nx.bipartite.random_graph(top_num, bottom_num, 0.9)
            label = [d['bipartite'] for n, d in graph.nodes(data=True)]
        elif 3 == opt:
            graph = nx.balanced_tree(4, 5)
        elif 4 == opt:
            graph = nx.complete_graph(data_num)
        elif 5 == opt:
            no1 = random.randint(1, data_num)
            no2 = random.randint(1, int(data_num / no1))
            no3 = data_num / no1 / no2
            graph = nx.complete_multipartite_graph(no1, no2, no3)
        elif 6 == opt:
            graph = nx.circular_ladder_graph(data_num)
        elif 7 == opt:
            graph = nx.cycle_graph(data_num)
        elif 8 == opt:
            graph = nx.dorogovtsev_goltsev_mendes_graph(5)
        elif 9 == opt:
            top_num = int(random.random() * data_num)
            bottom_num = data_num / top_num
            graph = nx.grid_2d_graph(top_num, bottom_num)
        elif 10 == opt:
            no1 = random.randint(1, data_num)
            no2 = random.randint(1, int(data_num / no1))
            no3 = data_num / no1 / no2
            graph = nx.grid_graph([no1, no2, no3])
        elif 11 == opt:
            graph = nx.hypercube_graph(10)
        elif 12 == opt:
            graph = nx.ladder_graph(data_num)
        elif 13 == opt:
            top_num = int(random.random() * data_num)
            bottom_num = data_num - top_num
            graph = nx.lollipop_graph(top_num, bottom_num)
        elif 14 == opt:
            graph = nx.path_graph(data_num)
        elif 15 == opt:
            graph = nx.star_graph(data_num)
        elif 16 == opt:
            graph = nx.wheel_graph(data_num)
        elif 17 == opt:
            graph = nx.margulis_gabber_galil_graph(35)
        elif 18 == opt:
            graph = nx.chordal_cycle_graph(data_num)
        elif 19 == opt:
            graph = nx.fast_gnp_random_graph(data_num, random.random())
        elif 20 == opt:  # jump eigen value
            graph = nx.gnp_random_graph(data_num, random.random())
        elif 21 == opt:  # disconnected graph
            graph = nx.dense_gnm_random_graph(data_num, data_num / 2)
        elif 22 == opt:  # disconnected graph
            graph = nx.gnm_random_graph(data_num, data_num / 2)
        elif 23 == opt:
            graph = nx.erdos_renyi_graph(data_num, data_num / 2)
        elif 24 == opt:
            graph = nx.binomial_graph(data_num, data_num / 2)
        elif 25 == opt:
            graph = nx.newman_watts_strogatz_graph(data_num, 5,
                                                   random.random())
        elif 26 == opt:
            graph = nx.watts_strogatz_graph(data_num, 5, random.random())
        elif 26 == opt:  # smooth eigen
            graph = nx.connected_watts_strogatz_graph(data_num, 5,
                                                      random.random())
        elif 27 == opt:  # smooth eigen
            graph = nx.random_regular_graph(5, data_num)
        elif 28 == opt:  # smooth eigen
            graph = nx.barabasi_albert_graph(data_num, 5)
        elif 29 == opt:  # smooth eigen
            graph = nx.powerlaw_cluster_graph(data_num, 5, random.random())
        elif 30 == opt:  # smooth eigen
            graph = nx.duplication_divergence_graph(data_num, random.random())
        elif 31 == opt:
            p = random.random()
            q = random.random()
            graph = nx.random_lobster(data_num, p, q)
        elif 32 == opt:
            p = random.random()
            q = random.random()
            k = random.random()

            graph = nx.random_shell_graph([(data_num / 3, 50, p),
                                           (data_num / 3, 40, q),
                                           (data_num / 3, 30, k)])
        elif 33 == opt:  # smooth eigen
            top_num = int(random.random() * data_num)
            bottom_num = data_num - top_num
            graph = nx.k_random_intersection_graph(top_num, bottom_num, 3)
        elif 34 == opt:
            graph = nx.random_geometric_graph(data_num, .1)
        elif 35 == opt:
            graph = nx.waxman_graph(data_num)
        elif 36 == opt:
            graph = nx.geographical_threshold_graph(data_num, .5)
        elif 37 == opt:
            top_num = int(random.random() * data_num)
            bottom_num = data_num - top_num
            graph = nx.uniform_random_intersection_graph(
                top_num, bottom_num, .5)

        elif 39 == opt:
            graph = nx.navigable_small_world_graph(data_num)
        elif 40 == opt:
            graph = nx.random_powerlaw_tree(data_num, tries=200)
        elif 41 == opt:
            graph = nx.karate_club_graph()
        elif 42 == opt:
            graph = nx.davis_southern_women_graph()
        elif 43 == opt:
            graph = nx.florentine_families_graph()
        elif 44 == opt:
            graph = nx.complete_multipartite_graph(data_num, data_num,
                                                   data_num)

        # OPT 1
        # norm_lap = nx.normalized_laplacian_matrix(graph).toarray()

        # OPT 2: renormalized

        # pk.dump(graph, open('tmp/g.pk', 'wb'))

    # plot_graph(graph, label)
    # note difference: normalized laplacian and normalzation by eigenvalue
    norm_lap, eigval, eigvec = normalize_lap(graph)

    return graph, norm_lap, eigval, eigvec
Esempio n. 19
0
import networkx
import pynetsim

a = networkx.navigable_small_world_graph(1000, 4, 2, 1, 1).to_undirected()
pynetsim.randomize(a)
b = a.copy()
c = a.copy()

numattackers = 2
attackers = list()

pynetsim.pickmalnodes(a, attackers, 2)
pynetsim.attacksimulation(a, attackers)

for m in attackers:
	print m

locations = list()
for n in a.nodes():
	locations.append(n[0])

hist(locations, 100)
Esempio n. 20
0
import matplotlib.pyplot as plt
import networkx as nx

G = nx.navigable_small_world_graph(
    2, 1, 1, 2, 2)  # Not Really sure what to do with this...
nx.draw(G)
plt.show()
Esempio n. 21
0
import networkx
import pynetsim

a = networkx.navigable_small_world_graph(1000, 4, 2, 1, 1).to_undirected()
pynetsim.randomize(a)

attackers = list()
pynetsim.pickmalnodes(a, attackers, 10)

pynetsim.attacksimulation(a, attackers)