Пример #1
0
def plot_layered_network(weight_matrices,
                         distance_between_layers=2,
                         distance_between_nodes=1,
                         layer_labels=None,
                         **kwargs):
    """
    Convenience function to plot layered network.

    Arguments:
    ----------
        weight_matrices: [w1, w2, ..., wn]
            list of weight matrices defining the connectivity between layers;
            each weight matrix is a 2-D ndarray with rows indexing source and columns indexing targets;
            the number of sources has to match the number of targets in the last layer

        distance_between_layers: int

        distance_between_nodes: int

        layer_labels: [str1, str2, ..., strn+1]
            labels of layers

        **kwargs: passed to netgraph.draw()

    Returns:
    --------
        ax: matplotlib axis instance

    """
    nodes_per_layer = _get_nodes_per_layer(weight_matrices)

    node_positions = _get_node_positions(nodes_per_layer,
                                         distance_between_layers,
                                         distance_between_nodes)

    w = _combine_weight_matrices(weight_matrices, nodes_per_layer)

    ax = netgraph.draw(w, node_positions, draw_arrows=True, **kwargs)

    if not layer_labels is None:
        ax.set_xticks(distance_between_layers *
                      np.arange(len(weight_matrices) + 1))
        ax.set_xticklabels(layer_labels)
        ax.xaxis.set_ticks_position('bottom')

    return ax
Пример #2
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""

"""

import matplotlib.pyplot as plt
import netgraph
import networkx as nx
n = 5
G = nx.DiGraph()
G.add_nodes_from(range(n))
G.add_edges_from([(i, (i+1)%n) for i in range(n)]) # directed cycle
plt.subplots(1,1)
netgraph.draw(G, directed=True) # doesn't draw arrows
# netgraph.draw(G, draw_arrows=True)
plt.show()
Пример #3
0
#netgraph.draw_node_labels({n:n for n in mdl.bipartite.nodes},node_positions=nx.spring_layout(mdl.bipartite))
#plot_instance = netgraph.InteractiveGraph(mdl.bipartite,node_size=10, node_color='gray',node_edge_width=0, node_positions=nx.spring_layout(mdl.bipartite), node_labels={n:n for n in mdl.bipartite.nodes},node_label_font_size=8)

pos = rd.graph.set_pos(mdl.graph)

#plot_instance.node_positions

rd.graph.show(mdl.graph, gtype='normal', pos=pos)

plt.figure()
g = mdl.graph
edgeflows = {}
for edge in g.edges:
    flows = list(g.get_edge_data(edge[0], edge[1]).keys())
    edgeflows[edge[0], edge[1]] = ''.join(flow for flow in flows)
netgraph.draw(g,
              node_size=20 * 1,
              node_shape='s',
              node_color='g',
              node_edge_width=0,
              node_positions=pos,
              edge_labels=edgeflows,
              edge_label_font_size=8,
              node_labels={n: n
                           for n in g.nodes},
              node_label_font_size=8)

#pos = rd.graph.set_pos(mdl.bipartite, gtype ='bipartite')
#rd.graph.show(mdl.bipartite, gtype='bipartite', pos=pos)
Пример #4
0
def plot_norm_netgraph(g,
                       labels,
                       faultfxns,
                       degfxns,
                       degflows,
                       faultlabels,
                       faultedges,
                       faultedgeflows,
                       faultscen,
                       time,
                       showfaultlabels,
                       edgeflows,
                       scale=1,
                       pos=[],
                       show=True,
                       retfig=False,
                       colors=['gray', 'orange', 'red']):
    """ Experimental method for plotting with netgraph instead of networkx"""
    nodesize = scale * 20
    fontsize = scale * 12
    if not pos: pos = nx.shell_layout(g)
    netgraph.draw(g,
                  pos,
                  node_size=nodesize,
                  fontsize=fontsize,
                  node_shape='s',
                  node_color=colors[0],
                  width=3,
                  font_weight='bold')
    netgraph.draw_edge_labels(list(edgeflows.keys()),
                              edgeflows,
                              pos,
                              edge_label_font_size=fontsize)
    netgraph.draw_nodes({n: pos[n]
                         for n in degfxns},
                        node_labels=degfxns,
                        node_shape='s',
                        node_color=colors[1],
                        width=3,
                        fontsize=fontsize,
                        font_weight='bold',
                        node_size=nodesize)
    netgraph.draw_nodes({n: pos[n]
                         for n in faultfxns},
                        node_labels=faultfxns,
                        node_shape='s',
                        node_color=colors[2],
                        width=3,
                        fontsize=fontsize,
                        font_weight='bold',
                        node_size=nodesize)
    netgraph.draw_edges(faultedges,
                        pos,
                        edge_color=colors[1],
                        fontsize=fontsize,
                        width=2)
    netgraph.draw_node_labels({p: p for p in pos}, pos)
    if showfaultlabels:
        faultlabels_form = {
            node:
            ''.join(['\n\n ', ''.join(f + ' ' for f in fault if f != 'nom')])
            for node, fault in faultlabels.items() if fault != {'nom'}
        }
        netgraph.draw_node_labels(faultlabels_form,
                                  pos,
                                  font_size=fontsize,
                                  font_color='k')
        netgraph.draw_edge_labels(list(faultedgeflows.keys()),
                                  faultedgeflows,
                                  pos,
                                  fontsize=fontsize,
                                  font_color=colors[1])
    if faultscen:
        plt.title('Propagation of faults to ' + faultscen + ' at t=' +
                  str(time))
    if retfig:
        return plt.gcf(), plt.gca()
    elif show:
        plt.show()
Пример #5
0
import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import netgraph

# Construct sparse, directed, weighted graph
# with positive and negative edges:
total_nodes = 20
weights = np.random.randn(total_nodes, total_nodes)
connection_probability = 0.2
is_connected = np.random.rand(total_nodes, total_nodes) <= connection_probability
graph = np.zeros((total_nodes, total_nodes))
graph[is_connected] = weights[is_connected]

# Make a standard plot:
netgraph.draw(graph, node_shape='^')
Пример #6
0
    def draw(self,
             ax,
             legend=True,
             title="",
             edge_label_size=10,
             show_node_labels=False,
             node_label_font_size=12.0):
        """ Draw the automaton.

        Important Note:
            Try select right size of the figure for the ax to
            assure readability of the picture.
        Note:
            This can be very buggy and edges can have tendency to cross and
            cover others labels. Try to run it multiple times if this
            problem appears, yet it is not guaranteed this procedure
            will solve it.

        Examples:
          - This code draws automaton for regular expression ab*a. Note that
            size of the matplotlib figure can be changed, usually by
            figsize parameter. Often it is necessary to make the figure bigger
            to make it clear and readable.

            Matplotlib import:

            >>> import matplotlib.pyplot as plt

            Build automaton:

            >>> automaton = Automaton.build_from_regex("ab*a")

            Create pyplot figure and Axes object:

            >>> fig, ax = plt.subplots(1, figsize=(10, 10))

            Draw automaton:

            >>> automaton.draw(ax, title="Example automaton")
            >>> plt.show()

        :param show_node_labels: (boolean)
        :param node_label_font_size: (float)
        :param edge_label_size: (float)
        :param legend: (boolean)
            If True display legend.
        :param title: (str)
            Make this string the title of plot.
        :param ax: (matplotlib Axes obj)
            Axes to draw the automaton in.
        """
        graph = nx.DiGraph()
        if (not self.enumeration_proper):
            self.__bfs_enumerate()

        node_labels, edge_labels = self.__bfs_for_draw(graph)
        initial_pos = {self.initial.idx: (0, 0), self.final.idx: (1, 0)}
        pos = ng.spring_layout(graph.edges,
                               pos=initial_pos,
                               fixed=initial_pos,
                               iterations=2000)
        ng.draw(graph, node_positions=pos, ax=ax)

        # Simple heuristic for node label font size. Size of label is dependant
        # on the number of digits of the maximal number of states f.e.
        # if there are states from 0 to 15, the size of the font must decrease
        # to make possible for label to be inside the
        node_label_font_size /= (int(log(len(node_labels), 10)**2) + 1)
        if (show_node_labels):
            ng.draw_node_labels(node_labels=node_labels,
                                node_positions=pos,
                                node_label_font_size=node_label_font_size,
                                ax=ax)

        ng.draw_nodes(graph=graph,
                      node_positions={self.initial.idx: pos[self.initial.idx]},
                      node_color=Automaton.VIS_INITIAL_COLOUR,
                      ax=ax)

        ng.draw_nodes(graph=graph,
                      node_positions={self.final.idx: pos[self.final.idx]},
                      node_color=Automaton.VIS_FINAL_COLOUR,
                      ax=ax)

        ng.draw_edge_labels(graph.edges,
                            node_positions=pos,
                            edge_labels=edge_labels,
                            edge_label_font_size=edge_label_size,
                            ax=ax)

        if (title):
            ax.set(title=title)
        if (legend):
            self.__show_legend(ax)
Пример #7
0
 def plotWeightedGraphs(self):
     for g in self.graphLst:
         adjmat = nx.adjacency_matrix(g).todense()
         fig, ax = plt.subplots(figsize=(10, 6))
         netgraph.draw(adjmat, ax=ax)
         yield (fig, ax)