Ejemplo n.º 1
0
    def test_dual_barabasi_albert(self, m1=1, m2=4, p=0.5):
        """
        Tests that the dual BA random graph generated behaves consistently.

        Tests the exceptions are raised as expected.

        The graphs generation are repeated several times to prevent lucky shots

        """
        seeds = [42, 314, 2718]
        initial_graph = nx.complete_graph(10)

        for seed in seeds:

            # This should be BA with m = m1
            BA1 = nx.barabasi_albert_graph(100, m1, seed)
            DBA1 = nx.dual_barabasi_albert_graph(100, m1, m2, 1, seed)
            assert BA1.edges() == DBA1.edges()

            # This should be BA with m = m2
            BA2 = nx.barabasi_albert_graph(100, m2, seed)
            DBA2 = nx.dual_barabasi_albert_graph(100, m1, m2, 0, seed)
            assert BA2.edges() == DBA2.edges()

            BA3 = nx.barabasi_albert_graph(100, m1, seed)
            DBA3 = nx.dual_barabasi_albert_graph(100, m1, m1, p, seed)
            # We can't compare edges here since randomness is "consumed" when drawing
            # between m1 and m2
            assert BA3.size() == DBA3.size()

            DBA = nx.dual_barabasi_albert_graph(100, m1, m2, p, seed,
                                                initial_graph)
            BA1 = nx.barabasi_albert_graph(100, m1, seed, initial_graph)
            BA2 = nx.barabasi_albert_graph(100, m2, seed, initial_graph)
            assert (min(BA1.size(), BA2.size()) <= DBA.size() <= max(
                BA1.size(), BA2.size()))

        # Testing exceptions
        dbag = nx.dual_barabasi_albert_graph
        pytest.raises(nx.NetworkXError, dbag, m1, m1, m2, 0)
        pytest.raises(nx.NetworkXError, dbag, m2, m1, m2, 0)
        pytest.raises(nx.NetworkXError, dbag, 100, m1, m2, -0.5)
        pytest.raises(nx.NetworkXError, dbag, 100, m1, m2, 1.5)
        initial = nx.complete_graph(max(m1, m2) - 1)
        pytest.raises(nx.NetworkXError,
                      dbag,
                      100,
                      m1,
                      m2,
                      p,
                      initial_graph=initial)
def ba_exp(t,
           n,
           m,
           p,
           transmissibility,
           sigma,
           gamma,
           symptomatic_rate,
           sir_0,
           seed,
           npi=None,
           t_apply_npi=None,
           t_open_up=None,
           **kwargs):
    random.seed(seed)
    np.random.seed(seed)
    G = nx.dual_barabasi_albert_graph(n, m1=m, m2=1, p=p)
    # print("ba number of edges", G.number_of_edges())
    graph = construct_network(G, n, sir_0)

    seir = np.zeros((t, len(SEIR_COMPARTMENTS)))

    if npi is None:
        seir = network_exp_with_seed(transmissibility, sigma, symptomatic_rate,
                                     gamma, n, t, graph)
    elif t_open_up is None:
        seir = network_exp_with_npi(transmissibility, sigma, symptomatic_rate,
                                    gamma, n, t, graph, npi, t_apply_npi,
                                    **kwargs)
    else:
        seir = network_exp_with_open_up(transmissibility, sigma,
                                        symptomatic_rate, gamma, n, t, graph,
                                        npi, t_apply_npi, t_open_up, **kwargs)
    return seir
def estimate_BA(n, m_range, p_range, seeds, transmissibility, sigma, symptomatic_rate, gamma, t, base_SEIR, sir_0):
    best_m, best_p, min_error = 0, 0, sys.maxsize

    for idx, m in enumerate(m_range):
        for idx, p in enumerate(p_range):
            error_lst = np.zeros(len(seeds))
            for seed_idx in range(len(seeds)):
                random.seed(seeds[seed_idx])
                np.random.seed(seeds[seed_idx])

                G = nx.dual_barabasi_albert_graph(n, m1=m, m2=2, p=p, seed=seeds[seed_idx])
                graph = construct_network(G, n, sir_0)

                seir = network_exp_with_seed(transmissibility, sigma, symptomatic_rate, gamma, n, t, graph)
                error = compute_error(base_SEIR[:, 2], seir[:, 2], t)

                error_lst[seed_idx] = error

            avg_error_p = np.average(error_lst)
            print("m", m, " p", p,
                  " error avg:", avg_error_p,
                  " std:", np.std(error_lst),
                  " max:", np.max(error_lst),
                  " min:", np.min(error_lst),
                  " best_seed:", seeds[np.argmin(error_lst)])

            if avg_error_p < min_error:
                min_error = avg_error_p
                best_p = p
                best_m = m

    return best_m, best_p
Ejemplo n.º 4
0
def netgen_dba(n, m1, m2, p, cull, maxDeg):
    I = nx.dual_barabasi_albert_graph(n=n, m1=m1, m2=m2,
                                      p=p)  # Call the basic function
    degs = [I.degree[node] for node in list(I.nodes)
            ]  # Calculate the node degree list for all nodes
    avg_deg = np.mean(
        degs)  # Calculate the mean node degree for the whole network.
    # conn = nx.average_node_connectivity(I)
    conn = 1
    if cull:  # Only if the network generator should remove supernodes.
        big_nodes = [
            node for node in list(I.nodes) if I.degree(node) >= maxDeg
        ]  # Assigned SuperNode size.
        I.remove_nodes_from(big_nodes)
        for numerro in big_nodes:  # My very simple function for removing SuperNodes.
            I.add_node(numerro)
            eN = random.choice([m1, m2])
            for _ in range(eN):
                to = random.choice(list(I.nodes()))
                I.add_edge(numerro, to)
        degs = [I.degree[node] for node in list(I.nodes)]
        avg_deg = np.mean(
            degs
        )  # This whole loop should be a function, but method will not produce any new SuperNodes
        # conn = nx.average_node_connectivity(I)
        conn = 1
    if not (nx.is_connected(I) and
            (4 <= avg_deg <= 10)):  # Test if network within parameters
        return netgen_dba(n=n, m1=m1, m2=m2, p=p, maxDeg=maxDeg,
                          cull=cull)  # If not within parameters, call self.
    else:
        print(
            f"Successfully generated naetwork with parameters {m1, m2, p, cull, maxDeg}\n"
        )
        return I, avg_deg, cull, maxDeg
def ba_exp(t, n, m, p, transmissibility, sigma, gamma, symptomatic_rate, sir_0,
           seed):
    random.seed(seed)
    np.random.seed(seed)
    G = nx.dual_barabasi_albert_graph(n, m1=m, m2=1, p=p)
    print("ba number of edges", G.number_of_edges())
    graph = construct_network(G, n, sir_0)
    return network_exp_with_seed(transmissibility, sigma, symptomatic_rate,
                                 gamma, n, t, graph)
Ejemplo n.º 6
0
def netgen_dba(n, m1, m2, p, cull, maxDeg):
    global attempt
    global usable_networks
    attempt += 1
    if attempt > 10:
        attempt = 0
        # When it exceeds 10, the function should stop the given run and return a code for failed attempt
        # at creating the net within assigned parameters.
        print(
            f"Failed generating network with parameters {m1, m2, p, cull, maxDeg}. Trying on."
        )
        return "fail"

    I = nx.dual_barabasi_albert_graph(n=n, m1=m1, m2=m2,
                                      p=p)  # Call the basic function
    degs = [I.degree[node] for node in list(I.nodes)
            ]  # Calculate the node degree list for all nodes
    avg_deg = np.mean(
        degs)  # Calculate the mean node degree for the whole network.
    # conn = nx.average_node_connectivity(I)
    conn = 1
    if cull:  # Only if the network generator should remove supernodes.
        big_nodes = [
            node for node in list(I.nodes) if I.degree(node) >= maxDeg
        ]  # Assigned SuperNode size.
        I.remove_nodes_from(big_nodes)
        for numerro in big_nodes:  # My very simple function for removing SuperNodes.
            I.add_node(numerro)
            eN = random.choice([m1, m2])
            for _ in range(eN):
                to = random.choice(list(I.nodes()))
                I.add_edge(numerro, to)
        degs = [I.degree[node] for node in list(I.nodes)]
        avg_deg = np.mean(
            degs
        )  # This whole loop should be a function, but method will not produce any new SuperNodes
        # conn = nx.average_node_connectivity(I)
        conn = 1
    if not (nx.is_connected(I) and
            (4 <= avg_deg <= 10)):  # Test if network within parameters
        return netgen_dba(n=n, m1=m1, m2=m2, p=p, maxDeg=maxDeg,
                          cull=cull)  # If not within parameters, call self.
    else:
        attempt = 0  # Zero the attempt counter.
        usable_networks += 1
        print(
            f"Successfully generated naetwork with parameters {m1, m2, p, cull, maxDeg}\n"
            f"Number of usable networks = {usable_networks}.")
        return I, avg_deg, cull, maxDeg
Ejemplo n.º 7
0

#Variables maximes
diesmax = 15
contagiratemax = 100
vacinespercentagemax = 100
novacinespercentagemax = 100
quarantinedpopulationmax = 100
infecteddpopulationmax = 100

#Variable boolean
tocat = False

#Generem aleatoriament el graph
global G
G = nx.dual_barabasi_albert_graph(2000, 2, 1, 0.1)
pos = nx.spring_layout(G, k=0.25, iterations=20)
nx.set_node_attributes(G, pos, 'pos')

nx.set_node_attributes(G, "blue", 'color')
nx.set_node_attributes(G, False, 'infectat')
nx.set_node_attributes(G, False, 'vacunat')
nx.set_node_attributes(G, True, 'vacunable')

#Generem estats
estats = []
estats.append(nx.get_node_attributes(G, "color"))

nx.set_node_attributes(G, estats[0], "color")
fig = go.Figure(data=create_graph_plot(G))
Ejemplo n.º 8
0
def harmonicDesign(mk,
                   nnodes,
                   refnodes,
                   refedges,
                   nedges=2,
                   dualedge=3,
                   nstart=None,
                   scfree='barabasialbert',
                   seed=None,
                   prob=None,
                   reverse=None,
                   display=None,
                   write=None,
                   verbose=False):
    # network generator (see documentation on networkx)
    if scfree == 'barabasialbert':
        if verbose: print('Barabasi-Albert')
        scfree = nx.barabasi_albert_graph(nnodes, nedges, seed)
    elif scfree == 'dual':
        if verbose: print('dual Barabasi-Albert')
        scfree = nx.dual_barabasi_albert_graph(nnodes, nedges, dualedge, prob,
                                               seed)
    elif scfree == 'erdosrenyi':
        if verbose: print('Erdos-Renyi')
        scfree = nx.erdos_renyi_graph(nnodes, prob)
    else:
        scfree = scfree
    # node degree distribution
    node = np.zeros((nnodes), dtype=int)
    weight = np.zeros((nnodes), dtype=int)
    for n in range(nnodes):
        node[n] = np.array(scfree.degree())[n][0]
        weight[n] = np.array(scfree.degree())[n][1]
    idx = np.argsort(weight)[::-1]
    if nstart == None:
        nstart = idx[0]
    euler_circuit = chinese_postman(scfree, starting_node=nstart)
    if verbose:
        print('Length of Eulerian circuit: {}'.format(len(euler_circuit)))
    # modularity
    if not scfree.is_directed():
        part = cm.best_partition(scfree)
        modul = cm.modularity(part, scfree)
    # average degree
    ntot = scfree.number_of_nodes()
    avg = 0
    for n in scfree.degree():
        avg += n[1]
    avgdeg = avg / float(ntot)
    if verbose: print('Average degree: ', avgdeg, ' modularity = ', modul)
    # reference node degree distribution
    try:
        bnet = nx.from_pandas_edgelist(refedges, 'Source', 'Target',
                                       ['Weight', 'Label'])
    except:
        bnet = nx.from_pandas_edgelist(refedges, 'Source', 'Target',
                                       ['Weight'])
    bnode = np.zeros((nnodes), dtype=int)
    bweight = np.zeros((nnodes), dtype=int)
    for n in range(nnodes):
        bnode[n] = np.array(bnet.degree())[n][0]
        bweight[n] = np.array(bnet.degree())[n][1]
    bidx = np.argsort(bweight)[::-1]
    # associate reference nodes to network
    a = node[idx[:]]
    b = bnode[bidx[:]]
    eudict = dict(zip(a, b))
    # write score
    eulerseq = []
    for i in range(len(euler_circuit)):
        ch = []
        for c in np.asarray(refnodes)[eudict[int(
                euler_circuit[i][0])]].tolist()[0]:
            if c == '#' or c == '-':
                pc = str(ch[-1]) + c
                ch.pop()
                ch.append(pc)
            else:
                ch.append(c)
        eulerseq.append(m21.chord.Chord(ch).normalOrder)
    ch = []
    for c in np.asarray(refnodes)[eudict[int(
            euler_circuit[i][1])]].tolist()[0]:
        if c == '#' or c == '-':
            pc = str(ch[-1]) + c
            ch.pop()
            ch.append(pc)
        else:
            ch.append(c)
    eulerseq.append(m21.chord.Chord(ch).normalOrder)
    if reverse: eulerseq = eulerseq[::-1]
    if display:
        eunodes, euedges, _, _, _, _, _ = mk.network(space='score',
                                                     seq=eulerseq,
                                                     ntx=True,
                                                     general=True,
                                                     distance='euclidean',
                                                     grphtype='directed')
        drawNetwork(nodes=eunodes, edges=euedges, grphtype='directed')
    if write:
        WRITEscoreOps(eulerseq, w=write)

    if not scfree.is_directed():
        return (eulerseq, avgdeg, modul)
    else:
        return (eulerseq, avgdeg, None)
Ejemplo n.º 9
0
        tmp.append(st.fromfile(gdict[n]['register'][rdx[n][r[0]]]))
        r = random.sample(range(len(ddx[n])), 1)
        tmp.append(st.fromfile(gdict[n]['dynamics'][ddx[n][r[0]]]))
        r = random.sample(range(len(ldx[n])), 1)
        tmp.append(st.fromfile(gdict[n]['lines'][ldx[n][r[0]]]))
        tmp.save('./FIGURES/COMPOUNDED/' + str(t) + '.svg')

    final = glob.glob('FIGURES/COMPOUNDED/*')
    idx = np.linspace(0, totgest - 1, totgest, dtype=int)
    finaldict = dict(zip(idx, [f.split('/')[-1] for f in final]))

    # ### Build the progression of gestures as a Eulerian circuit on a network
    if nxmodel == 'BA':
        Gx = nx.barabasi_albert_graph(totgest, 2, seed=seed)
    elif nxmodel == 'DBA':
        Gx = nx.dual_barabasi_albert_graph(totgest, 2, 1, 0.5, seed=seed)
    elif nxmodel == 'WS':
        Gx = nx.watts_strogatz_graph(totgest, 2, 0.2, seed=seed)
    elif nxmodel == 'NWS':
        Gx = nx.newman_watts_strogatz_graph(totgest, 2, 0.2, seed=seed)
    elif nxmodel == 'ER':
        # use with caution: the length of the Eulerian path tends to be VERY high
        Gx = nx.erdos_renyi_graph(totgest, 0.05, directed=True)
    else:
        print('network model not coded')
        sys.exit()

    if starting_node == None:
        starting_node = sorted(Gx.degree, key=lambda x: x[1],
                               reverse=True)[0][0]
    chino = chinese_postman(Gx, starting_node, verbose=False)