Ejemplo n.º 1
0
def nodeTravelGraph(pages_visited):
    rcParams['figure.figsize'] = 8, 4
    sb.set_style('white')
    G = nx.DiGraph()
    label_dict = {}

    if not pages_visited:
        G = nx.gn_graph(1)
        label_dict.update({0: "Home"})
        return G, label_dict
        #nx.draw_circular(G, labels=label_dict, node_color='white', with_labels=True)
    else:
        n_pages = len(pages_visited)
        for i in range(n_pages):
            if i + 1 == n_pages & n_pages != 1:
                label_dict.update({i: pages_visited[i]})
                break
            elif n_pages == 1:
                G = nx.gn_graph(n_pages)
                label_dict.update({i: pages_visited[i]})
            else:
                label_dict.update({i: pages_visited[i]})
                G.add_edge(i, i + 1)

        return G, label_dict
Ejemplo n.º 2
0
def nodeNetworkGraph(nodes_found):
    #rcParams['figure.figsize'] = 8,4
    sb.set_style('ticks')
    G = nx.DiGraph()
    label_dict = {}

    if nodes_found == 0:
        G = nx.gn_graph(1)
        label_dict.update({0: "No Nodes Found"})
        return G, label_dict
    else:
        for i in range(nodes_found):
            if i + 1 == nodes_found & nodes_found != 1:
                label_dict.update({i: i + 1})
                break
            elif nodes_found == 1:
                G = nx.gn_graph(nodes_found)
                label_dict.update({i: i + 1})
            else:
                label_dict.update({i: i + 1})
                G.add_edge(i, i + 1)
        global node_pos
        node_pos = nx.circular_layout(G)
        #graph = nx.draw_networkx(G, pos=node_pos, labels = label_dict, node_color='yellow', with_labels=True)
        return G, label_dict, node_pos
Ejemplo n.º 3
0
    def RandomDirectedGN(self, n, kernel=lambda x:x, seed=None):
        """
        Returns a random GN (growing network) digraph with n vertices.

        The digraph is constructed by adding vertices with a link to one
        previously added vertex. The vertex to link to is chosen with a
        preferential attachment model, i.e. probability is proportional to
        degree. The default attachment kernel is a linear function of
        degree. The digraph is always a tree, so in particular it is a
        directed acyclic graph.

        INPUT:

        -  ``n`` - number of vertices.

        -  ``kernel`` - the attachment kernel

        -  ``seed`` - for the random number generator

        EXAMPLE::

            sage: D = digraphs.RandomDirectedGN(25)
            sage: D.edges(labels=False)
            [(1, 0), (2, 0), (3, 1), (4, 0), (5, 0), (6, 1), (7, 0), (8, 3), (9, 0), (10, 8), (11, 3), (12, 9), (13, 8), (14, 0), (15, 11), (16, 11), (17, 5), (18, 11), (19, 6), (20, 5), (21, 14), (22, 5), (23, 18), (24, 11)]
            sage: D.show()  # long time

        REFERENCE:

        - [1] Krapivsky, P.L. and Redner, S. Organization of Growing
          Random Networks, Phys. Rev. E vol. 63 (2001), p. 066123.
        """
        if seed is None:
            seed = current_randstate().long_seed()
        import networkx
        return DiGraph(networkx.gn_graph(n, kernel, seed=seed))
Ejemplo n.º 4
0
    def RandomDirectedGN(self, n, kernel=lambda x: x, seed=None):
        """
        Returns a random GN (growing network) digraph with n vertices.

        The digraph is constructed by adding vertices with a link to one
        previously added vertex. The vertex to link to is chosen with a
        preferential attachment model, i.e. probability is proportional to
        degree. The default attachment kernel is a linear function of
        degree. The digraph is always a tree, so in particular it is a
        directed acyclic graph.

        INPUT:

        -  ``n`` - number of vertices.

        -  ``kernel`` - the attachment kernel

        -  ``seed`` - for the random number generator

        EXAMPLE::

            sage: D = digraphs.RandomDirectedGN(25)
            sage: D.edges(labels=False)
            [(1, 0), (2, 0), (3, 1), (4, 0), (5, 0), (6, 1), (7, 0), (8, 3), (9, 0), (10, 8), (11, 3), (12, 9), (13, 8), (14, 0), (15, 11), (16, 11), (17, 5), (18, 11), (19, 6), (20, 5), (21, 14), (22, 5), (23, 18), (24, 11)]
            sage: D.show()  # long time

        REFERENCE:

        - [1] Krapivsky, P.L. and Redner, S. Organization of Growing
          Random Networks, Phys. Rev. E vol. 63 (2001), p. 066123.
        """
        if seed is None:
            seed = current_randstate().long_seed()
        import networkx
        return DiGraph(networkx.gn_graph(n, kernel, seed=seed))
Ejemplo n.º 5
0
def make_class_hierarchy(n, n_intermediate=None, n_leaf=None):
    """Create a mock class hierarchy for testing purposes.

    Parameters
    ----------
    n : int
        Number of nodes in the returned graph

    n_intermediate : int
        Number of intermediate (non-root, non-terminal) nodes in the returned graph

    n_leaf : int
        Number of leaf (terminal) nodes in the returned graph

    Returns
    -------
    G : dict of lists adjacency matrix format representing the class hierarchy
    """
    if n_leaf is None and n_intermediate is None:
        # No specific structure specified, use a general purpose graph generator
        G = gn_graph(n=n, create_using=DiGraph())

    if n_intermediate == 0:
        # No intermediate nodes, build a 1-level rooted tree
        if n_leaf is None:
            n_leaf = n - 1

        G = DiGraph(data=product((ROOT, ), range(n_leaf)))

    return to_dict_of_lists(G)
Ejemplo n.º 6
0
Archivo: tuzc.py Proyecto: weifei/tuzc
    def set_random_gn_graph(self, num_nodes, num_edges=None, degree_s=[None, None]):
        """
            Set the graph to a "layered" random dag
        """
        # remove the current graph first
        self.clear()

        if num_edges is None:
            num_edges = int((num_nodes ** 2 / 4))
        #
        # first create a GN graph

        #G = nx.gn_graph(num_nodes)
        G = nx.gn_graph(num_nodes)
        H = nx.DiGraph()
        for u, v in G.edges():
            H.add_edge(v, u, weight=1)
        G = H
        for u, v in G.edges():
            G[u][v]['weight'] = 1

        nodes = nx.topological_sort(G)
        num_edges = num_edges - G.number_of_edges()
        for i in range(num_edges):
            u_idx = random.choice(range(len(nodes)-1))
            u = nodes[u_idx]
            v = random.choice(nodes[u_idx+1:])
            if (u,v) in G.edges():
                G[u][v]['weight'] += 1
            else:
                G.add_edge(u, v, weight=1)

        self.set_random_session(G, degree_s)
Ejemplo n.º 7
0
def _construct_graph_objs():

    graphs = []
    for graph_type in [nx.Graph, nx.MultiGraph, nx.DiGraph, nx.MultiDiGraph]:
        g1 = nx.from_edgelist([("2", "1"), ("3", "1"), ("1", "0")],
                              create_using=graph_type)

        g2 = g1.copy()
        attrs = {
            n: {
                l: i
            }
            for i, (n, l) in enumerate(zip(g2.nodes, string.ascii_lowercase))
        }
        nx.set_node_attributes(g2, attrs)

        g3 = copy.deepcopy(g2)
        attrs = {
            e: {
                l: i
            }
            for i, (e, l) in enumerate(zip(g2.edges, string.ascii_lowercase))
        }
        nx.set_edge_attributes(g3, attrs)

        graphs.extend([(g1, True), (g2, True), (g3, True)])

    graphs.extend([
        # one out edge; these are 'valid' in `nereid`
        (nx.gn_graph(25, seed=42), True),
        # many out edges; these are not 'valid' in `nereid`
        (nx.gnc_graph(25, seed=42), False),
    ])
    return graphs
 def test_directed_raises(self):
     with pytest.raises(nx.NetworkXNotImplemented):
         dir_G = nx.gn_graph(n=5)
         prev_cc = None
         edge = self.pick_add_edge(dir_G)
         insert = True
         nx.incremental_closeness_centrality(dir_G, edge, prev_cc, insert)
Ejemplo n.º 9
0
def iidG_gn(n, p, gain_var=1, k=None, p_radius=0.75):
    def aEij(i, j, a=1):
        Eij = np.zeros((n, n))
        Eij[i, j] = a
        return Eij

    G = nx.gn_graph(n, kernel=k)
    G = nx.adjacency_matrix(G)
    G = G.toarray()

    B = [np.zeros((n, n)) for i in range(p)]
    for i, row in enumerate(G.T):
        for j, x in enumerate(row):
            if x == 1:
                b, a = random_arma(p,
                                   0,
                                   k=np.random.normal(0, gain_var),
                                   p_radius=p_radius)
                B[0] = B[0] + aEij(i, j, b)
                B[1:] = [
                    B_tau + aEij(i, j, a_tau)
                    for (B_tau, a_tau) in zip(B, a[1:])
                ]

    M = block_companion(B)
    return B, M, G
def gn_semi_preferential(n,
                         pref_coefficient=None,
                         create_using=None,
                         seed=None):
    """Return the GN digraph with n nodes.

	The GN (growing network) graph is built by adding nodes one at a time with
	a link to one previously added node.

	The graph is always a (directed) tree.

	Parameters
	----------
	n : int
		The number of nodes for the generated graph.
	pref_coefficient : float between 0 and 1, determining how much
		an edge choice depends on prior popularity (in-degree)
	create_using : graph, optional (default DiGraph)
		Return graph of this type. The instance will be cleared.
	seed : hashable object, optional
	The seed for the random number generator.
	"""

    # r = random.random()
    # This kernel sometimes chooses randomly
    # and sometimes bandwagons.
    # It bandwagons with probability = pref_coefficient.
    # x-1 is the in-degree
    kernel = lambda x: (pref_coefficient * (x - 1)) + (1 - pref_coefficient)

    # Another kernel to try
    # kernel = lambda x: x**pref_coefficient
    G = nx.gn_graph(n, kernel, create_using, seed)
    return G
Ejemplo n.º 11
0
def generateSubGraphs(numgraphs=2, nodespersub=5, interconnects=0):
    kernel = lambda x: x**0.0001
    x = temp = nx.gn_graph(nodespersub, kernel)

    for i in range(numgraphs - 1):
        temp = nx.gn_graph(nodespersub, kernel)
        x = nx.disjoint_union(x, temp)
        #Now add some crosstalk
        workinglen = len(x) - len(temp)
        for i in range(interconnects):
            firstnode = ra.choice(range(workinglen))
            secondnode = ra.choice(range(workinglen, len(x)))

            newedge = [firstnode, secondnode]
            ra.shuffle(newedge)
            x.add_edge(newedge[0], newedge[1])
    return x
Ejemplo n.º 12
0
def generateSubGraphs(numgraphs = 2, nodespersub = 5, interconnects = 0):
    kernel = lambda x: x**0.0001
    x = temp = nx.gn_graph(nodespersub, kernel)

    for i in range(numgraphs-1):
        temp = nx.gn_graph(nodespersub, kernel)
        x = nx.disjoint_union(x, temp)
        #Now add some crosstalk
        workinglen = len(x) - len(temp)
        for i in range(interconnects):
            firstnode = ra.choice(range(workinglen))
            secondnode = ra.choice(range(workinglen,len(x)))

            newedge = [firstnode, secondnode]
            ra.shuffle(newedge)
            x.add_edge(newedge[0], newedge[1])
    return x
Ejemplo n.º 13
0
def _construct_graphs():
    graphs = [
        # one out edge; these are 'valid' in `nereid`
        (nx.gn_graph(25, seed=42)),
        # many out edges; these are not 'valid' in `nereid`
        (nx.gnc_graph(25, seed=42)),
    ]

    return graphs
Ejemplo n.º 14
0
def directed_graphs():
    print("Directed graphs")
    print("Growing network")
    D = nx.gn_graph(10)  # the GN graph
    draw_graph(D)
    G = D.to_undirected()  # the undirected version
    draw_graph(G)
    D = nx.gn_graph(10, kernel=lambda x: x**1.5)  # A_k = k^1.5
    draw_graph(D)
    print("Growing network graph")
    D = nx.gnr_graph(n=11, p=0.3)
    draw_graph(D)
    G = D.to_undirected()
    draw_graph(G)
    print("Growing network with copying graph")
    D = nx.gnc_graph(n=7)
    draw_graph(D)
    G = D.to_undirected()
    draw_graph(G)
    print("Scale-free graph")
    G = nx.scale_free_graph(10)
    draw_graph(G)
Ejemplo n.º 15
0
def main():

    nodes = [0, 1, 2, 3]
    edges = [(0, 1), (1, 0), (0, 2), (2, 1), (3, 0), (3, 1)]
    #G = nx.DiGraph(edges)
    # Generate random complete graph
    G = nx.gn_graph(100)
    root = random.randint(0, 100)

    my_visit = bfs(G, root)
    good_visit = list(nx.bfs_edges(G, source=root))
    print(f"My visit: {my_visit}")
    print(f"Good visit: {good_visit}")
def test_directed_subgraph_hash():
    """
    A directed graph with no bi-directional edges should yield different subgraph hashes
    to the same graph taken as undirected, if all hashes don't collide.
    """
    r = 10
    for i in range(r):
        G_directed = nx.gn_graph(10 + r, seed=100 + i)
        G_undirected = nx.to_undirected(G_directed)

        directed_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_directed)
        undirected_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_undirected)

        assert directed_subgraph_hashes != undirected_subgraph_hashes
Ejemplo n.º 17
0
 def graph_sel(graphType, n, p):
     '''
     Funzione che genera e restituisce un grafo del tipo prescelto.
     Viene invocata solo se, nell'inizializzazione del repository,
     non viene direttamente specifica un grafo ma solo un graph type.
     '''
     return {
         'gn': lambda: nx.gn_graph(n),
         'gnr': lambda: nx.gnr_graph(n, p),
         'gnc': lambda: nx.gnc_graph(n),
         'scale_free': lambda: nx.scale_free_graph(n),
         'erdos_renyi': lambda: nx.erdos_renyi_graph(n, p, directed=True),
         'nSCC_graph': lambda: self.nSCC_graph(n)
     }.get(graphType, graphType)()
def test_directed():
    """
    A directed graph with no bi-directional edges should yield different a graph hash
    to the same graph taken as undirected if there are no hash collisions.
    """
    r = 10
    for i in range(r):
        G_directed = nx.gn_graph(10 + r, seed=100 + i)
        G_undirected = nx.to_undirected(G_directed)

        h_directed = nx.weisfeiler_lehman_graph_hash(G_directed)
        h_undirected = nx.weisfeiler_lehman_graph_hash(G_undirected)

        assert h_directed != h_undirected
Ejemplo n.º 19
0
 def test_randomgraph_files(self):
     G = nx.gn_graph(20)
     targets = defaultdict(dict)
     depends = defaultdict(dict)
     allfiles = list()
     for a, b in G.edges():
         f = os.path.join(self.workdir, "{}_{}.txt".format(a, b))
         allfiles.append(f)
         targets[a][b] = depends[b][a] = f
     shall_fail = set(
         [random.choice(G.nodes()) for _ in range(int(len(G)**.5))])
     nodes = nx.algorithms.dag.topological_sort(G)
     task_nos = [None for _ in range(len(nodes))]
     for n in nodes:
         cmd = "touch /dev/null " + " ".join(targets[n].values())
         if n in shall_fail:
             cmd += " ;exit 1"
         t = self.ctx.add_task(cmd,
                               name=cmd,
                               targets=list(targets[n].values()),
                               depends=list(depends[n].values()))
         task_nos[n] = t.task_no
     # self.ctx.fail_idx = task_nos[G.successors(list(shall_fail)[0])[-1]]
     self.assertFalse(any(map(os.path.exists, allfiles)))
     with capture(stderr=StringIO()):
         import anadama2.reporters
         with self.assertRaises(anadama2.workflow.RunFailed):
             rep = anadama2.reporters.LoggerReporter("debug", "/tmp/analog")
             self.ctx.go(reporter=rep)
     child_fail = set()
     for n in shall_fail:
         task_no = task_nos[n]
         self.assertIn(task_no, self.ctx.failed_tasks,
                       ("tasks that raise exceptions should be marked"
                        " as failed"))
         self.assertTrue(bool(self.ctx.task_results[task_no].error),
                         "Failed tasks should have errors in task_results")
         for _, succ in dfs_edges(G, n):
             s_no = task_nos[succ]
             child_fail.add(succ)
             self.assertIn(s_no, self.ctx.failed_tasks,
                           "all children of failed tasks should fail")
             self.assertIn("parent task", self.ctx.task_results[s_no].error,
                           ("children of failed tasks should have errors"
                            " in task_results"))
     for n in set(nodes).difference(shall_fail.union(child_fail)):
         task_no = task_nos[n]
         self.assertIn(task_no, self.ctx.completed_tasks)
         self.assertFalse(bool(self.ctx.task_results[task_no].error))
Ejemplo n.º 20
0
 def test_randomgraph_files(self):
     G = nx.gn_graph(20)
     targets = defaultdict(dict)
     depends = defaultdict(dict)
     allfiles = list()
     for a, b in G.edges():
         f = os.path.join(self.workdir, "{}_{}.txt".format(a, b))
         allfiles.append(f)
         targets[a][b] = depends[b][a] = f
     shall_fail = set(
         [random.choice(G.nodes()) for _ in range(int(len(G)**.5))])
     nodes = nx.algorithms.dag.topological_sort(G)
     task_nos = [None for _ in range(len(nodes))]
     for n in nodes:
         cmd = "touch /dev/null " + " ".join(targets[n].values())
         if n in shall_fail:
             cmd += " ;exit 1"
         slurm_add_task = lambda *a, **kw: self.ctx.add_task_gridable(
             mem=50, time=5, cores=1, *a, **kw)
         add_task = self.ctx.add_task if bern(0.5) else slurm_add_task
         t = add_task(cmd,
                      name=cmd,
                      targets=list(targets[n].values()),
                      depends=list(depends[n].values()))
         task_nos[n] = t.task_no
     self.assertFalse(any(map(os.path.exists, allfiles)))
     with capture(stderr=StringIO()):
         with self.assertRaises(anadama2.workflow.RunFailed):
             self.ctx.go(grid_jobs=2)
     child_fail = set()
     for n in shall_fail:
         task_no = task_nos[n]
         self.assertIn(task_no, self.ctx.failed_tasks,
                       ("tasks that raise exceptions should be marked"
                        " as failed"))
         self.assertTrue(bool(self.ctx.task_results[task_no].error),
                         "Failed tasks should have errors in task_results")
         for _, succ in dfs_edges(G, n):
             s_no = task_nos[succ]
             child_fail.add(succ)
             self.assertIn(s_no, self.ctx.failed_tasks,
                           "all children of failed tasks should fail")
             self.assertIn("parent task", self.ctx.task_results[s_no].error,
                           ("children of failed tasks should have errors"
                            " in task_results"))
     for n in set(nodes).difference(shall_fail.union(child_fail)):
         task_no = task_nos[n]
         self.assertIn(task_no, self.ctx.completed_tasks)
         self.assertFalse(bool(self.ctx.task_results[task_no].error))
Ejemplo n.º 21
0
def generateHourGlassGraph(nodes=10, interconnects=0):
    def flipGraph(g):
        e = g.edges()
        g.remove_edges_from(e)
        g.add_edges_from(zip(*zip(*e)[::-1]))

    kernel = lambda x: x**0.0001
    if nodes < 4:
        return nx.gn_graph(nodes, kernel)
    n1, n2 = int(floor(nodes / 2.)), int(ceil(nodes / 2.))
    x1 = nx.gn_graph(n1, kernel)
    x2 = nx.gn_graph(n2, kernel)
    flipGraph(x2)
    x = nx.disjoint_union(x1, x2)
    x.add_edge(0, n1 + 1)

    for i in range(interconnects):
        firstnode = ra.choice(range(n1))
        secondnode = ra.choice(range(n1, n1 + n2))
        #newedge = [firstnode, secondnode]
        #ra.shuffle(newedge)
        #x.add_edge(newedge[0], newedge[1])
        x.add_edge(firstnode, secondnode)
    return x
Ejemplo n.º 22
0
def generateHourGlassGraph(nodes=10, interconnects = 0):
    def flipGraph(g):
        e = g.edges()
        g.remove_edges_from(e)
        g.add_edges_from(zip(*zip(*e)[::-1]))

    kernel = lambda x: x**0.0001
    if nodes < 4:
        return nx.gn_graph(nodes,kernel)
    n1 , n2 = int(floor(nodes/2.)), int(ceil(nodes/2.))
    x1 = nx.gn_graph(n1, kernel)
    x2 = nx.gn_graph(n2, kernel)
    flipGraph(x2)
    x = nx.disjoint_union(x1,x2)
    x.add_edge(0,n1+1)

    for i in range(interconnects):
        firstnode = ra.choice(range(n1))
        secondnode = ra.choice(range(n1,n1+n2))
        #newedge = [firstnode, secondnode]
        #ra.shuffle(newedge)
        #x.add_edge(newedge[0], newedge[1])
        x.add_edge(firstnode,secondnode)
    return x
Ejemplo n.º 23
0
    def test_randomgraph_tasks(self):
        G = nx.gn_graph(20)
        targets = defaultdict(dict)
        depends = defaultdict(dict)
        shall_fail = set(
            [random.choice(G.nodes()) for _ in range(int(len(G)**.5))])
        nodes = nx.algorithms.dag.topological_sort(G)
        task_nos = [None for _ in range(len(nodes))]
        for n in nodes:
            cmd = "touch /dev/null "
            name = None
            if n in shall_fail:
                cmd += " ;exit 1"
                name = "should fail"
            slurm_add_task = lambda *a, **kw: self.ctx.add_task_gridable(
                mem=50, time=5, cores=1, *a, **kw)
            add_task = self.ctx.add_task if bern(0.5) else slurm_add_task
            t = add_task(cmd,
                         name=name,
                         depends=[
                             self.ctx.tasks[task_nos[a]]
                             for a in G.predecessors(n)
                         ])
            task_nos[n] = t.task_no

        with capture(stderr=StringIO()):
            with self.assertRaises(anadama2.workflow.RunFailed):
                self.ctx.go(grid_jobs=2)
        child_fail = set()
        for n in shall_fail:
            task_no = task_nos[n]
            self.assertIn(task_no, self.ctx.failed_tasks,
                          ("tasks that raise exceptions should be marked"
                           " as failed"))
            self.assertTrue(bool(self.ctx.task_results[task_no].error),
                            "Failed tasks should have errors in task_results")
            for _, succ in dfs_edges(G, n):
                s_no = task_nos[succ]
                child_fail.add(succ)
                self.assertIn(s_no, self.ctx.failed_tasks,
                              "all children of failed tasks should fail")
                self.assertIn("parent task", self.ctx.task_results[s_no].error,
                              ("children of failed tasks should have errors"
                               " in task_results"))
        for n in set(nodes).difference(shall_fail.union(child_fail)):
            task_no = task_nos[n]
            self.assertIn(task_no, self.ctx.completed_tasks)
            self.assertFalse(bool(self.ctx.task_results[task_no].error))
Ejemplo n.º 24
0
def compute(infile, outfile):
    start = time.time()
    df = pd.read_csv(infile)
    N, n = df.shape
    G = nx.gn_graph(n)
    #==========================================#
    #to verify values
    # G = nx.DiGraph()
    # G_new, G_alt = create_random_graph(n, G)
    #==========================================#

    bayes = BayesScore(G, df)  # This is inside compute
    G_opt, score_opt = local_search(bayes, G, df)
    end = time.time()
    timer = end - start
    print('total time: %.2', timer)

    # G_opt = G; score_opt = 100;
    G_opt = nx.relabel_nodes(G_opt, bayes.idx2node)

    # plot_graph(G_opt, show=True)
    # pdb.set_trace()

    print('best final score:', score_opt)
    length = df.shape[1]

    d = bayes.node2idx
    node_list = sorted(d, key=d.get)
    # parents_values = [data[parent]-1 for parent in parents]
    # pdb.set_trace()

    timestamp = str(int(time.time()))
    new_dir = str("./out_") + timestamp
    os.mkdir(new_dir)

    filename = new_dir + ('/') + outfile
    write_gph(G_opt, bayes.node2idx, filename)

    fig = plot_graph(G_opt)
    title = 'score = %.2f, time taken = %.2f (s)' % (score_opt, timer)
    plt.title(title)
    # new_dir = str("./out_")+str(int(time.time()) )

    figname = new_dir + ('/') + (infile[:2]) + ('.png')
    plt.savefig(figname)
Ejemplo n.º 25
0
def main():
    """
        Main code:
        - creates nodes
        - instanciates a 'drawer' to display a graph of the network
    """

    if len(sys.argv) < 2:
        sys.stderr.write("Usage: %s number_of_nodes\n" % sys.argv[0])
        sys.exit(1)

    number_of_nodes = int(sys.argv[1])

    ### INIT NODES with a graph
    graph = nx.gn_graph(number_of_nodes)

    nodes = []
    for i in range(number_of_nodes):
        node_name = "%s" % i
        neighbors = [
            str(node)
            for node in chain(graph.predecessors(i), graph.successors(i))
        ]
        node = Node(node_name, neighbors)
        node.consumer.start()
        nodes.append(node)

    initialize_network(nodes, str(random.randint(0, number_of_nodes - 1)))

    graph_attributes = {}
    for i in range(len(nodes)):
        graph_attributes[i] = {"node": nodes[i], "label": nodes[i].name}

    nx.set_node_attributes(graph, graph_attributes)

    drawer = Drawer(graph)
    Controller(nodes).start()
    while True:
        drawer.generate_graph()
        drawer.draw_graph()
Ejemplo n.º 26
0
def generate_random_L(p=10,
                      a=0.3,
                      b=0.7,
                      diag_a=2,
                      diag_b=5,
                      plot=False,
                      G=None):
    """
    randomly generates a lower triangular matrix based on a growing network graph
    Input:
        p: number of nodes
        a: lower bound for off-diagonal
        b: upper bound for off_diagonal
        diag_a: lower bound for diagonal
        diag_b: upper bound for diagonal
        G: Directed graph
    Output:
        L: Lower triangular matrix
        A: Adjacency matrix
        G: Directed graph
    """
    if (G is None):
        G = nx.gn_graph(p)
    if (nx.is_directed(G) is False):
        print('G is not directed')
        exit(1)
    ### need to relabel vertices to agree with CSCS
    mapping = dict(zip(G.nodes(), list(range(p - 1, -1, -1))))
    G = nx.relabel_nodes(G, mapping)
    if (plot):
        import matplotlib.pyplot as plt
        plt.show()
        nx.draw_shell(G, with_labels=True, font_weight='bold')
    A = nx.adjacency_matrix(G).todense()
    L = np.multiply(A, ((b - a) * np.random.random_sample(size=p * p) +
                        a).reshape(p, p))
    np.fill_diagonal(L, np.random.uniform(diag_a, diag_b, p))
    return (L, A, G)
Ejemplo n.º 27
0
# ## 295. Connectivity matrix example

# + pycharm={"name": "#%%\n"}
import numpy as np
import scipy.sparse as sparse

A = sparse.random(8, 8, 0.2, data_rvs=np.ones)
A.toarray()  # To print A

# + [markdown] pycharm={"name": "#%% md\n"}
# ## 302. Incidence matrix

# + pycharm={"name": "#%%\n"}
import networkx.linalg.graphmatrix as gm

G = nx.gn_graph(5)
# oriented=True is needed to get the directed/oriented incidence matrix.
gm.incidence_matrix(G, oriented=True).toarray()

# + [markdown] pycharm={"name": "#%% md\n"}
# ## 305. Incidence matrix

# + pycharm={"name": "#%%\n"}
n = 4
arc_list = [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4)]
G = nx.DiGraph()
G.add_nodes_from(range(1, n + 1))
G.add_edges_from(arc_list)
gm.incidence_matrix(G, oriented=True).toarray()

# + [markdown] pycharm={"name": "#%% md\n"}
Ejemplo n.º 28
0
# -*- coding: utf-8 -*-
import networkx as nx
import random



# Testni graf
mGraph = nx.gn_graph(10)
for edge in mGraph.edges():
    print (edge)



## 1: Funkcija za iskanje števila povezav za vsak node
def getNodeInputAndOutputCount(g):
    #Inicializacija slovarjev
    countedIn = {}
    countedOut = {}
    #Za vsak rob - 
    for edge in g.edges_iter():
        #če krajišča še ni v števcih vhoda ali izhoda, ga dodaj in nastavi na 0
        if  not edge[0] in countedOut:
            countedOut[edge[0]] = 0
        if  not edge[1] in countedOut:
            countedOut[edge[1]] = 0
        if  not edge[0] in countedIn:
            countedIn[edge[0]] = 0
        if  not edge[1] in countedIn:
            countedIn[edge[1]] = 0

        #Krajišču izvora roba prištej ena v števcu izhodov    
Ejemplo n.º 29
0
#!/usr/bin/env python
import sys
sys.path.append(".")
import openpnl
import networkx
import matplotlib.pyplot as plt

nnodes = 26
G = networkx.gn_graph(nnodes)
mp = {}
for i in range(0,nnodes):
    mp[i+1] = chr(ord('A')+i-1)
G = networkx.relabel_nodes(G, mp)
networkx.draw(G)
plt.show()



pWSBnet = openpnl.pnlExCreateWaterSprinklerBNet()
pWSBnet.GetGraph().Dump();

pEvidForWS = openpnl.mkEvidence( pWSBnet, [0], [1] )
pNaiveInf = openpnl.CNaiveInfEngine.Create( pWSBnet )
pNaiveInf.EnterEvidence( pEvidForWS );

nodes = [1,3]
pNaiveInf.MarginalNodes( nodes );

pMarg = pNaiveInf.GetQueryJPD()

obsVls = openpnl.pConstValueVector()
import networkx as nx
import matplotlib.pyplot as plt
from random import randint

graphs = []
for i in range(100, 1000 + 1, 100):
    graphs.append(nx.gn_graph(i))
graphs.append(nx.gn_graph(10000))

s = "#use \"projet.ml\"\n\n"

for i, graph in enumerate(graphs):
    name = "ge" + str(graph.number_of_nodes())

    s += "let " + name + " = Dag.create ();;\n"

    s += "\n"
    for i, node in graph.nodes_iter(data=True):
        node['name'] = "v" + str(i)
        node['ressource'] = randint(1, 2)
        node['cout'] = randint(1, 3)

    for i, node in graph.nodes(data=True):
        s += "let " + node['name'] + " = Dag.createv (\"" \
            + node['name'] \
            + "\", " + str(node['ressource']) \
            + ", " + str(node['cout']) \
            + ".);;\n"

    s += "\n"
    for i, node in graph.nodes(data=True):
Ejemplo n.º 31
0
from random import randrange
#randomized optimal flow algorithms
from algorithms.minimum_flow.constrainedBoP_hitting import *
from algorithms.minimum_flow.constrainedBoP_nonhitting import *
from algorithms.maximum_flow.capacity_constraint import *
#graph functions
from algorithms.graph_functions.api import *

###########
# DATASET #
###########

list_of_dataset = []

#generation of graph with 100 nodes
T = nx.gn_graph(100, seed=1)
G1 = nx.DiGraph()
for node_i,node_j in T.edges():
    G1.add_edge(node_j, node_i, weight=5, capacity=20, flow=0)
list_of_no_succesors = []
for node in G1.nodes():
    lenght = sum(1 for _ in G1.successors(node))
    if lenght==0:
        list_of_no_succesors.append(node)
for node_no_succ in list_of_no_succesors:
    G1.add_edge(node_no_succ, 100, weight=5, capacity=20, flow=0)
G1.nodes[0]['b'] = 100
G1.nodes[100]['b'] = -100
list_of_dataset.append(G1)

#generation of graph with 500 nodes
Ejemplo n.º 32
0
import random
import networkx as nx
import dijkstraalgorithm as djk
import time
import matplotlib.pyplot as plt

lista_vertices = list()
lista_media_tempo = list()

for n in range(0, 5000, 5):
    print(n)
    G = nx.gn_graph(n)
    for (u, v, w) in G.edges(data=True):
        w['weight'] = random.randint(0, 100)
    soma = 0.
    for i in range(1, 11):
        start = time.time()
        djk.dijkstra(G, list(G.nodes())[0], G.number_of_nodes() - 1)
        tempo = time.time() - start
        soma = soma + tempo
    lista_vertices.append(n)
    lista_media_tempo.append(soma / 10)

plt.plot(lista_vertices, lista_media_tempo)
plt.axis([0, 5000, 0, max(lista_media_tempo) * 2])
plt.ylabel('Tempo de execução (Segundos)')
plt.xlabel('Número de Vértices')
plt.title("Desempenho Algoritmo de Dijkstra")
plt.show()
Ejemplo n.º 33
0
import networkx as nx
import matplotlib.pyplot as plt
import collections

#generation of a forest fire graph with GN incremental growth model
G = nx.gn_graph(100, kernel=lambda x: x**1.5)

# Graph display
coord = nx.spring_layout(G, iterations=1000)
fig = plt.figure()
axs = fig.add_subplot(111, aspect='equal')
axs.axis('off')
nx.draw_networkx_edges(G, coord)
nx.draw_networkx_nodes(G, coord, node_size=100, node_color='k')
plt.show()

# Degree distribution analysis
print("Degree Distribution :")
print(G.degree())
degree_sequence = sorted([d for n, d in G.degree()],
                         reverse=True)  # degree sequence
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())
print("Avg. degree : ",
      sum(deg) / len(deg), "Max. degree : ", max(deg), "Min. degree : ",
      min(deg))
fig, ax = plt.subplots()
plt.plot(deg, cnt, 'ro-')
plt.title("Degree Distribution")
plt.ylabel("Count")
plt.xlabel("Degree")
Ejemplo n.º 34
0
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sb

import networkx as nx

from pylab import rcParams

#%%
rcParams['figure.figsize'] = 5, 4
sb.set_style('whitegrid')

#%%
# Generating a graph object and edgelist
DG = nx.gn_graph(7, seed=25)

for line in nx.generate_edgelist(DG, data=False):
    print(line)

#%%
# Assign attributes to nodes, such as name, weight, directions.
print(DG.node[0])

#%%
DG.node[0]["name"] = 'Alice'
print(DG.node[0])

#%%
DG.node[1]["name"] = 'Bob'
DG.node[2]["name"] = 'Claire'
Ejemplo n.º 35
0
#!/usr/bin/env python
import sys
sys.path.append(".")
import openpnl
import networkx
import matplotlib.pyplot as plt

nnodes = 26
G = networkx.gn_graph(nnodes)
mp = {}
for i in range(0, nnodes):
    mp[i + 1] = chr(ord('A') + i - 1)
G = networkx.relabel_nodes(G, mp)
networkx.draw(G)
plt.show()

pWSBnet = openpnl.pnlExCreateWaterSprinklerBNet()
pWSBnet.GetGraph().Dump()
pEvidForWS = openpnl.mkEvidence(pWSBnet, [0], [1])

## Naive Inference Engine
print "Naive Inf Engine"
pNaiveInf = openpnl.CNaiveInfEngine.Create(pWSBnet)
pNaiveInf.EnterEvidence(pEvidForWS)
nodes = [1, 3]
pNaiveInf.MarginalNodes(nodes)
pMarg = pNaiveInf.GetQueryJPD()
obsVls = openpnl.pConstValueVector()
print openpnl.convertVector(
    pMarg.GetMatrix(openpnl.matTable).ConvertToDense().GetVector())
Ejemplo n.º 36
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)