def set_up_topology(topology, number_of_nodes, desired_avg_degree, ba_m):
    # generate network depending on topology parameter
    if topology == "UNIFORM":
        net_p2p = nx.random_degree_sequence_graph(
            [desired_avg_degree for i in range(number_of_nodes)])

    elif topology == "ER":
        p = desired_avg_degree / number_of_nodes
        net_p2p = nx.fast_gnp_random_graph(number_of_nodes, p)

    elif topology == "BA":
        net_p2p = nx.barabasi_albert_graph(number_of_nodes, ba_m)

    # get largest connected component
    lcc_set = max(nx.connected_components(net_p2p), key=len)
    net_p2p = net_p2p.subgraph(lcc_set).copy()
    # some nodes may have been removed because they were not port of the lcc.
    # relabel nodes so that only nodes in lcc are labelled. (without it we run into problems where node labels are higher than the number of nodes -> loops run into indexing problems)
    net_p2p = nx.convert_node_labels_to_integers(
        net_p2p, first_label=0)

    # some nodes may have been removed as they were not part of the lcc -> update num nodes
    number_of_nodes = len(net_p2p)
    # (brute-forcing number of selfish nodes to stay unchanged)
    number_honest_nodes = number_of_nodes - number_selfish_nodes

    return net_p2p, number_honest_nodes
def random_simple_deg_seq(sequence, brain_size=[7., 7., 7.], seed=None,
                          tries=10):
    '''Wrapper function to get a SIMPLE (no parallel or self-loop edges) graph
    that has a given degree sequence.

    This graph is used conventionally as a control because it yields a random
    graph that accounts for degree distribution.

    Parameters:
        sequence: list of int
            Degree of each node to be added to the graph.
        brain_size: list of 3 floats
            Size of the brain to use when distributing  node locations.
            Added for convenience, but does not affect connectivity pattern.
        seed: hashable object for random seed
            Seed for the random number generator.
        tries: int
            Number of attempts at creating graph (function will retry if
            self-loops exist.
    Returns:
        Networkx graph object, adjacency matrix, and random distances'''

    G = nx.random_degree_sequence_graph(sequence=sequence, seed=seed,
                                        tries=tries)

    A = nx.adjacency_matrix(G)
    N = len(sequence)
    centroids = np.random.uniform([0, 0, 0], brain_size, (N, 3))
    D = aux_tools.dist_mat(centroids)

    return G, A, D
Example #3
0
 def build_graph(self):
     while True:
         deg_list = np.random.randint(low=1, high=self.max_conn_per_node, size=self.n_nodes)
         if (nx.is_graphical(deg_list)):
             break
     graph = nx.random_degree_sequence_graph(deg_list, seed=123, tries=1000)
     graph = graph.to_directed()
     return graph
def grab_data(i, null=True):

    G1 = nx.random_degree_sequence_graph(deg_seq)
    if null:
        G2 = nx.random_degree_sequence_graph(deg_seq)
    else:
        G2 = nx.grid_2d_graph(N, M)

    A1, A2 = [nx.adjacency_matrix(G).todense() for G in [G1, G2]]
    adj_distances = pd.Series(
        [distance(dfun, A1, A2) for dfun in distances],
        index=labels,
        name="Adjacency Distances",
    )

    data = pd.concat([adj_distances], axis=1)

    return data
Example #5
0
 def randomMaxDeg4Graph(self):
     while True:
         try:
             seq = seqGen(self.n)
             g = nx.random_degree_sequence_graph(seq)
             break
         except nx.NetworkXError:
             pass
     for (u, v) in g.edges():
         g[u][v]['w'] = random.randint(1, 2**self.n)
     return g
def __generate_graph_by_degree(degrees: List[int] = None,
                               *,
                               seed: int = None,
                               variable_degree: bool = False,
                               n_nodes: int = None,
                               min_degree: int = 0,
                               max_degree: int = 0,
                               **kwargs) -> nx.Graph:

    degree_sequence = degrees

    if variable_degree:
        if n_nodes is not None:
            graph = None

            proposed_n_nodes = n_nodes
            while True:
                try:
                    _degrees = range(min_degree, max_degree + 1, 1)
                    degree_sequence = random.choices(_degrees,
                                                     k=proposed_n_nodes)

                    graph = nx.random_degree_sequence_graph(
                        sequence=degree_sequence, seed=seed)
                except nx.NetworkXUnfeasible:
                    proposed_n_nodes += 1
                    continue

                print(f"Took {proposed_n_nodes-n_nodes} tries")
                return graph
        else:
            raise ValueError()

    else:
        if degree_sequence is None or len(degree_sequence) == 0:
            raise ValueError()

        return nx.random_degree_sequence_graph(sequence=degree_sequence,
                                               seed=seed)
Example #7
0
def gen_graph(n, delta):
    for m in range(3, n - 1):
        deg_sequence = [delta - 1] * (n - m) + [delta] * m
        for _ in range(100):
            try:
                g = nx.random_degree_sequence_graph(deg_sequence, tries=100)
                d = g.degree()
                core = g.subgraph([u for u in range(n) if d[u] == delta])
                if max(dict(core.degree()).values()) == 2:
                    yield g
            except nx.exception.NetworkXUnfeasible:
                pass
            except nx.exception.NetworkXError:
                break
Example #8
0
def generate_graphs(delta, n, repeats=1000, underfull=True):
    r = [delta - 1, delta]
    for _ in range(repeats):
        seq = [delta] + [random.choice(r) for _ in range(n - 1)]
        if not nx.is_graphical(seq):
            continue
        try:
            g = nx2graph(nx.random_degree_sequence_graph(seq))
            if is_overfull(g) != underfull:
                yield g
        except nx.NetworkXUnfeasible:
            pass
        except nx.NetworkXException:
            pass
Example #9
0
def FindGraph(deg_seq, MakeGIF, cycle, num, noplotting):
    #After having done these by hand I wanted to find an algorithmic way of doing it.
    #That desire culminated in me finding this paper on Arxiv: https://arxiv.org/pdf/cs/0702124.pdf
    #The algorithm described in that paper was implemented in the python library networkx.
    #The goal then is to take the networkx implementation and making an animated "growth"
    #that would enable one to pick out different patterns.
    #More on the networkx library can be found here:
    #https://networkx.github.io/documentation/networkx-2.0
    n = num + 1
    for seq in deg_seq:
        seq.sort(reverse=True)
        exists = Existence(seq)
        if exists == False:
            print(exists)
        if (exists) and noplotting == False:
            if cycle:
                #The algorithm for this is described in the homework.
                G = nx.cycle_graph(n)
            else:
                #Since the algorithm is randomly seeded it has a failure rate directly proportional to n,
                #thus we should give it a number of tries proportional to n, 3n seems to be a good guess.
                G = nx.random_degree_sequence_graph(seq, tries=3 * n)
            plt.title('n: ' + str(n))
            if len(seq) > 70:
                #This is a quality of life feature so the screen isn't crowded by numbers.
                #Further, the node size should be a monotonically decreasing function of the number of nodes
                #so that the picture isn't just a big splotch of blue.
                nx.draw_circular(G, with_labels=False, node_size=800 / (n / 2))
            else:
                nx.draw_circular(G, with_labels=True, node_size=800 / (n / 2))
            #Formatting to save as nnnnnnnn.png
            plt.savefig(
                str(len(seq)).replace(',', '').replace('[', '').replace(
                    ']', '').replace(' ', '') + '.png')
            #pyplot is dumb and doesn't realize that it should clear itself after it's been saved.
            plt.clf()
        n += 1
    if MakeGIF and noplotting == False:
        images = []
        for file in listdir(getcwd()):
            if '.png' in file:
                #Take all of the png's generated above and form a GIF
                images.append(imageio.imread(file))
                remove(file)
        imageio.mimsave('GrowthBy' + str(num) + '.gif',
                        images,
                        duration=min(30 / (n - num - 1), .5))
        return
Example #10
0
def generate_graph(vertices: int, edges: int, maximum_grade: int) -> nx.Graph:
    if edges > maximum_grade * vertices / 2:
        return None
    elif edges > vertices * (vertices -
                             1) / 2:  # Test more edges than a complete graph
        return None
    elif edges == vertices * (vertices - 1) / 2:  # Complete graph
        return nx.complete_graph(vertices)
    else:
        while True:
            sequence = generate_degree_sequence(vertices, edges, maximum_grade)
            try:
                G = nx.random_degree_sequence_graph(sequence)
                return G
            except Exception:
                pass
def syntheticInferred(n, connectedDegree = True, keepConnected = True):
    dd = infer.infer_degree_sequence(n)
    mat = infer.infer_assortativity_matrix(n)

    if connectedDegree:
        G = havel_hakimi_custom_graph(dd)
    else:
        G = nx.random_degree_sequence_graph(dd)
    """
    print("Degree distribution : " + str(dd))
    print("Nb cc : " + str(nx.number_connected_components(G)))
    
    dh2 = nx.degree_histogram(G)
    print("Result Degree distribution : " + str(dh2))"""
    G = transform_graph_assortativity_coef(G,mat,keepConnected)

    return G
Example #12
0
def scale_free_powerlaw(n=4000, lam=3, k_avg=4):
    """
    n : number of nodes
    lam : exponent
    """
    noftries = 2147483647
    standard = k_avg + 0.5

    while (1):
        s = generate(n, lam)
        ratio = standard / np.mean(s)
        for i in range(len(s)):
            s[i] = int(ratio * s[i])
        if (nx.is_valid_degree_sequence(s)):
            G = nx.random_degree_sequence_graph(s, tries=noftries)
            break
    return G
Example #13
0
def degree_sequence_graphs():
    print("Degree sequence")
    print("Configuration model")
    z = nx.utils.create_degree_sequence(30, powerlaw_sequence)
    G = nx.configuration_model(z)
    draw_graph(G)
    # to remove paralel edges
    G = nx.Graph(G)
    draw_graph(G)
    # to remove self loops
    G.remove_edges_from(G.selfloop_edges())
    draw_graph(G)
    print("Directed configuration model")
    D = nx.DiGraph([(0, 1), (1, 2), (2, 3), (1, 3)])  # directed path graph
    din = list(D.in_degree().values())
    dout = list(D.out_degree().values())
    din.append(1)
    dout[0] = 2
    D = nx.directed_configuration_model(din, dout)
    D = nx.DiGraph(D)  # to remove paralell edges
    D.remove_edges_from(D.selfloop_edges())  # to remove self loops
    draw_graph(D)
    print("Expected degree graphs")
    z = [i for i in range(10)]
    G = nx.expected_degree_graph(z)
    draw_graph(G)
    print("Havel Hakimi graphs")
    z = [2, 4, 5, 6, 7, 3]
    G = nx.havel_hakimi_graph(z)
    draw_graph(G)
    print("Directed Havel Hakimi graphs")
    inds = [2, 4, 5, 6, 7, 3]
    outds = [2, 4, 5, 6, 7, 3]
    G = nx.directed_havel_hakimi_graph(in_deg_sequence=inds,
                                       out_deg_sequence=outds)
    draw_graph(G)
    print("Degree Sequence Tree")
    dg = [1, 2, 3, 4, 2, 3]
    G = nx.degree_sequence_tree(dg)
    draw_graph(G)
    print("Random Degree Sequence")
    sequence = [1, 2, 2, 3]
    G = nx.random_degree_sequence_graph(sequence)
    sorted(G.degree().values())
    draw_graph(G)
def synthetic(n, connectedDegree = True, keepConnected = True):
    F = data.readFeederData(n);
    dh = nx.degree_histogram(F)
    mat = nx.degree_mixing_matrix(F)
    
    dd = utils.degreehisto_to_degreeseq(dh)
    if connectedDegree:
        G = havel_hakimi_custom_graph(dd)
    else:
        G = nx.random_degree_sequence_graph(dd)
    
    """print("Degree distribution : " + str(dh))
    print("Nb cc : " + str(nx.number_connected_components(G)))
    
    dh2 = nx.degree_histogram(G)
    print("Result Degree distribution : " + str(dh2))"""
    G = transform_graph_assortativity_coef(G,mat,keepConnected)

    return G
 def get_edge_list():
     try:
         cn = random_degree_sequence_graph(GC.cn_degree_sequence,
                                           tries=GC.cn_tries,
                                           seed=GC.random_number_seed)
     except NetworkXUnfeasible:
         from os import chdir
         chdir(GC.START_DIR)
         assert False, "Contact network degree sequence is not graphical"
     except NetworkXError:
         from os import chdir
         chdir(GC.START_DIR)
         assert False, "NetworkX failed to produce graph after %d tries" % GC.cn_tries
     if GC.random_number_seed is not None:
         GC.random_number_seed += 1
     out = GC.nx2favites(cn, 'u')
     f = gopen(expanduser("%s/contact_network.txt.gz" % GC.out_dir), 'wb',
               9)
     f.write('\n'.join(out).encode())
     f.write(b'\n')
     f.close()
     return out
Example #16
0
def main():
    deg = 3
    num_graphs = 1000
    ty = sys.argv[1]
    if ty in ['TRIANGLE_EX' or 'LCC_EX' or 'MDS_EX']:
        sps = [('train', 20), ('test', 100)]
    else:
        sps = [('train', 20), ('test', 20)]
    for sp in sps:
        n = sp[1]
        Gs = []
        for _ in range(num_graphs):
            g = nx.random_degree_sequence_graph([deg for i in range(n)])
            G = [[] for i in range(n)]
            for e in g.edges:
                G[e[0]].append(e[1])
                G[e[1]].append(e[0])
            if ty in ['TRIANGLE', 'TRIANGLE_EX']:
                l = tri_check(G)
            elif ty in ['LCC', 'LCC_EX']:
                l = local_cluster_coefficient(G)
            else:
                l = [0 for i in range(n)]
            Gs.append((G, l))

        basedir = f'dataset/{ty}'
        if not os.path.exists(basedir):
            os.makedirs(basedir)
        with open(f'{basedir}/{ty}_{sp[0]}.txt', 'w') as f:
            f.write(f'{num_graphs}\n')
            for i in range(num_graphs):
                f.write(f'{n} 0\n')
                G, l = Gs[i]
                for j in range(n):
                    f.write(f'{l[j]} {deg}')
                    for k in G[j]:
                        f.write(f' {k}')
                    f.write('\n')
Example #17
0
def GenEdges(S,Group,Lambda):
    import networkx as nx
    import random
    import numpy as np

    Dtotal=[]

    CC=len(Group)
    Edges=[]
    for i in range(0,CC):
        Nodes_CC=Group[i]
        D=GenGraph(Nodes_CC,Lambda)
        Dtotal.append(D)
        G = nx.random_degree_sequence_graph(D,  tries=100)
    
        mapping={}
        for i in range(0,len(Nodes_CC)):
            mapping[i]=Nodes_CC[i]
        H=nx.relabel_nodes(G,mapping)
        for item in H.edges():
            Edges.append(item)
        G=0

    #print(Edges)


    Adj=np.zeros([S,S])
    for i in Edges:
        j=i[0]
        k=i[1]
        if random.randint(0, 1)==0:
            Adj[j,k]=1
        else:
            Adj[k,j]=1
    
    return(Adj,Dtotal,CC)
def test_random_degree_sequence_graph():
    d = [1, 2, 2, 3]
    G = nx.random_degree_sequence_graph(d)
    assert_equal(d, sorted(d for n, d in G.degree()))
Example #19
0
def test_random_degree_sequence_graph():
    d = [1, 2, 2, 3]
    G = nx.random_degree_sequence_graph(d, seed=42)
    assert d == sorted(d for n, d in G.degree())
Example #20
0
print 'Building graphs...'

# Load mouse connectivity graph
G_brain, W_brain, _ = extract.brain_graph.binary_undirected()
n_nodes = len(G_brain.nodes())
n_edges = len(G_brain.edges())
p_edge = float(n_edges) / ((n_nodes * (n_nodes - 1)) / 2.)

# Calculate degree & clustering coefficient distribution
brain_degree = nx.degree(G_brain).values()
brain_clustering = nx.clustering(G_brain).values()
brain_degree_mean = np.mean(brain_degree)

# Build standard graphs & get their degree & clustering coefficient
# Configuration model (random with fixed degree sequence)
G_CM = nx.random_degree_sequence_graph(brain_degree, tries=100)
CM_degree = nx.degree(G_CM).values()
CM_clustering = nx.clustering(G_CM).values()

# Watts-Strogatz
G_WS = nx.watts_strogatz_graph(n_nodes, int(round(brain_degree_mean)),
                               SW_REWIRE_PROB)
WS_degree = nx.degree(G_WS).values()
WS_clustering = nx.clustering(G_WS).values()

# Barabasi-Albert
G_BA = nx.barabasi_albert_graph(n_nodes, int(round(brain_degree_mean / 2.)))
BA_degree = nx.degree(G_BA).values()
BA_clustering = nx.clustering(G_BA).values()

##################
    # get small world coefficient
    #from the clustering coefficient (CC) and the average path length (PL) =
    # CC(actual network)/CC(random graph) divided by PL(actual network)/PL(random graph)
    # use just the largest connected component

    gcsize=G.number_of_nodes()
    apl=networkx.average_shortest_path_length(G)
    Gclust=networkx.average_clustering(G)



    sw=[]

    for i in range(36):
        try:
            rand=networkx.random_degree_sequence_graph(G.degree().values(),tries=10)
            Grand=networkx.connected_component_subgraphs(rand)[0]

        except:
            print 'problem on round',i
            continue
        print i
        sw.append((Gclust/networkx.average_clustering(Grand))/(apl/networkx.average_shortest_path_length(Grand)))

    if len(sw)>0:
        meansw=numpy.mean(sw)
    else:
        meansw=0


    alldata=numpy.array([modularity_infomap,eff,cc,bc,clust,rcc_at_cutoff,apl,power_exp,meansw])
Example #22
0
            sequence = sequence + [
                i for i in itertools.repeat(int(Edges[0]), int(Edges[1]))
            ]
    return sequence


###CALLING FUNCTIONS###
Degree_file = 'Data/Degree_file'
Corr_matrix = 'Data/Corr_matrix'
path_random_graph = 'Data/Random_graphs/'

#Loop to create 10000 random graphs with the same degree sequence as the original network and finding their optimal communities with MolTi software.
for i in range(0, 10000):
    deg_seq = sequence(Degree_file)
    G = nx.random_degree_sequence_graph(
        deg_seq, tries=10
    )  #Return a simple random graph with the given degree sequence.
    Adj = nx.to_dict_of_dicts(
        G, edge_data=1
    )  #Return adjacency representation of graph as a dictionary of dictionaries.
    fun = ncol_format(corr_matrix=Corr_matrix, random_graph=Adj)
    #Creating the files in the suitable NCOL format to give the input to MolTi software.
    t = ''
    for key in fun:
        for key2 in fun[key]:
            if t == '':
                t = str(key) + '\t' + str(key2[0]) + '\t' + str(key2[1]) + '\n'
            else:
                t += str(key) + '\t' + str(key2[0]) + '\t' + str(
                    key2[1]) + '\n'
    f3 = open(path_random_graph + 'Random_graph_micro_' + str(i), 'w')
Example #23
0
def csv_test_unparallel():
    eg.__eigen_info = True
    print("Strategy," + "Graph," + str("EigErr") + "," + str("DegCorr") + "," +
          str("ClustRatio") + "," + str("EigVErr") + "," +
          str("NodeDistCorr") + "," + str("DegBetCorr") + "," +
          str("KCoreCorr") + "," + str("CommNeighDist") + "," +
          str("PartRatio") + "," + str("AvgNeighDegCorr") + "," +
          str("Connected"),
          file=sys.stderr)
    for filo in os.listdir("/home/baldo/tmp/graph_generator/PL200/"):
        with open("/home/baldo/tmp/graph_generator/PL200/" + filo, "r") as net:
            eg.info(filo)
            eg.info("Loading graph..")
            G = nx.read_weighted_edgelist(net)  # , delimiter=":")
            # G = read_graphml(net)
            A = nx.to_numpy_matrix(G)
            n = nm.shape(A)[0]
            joint_degrees = nx.algorithms.mixing.degree_mixing_dict(G)
            eg.info("Computing centrality..")
            x, l = eg.eigen_centrality(A)

            for i in range(10):
                eg.info("Run: " + str(i))

                eg.info("Building JDM graph..")
                H = joint_degree_graph(joint_degrees)
                B = nx.to_numpy_matrix(H)
                write_statistics(A, B, "2k", filo, x, l)

                eg.info("Building degree sequence graph..")
                H = nx.random_degree_sequence_graph((nx.degree(G).values()))
                B = nx.to_numpy_matrix(H)
                write_statistics(A, B, "1k", filo, x, l)

                precision = 0.01
                eg.info("Building eigen " + str(precision) + " graph..")
                B = eg.build_matrix(x, l, precision)
                write_statistics(A, B, "eig" + str(precision), filo, x, l)

                precision = 0.001
                eg.info("Building eigen " + str(precision) + " graph..")
                B = eg.build_matrix(x, l, precision)
                write_statistics(A, B, "eig" + str(precision), filo, x, l)

                precision = 0.0001
                eg.info("Building eigen " + str(precision) + " graph..")
                B = eg.build_matrix(x, l, precision)
                write_statistics(A, B, "eig" + str(precision), filo, x, l)

                m = 0.25
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.5
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.75
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.9
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.95
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                eg.info("Building D2.5 graph..")
                test25 = Estimation()
                gen25 = Generation()
                test25.load_graph("", graph=G)
                test25.calcfull_CCK()
                test25.calcfull_JDD()
                gen25.set_JDD(test25.get_JDD('full'))
                gen25.set_KTRI(test25.get_KTRI('full'))
                gen25.construct_triangles_2K()
                gen25.mcmc_improved_2_5_K(error_threshold=0.05)
                H = gen25.G
                B = nx.to_numpy_matrix(H)
                write_statistics(A, B, "25k", filo, x, l)
Example #24
0
def graph_worker(inputlist, queue, print_queue):
    for filo in inputlist:
        if filo.split(".")[-1] == "graphml":
            G = read_graphml(filo)
        else:
            G = nx.read_weighted_edgelist(filo)

        A = nx.to_numpy_matrix(G)
        n = nm.shape(A)[0]
        joint_degrees = nx.algorithms.mixing.degree_mixing_dict(G)
        x, l = eg.eigen_centrality(A)

        H = nx.random_degree_sequence_graph((nx.degree(G).values()))
        B = nx.to_numpy_matrix(H)
        print_queue.put(write_statistics(A, B, "1k", filo, x, l, output=False))
        print_queue.put("\n")

        H = joint_degree_graph(joint_degrees)
        B = nx.to_numpy_matrix(H)
        print_queue.put(write_statistics(A, B, "2k", filo, x, l, output=False))
        print_queue.put("\n")

        precision = 0.01
        B = eg.build_matrix(x, l, precision)
        print_queue.put(
            write_statistics(A,
                             B,
                             "eig" + str(precision),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        precision = 0.001
        B = eg.build_matrix(x, l, precision)
        print_queue.put(
            write_statistics(A,
                             B,
                             "eig" + str(precision),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        precision = 0.0001
        B = eg.build_matrix(x, l, precision)
        print_queue.put(
            write_statistics(A,
                             B,
                             "eig" + str(precision),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.25
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.5
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.75
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.9
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.95
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        test25 = Estimation()
        gen25 = Generation()
        test25.load_graph("", graph=G)
        test25.calcfull_CCK()
        test25.calcfull_JDD()
        gen25.set_JDD(test25.get_JDD('full'))
        gen25.set_KTRI(test25.get_KTRI('full'))
        gen25.construct_triangles_2K()
        gen25.mcmc_improved_2_5_K(error_threshold=0.05)
        H = gen25.G
        B = nx.to_numpy_matrix(H)
        print_queue.put(write_statistics(A, B, "25k", filo, x, l,
                                         output=False))
        print_queue.put("\n")
Example #25
0

# Punto 5 : Mundos Pequeños
nx.draw(cg)  # networkx draw()
plt.draw()  # pyplot draw()
plt.show()


C= nx.average_clustering(cg)
print("Coeficiente de clustering C para cg: " + str(C))

l=nx.average_shortest_path_length(cg)
print("Camino mínimo medio l para cg: " + str(l))   

#random graph con la misma distribucón de grado    
rg = nx.random_degree_sequence_graph(sorted([e[1] for e in list(nx.degree(cg))], reverse=True))     

nx.draw(rg)  # networkx draw()
plt.draw()  # pyplot draw()
plt.show()

print("Coeficiente de clustering C para rg: " + str(nx.average_clustering(rg)))    
print("Camino mínimo medio l para rg: " + str(nx.average_shortest_path_length(rg)))
 






# Punto 6 : Estrellas
Example #26
0
def test_random_degree_sequence_graph():
    d = [1, 2, 2, 3]
    G = nx.random_degree_sequence_graph(d, seed=42)
    assert_equal(d, sorted(d for n, d in G.degree()))
    G = nx.random_degree_sequence_graph(d)
    assert_equal(d, sorted(d for n, d in G.degree()))
Example #27
0
def generate_one_graph_sample(initial_graph, seed=42):
    degree_sequence = [d for n, d in initial_graph.degree()]
    sample_graph = nx.random_degree_sequence_graph(degree_sequence, seed=seed)

    return sample_graph
Example #28
0
def graph_worker_oneshot(inputlist, queue, print_queue):
    for duty in inputlist:
        name = duty[0]
        G = duty[1]
        algo = duty[2]
        param = duty[3]

        A = nx.to_numpy_matrix(G)
        # x, l = eg.eigen_centrality(A)

        eg.info("Setup completed")
        start_time = time.time()

        if algo == "1k":
            H = nx.random_degree_sequence_graph((nx.degree(G).values()))
            # B = nx.to_numpy_matrix(H)

        elif algo == "2k":
            joint_degrees = nx.algorithms.mixing.degree_mixing_dict(G)
            H = joint_degree_graph(joint_degrees)
            # B = nx.to_numpy_matrix(H)

        elif algo == "eig":
            precision = float(param)
            # B = eg.build_matrix(x, l, precision)
            B = eg.generate_matrix(x, l * x, precision, gu.get_degrees(A))
            H = None
            algo += str(precision)

        elif algo == "modeig":
            precision = float(param)
            B = eg.synthetic_modularity_matrix(A, precision)
            H = None
            algo += str(precision)

        elif algo == "spectre":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.sample_simm_matrix2(A, int(round(n * m)))
            H = gu.simm_matrix_2_graph(B)
            while nx.is_isomorphic(G, H):
                B = eg.sample_simm_matrix2(A, int(round(n * m)))
                H = gu.simm_matrix_2_graph(B)
            algo += str(m)

        elif algo == "laplacian":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.laplacian_clone_matrix(A, int(round(n * m)))
            H = gu.simm_matrix_2_graph(B)
            while nx.is_isomorphic(G, H):
                B = eg.sample_simm_matrix2(A, int(round(n * m)))
                H = gu.simm_matrix_2_graph(B)
            algo += str(m)

        elif algo == "modspec":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.modspec_clone_matrix(A, int(round(n * m)))
            H = None
            algo += str(m)

        elif algo == "franky":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.franky_clone_matrix(A, int(round(n * m)))
            H = None
            algo += str(m)

        elif algo == "modularity":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.modularity_clone_matrix(A, int(round(n * m)))
            H = gu.simm_matrix_2_graph(B)
            while nx.is_isomorphic(G, H):
                B = eg.modularity_clone_matrix(A, int(round(n * m)))
                H = gu.simm_matrix_2_graph(B)
            algo += str(m)

        elif algo == "25k":
            test25 = Estimation()
            gen25 = Generation()
            test25.load_graph("", graph=G)
            test25.calcfull_CCK()
            test25.calcfull_JDD()
            gen25.set_JDD(test25.get_JDD('full'))
            gen25.set_KTRI(test25.get_KTRI('full'))
            gen25.construct_triangles_2K()
            gen25.mcmc_improved_2_5_K(error_threshold=0.05)
            H = gen25.G
            # B = nx.to_numpy_matrix(H)

        eg.info("Graph Generated")

        stat = get_statistics1(G, H, time.time() - start_time)
        s = algo + "," + name + "," + str(len(G.nodes()))
        for el in stat:
            s += "," + str(el)
        print_queue.put(s)
        print_queue.put("\n")
        gc.collect()
Example #29
0
def test_random_degree_sequence_large():
    G1 = nx.fast_gnp_random_graph(100, 0.1)
    d1 = (d for n, d in G1.degree())
    G2 = nx.random_degree_sequence_graph(d1, seed=42)
    d2 = (d for n, d in G2.degree())
    assert_equal(sorted(d1), sorted(d2))
Example #30
0
import numpy as np

flag = True

G = None
while flag:
    flag = False
    try:
        n_vertices = np.random.randint(6, 10)
        degrees = [2, 4, 6, 8]
        degree_sequence = None
        for i in range(n_vertices):
            degree_sequence = np.random.choice(degrees,
                                               n_vertices,
                                               replace=True)
        G = nx.random_degree_sequence_graph(degree_sequence)
    except (nx.NetworkXUnfeasible, nx.NetworkXError):
        flag = True

matrix = nx.adjacency_matrix(G)
matrix = np.array(matrix.todense(), dtype=int)

print(matrix)

with open('euler.txt', 'wt') as f:
    for row in range(0, n_vertices):
        for col in range(0, n_vertices):
            f.write("%d" % matrix[row, col])
            if col == n_vertices - 1: f.write("\n")
            else: f.write(" ")
Example #31
0
brain_degree = nx.degree(G_brain).values()
brain_degree_mean = np.mean(brain_degree)

# Initialize repetition matrices for standard graphs
# ER_deg_mat = -1 * np.ones((repeats, n_nodes))
RAND_deg_mat = -1 * np.ones((repeats, n_nodes))
WS_deg_mat = -1 * np.ones((repeats, n_nodes))
BA_deg_mat = -1 * np.ones((repeats, n_nodes))

print 'this could take a while...'
for r in np.arange(repeats):
    # Erdos-Renyi (pure random)
    # ER_deg_mat[r, :] = er(n_nodes, edge_density).degree().values()

    # Degree controlled random
    RAND_deg_mat[r, :] = nx.random_degree_sequence_graph(
        brain_degree, tries=100).degree().values()

    # Watts-Strogatz
    WS_deg_mat[r, :] = ws(n_nodes, int(round(brain_degree_mean)),
                          SW_REWIRE_PROB).degree().values()

    # Barabasi-Albert
    BA_deg_mat[r, :] = ba(n_nodes, int(round(brain_degree_mean /
                                             2.))).degree().values()
    print 'Finished repeat: ' + str(r)

deg_dists = [
    RAND_deg_mat.flatten(),
    WS_deg_mat.flatten(),
    BA_deg_mat.flatten()
]
def test_random_degree_sequence_large():
    G1 = nx.fast_gnp_random_graph(100, 0.1)
    d1 = (d for n, d in G1.degree())
    G2 = nx.random_degree_sequence_graph(d1, seed=0)
    d2 = (d for n, d in G2.degree())
    assert_equal(sorted(d1), sorted(d2))
Example #33
0
brain_degree = nx.degree(G_brain).values()
brain_degree_mean = np.mean(brain_degree)

# Initialize repetition matrices for standard graphs
# ER_deg_mat = -1 * np.ones((repeats, n_nodes))
RAND_deg_mat = -1 * np.ones((repeats, n_nodes))
WS_deg_mat = -1 * np.ones((repeats, n_nodes))
BA_deg_mat = -1 * np.ones((repeats, n_nodes))

print 'this could take a while...'
for r in np.arange(repeats):
    # Erdos-Renyi (pure random)
    # ER_deg_mat[r, :] = er(n_nodes, edge_density).degree().values()

    # Degree controlled random
    RAND_deg_mat[r, :] = nx.random_degree_sequence_graph(
        brain_degree, tries=100).degree().values()

    # Watts-Strogatz
    WS_deg_mat[r, :] = ws(n_nodes, int(round(brain_degree_mean)),
                          SW_REWIRE_PROB).degree().values()

    # Barabasi-Albert
    BA_deg_mat[r, :] = ba(n_nodes,
                          int(round(brain_degree_mean / 2.))).degree().values()
    print 'Finished repeat: ' + str(r)

deg_dists = [RAND_deg_mat.flatten(), WS_deg_mat.flatten(),
             BA_deg_mat.flatten()]
colors = [RAND_COLOR, WS_COLOR, BA_COLOR]
graph_names = ['Random', 'Small-world', 'Scale-free']
graph_ls = ['-', '-', '-']
Example #34
0
from pylab import *
import networkx as nx

subplot(2, 2, 1)
nx.draw(nx.gnm_random_graph(10, 20))
title('random graph with\n10 nodes, 20 edges')

subplot(2, 2, 2)
nx.draw(nx.gnp_random_graph(20, 0.1))
title('random graph with\n 20 nodes, 10% edge probability')

subplot(2, 2, 3)
nx.draw(nx.random_regular_graph(3, 10))
title('random regular graph with\n10 nodes of degree 3')

subplot(2, 2, 4)
nx.draw(nx.random_degree_sequence_graph([3, 3, 3, 3, 4, 4, 4, 4, 5, 5]))
title('random graph with\n degree sequence\n[3,3,3,3,4,4,4,4,5,5]')

show()
        rcc_at_cutoff = 0.0

    # get small world coefficient
    #from the clustering coefficient (CC) and the average path length (PL) =
    # CC(actual network)/CC(random graph) divided by PL(actual network)/PL(random graph)
    # use just the largest connected component

    gcsize = G.number_of_nodes()
    apl = networkx.average_shortest_path_length(G)
    Gclust = networkx.average_clustering(G)

    sw = []

    for i in range(36):
        try:
            rand = networkx.random_degree_sequence_graph(G.degree().values(),
                                                         tries=10)
            Grand = networkx.connected_component_subgraphs(rand)[0]

        except:
            print 'problem on round', i
            continue
        print i
        sw.append((Gclust / networkx.average_clustering(Grand)) /
                  (apl / networkx.average_shortest_path_length(Grand)))

    if len(sw) > 0:
        meansw = numpy.mean(sw)
    else:
        meansw = 0

    alldata = numpy.array([