Ejemplo n.º 1
0
 def create_directed_graph(self, n_nodes, min_w=10, max_w=100):
     G = nx.random_k_out_graph(n_nodes, 3, 0.9)
     Gw = nx.DiGraph()
     for edge in G.edges():
         Gw.add_edge(edge[0],
                     edge[1],
                     weight=np.random.uniform(min_w, max_w))
     return Gw
Ejemplo n.º 2
0
 def test_random_k_out_graph(self):
     g = networkx.random_k_out_graph(100, 50, 3.14159, True, 42)
     out_graph = retworkx.networkx_converter(g)
     self.assertIsInstance(out_graph, retworkx.PyDiGraph)
     self.assertEqual(out_graph.nodes(), list(g.nodes))
     self.assertEqual(out_graph.weighted_edge_list(),
                      list(g.edges(data=True)))
     self.assertEqual(out_graph.multigraph, g.is_multigraph())
Ejemplo n.º 3
0
    def random_k_out_graph(self, N, k, seed=123, plot_adj=False):
        self.N = N
        _alpha = 1
        self.G = nx.random_k_out_graph(N, k, _alpha, seed=seed)
        M = nx.to_numpy_matrix(self.G)
        if plot_adj:
            self.imshow_plot(M, "con")

        return tuple(np.asarray(M).reshape(-1))
def gen_PA(k_values,n):
    '''k_values: list of integers
    Generates an k-out with preferential attachment graph on n vertices with parameter k, for each k in k_values'''
    graphs = []
    i = 0
    print('Generating PA graphs')
    for k in k_values:
        print(i,end='\r')
        i += 1
        g = nx.random_k_out_graph(n,k,1,self_loops=False)
        graphs.append(g)
    return(graphs)
Ejemplo n.º 5
0
def random_generator(n: int, k: int, alpha: int, graph_version: int):
    """
    Generates a random connected graph with all the node attributes set to 3 and the edge weights to 1
    :param graph_version: file version
    :param alpha:
    :param n: number of nodes
    :param k:
    :return:
    """
    # Generate an almost complete graph
    graph = nx.DiGraph(
        nx.MultiDiGraph.to_directed(
            nx.random_k_out_graph(n, k, self_loops=False, alpha=alpha)))

    # # Delete incoming arcs from 0 -> starting node
    # graph.remove_edges_from([(v1, v2) for (v1, v2) in graph.in_edges if v2 is 0])

    # Connect the first and the last node
    graph.add_edges_from([(0, max(graph.nodes))])

    print(len(graph.edges))
    for node in graph.nodes:
        incoming = [(v1, v2) for (v1, v2) in graph.in_edges if v2 == node]
        deleted_nodes = 0
        # Randomly decide if an edge has to be kept or discarded
        for edge in incoming:
            keep = np.average(rnd.binomial(1, 0.55, 5))
            # Delete only if the nodes has more than one incoming and outcoming edge
            if keep >= 0.4 and deleted_nodes < len(incoming) - 1 and len(
                    graph.edges(edge[0])) > 1:
                graph.remove_edge(edge[0], edge[1])
                deleted_nodes = deleted_nodes + 1

    # Delete node cycles in order to save the graph as strict. Otherwise the graph is by default a multi-weight graph
    node_cycles = [(u, v) for (u, v) in graph.edges() if u in graph[v]]
    graph.remove_edges_from(node_cycles)

    # Connect every arc to the first one
    graph.add_edges_from([(node, 0) for node in graph.nodes if node is not 0])
    # Set the attributes
    nx.set_node_attributes(graph, 3, 'component_delay')
    nx.set_edge_attributes(graph, 1, 'wire_delay')
    # Save it only if it is connected
    if nx.is_weakly_connected(graph):
        nx.nx_agraph.write_dot(
            graph,
            os.getcwd() + '/../rand-graphs/clean/{}/rand-{}-{}.dot'.format(
                n, n, graph_version))
        return True
    else:
        return False
Ejemplo n.º 6
0
def main():
    G = nx.random_k_out_graph(15, 3, 1, False)
    # show_graph(G)
    show_graph_with_communities(G)
Ejemplo n.º 7
0
        (
            [["a", "b"], ["b", "c"], ["d", "c"], ["c", "e"], ["c", "e"]],
            False,
            ([], [], [["c", "2"]], [["c", "e"]]),
        ),  # duplicate edge
        (
            [["a", "b"], ["b", "c"], ["d", "c"], ["a", "e"]],
            False,
            ([], [], [["a", "2"]], []),
        ),  # multiple out edges, a->b & a->e
    ],
)
def test_validate_network(edgelist, isvalid, result):

    g = nx.from_edgelist(edgelist, create_using=nx.MultiDiGraph)
    assert isvalid == is_valid(g)
    assert result == validate_network(g)


@pytest.mark.parametrize(
    "g, expected",
    [  # multiple out connections
        (nx.gnc_graph(10, seed=42), False),
        # multiple out connections, cycles, duplicated edges
        (nx.random_k_out_graph(10, 2, 1, seed=42), False),
        (nx.gn_graph(10, seed=42), True),
    ],
)
def test_isvalid(g, expected):
    assert expected == is_valid(g)
Ejemplo n.º 8
0
"""
==============
Directed Graph
==============

Draw a graph with directed edges using a colormap and different node sizes.

Edges have different colors and alphas (opacity). Drawn using matplotlib.
"""

import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx

seed = 13648  # Seed random number generators for reproducibility
G = nx.random_k_out_graph(10, 3, 0.5, seed=seed)
pos = nx.spring_layout(G, seed=seed)

node_sizes = [3 + 10 * i for i in range(len(G))]
M = G.number_of_edges()
edge_colors = range(2, M + 2)
edge_alphas = [(5 + i) / (M + 4) for i in range(M)]
cmap = plt.cm.plasma

nodes = nx.draw_networkx_nodes(G,
                               pos,
                               node_size=node_sizes,
                               node_color="indigo")
edges = nx.draw_networkx_edges(
    G,
    pos,
Ejemplo n.º 9
0
    def initialize(self):
        '''
        Initializes the network according to the chosen structure.
        Community members have a given social value orientation. 
        
        For the start of the identity mechanism, if active, agents have 
        a first exchange about it with initializes their social norms.
        
        For the start of the reputation mechanism, if active, the
        agents have arrays storing the reputation of neighbors.
        The links between agents are weighted according to the 
        average trust between two nodes.
        '''
        #initialize the network as a Barabasi Albert graph with a power law node degree distribution
        if self.network_type == 'BA':
            self.graph = nx.barabasi_albert_graph(self.network_size,
                                                  self.neighborhood_size)
        elif self.network_type == 'complete':
            self.graph = nx.complete_graph(self.network_size)
        elif self.network_type == 'directed':
            self.graph = nx.random_k_out_graph(self.network_size,
                                               self.neighborhood_size,
                                               alpha=1,
                                               self_loops=False)

        #setting social value orientations
        social_value_orientations = np.full(self.network_size, 1)
        social_value_orientations[0:int(self.network_size *
                                        (1 - self.prosociality))] = 0.01
        for node in self.graph.nodes:
            self.graph.nodes[node]['current_use'] = social_value_orientations[
                node]

        #observing the social value orientation of neighbors and initiating one's social norm expectations and identification
        for node in self.graph.nodes:
            neighbors = list(self.graph.neighbors(node))
            norms_distribution = []
            norms_differences = []
            for i in neighbors:  #recording the prosociality of neighbors and the deviation from one's own norms
                norms_distribution.append(self.graph.nodes[i]['current_use'])
                norms_differences.append(
                    abs(self.graph.nodes[i]['current_use'] -
                        self.graph.nodes[node]['current_use']))

            #updating social norms with the observation of neighbors' SVOs
            norms_distribution = np.array(norms_distribution) * len(
                norms_distribution)
            prior = stats.beta(a=(1.01 -
                                  self.graph.nodes[node]['current_use']),
                               b=0.8).pdf(self.lambdas)
            posterior = self.compute_posterior(self.lambdas, prior,
                                               self.likelihood,
                                               norms_distribution)
            self.social_norms[node] = posterior

            #updating the expected social norm variation and induced identification with the distribution of SVO differences
            norms_differences = np.array(norms_differences) * len(
                norms_differences)
            var_prior = stats.truncnorm(
                a=(self.identification[node] - 1) / self.diversity,
                b=self.identification[node] / self.diversity,
                loc=(1 - self.identification[node]),
                scale=self.diversity).pdf(self.lambdas)
            var_posterior = self.compute_posterior(self.lambdas, var_prior,
                                                   self.likelihood,
                                                   norms_differences)
            self.social_norms_variance[node] = var_posterior
            expected_var = []
            for _ in range(1000):
                expected_var.append(
                    np.random.choice(self.lambdas,
                                     p=self.social_norms_variance[node] /
                                     np.sum(self.social_norms_variance[node])))
            self.identification[node] = 1 - np.mean(expected_var)

        #plotting the social norms of all agents
        if self.markup:
            for n in self.social_norms:
                plt.plot(self.lambdas, n, label='social norms')
            plt.title(
                'Initial social norm distributions of all agents in the network'
            )
            plt.xlabel('Expected cooperation')
            plt.ylabel('PDF')
            plt.show()

        self.layout = nx.spring_layout(self.graph)  # Initial visual layout

        #set reputations of neighbors according to agent's social value orientation
        for node in self.graph.nodes:
            self.graph.nodes[node]['reputation'] = np.empty(self.network_size)
            for i in self.graph.neighbors(node):
                self.graph.nodes[node]['reputation'][
                    i] = social_value_orientations[node]
        self.layout = nx.spring_layout(self.graph)  # Initial visual layout
Ejemplo n.º 10
0
cycles = nx.cycle_basis(graph.to_undirected())

################## ONLY FOR VISUALIZATION #######################
abs_tot = abs(tot)
graph1 = nx.from_numpy_matrix(abs_tot.T, create_using=nx.DiGraph)
npos = nx.kamada_kawai_layout(graph1)
#################################################################

##########################################################################################################
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)

f0 = 1
delta_f = 1

g = nx.random_k_out_graph(n=f0, k=2, alpha=0.5)

axcolor = 'lightgray'
axfreq = plt.axes([0.25, 0.06, 0.65, 0.03], facecolor=axcolor)

sfreq = Slider(axfreq,
               'noise',
               1,
               20,
               valinit=f0,
               valstep=delta_f,
               valfmt='%0.0f')

active_nodes = []
non_active_nodes = []
Ejemplo n.º 11
0
        for i in range(n):
            if (A[i, j] != 0):
                A[i, j] = 1 / N_u
    A = A * d
    return A

def draw_graph(G):
    pos = nx.spring_layout(G)
    plt.figure(figsize=(15,15))
    nx.draw_networkx_nodes(G, pos)
    nx.draw_networkx_edges(G, pos, arrows=True)
    plt.plot()
    plt.show()


G = nx.random_k_out_graph(n, 4, 15, self_loops=False, seed=None)
adj_matrix = nx.to_numpy_matrix(G)
A = transform_matrix(adj_matrix)

pr1 = compute_r_from_exponent_method(A, n, 100, eps)
pr2 = compute_r_from_sum(adj_matrix, n, d, eps)

print("PageRank from matrix method:")
print(pr1.flatten(), end='\n\n')
print("PageRank from sum method:")
print(pr2)

#draw_graph(G)