Exemple #1
0
def contraction_categorical(input_attribute=None,
                            graph=None,
                            id_nodes=None,
                            separator='.'):
    """contraction_categorical."""
    vals = sorted([_serialize_list(graph.node[v].get(input_attribute, 'N/A'))
                   for v in id_nodes])
    return _serialize_list(vals, separator=separator)
Exemple #2
0
def contraction_categorical(input_attribute=None,
                            graph=None,
                            id_nodes=None,
                            separator='.'):
    """contraction_categorical."""
    vals = sorted([
        _serialize_list(graph.node[v].get(input_attribute, 'N/A'))
        for v in id_nodes
    ])
    return _serialize_list(vals, separator=separator)
Exemple #3
0
def draw_graph(graph,
               vertex_label='label',
               secondary_vertex_label=None,
               edge_label='label',
               secondary_edge_label=None,
               vertex_color=None,
               vertex_alpha=0.6,
               vertex_border=False,
               vertex_size=600,

               edge_color=None,
               edge_alpha=0.5,

               dark_edge_color=None,
               dark_edge_dotted=True,
               dark_edge_alpha=0.3,

               size=10,
               size_x_to_y_ratio=1,
               font_size=9,
               layout='graphviz',
               prog='neato',
               pos=None,

               colormap='YlOrRd',
               vmin=0,
               vmax=1,
               invert_colormap=False,
               verbose=True,
               file_name=None,
               title_key='id',
               ignore_for_layout="edge_attribute",

               logscale=False):
    """Plot graph layout."""
    if size is not None:
        size_x = size
        size_y = int(float(size) / size_x_to_y_ratio)
        plt.figure(figsize=(size_x, size_y))
    plt.grid(False)
    plt.axis('off')

    if vertex_label is not None:
        if secondary_vertex_label:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label1 = _serialize_list(d.get(vertex_label, 'N/A'))
                label2 = _serialize_list(d.get(secondary_vertex_label, 'N/A'))
                vertex_labels[u] = '%s\n%s' % (label1, label2)
        else:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label = d.get(vertex_label, 'N/A')
                vertex_labels[u] = _serialize_list(label)

    edges_normal = [(u, v) for (u, v, d) in graph.edges(data=True)
                    if d.get('nesting', False) is False]
    edges_nesting = [(u, v) for (u, v, d) in graph.edges(data=True)
                     if d.get('nesting', False) is True]

    if edge_label is not None:
        if secondary_edge_label:
            edge_labels = dict([((u, v,), '%s\n%s' %
                                 (d.get(edge_label, ''),
                                  d.get(secondary_edge_label, '')))
                                for u, v, d in graph.edges(data=True)])
        else:
            edge_labels = dict([((u, v,), d.get(edge_label, ''))
                                for u, v, d in graph.edges(data=True)])

    if vertex_color is None:
        node_color = 'white'
    elif vertex_color in ['_labels_', '_label_', '__labels__', '__label__']:
        node_color = []
        for u, d in graph.nodes(data=True):
            label = d.get('label', '.')
            node_color.append(hash(_serialize_list(label)))
        color_set = set(node_color)
        color_map = {c: i for i, c in enumerate(color_set)}
        node_color = [color_map[c] for c in node_color]
    else:
        if invert_colormap:
            node_color = [- d.get(vertex_color, 0)
                          for u, d in graph.nodes(data=True)]
        else:
            node_color = [d.get(vertex_color, 0)
                          for u, d in graph.nodes(data=True)]
        if logscale is True:
            log_threshold = 0.01
            node_color = [math.log(c) if c > log_threshold
                          else math.log(log_threshold)
                          for c in node_color]

    if edge_color is None:
        edge_colors = 'black'
    elif edge_color in ['_labels_', '_label_', '__labels__', '__label__']:
        edge_colors = [hash(str(d.get('label', '.')))
                       for u, v, d in graph.edges(data=True)
                       if 'nesting' not in d]
    else:
        if invert_colormap:
            edge_colors = [- d.get(edge_color, 0)
                           for u, v, d in graph.edges(data=True)
                           if 'nesting' not in d]
        else:
            edge_colors = [d.get(edge_color, 0)
                           for u, v, d in graph.edges(data=True)
                           if 'nesting' not in d]
    if dark_edge_color is None:
        dark_edge_colors = 'black'
    else:
        dark_edge_colors = [d.get(dark_edge_color, 0)
                            for u, v, d in graph.edges(data=True)
                            if 'nesting' in d]
    tmp_edge_set = [(a, b, d)
                    for (a, b, d) in graph.edges(data=True)
                    if ignore_for_layout in d]
    graph.remove_edges_from(tmp_edge_set)

    if pos is None:
        if layout == 'graphviz':
            graph_copy = graph.copy()
            # remove all attributes for graphviz layout
            for u, d in graph_copy.nodes(data=True):
                graph_copy.node[u] = {}
            for u, v, d in graph_copy.edges(data=True):
                graph_copy.edge[u][v] = {}
            pos = nx.graphviz_layout(graph_copy, prog=prog, args="-Gmode=KK")
        elif layout == "RNA":
            import RNA
            rna_object = RNA.get_xy_coordinates(graph.graph['structure'])
            pos = {i: (rna_object.get(i).X, rna_object.get(i).Y)
                   for i in range(len(graph.graph['structure']))}
        elif layout == 'circular':
            pos = nx.circular_layout(graph)
        elif layout == 'random':
            pos = nx.random_layout(graph)
        elif layout == 'spring':
            pos = nx.spring_layout(graph)
        elif layout == 'shell':
            pos = nx.shell_layout(graph)
        elif layout == 'spectral':
            pos = nx.spectral_layout(graph)
        else:
            raise Exception('Unknown layout format: %s' % layout)

    if vertex_border is False:
        linewidths = 0.001
    else:
        linewidths = 1

    graph.add_edges_from(tmp_edge_set)

    nx.draw_networkx_nodes(graph, pos,
                           node_color=node_color,
                           alpha=vertex_alpha,
                           node_size=vertex_size,
                           linewidths=linewidths,
                           cmap=plt.get_cmap(colormap))

    nx.draw_networkx_edges(graph, pos,
                           edgelist=edges_normal,
                           width=2,
                           edge_color=edge_colors,
                           cmap=plt.get_cmap(colormap),
                           alpha=edge_alpha)
    if dark_edge_dotted:
        style = 'dotted'
    else:
        style = 'solid'
    nx.draw_networkx_edges(graph, pos,
                           edgelist=edges_nesting,
                           width=1,
                           edge_color=dark_edge_colors,
                           style=style,
                           alpha=dark_edge_alpha)
    if edge_label is not None:
        nx.draw_networkx_edge_labels(graph,
                                     pos,
                                     edge_labels=edge_labels,
                                     font_size=font_size)
    if vertex_label is not None:
        nx.draw_networkx_labels(graph,
                                pos,
                                vertex_labels,
                                font_size=font_size,
                                font_color='black')
    if title_key:
        title = str(graph.graph.get(title_key, ''))
        font = FontProperties()
        font.set_family('monospace')
        plt.title(title, fontproperties=font)
    if size is not None:
        # here we decide if we output the image.
        # note: if size is not set, the canvas has been created outside
        # of this function.
        # we wont write on a canvas that we didn't create ourselves.
        if file_name is None:
            plt.show()
        else:
            plt.savefig(file_name,
                        bbox_inches='tight',
                        transparent=True,
                        pad_inches=0)
            plt.close()
Exemple #4
0
def draw_graph(graph,
               vertex_label='label',
               vertex_color=None,
               vertex_color_dict=None,
               vertex_alpha=0.6,
               vertex_border=1,
               vertex_size=600,
               compact=False,
               colormap='YlOrRd',
               vmin=0,
               vmax=1,
               invert_colormap=False,
               secondary_vertex_label=None,
               secondary_vertex_color=None,
               secondary_vertex_alpha=0.6,
               secondary_vertex_border=1,
               secondary_vertex_size=600,
               secondary_vertex_colormap='YlOrRd',
               secondary_vertex_vmin=0,
               secondary_vertex_vmax=1,
               edge_label='label',
               secondary_edge_label=None,
               edge_colormap='YlOrRd',
               edge_vmin=0,
               edge_vmax=1,
               edge_color=None,
               edge_width=None,
               edge_alpha=0.5,
               dark_edge_colormap='YlOrRd',
               dark_edge_vmin=0,
               dark_edge_vmax=1,
               dark_edge_color=None,
               dark_edge_dotted=True,
               dark_edge_alpha=0.3,
               size=10,
               size_x_to_y_ratio=1,
               font_size=9,
               layout='graphviz',
               prog='neato',
               pos=None,
               verbose=True,
               file_name=None,
               title_key='id',
               ignore_for_layout="edge_attribute",
               logscale=False):
    """Plot graph layout."""
    if size is not None:
        size_x = size
        size_y = int(float(size) / size_x_to_y_ratio)
        plt.figure(figsize=(size_x, size_y))
    plt.grid(False)
    plt.axis('off')

    if vertex_label is not None:
        if secondary_vertex_label:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label1 = _serialize_list(d.get(vertex_label, 'N/A'))
                label2 = _serialize_list(d.get(secondary_vertex_label, 'N/A'))
                vertex_labels[u] = '%s\n%s' % (label1, label2)
        else:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label = d.get(vertex_label, 'N/A')
                vertex_labels[u] = _serialize_list(label)

    edges_normal = [(u, v) for (u, v, d) in graph.edges(data=True)
                    if d.get('nesting', False) is False]
    edges_nesting = [(u, v) for (u, v, d) in graph.edges(data=True)
                     if d.get('nesting', False) is True]

    if edge_label is not None:
        if secondary_edge_label:
            edge_labels = dict([
                ((
                    u,
                    v,
                ), '%s\n%s' %
                 (d.get(edge_label, ''), d.get(secondary_edge_label, '')))
                for u, v, d in graph.edges(data=True)
            ])
        else:
            edge_labels = dict([((
                u,
                v,
            ), d.get(edge_label, '')) for u, v, d in graph.edges(data=True)])

    if vertex_color is None:
        node_color = 'white'
    elif vertex_color in ['_labels_', '_label_', '__labels__', '__label__']:
        node_color = []
        for u, d in graph.nodes(data=True):
            label = d.get('label', '.')
            if vertex_color_dict is not None:
                node_color.append(vertex_color_dict.get(label, 0))
            else:
                node_color.append(hash(_serialize_list(label)))
    else:
        if invert_colormap:
            node_color = [
                -d.get(vertex_color, 0) for u, d in graph.nodes(data=True)
            ]
        else:
            node_color = [
                d.get(vertex_color, 0) for u, d in graph.nodes(data=True)
            ]
        if logscale is True:
            log_threshold = 0.01
            node_color = [
                math.log(c) if c > log_threshold else math.log(log_threshold)
                for c in node_color
            ]
    if edge_width is None:
        widths = 1
    elif isinstance(edge_width, int):
        widths = edge_width
    else:
        widths = [
            d.get(edge_width, 1) for u, v, d in graph.edges(data=True)
            if 'nesting' not in d
        ]
    if edge_color is None:
        edge_colors = 'black'
    elif edge_color in ['_labels_', '_label_', '__labels__', '__label__']:
        edge_colors = [
            hash(str(d.get('label', '.')))
            for u, v, d in graph.edges(data=True) if 'nesting' not in d
        ]
    else:
        if invert_colormap:
            edge_colors = [
                -d.get(edge_color, 0) for u, v, d in graph.edges(data=True)
                if 'nesting' not in d
            ]
        else:
            edge_colors = [
                d.get(edge_color, 0) for u, v, d in graph.edges(data=True)
                if 'nesting' not in d
            ]
    if dark_edge_color is None:
        dark_edge_colors = 'black'
    else:
        dark_edge_colors = [
            d.get(dark_edge_color, 0) for u, v, d in graph.edges(data=True)
            if 'nesting' in d
        ]
    tmp_edge_set = [(a, b, d) for (a, b, d) in graph.edges(data=True)
                    if ignore_for_layout in d]
    graph.remove_edges_from(tmp_edge_set)

    if pos is None:
        if layout == 'graphviz':
            graph_copy = graph.copy()
            pos = nx.nx_pydot.graphviz_layout(graph_copy, prog=prog)
        elif layout == "RNA":
            import RNA  # this is part of the vienna RNA package
            rna_object = RNA.get_xy_coordinates(graph.graph['structure'])
            pos = {
                i: (rna_object.get(i).X, rna_object.get(i).Y)
                for i in range(len(graph.graph['structure']))
            }
        elif layout == 'circular':
            pos = nx.circular_layout(graph)
        elif layout == 'random':
            pos = nx.random_layout(graph)
        elif layout == 'spring':
            pos = nx.spring_layout(graph)
        elif layout == 'shell':
            pos = nx.shell_layout(graph)
        elif layout == 'spectral':
            pos = nx.spectral_layout(graph)
        elif layout == 'KK':
            pos = KKEmbedder().transform(graph)
        else:
            raise Exception('Unknown layout format: %s' % layout)

    if vertex_border is False:
        linewidths = 0.001
    else:
        linewidths = vertex_border

    graph.add_edges_from(tmp_edge_set)

    if secondary_vertex_color is not None:
        if secondary_vertex_border is False:
            secondary_linewidths = 0.001
        else:
            secondary_linewidths = secondary_vertex_border
        secondary_node_color = [
            d.get(secondary_vertex_color, 0) for u, d in graph.nodes(data=True)
        ]
        secondary_nodes = nx.draw_networkx_nodes(
            graph,
            pos,
            node_color=secondary_node_color,
            alpha=secondary_vertex_alpha,
            node_size=secondary_vertex_size,
            linewidths=secondary_linewidths,
            cmap=plt.get_cmap(secondary_vertex_colormap),
            vmin=secondary_vertex_vmin,
            vmax=secondary_vertex_vmax)
        secondary_nodes.set_edgecolor('k')

    if compact:
        nodes = nx.draw_networkx_nodes(graph,
                                       pos,
                                       node_color='w',
                                       alpha=1,
                                       node_size=vertex_size,
                                       linewidths=linewidths)
        nodes.set_edgecolor('k')
        nx.draw_networkx_nodes(graph,
                               pos,
                               node_color=node_color,
                               alpha=vertex_alpha,
                               node_size=vertex_size,
                               linewidths=None,
                               cmap=plt.get_cmap(colormap),
                               vmin=vmin,
                               vmax=vmax)

    else:
        nodes = nx.draw_networkx_nodes(graph,
                                       pos,
                                       node_color=node_color,
                                       alpha=vertex_alpha,
                                       node_size=vertex_size,
                                       linewidths=linewidths,
                                       cmap=plt.get_cmap(colormap),
                                       vmin=vmin,
                                       vmax=vmax)
        nodes.set_edgecolor('k')

    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=edges_normal,
                           width=widths,
                           edge_color=edge_colors,
                           edge_cmap=plt.get_cmap(edge_colormap),
                           edge_vmin=edge_vmin,
                           edge_vmax=edge_vmax,
                           alpha=edge_alpha)
    if dark_edge_dotted:
        style = 'dotted'
    else:
        style = 'solid'
    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=edges_nesting,
                           width=1,
                           edge_cmap=plt.get_cmap(dark_edge_colormap),
                           edge_vmin=dark_edge_vmin,
                           edge_vmax=dark_edge_vmax,
                           edge_color=dark_edge_colors,
                           style=style,
                           alpha=dark_edge_alpha)
    if edge_label is not None:
        nx.draw_networkx_edge_labels(graph,
                                     pos,
                                     edge_labels=edge_labels,
                                     font_size=font_size)
    if vertex_label is not None:
        nx.draw_networkx_labels(graph,
                                pos,
                                vertex_labels,
                                font_size=font_size,
                                font_weight='normal',
                                font_color='black')
    if title_key:
        title = str(graph.graph.get(title_key, ''))
        font = FontProperties()
        font.set_family('monospace')
        plt.title(title, fontproperties=font)
    if size is not None:
        # here we decide if we output the image.
        # note: if size is not set, the canvas has been created outside
        # of this function.
        # we wont write on a canvas that we didn't create ourselves.
        if file_name is None:
            plt.show()
        else:
            plt.savefig(file_name,
                        bbox_inches='tight',
                        transparent=True,
                        pad_inches=0)
            plt.close()