Ejemplo n.º 1
0
def create_session_graph(session: AbstractSession,
                         ignore: Sequence[str] = None) -> Dot:
    """
    Return pydot graph representation of session.

    If present, the ignore parameter contains a list of regular expressions which are matched
    against state names and the names of edge targets in order. If a regular expression matches
    a state name or an edge target name, the respective state or edge is excluded from the result
    graph.
    """
    def _is_ignored(name: ID) -> bool:
        if not ignore:
            return False
        for regex in ignore:
            if re.search(regex, str(name), re.IGNORECASE):
                return True
        return False

    result = _graph_with_defaults(str(session.identifier))
    for state in session.states:

        if _is_ignored(state.identifier):
            continue

        if state.identifier == session.initial:
            result.add_node(
                Node(
                    name=str(state.identifier.name),
                    fillcolor="#ffffff",
                    fontcolor="black",
                ))
        elif state.identifier == session.final:
            result.add_node(
                Node(
                    name=str(state.identifier.name),
                    fillcolor="#6f6f6f",
                ))
        else:
            result.add_node(Node(name=str(state.identifier.name)))

        for index, t in enumerate(state.transitions):
            if not _is_ignored(t.target.name):
                label = (
                    f"{state.identifier.name} → {t.target.name}\n\n[{index}] {t.condition}"
                    if t.condition != TRUE else "")
                result.add_edge(
                    Edge(
                        src=str(state.identifier.name),
                        dst=str(t.target.name),
                        tooltip=label,
                        minlen="3",
                    ))

    return result
Ejemplo n.º 2
0
def create_message_graph(message: Message) -> Dot:
    """Return pydot graph representation of message."""
    def _edge_label(link: Link) -> str:
        return "({cond},{sep1}{size},{sep2}{first})".format(  # pylint: disable = consider-using-f-string
            cond=str(link.condition) if link.condition != TRUE else "⊤",
            sep1=" "
            if link.condition == TRUE or link.size == UNDEFINED else "\n",
            size=str(link.size)
            if link.size != UNDEFINED else message.field_size(link.target),
            sep2=" " if link.first == UNDEFINED else "\n",
            first=str(link.first) if link.first != UNDEFINED else "⋆",
        )

    msg = copy(message)
    if not msg.structure:
        # https://github.com/Componolit/RecordFlux/issues/643
        # pylint: disable-next = protected-access
        msg._structure = [Link(INITIAL, FINAL)]

    result = _graph_with_defaults(msg.full_name)
    result.add_node(
        Node(name="Initial",
             fillcolor="#ffffff",
             shape="circle",
             width="0.5",
             label=""))
    for f in msg.fields:
        result.add_node(Node(name=f.name))
    for i, l in enumerate(msg.structure):
        intermediate_node = f"intermediate_{i}"
        result.add_node(
            Node(
                name=intermediate_node,
                label=_edge_label(l),
                style="",
                fontname="Fira Code",
                fontcolor="#6f6f6f",
                color="#6f6f6f",
                penwidth="0",
                width="0",
                height="0",
            ))
        result.add_edge(
            Edge(src=l.source.name, dst=intermediate_node, arrowhead="none"))
        result.add_edge(
            Edge(src=intermediate_node, dst=l.target.name, minlen="1"))
    result.add_node(
        Node(name="Final",
             fillcolor="#6f6f6f",
             shape="circle",
             width="0.5",
             label=""))
    return result
Ejemplo n.º 3
0
def format_create(layer,
                  format_map,
                  color_map=DEFAULT_MAP,
                  formatter=ParamFormatter(),
                  **kwargs):
    """Create a :class:`Node` from a formatting system.

    Parameters
    ----------
    layer : a :class:`Layer` instance
        The layer.
    format_map : a dictionary mapping layer types to format strings
        A dictionary that contains a format string for each of the
        layer's types. The information for the node is created by using
        ``formatter`` to call format with all the layer attributes as
        (keyword) arguments.
    color_map: a dictionary mapping layer types to strings
        The dictionary should contain all the colors for all the used
        layer types.
    formatter : :class:`Formatter` instance
        The formatter for creating the node information.
    kwargs : keyword arguments
        Those will be passed down to :class:`Node`.
    """
    color = color_map[type(layer)]
    variables = {n: getattr(layer, n) for n in dir(layer)}
    label = formatter.format(format_map[type(layer)], **variables)
    return Node(repr(layer),
                label=label,
                shape='record',
                fillcolor=color,
                style='filled',
                **kwargs)
Ejemplo n.º 4
0
def verbose_create(layer,
                   color_map=DEFAULT_MAP,
                   blacklist=('input_layer', 'input_layers'),
                   **kwargs):
    """Create a node for the layer with a lot of information.

    Parameters
    ----------
    layer : a :class:`Layer` instance
        The layer.
    color_map ; dictionary
        A dictionary that maps all layer types to a color value.
    blacklist : sequence of strings
        A list of attribute names that are not included.
    kwargs : keyword arguments
        Those will be passed down to :class:`Node`.
    """
    label = type(layer).__name__
    color = color_map[type(layer)]
    variables = vars(layer)
    label += '\n' + '\n'.join(
        (f'{n} : {dot_escape(variables[n])}'
         for n in sorted(variables) if n not in blacklist))
    return Node(repr(layer),
                label=label,
                shape='record',
                fillcolor=color,
                style='filled',
                **kwargs)
 def make_node(self, name):
     return Node(
         name,
         style='filled',
         color='turquoise',
         labelloc='b',
         fontname="Times-Roman:bold",
         fontcolor='black',
         fontsize=50,
     )
Ejemplo n.º 6
0
def build(graph: Dg) -> Subgraph:
    """Generate the dependency digraph.

    Builds the dependency digraph recursively from the main node.

    :param graph: main node.
    :type graph: Dg
    :return: Dot type digraph.
    :rtype: Dot
    """
    digraph = Subgraph()
    main_node_name = str(graph.root_filename).split(sep)[-1]
    main_node = Node(main_node_name)
    digraph.add_node(main_node)
    for dep in graph.module_deps:
        node_name = str(dep.root_filename).split(sep)[-1]
        node = Node(node_name)
        edge = Edge(main_node_name, node_name)
        digraph.add_node(node)
        digraph.add_edge(edge)
        digraph.add_subgraph(build(dep))
        pass
    return digraph
Ejemplo n.º 7
0
 def make_node(self, name):
     return Node(
         name,
         shape='none',
         style='filled',
         color='azure2',
         image='voter.png',
         labelloc='b',
         fontname="Times-Roman:bold",
         fixedsize='true',
         width=1.0,
         height=1.0,
         fontcolor='white',
         fontsize=15,
     )
Ejemplo n.º 8
0
 def get(self) -> Dot:
     """Return pydot graph representation of message."""
     result = Dot(graph_name=self.__message.full_name)
     result.set_graph_defaults(splines="ortho", ranksep="0.8 equally")
     result.set_edge_defaults(fontname="Fira Code",
                              fontcolor="#6f6f6f",
                              color="#6f6f6f")
     result.set_node_defaults(
         fontname="Arimo",
         fontcolor="#ffffff",
         color="#6f6f6f",
         fillcolor="#009641",
         width="1.5",
         style='"rounded,filled"',
         shape="box",
     )
     result.add_node(
         Node(name="Initial",
              fillcolor="#ffffff",
              shape="circle",
              width="0.5",
              label=""))
     for f in self.__message.fields:
         result.add_node(Node(name=f.name))
     for l in self.__message.structure:
         result.add_edge(
             Edge(src=l.source.name,
                  dst=l.target.name,
                  xlabel=self.__edge_label(l)))
     result.add_node(
         Node(name="Final",
              fillcolor="#6f6f6f",
              shape="circle",
              width="0.5",
              label=""))
     return result
Ejemplo n.º 9
0
def nolearn(layer, output_shape=True, verbose=False, **kwargs):
    """Create a :class:`Node` for a given layer, like nolearn would.

    Parameters
    ----------
    layer : a class:`Layer` instance
        The layer for which a node shall be created.
    output_shape : boolean (``True``)
        If ``True`` the output shape of the layer will be displayed.
    verbose : boolean (''False`)
        If ``True`` layer attributes like filter shape, stride, etc.
        will be displayed.
    kwargs : keyword arguments
        Those will be passed down to :class:`Node`.
    """
    label = type(layer).__name__
    color = _nolearn_color(layer)
    if verbose:
        for attr in [
                'num_filters', 'num_units', 'ds', 'filter_shape', 'stride',
                'strides', 'p'
        ]:
            if hasattr(layer, attr):
                label += f'\n{attr}: {getattr(layer, attr)}'
        if hasattr(layer, 'nonlinearity'):
            try:
                nonlinearity = layer.nonlinearity.__name__
            except AttributeError:
                nonlinearity = layer.nonlinearity.__class__.__name__
            label += f'\nnonlinearity: {nonlinearity}'

    if output_shape:
        label += f'\nOutput shape: {layer.output_shape}'

    return Node(repr(layer),
                label=label,
                shape='record',
                fillcolor=color,
                style='filled',
                **kwargs)
Ejemplo n.º 10
0
    def dot_node(self):
        # label_value = "\"<left>left|<parent>parent|<value>" + \
        #    str(self.value) + "|<right>right\""
        # return Node(str(self._dot_index), label=label_value, shape='Mrecord',
        # fontcolor='blue')

        # HTML 实现table表,功能更加强大
        # 搜资料:HTML5 不再支持table的bgcolor
        label_value = '''<\
<table>\
    <tr>\
        <td port="left">left</td>\
        <td port="parent" width="50" bgcolor="#FFFF00">parent</td>\
        <td port="value" width="50" bgcolor="#00FF00">''' + str(
            self.value) + '''</td>\
        <td port="right">right</td>\
    </tr>\
</table>\
>'''
        return Node(str(self._dot_index),
                    label=label_value,
                    shape='plaintext',
                    fontcolor='blue')
Ejemplo n.º 11
0
# -*- coding: utf-8 -*-
# coding:utf-8

from pydotplus import Dot, Edge, Node
from PIL import Image
from q41 import make_chunk_list
from q42 import extract_surface

txt_path = '../5/ai.ja.txt.parsed'
sentences = make_chunk_list(txt_path)

sentence_idx = 7
sentence = sentences[sentence_idx]

graph = Dot(graph_type='digraph')
graph.set_fontname('MS Gothic')

# make Node and Edge
for id, chunk in enumerate(sentence):
    word = extract_surface(sentences, sentence_idx, id)
    node = Node(id, label=word)
    graph.add_node(node)
    if chunk.dst != -1:
        edge = Edge(id, chunk.dst)
        graph.add_edge(edge)

graph.write_png('sentence.png')
Image.open('sentence.png')
Ejemplo n.º 12
0
node_name = tuple(data.keys())

graph.set_node_defaults(shape='record')
# 将结点和边关联
i = 0
for key, value in data.items():
    if i == 0 or i == len(data) - 1:
        # node label中{}的作用,相当于开辟新的作用域,且垂直水平方向会相对于当前来进行切换
        """
        digraph G {
            node [shape=record];
            1 [label="<left>左|{<top>上|<buttom>下}|<right>右"];
        }
        """
        node = Node(key, shape='ellipse')
    else:
        label_value = "\"<data> " + value + "|<next>\""
        node = Node(key, label=label_value)

    # print(node.get_name())
    # node.set_shape('record')  # 直接配置默认了set_node_defaults
    graph.add_node(node)

    if i == 0:
        i += 1
        continue
    elif i == 1:
        edge = Edge(node_name[i - 1], node.get_name() + ':data')
    elif i == len(data) - 1:
        edge = Edge(node_name[i - 1] + ':next', node.get_name())