Beispiel #1
0
def main():
    G = nx.DiGraph()
    fgs = []
    rs = []
    ps = set()
    cnt = 0
    all_data = []
    for r in range(1, 10):
        last = -1
        last_data = joblib.load(
            "data/policy-fingerprints/fixed-init.run-{}.update-{}.data".format(
                r, 32))
        if last_data[0][0][0] == 2:
            continue
        for u in range(1, 33):
            _data = joblib.load(
                "data/policy-fingerprints/fixed-init.run-{}.update-{}.data".
                format(r, u))
            for fg, e, m in _data:
                all_data.append((fg, r, u, e, m))
                if e == 0 and m == 0:
                    fgs.append(fg)
                    rs.append("run-{}".format(r))
                    h = hashing(fg)
                    cnt += 1
                    if last != -1 and last != h:
                        # print(last, h)
                        G.add_edge(last, h)
                    last = h
                    if h not in ps:
                        ps.add(h)
    # joblib.dump(all_data, "data/policy-fingerprints/all.data")
    print(len(ps), cnt)
    nx.draw_shell(G, node_size=30)
    plt.show()
Beispiel #2
0
    def __call__(self, population: list) -> list:
        """Take a population, plot the best individual (if `step % modulo == 0`),
        and return the population unmodified.
        """
        assert (population is not None)
        assert ('leap' in self.context)
        assert ('generation' in self.context['leap'])
        step = self.context['leap']['generation']

        if step % self.modulo == 0:
            best = max(population)
            graph = best.decode().graph
            self.ax.clear()
            if self.weights:
                weights = list(
                    nx.get_edge_attributes(graph, 'weight').values())
                weights = [self.weight_multiplier * w for w in weights]
                nx.draw_shell(graph,
                              width=weights,
                              with_labels=True,
                              ax=self.ax)
            else:
                nx.draw_shell(graph, with_labels=True, ax=self.ax)

        return population
Beispiel #3
0
    def draw_graph(self, G, node_list=None, edge_colour='k', node_size=15, node_colour='r', graph_type='spring',
                   back_bone=None, side_chains=None, terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                          edge_color=edge_colour, node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        plt.show()
def draw_graph(graph_file="graph_data.txt", f_name="social_path.png"):
    """
    Create a graph object from a file, draw the graph on the screen,
    and output it to a .png image file.

    Args:
        graph_file (string): The file name or file path to read in
        a graph representation from.
        f_name (string): The file name or file path to save the
        generated figure to as a .png image.
    """
    # create graph from file
    g = Graph(graph_file)
    # create nx graph with edges
    nxGraph = nx.DiGraph(g.get_edges())
    plt.figure(1, figsize=(12, 9))
    plt.margins(0.1)
    # draw graph
    nx.draw_shell(nxGraph,
                  with_labels=True,
                  node_size=9000,
                  font_size=10,
                  width=1.4,
                  font_color='w')

    # save to png
    plt.savefig(f_name)
    # display on screen
    plt.show()
Beispiel #5
0
def generate_graph(lecture):

	edge_list = []
	edge_time_list = []
	for attendant in lecture.attendant_set.all():
		for classmate in attendant.diredge_set.all():
			edge_list.append((str2(classmate.attendant.student_id), str2(classmate.direction_id)))
			edge_time_list.append(classmate.pub_date)

	attendance = nx.DiGraph()
	weights = {}
	g = BytesIO()

	# Add every single node and edge to the NetworkX graph, in addition to 
	# marking students as "present" by initializing weight to 0
	for (origin, destination) in edge_list:
		attendance.add_edge(origin, destination)
		weights[origin] = 0
		weights[destination] = 0

	node_names = []

	# Add proper number of connections associated with each student, both inbound and outbound
	# Create list for labelling nodes in graph
	for (origin, destination) in edge_list:
		weights[origin] = weights[origin] + 1 # not NetworkX weights. These are for printing.
		weights[destination] = weights[destination] + 1
		if origin not in node_names:
			node_names.append(origin)
		if destination not in node_names:
			node_names.append(destination)

	sizes = []
	names = {}
	# Create the actual node labels
	for n in node_names:
		names[str(n)] = n[:5] # first five characters of ID, add this to print connection count: + ": " + str(weights[n])
		sizes.append(70*len(n))
	
	light_blue = cmap_map(lambda x: x/2 + 0.5, matplotlib.cm.winter) # winter is a nice, theme-consistent color

	# Draw the NetworkX graph
	nx.draw_shell(attendance,
		node_size = 100,
		font_size = 2, 
		node_color=range(len(node_names)), # gradient colors 
		edge_color=range(len(edge_list)),
		cmap=light_blue, # node color is a mix of light greens through blues
		labels = names, 
		with_labels = True)
	try:
		# Save the image in a pseudofile in memory
		plt.savefig(g, format='png', dpi=500)
		# Save the image in the media directory so Django can find it
		lecture.lecture_graph.save(lecture.lecture_title_slug, ContentFile(g.getvalue()))
		# Clean up objects
		attendance.clear()
		plt.clf()
	finally:
		g.close()
Beispiel #6
0
def start_graph(Nomserie, type_graph):
    print(type_graph)
    options = {
        'node_color': 'red',
        'node_size': 200,
        'width': 3,
    }

    if Nomserie == "Game of Thrones":
        G1 = nx.read_graphml("data/got/GoT_S05E09_1039.graphml")
        print(G1)
    if Nomserie == "Breaking Bad":
        G1 = nx.read_graphml("data/bb/BB_S03E11_598.graphml")
    if Nomserie == "House of Card":
        G1 = nx.read_graphml("data/hoc/HoC_S02E13_879.graphml")

    G1.remove_nodes_from(nx.isolates(G1))
    if type_graph == "Classical":
        nx.draw_networkx(G1, pos=nx.spring_layout(G1))
    if type_graph == "Random":
        nx.draw_random(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Circular":
        nx.draw_circular(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Spectral":
        nx.draw_spectral(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Shell":
        nx.draw_shell(G1, **options, with_labels=True, font_weight='bold')
    plt.savefig("images/" + Nomserie + "_" + type_graph + ".jpg")
    plt.close('all')
    def show(self):
        """! @brief Shows a dirty version of the graph structure in a interactive window 
            @deprecated Use visualize(path)
        """
        nx.draw_shell(self, with_labels=False, font_weight='bold')

        plt.show()
Beispiel #8
0
def draw_networkx_ex():
    G = nx.dodecahedral_graph()
    nx.draw(G)
    plt.show()
    nx.draw_networkx(G, pos=nx.spring_layout(G))
    limits = plt.axis('off')
    plt.show()
    nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
    plt.show()
    edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    plt.show()
    labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
    plt.show()
    edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
    plt.show()
    print("Circular layout")
    nx.draw_circular(G)
    plt.show()
    print("Random layout")
    nx.draw_random(G)
    plt.show()
    print("Spectral layout")
    nx.draw_spectral(G)
    plt.show()
    print("Spring layout")
    nx.draw_spring(G)
    plt.show()
    print("Shell layout")
    nx.draw_shell(G)
    plt.show()
    print("Graphviz")
Beispiel #9
0
def nx_graph_freq_weighted():
    """Make graph with state indication between nodes.
    """
    adj_list = TextCorpus().global_adj_list_for_nx
    print '-- Adjacency List --\n{0}'.format(adj_list)
    G = nx.Graph()
    pos = nx.spring_layout(G)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if contact.avg_sentiment < 0.33],
    #                       node_color='r', node_size=300, alpha=0.8)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if 0.33 < contact.avg_sentiment && contact.avg_sentiment < 0.66],
    #                         node_color='y', node_size=300, alpha=0.8)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if 0.66 < contact.avg_sentiment && contact.avg_sentiment < 0.80],
    #                         node_color='c', node_size=300, alpha=0.8)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if 0.80 < contact.avg_sentiment],
    #                         node_color='m', node_size=300, alpha=0.8)
    # nx.draw_networkx_edges(G, pos, width = 1.0, alpha = 0.5)
    # nx.draw_networkx_edges(G, pos, edgelist=adj_list, width=(8), )

    G.add_edges_from(adj_list)
    G = nx.MultiGraph(G)
    G.add_weighted_edges_from(get_uvweights())
    nx.draw_shell(G)
    img_fn = "w_graph-{0}".format(strftime('%Y-%m-%d %H:%M:%S.png', gmtime()))
    plt.savefig(img_fn)
    plt.show()
Beispiel #10
0
def shortestpath(request):
    G = nx.DiGraph()

    for user in CustomUser.objects.all():
        G.add_node(user.username)
    for user in CustomUser.objects.all():
        for friend in user.friends.all():
            G.add_edge(user.username, friend.username, color='grey')
    #nx.draw(G, with_labels=True)
    paths = nx.all_shortest_paths(G, 'abbas', 'samy')
    for path in paths:
        for x in range(0, len(list(path)) - 1):
            G.edges[path[x], path[x + 1]]['color'] = 'red'
            G.edges[path[x + 1], path[x]]['color'] = 'red'

    edges = G.edges()
    colors = [G[u][v]['color'] for u, v in edges]

    nx.draw_shell(G,
                  with_labels=True,
                  node_color='green',
                  arrows=False,
                  font_size=12,
                  node_size=500,
                  edge_color=colors)

    #nx.draw_networkx_labels(G, pos)
    #nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
    #nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
    #plt.scatter(10, 10, alpha=10)
    plt.draw()
    #plt.scatter(0.01,0.01)
    plt.show()
    return redirect('home')
Beispiel #11
0
def draw_graph(g):
    plt.subplot(111)
    nx.draw_shell(g, with_labels=True, font_weight='bold')
    labels = nx.get_edge_attributes(g, 'weight')
    pos = nx.shell_layout(g)
    nx.draw_networkx_edge_labels(g, pos, edge_labels=labels)
    plt.show()
Beispiel #12
0
def draw_networkx_ex():
    G = nx.dodecahedral_graph()
    nx.draw(G)
    plt.show()
    nx.draw_networkx(G, pos=nx.spring_layout(G))
    limits = plt.axis('off')
    plt.show()
    nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
    plt.show()
    edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    plt.show()
    labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
    plt.show()
    edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
    plt.show()
    print("Circular layout")
    nx.draw_circular(G)
    plt.show()
    print("Random layout")
    nx.draw_random(G)
    plt.show()
    print("Spectral layout")
    nx.draw_spectral(G)
    plt.show()
    print("Spring layout")
    nx.draw_spring(G)
    plt.show()
    print("Shell layout")
    nx.draw_shell(G)
    plt.show()
    print("Graphviz")
 def draw_shell_communities(self):
     partition = self.find_partition()[1]
     node_color=[float(partition[v]) for v in partition]
     labels = self.compute_labels()
     nx.draw_shell(self.G,node_color=node_color, labels=labels)
     plt.show()
     plt.savefig("C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_shell.pdf")
Beispiel #14
0
    def food_web(self, draw=False):
        '''It prints, when draw=True, a graphic visualization of the food web related to the ecosystem interactions. Also it prints a set of network measurements about the food web.'''

        self.G = nx.from_numpy_matrix(self.C, create_using=nx.DiGraph)
        if (draw):
            #The out_degree value for a species represent its number of preys
            d = dict(self.G.out_degree)
            low, *_, high = sorted(d.values())
            norm = mpl.colors.Normalize(vmin=low, vmax=high, clip=True)
            mapper = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.coolwarm)
            nx.draw_shell(self.G,
                          nodelist=d,
                          node_size=500,
                          node_color=[mapper.to_rgba(i) for i in d.values()],
                          with_labels=True,
                          font_color='white')
            plt.show()

        out_degree = self.G.out_degree
        in_degree = self.G.in_degree
        n_predators = len(self.Predators)
        print("Average predators for species:", np.average(in_degree, 0)[1])
        print("Average preys for predator :",
              (np.sum(out_degree, 0)[1]) / n_predators)
        print("Number of edges in the foodweb: ", nx.number_of_edges(self.G))
Beispiel #15
0
def graph(request):
    G = nx.DiGraph()

    for user in CustomUser.objects.all():
        G.add_node(user.username)
    for user in CustomUser.objects.all():
        for friend in user.friends.all():
            G.add_edge(user.username, friend.username)
    # nx.draw(G, with_labels=True)

    nx.draw_shell(G,
                  with_labels=True,
                  node_color='green',
                  arrows=False,
                  font_size=12,
                  node_size=500,
                  edge_color='grey')

    # nx.draw_networkx_labels(G, pos)
    # nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
    # nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
    # plt.scatter(10, 10, alpha=10)
    plt.draw()
    # plt.scatter(0.01,0.01)
    plt.show()
    return redirect('home')
Beispiel #16
0
def format_graph(G):
    """
    Format a Graph
    """
    # FIXME handle graphviz as well
    import matplotlib.pyplot as plt

    global node_size
    global cached_pair

    cached_pair = None

    graph_layout = G.graph_layout if hasattr(G, "graph_layout") else None
    node_shape = G.node_shape if hasattr(G, "node_shape") else "o"

    node_size = DEFAULT_NODE_SIZE
    draw_options = {
        "node_size": node_size,
        "node_shape": node_shape,
        # "with_labels": vertex_labels # Set below
        # "font_size": 12,        # Harmonized
        # "node_color": "white",  # Set below
        # "edgecolors": "black",  # Set below
        # "width": 5,             # Marmonized
    }

    vertex_labels = G.vertex_labels if hasattr(G, "vertex_labels") else False
    if vertex_labels:
        draw_options["with_labels"] = bool(vertex_labels)

    if hasattr(G, "title") and G.title:
        fig, ax = plt.subplots()  # Create a figure and an axes
        ax.set_title(G.title)

    layout_fn = None
    if graph_layout:
        if not isinstance(graph_layout, str):
            graph_layout = graph_layout.get_string_value()
        layout_fn = NETWORKX_LAYOUTS.get(graph_layout, None)
        if graph_layout in ["circular", "spiral", "spiral_equidistant"]:
            plt.axes().set_aspect("equal")

    harmonize_parameters(G, draw_options)

    if layout_fn:
        nx.draw(G, pos=layout_fn(G), **draw_options)
    else:
        nx.draw_shell(G, **draw_options)
    tempbuf = NamedTemporaryFile(
        mode="w+b",
        buffering=-1,
        encoding=None,
        newline=None,
        delete=False,
        suffix=".svg",
        prefix="MathicsGraph-",
    )
    plt.savefig(tempbuf.name, format="svg")
    plt.show()
    return tempbuf.name
Beispiel #17
0
def plot_graph(graph, type="shell", layout=None):
    cols = list()
    for n in graph.nodes:
        if graph.nodes[n]['state'] == "S":
            cols.append("blue")
        elif graph.nodes[n]['state'] == "I":
            cols.append("red")
        else:
            cols.append("green")
    options = {
        'node_color': cols,
        'node_size': 50,
        'width': 2,
    }
    if not layout is None:
        nx.draw(graph, pos=layout, **options)
    elif type == "shell":
        nx.draw_shell(graph, **options)
    elif type == "spectral":
        nx.draw_spectral(graph, **options)
    elif type == "spring":
        nx.draw_spring(graph, **options)
    else:
        nx.draw(graph, **options)
    return
Beispiel #18
0
    def food_web(self, labels=False):
        '''returns the graphic visualization of the graph associated to the interaction matrix referred only to living species. Since the species ID for DCM are unsuitable for nodes label in the plot, they will be labelled starting from 0. When argument labels is True, a dictionary is printed with all the relationship between plot labels and species ID.'''

        #Creating an adjacency matrix with only Living species values
        gamma_adj = np.copy(self.gamma)
        gamma_adj = gamma_adj[self.livings()]
        gamma_adj = gamma_adj[:, self.livings()]

        #make the adjacency matrix square
        dim = np.shape(gamma_adj)[0]
        gamma_adj = np.reshape(gamma_adj, (dim, dim))

        #remove all the negative values
        gamma_adj[gamma_adj < 0] = 0
        self.G = nx.from_numpy_matrix(gamma_adj, create_using=nx.DiGraph)
        d = dict(self.G.out_degree)
        low, *_, high = sorted(d.values())
        norm = mpl.colors.Normalize(vmin=low, vmax=high, clip=True)
        mapper = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.coolwarm)
        nx.draw_shell(self.G,
                      nodelist=d,
                      node_size=500,
                      node_color=[mapper.to_rgba(i) for i in d.values()],
                      with_labels=True,
                      font_color='white')

        if (labels):
            #Associate each living species ID to the node labels.
            labels = {}
            for i in range(len(self.livings()[0])):
                labels[i] = self.livings()[0][i]
            print(labels)

        return plt.show()
    def test_join_split_trees(self):
        eq_(len(self.mesh), 18)
        join = ct.join_split_tree(self.mesh, self.height_func)
        split = ct.join_split_tree(self.mesh, self.height_func, split=True)
        eq_(join.order(), split.order())
        eq_(sorted(join.nodes()), sorted(split.nodes()))
        eq_(sorted(ct.join_split_peak_pit_nodes(join)), [7, 8, 9, 10])
        eq_(sorted(ct.join_split_peak_pit_nodes(split)), [1, 2])
        eq_(sorted(ct.join_split_pass_nodes(join)), [4, 5, 6])
        eq_(sorted(ct.join_split_pass_nodes(split)), [3])

        compare_adj(join.adj, join_adj)
        compare_adj(split.adj, split_adj)

        if 0:
            import pylab as pl
            pl.ion()
            nx_join = join.to_networkx()
            _nx.draw_shell(nx_join)
            pl.title('join')
            pl.figure()
            nx_split = split.to_networkx()
            _nx.draw_shell(nx_split)
            pl.title('split')
            raw_input("enter to continue")
Beispiel #20
0
def graph(A, c, title):
    """
    Arguments:
        A: An adjacency matrix.
        c: Cluster labeling.
        title: The title for the graph
    """

    colors = ['red', 'blue']

    graph = nx.Graph()
    for i in range(len(A)):
        graph.add_node(i, style='filled', fillcolor=colors[c[i]])
    for i in range(len(A)):
        row = A[i]
        for j in range(len(row)):
            if row[j] == 1:
                graph.add_edge(i, j)

    node_list = []
    node_colors = []
    for node_info in graph.nodes(data=True):
        node_list.append(node_info[0])
        node_colors.append(node_info[1]['fillcolor'])

    pos = nx.spring_layout(graph)
    pylab.clf()
    pylab.title(title)
    nx.draw_shell(graph, nodelist=node_list, node_color=node_colors)
    pylab.savefig(title + '.png')
    pylab.show()
Beispiel #21
0
def draw_network(G: Graph,
                 output_name: str,
                 type_of_network: str = None) -> None:
    """
    Creates a drawing of the network, according to the selected type of network.

    Args:
        G (graph): the input graph
        output_name (string): the output name
        type_of_network (string): the type of network

    Returns:
        None. Just prints the image to a file into the folder data/
    """
    if type_of_network == "planar":
        nx.draw_planar(G, with_labels=True)
    elif type_of_network == "circular":
        nx.draw_circular(G, with_labels=True)
    elif type_of_network == "random":
        nx.draw_random(G, with_labels=True)
    elif type_of_network == "spectral":
        nx.draw_random(G, with_labels=True)
    elif type_of_network == "kamada_kawai":
        nx.draw_kamada_kawai(G, with_labels=True)
    elif type_of_network == "spring":
        nx.draw_spring(G, with_labels=True)
    elif type_of_network == "shell":
        nx.draw_shell(G, with_labels=True)
    else:
        nx.draw(G, with_labels=True)
    plt.savefig("images/" + output_name + "network_" + str(type_of_network) +
                ".png")
    plt.close()
Beispiel #22
0
 def loadGraph(self):
     nx.draw_shell(self.g, with_labels=True)
     plt.savefig("grafo.png")
     plt.clf()
     img = PhotoImage(file="grafo.png", )
     self.aplicativo[3].config(image=img)
     self.aplicativo[3].image = img
Beispiel #23
0
def nx_graph_freq_weighted():
    """Make graph with state indication between nodes.
    """
    adj_list = TextCorpus().global_adj_list_for_nx
    print '-- Adjacency List --\n{0}'.format(adj_list)
    G = nx.Graph()
    pos = nx.spring_layout(G)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if contact.avg_sentiment < 0.33],
    #                       node_color='r', node_size=300, alpha=0.8)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if 0.33 < contact.avg_sentiment && contact.avg_sentiment < 0.66],
    #                         node_color='y', node_size=300, alpha=0.8)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if 0.66 < contact.avg_sentiment && contact.avg_sentiment < 0.80],
    #                         node_color='c', node_size=300, alpha=0.8)
    # nx.draw_networkx_nodes(G, pos, nodelist=[contact for contact in get_contact_objs() if 0.80 < contact.avg_sentiment],
    #                         node_color='m', node_size=300, alpha=0.8)
    # nx.draw_networkx_edges(G, pos, width = 1.0, alpha = 0.5)
    # nx.draw_networkx_edges(G, pos, edgelist=adj_list, width=(8), )


    G.add_edges_from(adj_list)
    G = nx.MultiGraph(G)
    G.add_weighted_edges_from(get_uvweights())
    nx.draw_shell(G)
    img_fn = "w_graph-{0}".format(strftime('%Y-%m-%d %H:%M:%S.png', gmtime()))
    plt.savefig(img_fn)
    plt.show()
Beispiel #24
0
    def BFS(self, s, t, parent, G):

        visited = [False] * (self.ROW)

        queue = []

        queue.append(s)
        visited[s] = True

        self.color_map = [
            'green' if node_visit else 'grey' for node_visit in visited
        ]
        for i in parent:
            self.color_map[i] = 'green'
        self.color_map[t] = 'blue'
        plt.subplot()
        nx.draw_shell(G,
                      node_color=self.color_map,
                      node_size=900,
                      with_labels=True,
                      width=3)
        plt.show()

        while queue:

            u = queue.pop(0)

            for ind, val in enumerate(self.graph[u]):
                if visited[ind] == False and val > 0:
                    queue.append(ind)
                    visited[ind] = True
                    parent[ind] = u

        return True if visited[t] else False
Beispiel #25
0
    def update_figure(self, G, root, graphon=1):
        self.figure1 = plt.figure(self.canvas_no)  # 回到自己的显示区
        plt.clf()  # 清空显示区
        if (graphon == 0):
            self.canvas1.draw()
            return

        # 一系列步骤创造networkx图的点的排列方式
        shellLay = [[root]]
        tmp = [root]
        close = tmp
        while len(tmp) != 0:
            thisLay = [[j for j in nx.all_neighbors(G, i)] for i in tmp]
            shellLay.append([])
            for i in thisLay:
                shellLay[-1] += i
            for i in close:
                while i in shellLay[-1]:
                    shellLay[-1].remove(i)
            tmp = shellLay[-1]
            if len(shellLay[-1]) <= 1:
                shellLay[-2] += shellLay[-1]
                shellLay.remove(shellLay[-1])
            close += tmp

        #   画图,指定点排列,指定画图属性
        nx.draw_shell(G, nlist=shellLay, **self.options)
        self.canvas1.draw()
def graph_drawing(graph_list):
    graph = nx.Graph()
    for key in graph_list.keys():
        for node in graph_list[key]:
            graph.add_edge(key, node)
    nx.draw_shell(graph, with_labels=True)
    plt.show()
Beispiel #27
0
def shortestpath(request):
    G = nx.Graph()
    #all_simple_paths(G, source, target, cutoff=3):

    for user in CustomUser.objects.all():
        G.add_node(user.username)
    for user in CustomUser.objects.all():
        for friend in user.friends.all():
            G.add_edge(user.username, friend.username, color='black')

    paths_colors=['blue','violet','pink','purple']
    paths = nx.all_shortest_paths(G, request.POST['msgfrom'], request.POST['msgto'])

    loop_count = 0
    for path in paths:
        indx = loop_count % len(paths_colors)
        loop_count += 1
        for x in range(0, len(list(path))-1):
            G.edges[path[x], path[x+1]]['color'] = paths_colors[indx]

    edges = G.edges()
    colors = [G[u][v]['color'] for u, v in edges]

    nx.draw_shell(G, with_labels=True, node_color='#80bfff', arrows=False, font_size=12,
                     node_size=500, edge_color=colors)
    # temp = list(nx.common_neighbors(G, 'samy', 'abbas'))
    #nx.draw_networkx_labels(G, pos)
    #nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
    #nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
    #plt.scatter(10, 10, alpha=10)
    plt.draw()
    #plt.scatter(0.01,0.01)
    plt.show()
    return redirect('home')
Beispiel #28
0
def run():
    g = load()

    q_id = add_question(g, {'title': 'Что вы пьёте по утрам?'})

    qq_id = add_question(g, {'title': 'Что едите?'})

    q2_id = add_question(g, {'title': 'С молоком?', 'next': qq_id})
    q3_id = add_question(g, {'title': 'Какой?', 'next': qq_id})
    q4_id = add_question(g, {
        'title': 'Какой виски предпочитаете?',
        'next': qq_id
    })

    a11 = add_answer(g, q_id, {'title': 'Чай', 'next': q2_id})
    a12 = add_answer(g, q_id, {'title': 'Кофе', 'next': q3_id})
    a13 = add_answer(g, q_id, {'title': 'Виски', 'next': q4_id})
    a13 = add_answer(g, q_id, {'title': 'Ничего'})

    a21 = add_answer(g, q2_id, {'title': 'Да', 'next': qq_id})
    a22 = add_answer(g, q2_id, {'title': 'Нет', 'next': qq_id})

    a31 = add_answer(g, q3_id, {'title': 'Черный', 'next': qq_id})
    a31 = add_answer(g, q3_id, {'title': 'Зеленый', 'next': qq_id})

    a41 = add_answer(g, q4_id, {'title': 'Солодовый', 'next': qq_id})
    a42 = add_answer(g, q4_id, {'title': 'Зерновой', 'next': qq_id})
    a43 = add_answer(g, q4_id, {'title': 'Купажированный', 'next': qq_id})

    aq1 = add_answer(g, qq_id, {'title': 'Тост'})
    aq2 = add_answer(g, qq_id, {'title': 'Круассан'})
    aq3 = add_answer(g, qq_id, {'title': 'Ничего'})

    update_question(g, q_id, {'next': qq_id})

    # update_answer(g, 1, 'ac65f37d-97d7-4dd5-b8ce-e3fb8426c9fe', {'title': 'Ответ 1-2 ТЕСТ'})
    # update_answer(g, 2, '1a5b082f-6ab4-4a26-bfa0-0b58858e24d7', {'next': 5})

    for i in g.nodes(data=True):
        print(f'node = {i}')

    for i in g.edges(data=True):
        print(f'edge = {i}')

    # Получить ребра для текущего вопроса
    # print(g.out_edges(q_id, 'answer_id'))
    # print([i for i in nx.neighbors(g, 1)])

    # print(next_question(g, q_id, a11))
    # print(next_question(g, q_id, a12))

    # print(get_question(g, 1))

    save(g)
    # Рисуем граф
    import matplotlib.pyplot as plt
    nx.draw_shell(g, with_labels=True)
    # nx.draw_spectral(g, with_labels=True)
    plt.show()
Beispiel #29
0
 def draw(self):
     plt.subplot()
     # nx.draw(self.g, with_labels=True, font_weight='bold')
     nx.draw_shell(self.g,
                   nlist=['ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'],
                   with_labels=True,
                   font_weight='bold')
     plt.show()
Beispiel #30
0
 def Show(self):
     self.UpdateColors()
     self.UpdateLabels()
     nx.draw_shell(self.G,
                   with_labels=True,
                   labels=self.labels,
                   node_color=self.colorMap,
                   font_color='w')
Beispiel #31
0
def plot_graph(G):
    """ Given the graph created in create_graph(), divide the nodes into two
    shells and plot the graph.
    """
    plt.figure(figsize=(12, 12))
    nx.draw_shell(G, nlist=[[0], range(1, 22)], **options)
    plt.savefig("Kumirei_graph.png", dpi=300)
    plt.show()
Beispiel #32
0
    def plot(self):
        import matplotlib.pyplot as plt
        with open('graph.cha', 'rb') as f:
            G = pkl.load(f)

        nx.draw(G, with_labels=True)
        nx.draw_shell(G, with_labels=True)
        plt.show()
Beispiel #33
0
def networkGraph(log, frame=-1):
    network = nx.Graph()
    for node in log[frame]:
        network.add_edge(node[0], node[1])
        print node
        if node[0] == node[1]:
            print "self reference!"
    nx.draw_shell(network, node_color='b')
Beispiel #34
0
def draw_cfg(edges, nodes, filename):
    filepath = "result//cfg//" + filename + ".png"
    G = nx.DiGraph()
    G.add_nodes_from(nodes)
    G.add_edges_from(edges)
    nx.draw_shell(G)
    plt.savefig(filepath)
    plt.show()
Beispiel #35
0
	def graph_cycle_of_a_element(self, number_list):
		the_relationsip = self._context.get_relationship()
		cycle_list = self.cycle_of_a_element(number_list)
		cycle_list_str = [the_relationsip.search(ele) for ele in cycle_list]
		G = nx.DiGraph()
		G.add_cycle(cycle_list_str)
		nx.draw_shell(G, arrows=True, with_labels=True, node_size=800, width=2, node_color='r')
		plt.show()
Beispiel #36
0
 def _repr_svg_(self):
    plt.ioff() # turn off interactive mode
    fig=plt.figure(figsize=(2,2))
    ax = fig.add_subplot(111)
    nx.draw_shell(self, ax=ax)
    output = StringIO.StringIO()
    fig.savefig(output,format='svg')
    plt.ion() # turn on interactive mode
    return output.getvalue()
Beispiel #37
0
 def _repr_svg_(self):
    plt.ioff() # turn off interactive mode
    fig=plt.figure(figsize=(2,2))
    ax = fig.add_subplot(111)
    nx.draw_shell(self, ax=ax)
    output = StringIO.StringIO()
    fig.savefig(output,format='svg')
    plt.ion() # turn on interactive mode
    return output.getvalue()
    def draw_circ(self):
        G = nx.DiGraph()
        for i, v in self.adjList.items():
            for j in v.neighbours:
                G.add_edge(i, j)

        labels = {k:k  for k in self.adjList.keys() }
        nx.draw_shell(G, node_size=1000, node_color='g', labels=labels)
        plt.show()
Beispiel #39
0
def graph_to_svg(g):
    """ return the SVG of a matplotlib figure generated from a graph
        ref: http://pig-in-the-python.blogspot.com/2012/09/
    """
    if not plt:
        return None
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111)
    nx.draw_shell(g, ax=ax)
    output = BytesIO()
    fig.savefig(output, format='svg')
    plt.close(fig)
    return output.getvalue()
Beispiel #40
0
def PlotGraph(gr, img_path):
    try:
        (filepath, filename) = os.path.split(img_path)
        if not os.path.exists(filepath):
            os.makedirs(filepath)
        nx.draw_shell(gr, arrows=True, with_labels=True)
        print str(img_path) + "graph.pdf"
        plt.savefig(str(img_path) + "graph.pdf")

    except IOError:
        print "Can not write image data."
        return
    plt.cla()
    plt.clf()
 def draw(self, save=False, with_labels=False, ind=0, ax=None, clf=False, colours=None):
     """ @param save: do we save the picture
         @param with_labels: do we write the labels of the nodes on the picture
         @param ind: index of the picture
         @param ax: if we have an ax we draw on it
         @param clf: after saving we clean the figure if clf==True
         Draw the graph with the self.colours and save it if save==true
     """
     cols = [colour for _, colour in colours.iteritems()] or [colour for _, colour in self.colours.iteritems()]
     nx.draw_shell(self.graph, node_color=cols, with_labels=with_labels, ax=ax)
     if save:
         filename = self.DIRECTORY + self.plotname
         if(ind < 10):
             filename = filename + '00'
         elif(ind < 100):
             filename = filename + '0'
         plt.savefig("%s%s.jpg" % (filename, ind))
     if clf:
         plt.clf()
Beispiel #42
0
def draw_all(graph):
    """ Draw all different layout types for graph """
    nx.draw(graph)
    plt.savefig(path + 'draw.png')
    plt.close()
    nx.draw_circular(graph)
    plt.savefig(path + 'draw_circular.png')
    plt.close()
    nx.draw_random(graph)
    plt.savefig(path + 'draw_random.png')
    plt.close()
    nx.draw_spectral(graph)
    plt.savefig(path + 'draw_spectral.png')
    plt.close()
    nx.draw_spring(graph)
    plt.savefig(path + 'draw_spring.png')
    plt.close()
    nx.draw_shell(graph)
    plt.savefig(path + 'draw_shell.png')
    plt.close()
Beispiel #43
0
def try_different_layouts(graph):
    layout_dir = 'graph_layout'
    if not os.path.exists(layout_dir):
        os.mkdir('graph_layout')
    nx.draw_random(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'rand.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_circular(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'circular.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_spectral(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'spectral.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_networkx(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'networkx.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw(graph, pos=graphviz_layout(graph), with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4,
            edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'graphviz.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_shell(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'shell.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_spring(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'spring.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()
Beispiel #44
0
def drawgraph(g):

	nx.draw_shell(g,with_labels=True)
    def sketch(
        self):
        """Simple method to show a visualization of the gut graph."""

        nx.draw_shell(self, font_size=6, alpha=.8)
        pylab.show()
Beispiel #46
0
    def quickplot(self, fname, k="4/sqrt(n)", iterations=50, layout="neato", size=20, default_colour="lightgrey"):
        """
        Makes a quick visualization of the network.

        **Parameters** :

        > *fname* : `string`

        >> A string indicating the path or file name to write to.

        > *k* : `None`

        >> Default function used for plotting.

        > *iterations* : `int`

        >> Default number of iterations to run on the plot.

        > *layout* : `string`

        >> The type of layout to draw, the available layouts are: ("spring", "circular", "shell", "spectral", or "random").

        > *size* : `int`

        >> The size of the nodes. Default is 20.

        > *default_colour* : `string`

        >> Only default nodes will be coloured with this colour.

        **Return** : `None`

        """

        if type(k) is str:
            k = 4/np.sqrt(self.number_of_nodes())
        # Make a copy
        copy_net = copy.deepcopy(self)
        # Remove isolates
        copy_net.remove_nodes_from(nx.isolates(copy_net))
        # Add detect colour attribute
        colour_data = {}
        for n in copy_net.nodes():
            if "colour" in copy_net.node[n].keys():
                colour_data[n] = copy_net.node[n]["colour"]
            elif "color" in copy_net.node[n].keys():
                colour_data[n] = copy_net.node[n]["color"]
            else:
                colour_data[n] = default_colour
        colour_list = [colour_data[node] for node in copy_net.nodes()]
        # Plot the network
        print("Plotting...")
        if layout in ["dot", "neato", "fdp", "circo"]:
            nx.draw(copy_net,
                pos=graphviz_layout(copy_net, prog=layout),
                node_size=size,
                font_size=5,
                node_color=colour_list,
                linewidths=.5,
                edge_color="DarkGray",
                width=.1)
        if layout == "spring":
            nx.draw(copy_net,
                pos=nx.spring_layout(copy_net, k=k, iterations=iterations),
                node_size=size,
                font_size=5,
                node_color=colour_list,
                linewidths=.5,
                edge_color="DarkGray",
                width=.1)
        elif layout == "circular":
            nx.draw_circular(copy_net,
                node_size=size,
                font_size=5,
                node_color=colour_list,
                linewidths=.5,
                edge_color="DarkGray",
                width=.1)
        elif layout == "shell":
            nx.draw_shell(copy_net,
                node_size=size,
                font_size=5,
                node_color=colour_list,
                linewidths=.5,
                edge_color="DarkGray",
                width=.1)
        elif layout == "spectral":
            nx.draw_spectral(copy_net,
                node_size=size,
                font_size=5,
                node_color=colour_list,
                linewidths=.5,
                edge_color="DarkGray",
                width=.1)
        elif layout == "random":
            nx.draw_random(copy_net,
                node_size=size,
                font_size=5,
                node_color=colour_list,
                linewidths=.5,
                edge_color="DarkGray",
                width=.1)
        # Save figure if applicable
        if fname is not None:
            plt.savefig(fname, bbox_inches="tight")
            print("Wrote file: {} to {}".format(fname, os.getcwd()))
Beispiel #47
0
     fromnode = aktor.objects.filter(aktorid=t.fraaktorid)[0]
     tonode = aktor.objects.filter(aktorid=t.tilaktorid)[0]
     if (fromnode.typeid == 11 and fromnode.periodeid==32)  and (tonode.typeid == 5)  :
            G.add_node(fromnode.aktorid, navn=fromnode.navn)
            G.add_node(tonode.aktorid, navn=tonode.navn)
            G.add_edge(fromnode.aktorid,tonode.aktorid)
            

                        for roller in aktoraktor.objects.filter(tilaktorid=tonode.aktorid):
                if (roller.rolleid == 15):
             
      
plt.clf()      
plt.figure(figsize=(40, 40))
labels=dict((n,d['navn']) for n,d in G2.nodes(data=True))                    
nx.draw_shell(G2, with_labels=True, labels=labels, alpha=0.6, edge_color='g', style='dotted')

plt.axis('off')

plt.savefig("limited.png")



pos=nx.spring_layout(G)
labels=dict((n,d['navn']) for n,d in G.nodes(data=True))
nx.draw_networkx_labels(G,pos,labels,font_size=6)



# 
allelefreq=[.1,.9]
chrom='12'
position=1000
g1=GeneticNetworkFactory('sixperson.ped',alphaList,allelefreq, chrom,position)
g1.constructNetwork()
factorList=g1.getFactorList()

#for f in factorList:
#    print f
#    print 
#print "+++++++++"

cTree = createCliqueTree(factorList)
G=nx.from_numpy_matrix( cTree.getEdges() )

nx.draw_shell(G)
plt.show()
#print cTree.getEdges()

#cTree.toString()


prunedCTree=PruneTree( cTree )
P=CliqueTreeInitialPotential( prunedCTree )

#for f in P.getNodeList():
#    print f
#    print


Beispiel #49
0
    used = {start}
    while queue:
        curr = queue.pop(0)
        for n in G[curr]:
            if n not in used:
                used.add(n)
                tree.add_edge(curr, n, weight=G[curr][n]['weight'])
                queue.append(n)
    return tree

def components(G):
    result = set()
    used = []
    for i in G:
        if i not in used:
            wing = bfs(G,i)
            for element in wing:
                if element not in used:
                    used.append(element)
            result.add(wing)
    return result
Graph = file_into_tuple_list('Fruit.txt')
for t in components(Graph):
    nx.draw_shell(t)
plt.show()
Number_of_trees = len(components(Graph))
print('The number of trees is',Number_of_trees)
if Number_of_trees > 1:
    print('The graph is not connected')
if Number_of_trees == 1:
    print('The graph is connected')