コード例 #1
0
def plot_tree(tree, name):
    """ Plot and generate a png image of a tree with the tree hashed name

    Args:
        tree (dict): A dictionary contains all information of a tree
        name (str): The hashed name of the tree
    """
    graph = pydot.Dot(graph_type='graph')
    tree_graph = pydot.Cluster(
        graph_name="Learner Tree",
        label="Learner Tree",
        fontsize="15",
    )
    graphlegend = pydot.Cluster(graph_name="legend",
                                label="Legend",
                                fontsize="15",
                                rankdir="LR")
    legends = []
    for NODE_KEY in list(NODE_TYPES.keys()):
        legend = pydot.Node(NODE_KEY,
                            style="filled",
                            fillcolor=NODE_COLOR_DICT[NODE_KEY],
                            rank="same")
        graphlegend.add_node(legend)
        legends.append(legend)

    walk_dictionary(tree_graph, tree)
    graph.add_subgraph(tree_graph)
    graph.add_subgraph(graphlegend)
    for legend_index in range(1, len(legends)):
        graph.add_edge(
            pydot.Edge(legends[legend_index - 1],
                       legends[legend_index],
                       style="invis"))
    graph.write_png('./' + name + '.png')
コード例 #2
0
    def _add_node(diagram: Union[pydot.Dot, pydot.Cluster], op: Union[Op, Trace], node_id: str) -> None:
        """Draw a node onto a diagram based on a given op.

        Args:
            diagram: The diagram to be appended to.
            op: The op (or trace) to be visualized.
            node_id: The id to use as the node label.
        """
        if isinstance(op, Sometimes) and op.numpy_op:
            wrapper = pydot.Cluster(style='loosely dotted', graph_name=str(id(op)))
            wrapper.set('label', f'Sometimes ({op.prob}):')
            wrapper.set('labeljust', 'r')
            Traceability._add_node(wrapper, op.numpy_op, node_id)
            diagram.add_subgraph(wrapper)
        elif isinstance(op, OneOf) and op.numpy_ops:
            wrapper = pydot.Cluster(style='loosely dotted', graph_name=str(id(op)))
            wrapper.set('label', 'One Of:')
            wrapper.set('labeljust', 'r')
            Traceability._add_node(wrapper, op.numpy_ops[0], node_id)
            for sub_op in op.numpy_ops[1:]:
                Traceability._add_node(wrapper, sub_op, str(id(sub_op)))
            diagram.add_subgraph(wrapper)
        else:
            if isinstance(op, ModelOp):
                label = f"{op.__class__.__name__} ({FEID(id(op))}): {op.model.model_name}"
                model_ref = Hyperref(Marker(name=str(op.model.model_name), prefix='subsec'),
                                     text=NoEscape(r'\textcolor{blue}{') + bold(op.model.model_name) +
                                     NoEscape('}')).dumps()
                texlbl = f"{HrefFEID(FEID(id(op)), name=op.__class__.__name__).dumps()}: {model_ref}"
            else:
                label = f"{op.__class__.__name__} ({FEID(id(op))})"
                texlbl = HrefFEID(FEID(id(op)), name=op.__class__.__name__).dumps()
            diagram.add_node(pydot.Node(node_id, label=label, texlbl=texlbl))
コード例 #3
0
def drawOmciSession():
    dot_object = pydot.Dot(graph_type='digraph',
                           rankdir="LR",
                           labelloc='b',
                           ranksep=4,
                           nodesep=0.2,
                           splines='true')
    dot_object.set_node_defaults(shape='circle',
                                 fixedsize='true',
                                 height=.2,
                                 width=.2,
                                 fontsize=6)

    plate_olt = pydot.Cluster(graph_name='OLT',
                              label='OLT',
                              fontsize=12,
                              color='black',
                              lp=1)
    plate_onu = pydot.Cluster(graph_name='ONU',
                              label='ONU',
                              fontsize=12,
                              color='black')

    j = 1
    while (j < len(MS) * 2 + 1):
        if j % 2 == 1:
            label_seq = str(int((j + 1) / 2))
            plate_olt.add_node(
                pydot.Node(name=str(j), color="black", label=label_seq))
        else:
            plate_onu.add_node(pydot.Node(name=str(j), color="black",
                                          label=""))
        j = j + 1

    k = 1
    while (k < len(MS) * 2 + 1):
        index = int(k / 2)
        try:
            label_text = MS[index] + "   " + ME[index] + "     " + ID[
                index] + "   " + INFO[index]
        except IndexError:
            print("Index out of range...")
            break
        xdir = "forword"
        if "RESPONSE" in MS[index]:
            xdir = "back"

        dot_object.add_edge(
            pydot.Edge(pydot.Node(name=str(k)),
                       pydot.Node(name=str(k + 1)),
                       label=label_text,
                       dir=xdir,
                       fontsize=6))

        k = k + 2

    dot_object.add_subgraph(plate_olt)
    dot_object.add_subgraph(plate_onu)
    dot_object.write('graph.dotfile', format='raw', prog='dot')
    dot_object.write_pdf('omci_session.pdf', prog='dot')
コード例 #4
0
ファイル: graph2.py プロジェクト: MZachura/Grafy
    def drawGrafFunkcjaPlikPar(self):
        fundata = self.fundata1
        n1 = 0
        m1 = 0

        for name1 in fundata:
            if (name1 != "data.json" and name1 != "func.json"
                    and name1 != "cls.json" and name1 != "relfunc.json"):
                n1 = pydot.Cluster(label=name1, style="filled", color="white")
                n1.add_node(
                    pydot.Node(name1,
                               label=name1,
                               shape="circle",
                               style="filled",
                               fillcolor="darkgoldenrod1"))
                self.graph1.add_subgraph(n1)

                for p1 in fundata[name1]:

                    m1 = pydot.Cluster(label=p1, style="filled", color="white")
                    m1.add_node(
                        pydot.Node(p1,
                                   label=p1,
                                   shape="circle",
                                   style="filled",
                                   fillcolor="darkgoldenrod3"))
                    self.graph1.add_subgraph(m1)
                    self.graph1.add_edge(pydot.Edge(name1, p1,
                                                    fontsize="10.0"))
            else:
                wd40 = 0
コード例 #5
0
ファイル: graph2.py プロジェクト: MZachura/Grafy
 def drawGrafModuluPar(self):
     clsdata = self.clsdata1
     fundata = self.fundata1
     z = 0
     x = 0
     str = "z"
     str2 = "x"
     for namec in clsdata:
         if (namec != "data.json" and namec != "func.json"
                 and namec != "cls.json" and namec != "relfunc.json"):
             for pc in clsdata[namec]:
                 z = pydot.Cluster(label=pc, style="filled", color="white")
                 a = pc + str
                 z.add_node(
                     pydot.Node(a,
                                label=pc,
                                shape="circle",
                                style="filled",
                                fillcolor="antiquewhite"))
                 self.graph1.add_subgraph(z)
         else:
             wd40 = 0
         for pc in fundata[namec]:
             x = pydot.Cluster(label=pc, style="filled", color="white")
             b = pc + str2
             x.add_node(
                 pydot.Node(b,
                            label=pc,
                            shape="circle",
                            style="filled",
                            fillcolor="antiquewhite3"))
             self.graph1.add_subgraph(x)
             self.graph1.add_edge(pydot.Edge(a, b, fontsize="10.0"))
コード例 #6
0
ファイル: agent.py プロジェクト: afcarl/tmdp
def get_policy_graph(policy):
    graph = pydot.Dot('ordered',
                      graph_type='digraph',
                      compound='true',
                      fontname='Times',
                      fontsize=20)
    gcontexts = pydot.Cluster('context', rank='same', label='Contexts')
    gcommands = pydot.Cluster('commands', rank='same', label='Commands')
    graph.add_subgraph(gcommands)
    graph.add_subgraph(gcontexts)

    for cmd in set(policy.values()):
        gcommands.add_node(pydot.Node(cmd))

    stategroup = {}
    for (state, obsset), cmd in policy.items():
        if not state in stategroup:
            stategroup[state] = pydot.Cluster('state%s' % str(state),
                                              label=state)
            gcontexts.add_subgraph(stategroup[state])

    for (state, obsset), cmd in policy.items():
        n = '%s, %s' % (state, obsset)
        parent = gcontexts
        parent = stategroup[state]
        parent.add_node(pydot.Node(n, label=obsset))

        #         graph.add_edge(pydot.Edge(n, cmd,
        #                                       ltail=gcontexts.get_name(),
        #                                       lhead=gcommands.get_name()))

        graph.add_edge(pydot.Edge(n, cmd))

    return graph
コード例 #7
0
 def test_edge_point_object_cluster(self):
     self._reset_graphs()
     self.graph_directed.add_edge(pydot.Edge(pydot.Cluster('a'),
         pydot.Cluster('b')))
     self.assertEqual(
         self.graph_directed.get_edges()[0].to_string(),
             'cluster_a -> cluster_b;')
コード例 #8
0
ファイル: mapping.py プロジェクト: tud-ccc/mocasin
    def to_pydot(self, channels=True):
        """Convert the mapping to a dot graph

        The generated graph visualizes how a dataflow application is mapped
        to a platform.

        :returns: pydot object
        """
        dot = pydot.Dot(graph_type="digraph")

        processor_clusters = {}
        for s in self.platform.schedulers():
            cluster = pydot.Cluster("scheduler_" + s.name, label=s.name)
            dot.add_subgraph(cluster)
            for p in s.processors:
                p_cluster = pydot.Cluster("processor_" + p.name, label=p.name)
                p_cluster.add_node(pydot.Node("dummy_" + p.name,
                                              style="invis"))
                processor_clusters[p.name] = p_cluster
                cluster.add_subgraph(p_cluster)

        primitive_nodes = {}
        if channels:
            for p in self.platform.primitives():
                if p.name not in primitive_nodes:
                    node = pydot.Node("primitive_" + p.name, label=p.name)
                    dot.add_node(node)
                    primitive_nodes[p.name] = node

        process_nodes = {}
        for p in self.graph.processes():
            info = self._process_info[p.name]
            p_cluster = processor_clusters[info.affinity.name]
            node = pydot.Node("process_" + p.name, label=p.name)
            process_nodes[p.name] = node
            p_cluster.add_node(node)

        channel_nodes = {}
        if channels:
            for c in self.graph.channels():
                node = pydot.Node("channel_" + c.name,
                                  label=c.name,
                                  shape="diamond")
                channel_nodes[c.name] = node
                dot.add_node(node)
                from_node = process_nodes[c.source.name]
                dot.add_edge(pydot.Edge(from_node, node, minlen=4))
                for p in c.sinks:
                    to_node = process_nodes[p.name]
                    dot.add_edge(pydot.Edge(node, to_node, minlen=4))
                info = self._channel_info[c.name]
                prim_node = primitive_nodes[info.primitive.name]
                dot.add_edge(
                    pydot.Edge(node,
                               prim_node,
                               style="dashed",
                               arrowhead="none"))

        return dot
コード例 #9
0
ファイル: utilities.py プロジェクト: hiradg/drone_trees
 def add_children_and_edges(root, root_node, root_dot_name,
                            visibility_level, collapse_decorators, sub):
     if isinstance(root, decorators.Decorator) and collapse_decorators:
         return
     if visibility_level < root.blackbox_level:
         node_names = []
         for c in root.children:
             (node_shape, node_colour,
              node_font_colour) = get_node_attributes(c)
             node_name = c.name
             while node_name in behaviour_id_name_map.values():
                 node_name += "*"
             behaviour_id_name_map[c.id] = node_name
             # Node attributes can be found on page 5 of
             #    https://graphviz.gitlab.io/_pages/pdf/dot.1.pdf
             # Attributes that may be useful: tooltip, xlabel
             node = pydot.Node(
                 name=node_name,
                 label=get_node_label(node_name, c),
                 shape=node_shape,
                 style="filled",
                 fillcolor=node_colour,
                 fontsize=fontsize,
                 fontcolor=node_font_colour,
             )
             node_names.append(node_name)
             if root.blackbox_level == common.BlackBoxLevel.COMPONENT:
                 if sub is not None:
                     subgraph = pydot.Cluster(graph_name=root_dot_name,
                                              label=root_dot_name,
                                              style='dotted')
                     sub.add_subgraph(subgraph)
                     subgraph.add_node(node)
                     edge = pydot.Edge(root_dot_name, node_name)
                     subgraph.add_edge(edge)
                 else:
                     subgraph = pydot.Cluster(graph_name=root.name,
                                              label=root.name,
                                              style='dotted')
                     graph.add_subgraph(subgraph)
                     subgraph.add_node(node)
                     edge = pydot.Edge(root_dot_name, node_name)
                     subgraph.add_edge(edge)
             elif sub is not None:
                 sub.add_node(node)
                 edge = pydot.Edge(root_dot_name, node_name)
                 sub.add_edge(edge)
                 subgraph = sub
             else:
                 subgraph = None
                 graph.add_node(node)
                 edge = pydot.Edge(root_dot_name, node_name)
                 graph.add_edge(edge)
             if c.children != []:
                 add_children_and_edges(c, node, node_name,
                                        visibility_level,
                                        collapse_decorators, subgraph)
コード例 #10
0
ファイル: mapping.py プロジェクト: Quantumgame/mn256r1_ncs
    def add_edge(self, groupsrc, groupdst, arrowhead='normal', dir='forward'):
        scluster = pydot.Cluster(str(groupsrc.channel))
        s = pydot.Node(str(groupsrc.name))
        scluster.add_node(s)

        dcluster = pydot.Cluster(str(groupdst.channel))
        d = pydot.Node(str(groupdst.name))
        dcluster.add_node(d)

        self.graph.add_subgraph(dcluster)
        self.graph.add_subgraph(scluster)

        e = pydot.Edge(s, d, arrowhead=arrowhead, dir=dir)

        self.graph.add_edge(e)
コード例 #11
0
    def writePopulationDot(ga_engine, filename, format="jpeg", start=0, end=0):

        """ Writes to a graphical file using pydot, the population of trees
        Example:
           >>> GTreeGP.writePopulationDot(ga_engine, "pop.jpg", "jpeg", 0, 10)

        This example will draw the first ten individuals of the population into
        the file called "pop.jpg".

        :param ga_engine: the GA Engine
        :param filename: the filename, ie. population.jpg
        :param start: the start index of individuals
        :param end: the end index of individuals
        """
        if not HAVE_PYDOT:
            utils.raiseException("You must install Pydot to use this feature !")

        pop = ga_engine.get_population()
        graph = pydot.Dot(graph_type="digraph")

        if not isinstance(pop[0], GTreeGP):
            utils.raiseException("The population must have individuals of the GTreeGP chromosome !")

        n = 0
        end_index = len(pop) if end == 0 else end
        for i in xrange(start, end_index):
            ind = pop[i]
            subg = pydot.Cluster(
                "cluster_%d" % i,
                label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore())
            )
            n = ind.writeDotGraph(subg, n)
            graph.add_subgraph(subg)

        graph.write(filename, prog='dot', format=format)
コード例 #12
0
    def _draw_subgraph(diagram: pydot.Dot,
                       label_last_seen: DefaultDict[str, str],
                       subgraph_name: str,
                       subgraph_ops: List[Union[Op, Trace, Any]]) -> None:
        """Draw a subgraph of ops into an existing `diagram`.

        Args:
            diagram: The diagram to be appended to.
            label_last_seen: A mapping of {data_dict_key: node_id} indicating the last node which generated the key.
            subgraph_name: The name to be associated with this subgraph.
            subgraph_ops: The ops to be wrapped in this subgraph.
        """
        subgraph = pydot.Cluster(style='dashed', graph_name=subgraph_name)
        subgraph.set('label', subgraph_name)
        subgraph.set('labeljust', 'l')
        for idx, op in enumerate(subgraph_ops):
            node_id = str(id(op))
            Traceability._add_node(subgraph, op, node_id)
            if isinstance(op, (Op, Trace)):
                # Need the instance check since subgraph_ops might contain a tf dataset or torch dataloader
                edge_srcs = defaultdict(lambda: [])
                for inp in op.inputs:
                    if inp == '*':
                        continue
                    edge_srcs[label_last_seen[inp]].append(inp)
                for src, labels in edge_srcs.items():
                    diagram.add_edge(pydot.Edge(src=src, dst=node_id, label=f" {', '.join(labels)} "))
                for out in op.outputs:
                    label_last_seen[out] = node_id
            if isinstance(op, Trace) and idx > 0:
                # Invisibly connect traces in order so that they aren't all just squashed horizontally into the image
                diagram.add_edge(pydot.Edge(src=str(id(subgraph_ops[idx - 1])), dst=node_id, style='invis'))
        diagram.add_subgraph(subgraph)
コード例 #13
0
ファイル: individualvisualizer.py プロジェクト: Remosy/MENNAG
 def draw_modular(self, loc='test_mod.pdf'):
     nn = self.individual.nn
     Qscore, groups = Q(nn)
     g = pydot.Dot(graph_type='digraph', ranksep='0.5 equally', nodesep=0.2)
     g.set_node_defaults(shape='circle',style='filled')
     inputs = pydot.Subgraph('inputs',graph_type='digraph',rank='source')
     outputs = pydot.Subgraph('outputs',graph_type='digraph',rank='same')
     g.add_subgraph(inputs)
     g.add_subgraph(outputs)
     for i in range(nn.input_size):
         inputs.add_node(pydot.Node(str(i), label='input'+str(i)))
         if (i > 0):
             inputs.add_edge(pydot.Edge(str(i - 1), str(i), style='invis'))
     for i in range(nn.input_size, nn.input_size + nn.output_size):
         outputs.add_node(pydot.Node(str(i), label='output'+str(i - nn.input_size)))
         if (i > nn.input_size):
             outputs.add_edge(pydot.Edge(str(i - 1), str(i), style='invis'))
     count = -1
     for group in groups:
         count += 1
         random_number = random.randint(0,16777215)
         hex_color = str(hex(random_number))
         hex_color = '#' + hex_color[2:]
         cluster = pydot.Cluster('c' + str(count))
         for n in group:
             if (n >= nn.input_size + nn.output_size):
                 cluster.add_node(pydot.Node(str(n), fillcolor= hex_color))
         g.add_subgraph(cluster)
     edges = tuple(zip(nn.connList.connSource, nn.connList.connTarget))
     for e in edges:
         g.add_edge(pydot.Edge(str(e[0]), str(e[1])))
     g.write(loc, format='pdf')
コード例 #14
0
def get_legend(subgraph, name, show_ic=False, **kwargs):
    legend = pydot.Cluster(graph_type="digraph",
                           graph_name="Legend",
                           label="Legend",
                           rankdir="LR",
                           color="white")
    colors = list(color_map.values())
    ic_label = ""
    if show_ic: ic_label = "\nIC"
    edge_types = set(map(lambda e: e[2]["value"], subgraph.edges(data=True)))
    for k in filter(lambda k: k in edge_types,
                    reversed(edge_map.keys())):  # count down
        legend.add_node(
            pydot.Node(label_map[k],
                       shape="underline",
                       color=edge_grey,
                       style=edge_map[k]))
        # legend.add_node(pydot.Node(i, shape="point", color="white"))
        # legend.add_edge(pydot.Edge(labels[i], i, label = labels[i], color = colors[i]))
    legend.add_node(
        pydot.Node("concept" + ic_label,
                   shape="ellipse",
                   color=normal_color,
                   style=concept_style))
    legend.add_node(
        pydot.Node("idea \n concept" + ic_label,
                   shape="ellipse",
                   color=concept_color,
                   style=concept_style))
    G = pydot.Dot()
    G.add_subgraph(legend)
    G.write_png("pic/%s_legend.png" % name)
    return G
コード例 #15
0
def draw_legend(graph):
    graphlegend = pydot.Cluster(graph_name="legend", label="Labels", fontsize="20", color="red",
                                fontcolor="blue", style="filled", fillcolor="white",fontname='Impact')

    legend1 = pydot.Node('Processed', shape="plaintext",fontname='Impact')
    graphlegend.add_node(legend1)
    legend2 = pydot.Node("Killed ", shape="plaintext",fontname='Impact')
    graphlegend.add_node(legend2)
    legend3 = pydot.Node('Impossible', shape="plaintext",fontname='Impact')
    graphlegend.add_node(legend3)
    legend4 = pydot.Node('Goal', shape="plaintext",fontname='Impact')
    graphlegend.add_node(legend4)

    node1 = pydot.Node("1", style="filled", fillcolor="green", label="")
    graphlegend.add_node(node1)
    node2 = pydot.Node("2", style="filled", fillcolor="red", label="")
    graphlegend.add_node(node2)
    node3 = pydot.Node("3", style="filled", fillcolor="blue", label="")
    graphlegend.add_node(node3)
    node4 = pydot.Node("4", style="filled", fillcolor="gold", label="")
    graphlegend.add_node(node4)

    graph.add_subgraph(graphlegend)
    graph.add_edge(pydot.Edge(legend1, legend2, style="invis"))
    graph.add_edge(pydot.Edge(legend2, legend3, style="invis"))
    graph.add_edge(pydot.Edge(legend3, legend4, style="invis"))
    # graph.add_edge(pydot.Edge(legend4, legend5, style="invis"))
    graph.add_edge(pydot.Edge(node1, node2, style="invis"))
    graph.add_edge(pydot.Edge(node2, node3, style="invis"))
    graph.add_edge(pydot.Edge(node3, node4, style="invis"))
コード例 #16
0
 def make_subgraph(path, parent_graph):
     subgraph = pydot.Cluster(path,
                              label=split(path)[1],
                              style='rounded, filled',
                              fillcolor='#77777744')
     parent_graph.add_subgraph(subgraph)
     return subgraph
コード例 #17
0
def index(graph):
    graphlegend = pydot.Cluster(graph_name="legend",
                                label="Legend",
                                fontsize="20",
                                color="red",
                                fontcolor="blue",
                                style="filled",
                                fillcolor="white")

    processed_node = pydot.Node('Processed node', shape="plaintext")
    graphlegend.add_node(processed_node)
    depth_lnode = pydot.Node("Depth limit reached", shape="plaintext")
    graphlegend.add_node(depth_lnode)
    gol_node = pydot.Node('Goal Node', shape="plaintext")
    graphlegend.add_node(gol_node)

    node1 = pydot.Node("1", style="filled", fillcolor="green", label="")
    graphlegend.add_node(node1)
    node2 = pydot.Node("2", style="filled", fillcolor="grey", label="")
    graphlegend.add_node(node2)
    node3 = pydot.Node("3", style="filled", fillcolor="blue", label="")
    graphlegend.add_node(node3)

    graph.add_subgraph(graphlegend)
    graph.add_edge(pydot.Edge(processed_node, depth_lnode, style="invis"))
    graph.add_edge(pydot.Edge(depth_lnode, gol_node, style="invis"))

    graph.add_edge(pydot.Edge(node1, node2, style="invis"))
    graph.add_edge(pydot.Edge(node2, node3, style="invis"))
コード例 #18
0
ファイル: dumpgraphs.py プロジェクト: winex/pystream
    def makeNode(tree, sg, node):
        if node is not None:
            code = node

            if not code.isStandardCode():
                nodecolor = "#4444FF"
            elif code.annotation.descriptive:
                nodecolor = "#FF3333"
            elif code.codeparameters.selfparam is None:
                nodecolor = '#BBBBBB'
            else:
                nodecolor = '#33FF33'
            sg.add_node(
                pydot.Node(str(id(node)),
                           label=dumputil.codeShortName(code),
                           shape='box',
                           style="filled",
                           fontsize=8,
                           fillcolor=nodecolor,
                           URL=links.codeRef(node, None)))
        else:
            sg.add_node(
                pydot.Node(str(id(node)),
                           label="entry",
                           shape='point',
                           style="filled",
                           fontsize=8))

        children = tree.get(node)
        if children:
            csg = pydot.Cluster(str(id(node)))
            sg.add_subgraph(csg)
            for child in children:
                makeNode(tree, csg, child)
コード例 #19
0
def draw_legend(graph):
    graphlegend = pydot.Cluster(graph_name="legend",
                                label="Legend",
                                fontsize="20",
                                color="green",
                                fontcolor="blue",
                                style="filled",
                                fillcolor="white")

    legend1 = pydot.Node('Visited node', shape="plaintext")
    graphlegend.add_node(legend1)
    legend2 = pydot.Node("Reached max height", shape="plaintext")
    graphlegend.add_node(legend2)
    legend3 = pydot.Node('Goal Node', shape="plaintext")
    graphlegend.add_node(legend3)

    node1 = pydot.Node("1", style="filled", fillcolor="yellow", label="")
    graphlegend.add_node(node1)
    node2 = pydot.Node("2", style="filled", fillcolor="red", label="")
    graphlegend.add_node(node2)
    node3 = pydot.Node("3", style="filled", fillcolor="green", label="")
    graphlegend.add_node(node3)

    graph.add_subgraph(graphlegend)
    graph.add_edge(pydot.Edge(legend1, legend2, style="invis"))
    graph.add_edge(pydot.Edge(legend2, legend3, style="invis"))

    graph.add_edge(pydot.Edge(node1, node2, style="invis"))
    graph.add_edge(pydot.Edge(node2, node3, style="invis"))
コード例 #20
0
    def generate_typesdiagram(self):
        self.graficotypes = pydot.Dot(grap_name = "Diagrama de types",
                                      graph_type = "digraph")
                                      #dpi = 300 )
        filetypes = self.__get_filetypes()
        fileclusters = []
        for filename in filetypes:
            with open(filename) as searchfile:
                unitname = self.__get_unit_name(searchfile)
            print( unitname)
            fileclusters.append(pydot.Cluster(unitname, label = unitname))
            self.graficotypes.add_subgraph(fileclusters[-1])
            for tipo in filetypes[filename]:
                fileclusters[-1].add_node(pydot.Node(tipo))

        for filename in filetypes:
            for tipo in filetypes[filename]:
                with open(filename) as searchfile:
                    typecode = self.get_type_code(tipo, searchfile)
                    print( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", typecode)
                    print( re.sub("\\\l","\n",typecode,re.ASCII))
                used_types = self.get_used_types(re.sub("\\\l","\n",typecode,flags=re.ASCII))
                for used_type in used_types:
                    self.graficotypes.add_edge(pydot.Edge(tipo, used_type))
        self.graficotypes.write_png('graphs\\types_diagram.png'.format(time.strftime("%d%m%y%H%M")))
        self.graficotypes.write_jpg('graphs\\types_diagram.jpg'.format(time.strftime("%d%m%y%H%M")))
        self.graficotypes.write_pdf('graphs\\types_diagram.pdf'.format(time.strftime("%d%m%y%H%M")))
        self.graficotypes.write_dot('graphs\\types_diagram.dot'.format(time.strftime("%d%m%y%H%M")))
コード例 #21
0
ファイル: provgraph.py プロジェクト: pombredanne/testkraut
    def _bundle_to_dot(dot, bundle):
        records = bundle.get_records()
        relations = []
        for rec in records:
            if rec.is_element():
                if isinstance(rec, ProvBundle):
                    count[2] = count[2] + 1
                    subdot = pydot.Cluster(graph_name='c%d' % count[2])
                    if use_labels:
                        subdot.set_label('"%s"' % str(rec.get_label()))
                    else:
                        subdot.set_label('"%s"' % str(rec.get_identifier()))
                    _bundle_to_dot(subdot, rec)
                    dot.add_subgraph(subdot)
                else:
                    count[0] = count[0] + 1
                    node_id = 'n%d' % count[0]
                    if use_labels:
                        node_label = '"%s"' % str(rec.get_label())
                    else:
                        node_label = '"%s"' % str(rec.get_identifier())
                    style = DOT_PROV_STYLE[rec.get_type()]
                    node = pydot.Node(node_id, label=node_label, **style)
                    node_map[rec] = node
                    dot.add_node(node)
            else:
                relations.append(rec)
        for rec in relations:
            nodes = [
                node for node in rec._attributes.values()
                if node is not None and isinstance(node, ProvElement)
            ]
            if len(nodes) < 2:
                # Cannot draw this
                pass
            elif len(nodes) == 2 or not show_nary:
                # binary relations
                style = DOT_PROV_STYLE[rec.get_type()]
                dot.add_edge(
                    pydot.Edge(node_map[nodes[0]], node_map[nodes[1]],
                               **style))
            else:
                # n-ary relations
                style = DOT_PROV_STYLE[rec.get_type()]
                # add a blank node
                count[1] = count[1] + 1
                bnode_id = 'b%d' % count[1]
                bnode = pydot.Node(bnode_id, label='""', shape='point')
                dot.add_node(bnode)

                dot.add_edge(
                    pydot.Edge(node_map[nodes[0]],
                               bnode,
                               arrowhead='none',
                               **style))
                style = dict(style)
                del style['label']
                for node in nodes[1:]:
                    dot.add_edge(pydot.Edge(bnode, node_map[node], **style))
                    style['color'] = 'gray'
コード例 #22
0
    def Gear(self, module):
        if self.node_filter(module):
            self.dot.node_map[module] = pydot.Node(module.name,
                                                   fontsize=18,
                                                   margin=0.01,
                                                   tooltip=module.name,
                                                   label=module.basename,
                                                   shape="doubleoctagon")

            self.hier[-1].add_node(self.dot.node_map[module])
        else:
            self.dot.cluster_map[module] = pydot.Cluster(
                graph_name=module.name,
                label=module.basename,
                tooltip=module.name,
                fontsize=48,
                fontcolor='blue',
                labeljust='l',
                overlap=False)

            self.enter_hier(module)

            super().HierNode(module)

            self.exit_hier(module)

        return True
コード例 #23
0
ファイル: EnvironmentModel.py プロジェクト: tjholodnik/cairis
    def graph(self):
        self.nodeNameSet = set([])
        self.dimNameSet = set([])

        for dotLink in self.theTraceLinks:
            fromDimName = dotLink.fromObject()
            self.dimNameSet.add(fromDimName)
            fromName = dotLink.fromName()
            if (fromName not in self.nodeNameSet):
                self.buildNode(fromDimName, fromName)
                self.nodeNameSet.add(fromName)
                self.theNodeLookup[
                    fromName] = fromDimName + ' ' + dotLink.fromName()
            toDimName = dotLink.toObject()
            self.dimNameSet.add(toDimName)
            toName = dotLink.toName()
            if (toName not in self.nodeNameSet):
                self.buildNode(toDimName, toName)
                self.nodeNameSet.add(toName)
                self.theNodeLookup[toName] = toDimName + ' ' + dotLink.toName()
            dirType = 'none'
            if (fromDimName == 'risk' and toDimName == 'vulnerability'):
                dirType = 'forward'
            edge = pydot.Edge(str(fromName), str(toName), dir=dirType)
            self.theGraph.add_edge(edge)

            if (self.isTagged == True):
                tags = self.dbProxy.riskModelTags(self.theEnvironmentName)
                if (len(tags) > 0):
                    for tag in tags:
                        cluster = pydot.Cluster(tag, label=tag)
                        for objt in tags[tag]:
                            cluster.add_node(pydot.Node(objt))
                        self.theGraph.add_subgraph(cluster)
        return self.layout()
コード例 #24
0
def visualize_graph(trgt, rules, outpath):
    """Draw a figure representing the dependency graph.

    By default writes the graph to a file named the same as the calling
    script.

    """
    import pydot
    root, graph = build_dep_graph(trgt, rules)
    orders, newester_order_update = build_orders(root, graph)
    dot = pydot.Dot(graph_name="Dependency",
                    graph_type='digraph',
                    labelloc='r',
                    rankdir="BT")
    dot.set_node_defaults(shape='ellipse', fontsize=24)
    for req in graph:
        for preq in graph[req]:
            dot.add_edge(pydot.Edge(preq.target, req.target))
    for rank, rank_reqs in enumerate(reversed(orders), 1):
        rank_plate = pydot.Cluster(graph_name=str(rank),
                                   label="Order set {r}".format(r=rank))
        for req in rank_reqs:
            rank_plate.add_node(pydot.Node(req.target))
        dot.add_subgraph(rank_plate)
    return dot.write_png(outpath)
コード例 #25
0
ファイル: traceability.py プロジェクト: psfoley/fastestimator
    def _draw_subgraph(progenitor: pydot.Dot, diagram: Union[pydot.Dot,
                                                             pydot.Cluster],
                       label_last_seen: DefaultDict[str,
                                                    str], subgraph_name: str,
                       subgraph_ops: List[Union[Op, Trace, Any]]) -> None:
        """Draw a subgraph of ops into an existing `diagram`.

        Args:
            progenitor: The very top level diagram onto which Edges should be written.
            diagram: The diagram into which to add new Nodes.
            label_last_seen: A mapping of {data_dict_key: node_id} indicating the last node which generated the key.
            subgraph_name: The name to be associated with this subgraph.
            subgraph_ops: The ops to be wrapped in this subgraph.
        """
        subgraph = pydot.Cluster(style='dashed',
                                 graph_name=subgraph_name,
                                 color='black')
        subgraph.set('label', subgraph_name)
        subgraph.set('labeljust', 'l')
        for idx, op in enumerate(subgraph_ops):
            node_id = str(id(op))
            Traceability._add_node(progenitor, subgraph, op, label_last_seen)
            if isinstance(op, Trace) and idx > 0:
                # Invisibly connect traces in order so that they aren't all just squashed horizontally into the image
                progenitor.add_edge(
                    pydot.Edge(src=str(id(subgraph_ops[idx - 1])),
                               dst=node_id,
                               style='invis'))
        diagram.add_subgraph(subgraph)
コード例 #26
0
 def add_subgraph_to_graph(self,
                           graph,
                           subgraphlabel,
                           rank='same',
                           simplify=True,
                           rankdir='TB',
                           ranksep=0.2,
                           compound=True,
                           color=None,
                           shape='box',
                           style='bold'):
     """
     creates a cluster subgraph  item for this factory, adds it to the graph.
     cluster name can vary from label but must always be same for the same node label.
     Most layouters require cluster names to start with cluster.
     """
     if subgraphlabel is None or subgraphlabel == '':
         raise ValueError('Empty subgraph label')
     g = pydot.Cluster(self.escape_name(subgraphlabel),
                       rank=rank,
                       rankdir=rankdir,
                       simplify=simplify)
     if 'set_style' in g.__dict__:
         g.set_style(style)
     if 'set_shape' in g.__dict__:
         g.set_shape(shape)
     if LooseVersion(pydot.__version__) > LooseVersion('1.0.10'):
         g.set_compound(compound)
         g.set_ranksep(ranksep)
     g.set_label(subgraphlabel)
     if 'set_color' in g.__dict__:
         if color is not None:
             g.set_color(color)
     graph.add_subgraph(g)
     return g
コード例 #27
0
 def __missing__(self, path):
     subgraph = pydot.Cluster(sep.join(path),
                              label=stub(path),
                              style='rounded, filled',
                              fillcolor='#77777744')
     self[parent(path)].add_subgraph(subgraph)
     return subgraph
コード例 #28
0
ファイル: stateMachine.py プロジェクト: fmartinez14/ntsg
    def createMachine(self):
        #creates the initial version of the state machine
        self.graph = pydot.Dot(graph_type='digraph', rankdir="LR")

        graphlegend = pydot.Cluster(graph_name="NTSG",
                                    label="NTSG",
                                    rankdir="TB")

        self.node = []

        for i in range(self.numNodes):
            #self.node.append(pydot.Node("Node %d" % (i) + " : " + messageTypes[i].name, rank="same"))
            self.node.append(pydot.Node("Node %d" % (i), rank="same"))
            self.graph.add_node(self.node[i])

        for i in range(self.numNodes):
            if (i < (self.numNodes - 1)):
                #draw the initial edges
                self.graph.add_edge(pydot.Edge(self.node[i], self.node[i + 1]))
                #create a transition and append it to the list

                self.transitions.append(transition().createTransition(
                    i, (i + 1)))

        self.graph.write_png('stateMachine.png')
コード例 #29
0
    def add_cluster(self,
                    name,
                    label=None,
                    rank='same',
                    rankdir='TB',
                    simplify=True,
                    color=None,
                    shape='circle',
                    compound=True,
                    style='bold',
                    ranksep=0.2,
                    orientation='portrait'):

        name = escape_text(name)
        c = pydot.Cluster(escape_text(name),
                          rank=rank,
                          rankdir=rankdir,
                          simplify=simplify)
        if 'set_shape' in c.__dict__:
            c.set_shape(shape)
        if 'set_style' in c.__dict__:
            c.set_style(style)
        if 'set_color' in c.__dict__:
            c.set_color(color)
        c.set_compound(compound)
        c.set_ranksep(ranksep)
        c.set_label(label or name)
        self.graph.add_subgraph(c)
        self.subgraphs[name] = GraphWrapper(graph=c)
        # print(c.get_name())
        return self.subgraphs[name]
コード例 #30
0
ファイル: lg.py プロジェクト: petabyteboy/bird-lg
 def add_subgraph(_as, **kwargs):
     if _as not in subgraphs:
         subgraphs[_as] = pydot.Cluster("cluster_%s" % _as,
                                        label="",
                                        **kwargs)
         graph.add_subgraph(subgraphs[_as])
     return subgraphs[_as]