Пример #1
0
    def show_diagram(self, path=None):
        """
            Creates the graph associated with this DFA
        """
        # Nodes are set of states

        graph = Dot(graph_type='digraph', rankdir='LR')
        nodes = {}
        for state in self.states:
            if state == self.initial_state:
                # color start state with green
                initial_state_node = Node(
                    state, style="filled", fillcolor="green")
                nodes[state] = initial_state_node
                graph.add_node(initial_state_node)
            else:
                state_node = Node(state)
                nodes[state] = state_node
                graph.add_node(state_node)
        # adding edges
        for from_state, lookup in self.transitions.items():
            for to_label, to_state in lookup.items():
                graph.add_edge(Edge(
                    nodes[from_state],
                    nodes[to_state],
                    label=to_label
                ))
        if path:
            graph.write_png(path)
        return graph
Пример #2
0
def gen_dot():
    d = Dot()
    nodes = dict()
    login = read_ssv_file('vpopmail.login')
    db = MySQLdb.connect(host='localhost',
                         user=login[0],
                         passwd=login[2],
                         db=login[1])
    c = db.cursor()
    c.execute("SELECT alias, valias_line FROM valias WHERE domain=%s",
              (MAILDOMAIN, ))
    for alias, target in c.fetchall():
        assert target[0] == '&'
        target = target[1:]
        alias += "@" + MAILDOMAIN
        if not alias in nodes:
            nodes[alias] = Node(alias)
            d.add_node(nodes[alias])
        if not target in nodes:
            nodes[target] = Node(target)
            d.add_node(nodes[target])
        d.add_edge(Edge(nodes[alias], nodes[target]))
    for list in Utils.list_names():
        if list == 'plukdenacht2008': continue
        source = list + "@" + LISTDOMAIN
        if not source in nodes:
            nodes[source] = Node(source)
            d.add_node(nodes[source])
        m = MailList.MailList(list, lock=False)
        for member in m.members:
            if not member in nodes:
                nodes[member] = Node(member)
                d.add_node(nodes[member])
            d.add_edge(Edge(nodes[source], nodes[member]))
    d.write('the.dot')
Пример #3
0
def create_example_graph():
    g = Dot(graph_name="workflow: example",
            labelloc="t",
            label="workflow: example",
            fontsize=18,
            fontcolor="blue")
    g.set_node_defaults(shape="box", fontsize=12)
    g.set_edge_defaults(fontsize=13, labeldistance=3)
    n1 = Node(name="Start")
    g.add_node(n1)
    n2 = Node(name="StepTrueEnd", color="#04B45F")
    g.add_node(n2)
    n3 = Node(name="StepFalse")
    g.add_node(n3)
    n4 = Node(name="StepFalse2")
    g.add_node(n4)
    n5 = Node(name="StepFalse3End", color="#04B45F")
    g.add_node(n5)
    e1 = true_edge(n1, n2)
    g.add_edge(e1)
    e2 = false_edge(n1, n3)
    g.add_edge(e2)
    e3 = true_edge(n3, n4)
    g.add_edge(e3)
    e_back = false_edge(n4, n1, label="back if false")
    g.add_edge(e_back)
    e4 = true_edge(n4, n5)
    g.add_edge(e4)
    return g
Пример #4
0
 def generateGraphNode(self, idx, proofRoot=False):
     vertex = Node(idx, label='"%s"' % repr(self), shape='plaintext')
     # vertex.shape = 'plaintext'
     # vertex.width = '5em'
     if proofRoot:
         vertex.root = 'true'
     # vertex.peripheries = '1'
     return vertex
Пример #5
0
 def generateGraphNode(self, idx, proofRoot=False):
     vertex = Node(idx, label='"%s"' % repr(self), shape='plaintext')
     # vertex.shape = 'plaintext'
     # vertex.width = '5em'
     if proofRoot:
         vertex.root = 'true'
     # vertex.peripheries = '1'
     return vertex
Пример #6
0
 def mk_node(graph, name, label=None):
     """Add a node to the graph, if not already present"""
     if not graph.get_node(name):
         if not label:
             label = name
         if name in graph.changes:
             graph.add_node(Node(name, label=label))
         else:
             graph.add_node(Node(name, color='grey', label=''))
    def construct_node(self, _function: Function):
        """
        Takes a Function object and constructs a Dot Node object for it.
        Adds the created object to the dictionary.

        Finished.
        """
        n = Node(_function.name)
        n.set_tooltip(construct_tooltip(_function))
        self.node_dic[_function.name] = n
        self.graph.add_node(n)
Пример #8
0
def render_graph(root, hierarchy, args):
    g = Dot()
    g.set_root(root[0])

    for manager in hierarchy:
        g.add_node(Node(manager[0], shape='box'))
        for subordinate in hierarchy[manager]:
            g.add_node(Node(subordinate[0], shape='box'))
            g.add_edge(Edge(manager[0], subordinate[0]))

    g.write_svg(args.file, args.imageType, args.layout)
Пример #9
0
 def append_edgelist(self):
     ''' Internal function for generating Graphviz tree.'''
     edgelist = []
     for child in self.children:
         edgelist.append((Node(self.display(),
                               shape='invhouse',
                               fontname='monospace'),
                          Node(child.display(),
                               shape='rectangle',
                               fontname='monospace')))
         edgelist += child.append_edgelist()
     return edgelist
Пример #10
0
 def add_node(self,*args,**kwargs):
     # some args are
     #   name = 'N'
     #   texlbl = 'N_{n,m}'
     if len(args)==1 and isinstance(args[0],Node):
         node = args[0]
     else:
         node = Node(*args,**kwargs)
     #end if
     name = node.get_name()
     self.nodes[name] = node
     self.graph.add_node(node)
Пример #11
0
 def add_node(self,*args,**kwargs):
     # some args are
     #   name = 'N'
     #   texlbl = 'N_{n,m}'
     if len(args)==1 and isinstance(args[0],Node):
         node = args[0]
     else:
         node = Node(*args,**kwargs)
     #end if
     name = node.get_name()
     self.nodes[name] = node
     self.graph.add_node(node)
Пример #12
0
def RenderSIPCollection(sipGraph, dot=None):
    try:
        from pydot import Node, Edge, Dot
    except:
        import warnings
        warnings.warn("Missing pydot library", ImportWarning)
    if not dot:
        dot = Dot(graph_type='digraph')
        dot.leftNodesLookup = {}
    nodes = {}
    for N, prop, q in sipGraph.query(
            'SELECT ?N ?prop ?q {  ?prop a magic:SipArc . ?N ?prop ?q . }',
            initNs={u'magic': MAGIC}):

        if MAGIC.BoundHeadPredicate in sipGraph.objects(subject=N,
                                                        predicate=RDF.type):
            NCol = [N]
        else:
            NCol = Collection(sipGraph, N)

        if q not in nodes:
            newNode = Node(makeMD5Digest(q),
                           label=normalizeTerm(q, sipGraph),
                           shape='plaintext')
            nodes[q] = newNode
            dot.add_node(newNode)

        bNode = BNode()
        nodeLabel = ', '.join([normalizeTerm(term, sipGraph) for term in NCol])
        edgeLabel = ', '.join([
            var.n3() for var in Collection(
                sipGraph, first(sipGraph.objects(prop, MAGIC.bindings)))
        ])
        markedEdgeLabel = ''
        if nodeLabel in dot.leftNodesLookup:
            bNode, leftNode, markedEdgeLabel = dot.leftNodesLookup[nodeLabel]


#            print "\t",nodeLabel,edgeLabel, markedEdgeLabel,not edgeLabel == markedEdgeLabel
        else:
            leftNode = Node(makeMD5Digest(bNode),
                            label=nodeLabel,
                            shape='plaintext')
            dot.leftNodesLookup[nodeLabel] = (bNode, leftNode, edgeLabel)
            nodes[bNode] = leftNode
            dot.add_node(leftNode)

        if not edgeLabel == markedEdgeLabel:
            edge = Edge(leftNode, nodes[q], label=edgeLabel)
            dot.add_edge(edge)
    return dot
Пример #13
0
def plot_tree(sent_id):
    global sentences

    graph = Dot(graph_type='digraph')

    basic_dependencies = sentences[sent_id].findall(
        "./dependencies[@type='collapsed-dependencies']/dep")
    for dep in basic_dependencies:

        gov = "{}\n{}".format(dep[0].get("idx"), dep[0].text)
        dep = "{}\n{}".format(dep[1].get("idx"), dep[1].text)
        graph.add_node(Node(gov))
        graph.add_node(Node(dep))
        graph.add_edge(Edge(dep, gov))
    graph.write_png(f"sentence_{sent_id}.png")
Пример #14
0
    def draw(self, path: str, format: str = "raw") -> None:

        node_aggr = {}
        for node in self._nodes:
            level = node.get_level()
            label = node.get_label()
            identifier = node.get_id()
            if node_aggr.get(level) is None:
                node_aggr[level] = {}
            if level != 0:
                gv_cluster = GVCluster(identifier)
                gv_cluster.set("label", label)
                node_aggr[level][identifier] = gv_cluster
            else:
                gv_node = GVNode(identifier)
                gv_node.set("label", label)
                node_aggr[level][identifier] = gv_node

        gv_dot = GVDot()
        gv_dot.set("ranksep", "1.0 equally")

        if self._lable is not None:
            gv_dot.set("label", self._lable)

        for node in self._nodes:
            level = node.get_level()
            parent = node.get_parent()
            parent_level = node.get_parent_level()
            identifier = node.get_id()
            if level != 0:
                if parent is not None:
                    node_aggr[parent_level][parent].add_subgraph(node_aggr[level][identifier])
                else:
                    gv_dot.add_subgraph(node_aggr[level][identifier])
            else:
                if parent is not None:
                    node_aggr[parent_level][parent].add_node(node_aggr[level][identifier])
                else:
                    gv_dot.add_node(node_aggr[level][identifier])

        for edge in self._edges:
            label = edge.get_label()
            gv_edge = GVEdge(edge.get_src(), edge.get_dst())
            if label is not None:
                gv_edge.set("label", edge.get_label())
            gv_dot.add_edge(gv_edge)

        gv_dot.write(path, format=format)
Пример #15
0
def visualize_fpta(red):
    red_sorted = sorted(list(red), key=lambda x: len(x.prefix))
    graph = Dot('fpta', graph_type='digraph')

    for i, r in enumerate(red_sorted):
        r.state_id = f'q{i}'
        graph.add_node(Node(r.state_id, label=r.state_id))

    for r in red_sorted:
        for i, c in r.children.items():
            graph.add_edge(Edge(r.state_id, c.state_id, label=i))

    graph.add_node(Node('__start0', shape='none', label=''))
    graph.add_edge(Edge('__start0', red_sorted[0].state_id, label=''))

    return graph
Пример #16
0
    def add_annotation(graph, node, label, color='lightblue'):
        """Add a graph node that serves as an annotation to a normal node.
       More than one annotation can be added to the same normal node."""
        subg_name = node + '_annotations'

        def get_subgraph(graph, name):
            """Equivalent to pydot.Graph.get_subgraph() when there is no more than
         one subgraph of the given name, but working aroung a bug in
         pydot.Graph.get_subgraph()."""
            for subg in graph.get_subgraph_list():
                if subg.get_name() == name:
                    return subg
            return None

        g = get_subgraph(graph, subg_name)
        if not g:
            g = pydot.Subgraph(subg_name, rank='same')
            graph.add_subgraph(g)

        ann_node = node + '_'
        while g.get_node(ann_node):
            ann_node = ann_node + '_'
        g.add_node(
            Node(ann_node,
                 shape='box',
                 style='filled',
                 color=color,
                 label='"' + label + '"'))
        g.add_edge(
            Edge(ann_node,
                 node,
                 style='solid',
                 color=color,
                 dir='none',
                 constraint='false'))
Пример #17
0
    def OnNode(self, node: pydot.Node) -> typing.Dict[str, typing.Any]:
        for region in self.regions.values():
            if node.get_name() in [str(r)[:-1] for r in region
                                   ]:  # Need to cut off semicolon
                return {"polyhedral": True}

        return {"polyhedral": False}
Пример #18
0
def get_session_svg(viz_data):
    """Take session visualization data and return svg."""

    graph = Dot('graphname', graph_type='digraph')

    #loop create all nodes and store by id
    node_dict = {}
    for i, node_data in enumerate(viz_data['nodes']):
        id = node_data['id']
        node_dict[id] = str(i)
        graph.add_node(Node(str(i)))

    #add edges by links
    for link_data in viz_data['links']:
        snode = node_dict[viz_data['nodes'][link_data['source']]['id']]
        tnode = node_dict[viz_data['nodes'][link_data['target']]['id']]
        graph.add_edge(Edge(snode, tnode))

    #get svg of graph
    file = NamedTemporaryFile()
    graph.write_svg(file.name)
    svg = file.read()
    file.close()

    #f = open('/tmp/session/session.svg', 'w')
    #f.write("%s\n" % svg)
    #f.close()

    return svg
Пример #19
0
    def visualize(self, filename):
        """Save a graphical representation of this AF."""
        graph = Dot(graph_type='digraph')

        for arg in self.args:
            text = arg.text

            # Add any offers to the text that this argument may support
            for off, supp in self.supp_args.items():
                if arg in supp:
                    text += f"\n[{off}]"

            graph.add_node(Node(name=text))

        for att in self.attacks:
            texts = []

            for arg in [att.arg_start, att.arg_end]:
                texts.append(arg.text)

                for off, supp in self.supp_args.items():
                    if arg in supp:
                        texts[-1] += f"\n[{off}]"
            if att.arg_start not in self.args or \
                    att.arg_end not in self.args:
                print(f"Warning: attack in AF but not its start or end")

            graph.add_edge(Edge(texts[0], texts[1], dirType="forward"))

        graph.write_png(filename)
def add_node(graph,
             node_name,
             label,
             shape='record',
             style='filled',
             fillcolor='lightgrey'):
    """
       Add a node to a graph or subgraph
       
       :param graph: graph or subgraph to which the node is added
       :param node_name: name of the node
       :param label: label of the node
       :param shape: shape of the node (default "record")
       :param style: style of the node (default "field")
       :param fillcolor: color of the node (default "lightgrey")
       :return: the node created
       :rtype: Node
    """
    node = Node(name=node_name,
                shape=shape,
                style=style,
                fillcolor=fillcolor,
                label=label)
    graph.add_node(node)
    return node
Пример #21
0
 def draw(self, prob, targetFile):
     # Do the graphing stuff here...
     # Root graph
     g = Dot(graph_type="digraph", nodesep=2, overlap=False)
     #g.set_edge_defaults(weight="0", minlen="10")
     # Organise by adding constraints (adds edges too)
     for constr in prob.constrs:
         # Node for constraint
         constrNode = Node(constr.name, shape="ellipse", style="filled", fillcolor = "#aaaaff")
         constrNode.set_label(constr.name + ": " + constr.getTextFormula())
         g.add_node(constrNode)
         # Associated expressions
         for expr in constr.exprs:
             self.addNodesForChildren(g, expr, constr)
     # Finally, render
     #g.write_png("problem_structure.png", prog="dot")
     g.write_png(targetFile, prog="neato")
Пример #22
0
 def mk_merge_target(graph, target_node, important):
     """Add a merge target node to the graph."""
     if important:
         color = 'red'
     else:
         color = 'black'
     graph.add_node(
         Node(target_node, color=color, fontcolor=color, style='bold'))
Пример #23
0
    def _create_node(self, bb, name, print_ir, options):
        bb_dump = self._render_bb(bb, name, print_ir, options)
        bb_type = bb_get_type(bb)

        return Node(bb.address,
                    label=bb_dump,
                    color=self.node_color[bb_type],
                    **self.node_format)
Пример #24
0
 def start_graph(g, node, parent_node_name=None):
     g.add_node(
         Node(name=node.getNodeNum(),
              shape='plaintext',
              label=node.getLabel()))
     if parent_node_name:
         g.add_edge(Edge(parent_node_name, node.getNodeNum()))
     if len(node.getKids()) > 0:
         for kid in node.getKids():
             start_graph(g, kid, node.getNodeNum())
     else:
         g.add_node(
             Node(name=f'{node.getNodeNum()}_content',
                  shape='plaintext',
                  label=node.getContent()))
         g.add_edge(
             Edge(node.getNodeNum(), f'{node.getNodeNum()}_content'))
Пример #25
0
    def save(self, filename, print_ir=False, format='dot'):
        """Save basic block graph into a file.
        """
        node_format = {
            'shape': 'Mrecord',
            'rankdir': 'LR',
            'fontname': 'monospace',
            'fontsize': '9.0'
        }

        edge_format = {'fontname': 'monospace', 'fontsize': '8.0'}

        edge_colors = {'taken': 'green', 'not-taken': 'red', 'direct': 'blue'}

        try:
            # for each conneted component
            for idx, gr in enumerate(
                    networkx.connected_component_subgraphs(
                        self._graph.to_undirected())):
                graph = Dot(graph_type="digraph", rankdir="TB")

                # add nodes
                nodes = {}
                for bb_addr in gr.node.keys():
                    dump = self._dump_bb(self._bb_by_addr[bb_addr], print_ir)

                    # html-encode colon character
                    dump = dump.replace("!", "!")
                    dump = dump.replace("#", "#")
                    dump = dump.replace(":", ":")
                    dump = dump.replace("{", "{")
                    dump = dump.replace("}", "}")

                    label = "{<f0> 0x%08x | %s}" % (bb_addr, dump)

                    nodes[bb_addr] = Node(bb_addr, label=label, **node_format)

                    graph.add_node(nodes[bb_addr])

                # add edges
                for bb_src_addr in gr.node.keys():
                    for bb_dst_addr, branch_type in self._bb_by_addr[
                            bb_src_addr].branches:
                        graph.add_edge(Edge(nodes[bb_src_addr],
                            nodes[bb_dst_addr], label=branch_type, \
                            color=edge_colors[branch_type], **edge_format))

                graph.write("%s_%03d.%s" % (filename, idx, format),
                            format=format)
        except Exception as err:
            import traceback
            import sys
            print("[E] Error loading BARF (%s:%d) : '%s'" %
                  (__name__, sys.exc_traceback.tb_lineno, str(err)))
            print("")
            print(traceback.format_exc())
Пример #26
0
 def bipartite_node(cls, node_name, node_label, node_color):
     node = Node(node_name,
                 label=node_label,
                 fillcolor=node_color,
                 style='filled',
                 penwidth=2,
                 width=0.3,
                 shape='oval',
                 fontsize=11)
     return node
Пример #27
0
 def __init__(self, vertices, use_pydot=False):
     self.__verts__ = vertices
     self.__adjmx__ = [[] for i in range(vertices)]
     self.__arest__ = 0
     if use_pydot:
         self.__graph__ = Dot(graph_type='graph')
         for i in range(vertices):
             self.__graph__.add_node(Node(str(i)))
     else:
         self.__graph__ = None
Пример #28
0
    def graph(self, model_classes):
        graph = Dot(**self.graph_options)
        relations = set()

        # Create nodes from mappers
        mappers = list(map(class_mapper, model_classes))
        for mapper in mappers:
            graph.add_node(
                Node(
                    self.quote(mapper),
                    label=self.node_table(
                        mapper.class_.__name__,
                        self._model_columns(mapper),
                        self._model_operations(mapper),
                    ),
                    **self.style["node"],
                )
            )
            if mapper.inherits:
                graph.add_edge(
                    Edge(
                        *map(self.quote, (mapper.inherits, mapper)),
                        **self.style["inheritance"],
                    )
                )
            for loader in mapper.iterate_properties:
                if (
                    isinstance(loader, RelationshipProperty)
                    and loader.mapper in mappers
                ):
                    reverse = getattr(loader, "_reverse_property")
                    if len(reverse) == 1:
                        relations.add(frozenset((loader, next(iter(reverse)))))
                    else:
                        relations.add((loader,))

        # Create edges from relationships between mappers
        for relation in relations:
            options = self.style["relationship"].copy()
            if len(relation) == 2:
                src, dest = relation
                if src.viewonly and dest.viewonly:
                    options.update(self.style["relationship-viewonly"])
                between = src.parent, dest.parent
                options["headlabel"] = self._format_relationship(src)
                options["taillabel"] = self._format_relationship(dest)
                options["dir"] = "both"
            else:
                (prop,) = relation
                between = prop.parent, prop.mapper
                options["headlabel"] = self._format_relationship(prop)
                if prop.viewonly:
                    options.update(self.style["relationship-viewonly"])
            graph.add_edge(Edge(*map(self.quote, between), **options))
        return graph
Пример #29
0
def main():
    g = pydot.Dot('manifolds', graph_type='digraph')

    only_direct = True

    for m in all_manifolds:
        g.add_node(Node(str(m), rank=m.dimension))

    for m in all_manifolds:
        for m2, rel in m._embedding.items():

            steps = rel.steps
            direct = len(steps) == 1

            if only_direct and not direct: continue

            color = embedding_type2color(rel.type)
            g.add_edge(Edge(Node(str(m)), Node(str(m2)), color=color))

        for m2, rel in m._isomorphisms.items():

            steps = rel.steps
            direct = len(steps) == 1

            color = isomorphism_type2color(rel.type)
            if only_direct and not direct: continue

            if id(m) < id(m2):
                g.add_edge(
                    Edge(Node(str(m)),
                         Node(str(m2)),
                         color=color,
                         undirected=True,
                         dir='none'))
                #g.add_edge(Edge(Node(str(m)), Node(str(m2)), color='red'))

    out = 'manifolds.dot'
    print('Writing to %r' % out)
    g.write(out)
    cmd = 'dot manifolds.dot -T png -o manifolds.png'
    print('$ %s' % cmd)
    os.system(cmd)
Пример #30
0
    def _create_node(self, cfg_addr, cf):
        if cfg_addr != "unknown":
            if cfg_addr in cf._cfg_by_addr and not isinstance(cf._cfg_by_addr[cfg_addr], str) and cf._cfg_by_addr[cfg_addr].name:
                cfg_label = cf._cfg_by_addr[cfg_addr].name
            else:
                cfg_label = "sub_{:x}".format(cfg_addr)
        else:
            cfg_label = "unknown"

        label = self.node_tpl.format(label=cfg_label)

        return Node(cfg_addr, label=label, **self.node_format)
Пример #31
0
    def IsExitNode(node: pydot.Node) -> bool:
        """Determine if the given node is an exit block.

    In LLVM bytecode, an exit block is one in which the final instruction begins
    with 'ret '. There should be only one exit block per graph.
    """
        label = node.get_attributes().get('label', '')
        # Node labels use \l to escape newlines.
        label_lines = label.split('\l')
        # The very last line is just a closing brace.
        last_line_with_instructions = label_lines[-2]
        return last_line_with_instructions.lstrip().startswith('ret ')
Пример #32
0
 def addNodesForChildren(self, g, expr, parent):
     if expr.isComposite():
         # If it's its own composite expression
         # Add a node
         #exprNode = Node(expr.name, shape="box", style="filled", fillcolor="#aaffaa")
         #g.add_node(exprNode)
         # Add nodes for children recursively...
         for childexpr in expr.getChildren():
             self.addNodesForChildren(g, childexpr, parent)
     else: # Not composite - just a variable
         # Add a node for a value
         # Colour depending on type
         if isinstance(expr,ScalarVariable):
             exprNode = Node(expr.name, shape="box", style="filled")
             exprNode.set_fillcolor("#ffaaaa")
             g.add_node(exprNode)
             # Lastly, add an edge to the expression node
             g.add_edge(Edge(expr.name, parent.name))
         else:
             #exprNode.set_fillcolor("#ffffaa")
             pass
Пример #33
0
        def add_node_rek(node):
            """Recurses through the workflow graph and adds nodes and edges.
            Repeated nodes are ignored (cycle detection).
            :type node: core.tree.Node
            """
            name = node.getName()
            if name in known_nodes:
                return known_nodes[name]
            dot_node = Node(name=name)
            g.add_node(dot_node)
            known_nodes[name] = dot_node
            logg.debug("created node %s", name)
            try:
                true_next_id = node.getTrueId()
            except:
                true_next_id = None
            if true_next_id:
                true_next = workflow.getStep(true_next_id)
                true_dot_next = add_node_rek(true_next)
                true_label = node.getTrueLabel() or " "
                g.add_edge(true_edge(dot_node, true_dot_next,
                                     label=true_label))
                logg.debug("created True edge: %s -> %s", name, true_next_id)
            try:
                false_next_id = node.getFalseId()
            except:
                false_next_id = None
            if false_next_id:
                false_next = workflow.getStep(false_next_id)
                false_dot_next = add_node_rek(false_next)
                false_label = node.getFalseLabel() or " "
                g.add_edge(
                    false_edge(dot_node, false_dot_next, label=false_label))
                logg.debug("created False edge: %s -> %s", name, false_next_id)

            if not (true_next_id or false_next_id):
                # end node with no connections
                dot_node.set("color", "#04B45F")
            return dot_node
Пример #34
0
    def __init__(self, ipdests, node_seq, **argv):
        assert( type(ipdests)== types.TupleType or type(ipdests)== types.ListType )
        self.node_seq = node_seq
        # default attribute
        attr = dict(
                autoack = '"False"',
                ipdests = '"' + ' '.join(ipdests) + '"',
                mod_num = '0',
                traffic = ''
                )
        obj_dict = {'attributes': attr,
                'name': 'n'+str( self.node_seq ),
                'parent_node_list': None,
                'port': None,
                'sequence': 1,
                'type': 'node'}

        Node.__init__(self, name = 'n'+str(self.node_seq), obj_dict = obj_dict)

        self.ipdests = ipdests
        self.mod_num = 0
        self.modulator = dict()
        self.generator = dict()
Пример #35
0
        def add_node_rek(node):
            """Recurses through the workflow graph and adds nodes and edges.
            Repeated nodes are ignored (cycle detection).
            :type node: core.tree.Node
            """
            name = node.getName()
            if name in known_nodes:
                return known_nodes[name]
            dot_node = Node(name=name)
            g.add_node(dot_node)
            known_nodes[name] = dot_node
            logg.debug("created node %s", name)
            try:
                true_next_id = node.getTrueId()
            except:
                true_next_id = None
            if true_next_id:
                true_next = workflow.getStep(true_next_id)
                true_dot_next = add_node_rek(true_next)
                true_label = node.getTrueLabel() or " "
                g.add_edge(true_edge(dot_node, true_dot_next, label=true_label))
                logg.debug("created True edge: %s -> %s", name, true_next_id)
            try:
                false_next_id = node.getFalseId()
            except:
                false_next_id = None
            if false_next_id:
                false_next = workflow.getStep(false_next_id)
                false_dot_next = add_node_rek(false_next)
                false_label = node.getFalseLabel() or " "
                g.add_edge(false_edge(dot_node, false_dot_next, label=false_label))
                logg.debug("created False edge: %s -> %s", name, false_next_id)

            if not (true_next_id or false_next_id):
                # end node with no connections
                dot_node.set("color", "#04B45F")
            return dot_node
Пример #36
0
 def generateGraphNode(self, idx):
     vertex = Node(idx, label='"%s"' % repr(self), shape='box')
     vertex.shape = 'plaintext'
     return vertex
Пример #37
0
def generateBGLNode(dot, node, namespace_manager, identifier):
    from FuXi.Rete import ReteNetwork, BetaNode, BuiltInAlphaNode, AlphaNode
    from .BetaNode import LEFT_MEMORY, RIGHT_MEMORY

    vertex = Node(identifier)

    shape = "circle"
    root = False
    if isinstance(node, ReteNetwork):
        root = True
        peripheries = "3"
    elif isinstance(node, BetaNode) and not node.consequent:
        peripheries = "1"
        if node.fedByBuiltin:
            label = "Built-in pass-thru\\n"
        elif node.aPassThru:
            label = "Pass-thru Beta node\\n"
        elif node.commonVariables:
            label = "Beta node\\n(%s)" % (",".join(["?%s" % i for i in node.commonVariables]))
        else:
            label = "Beta node"
        if not node.fedByBuiltin:
            leftLen = node.memories[LEFT_MEMORY] and len(node.memories[LEFT_MEMORY]) or 0
            rightLen = len(node.memories[RIGHT_MEMORY])
            label += "\\n %s in left, %s in right memories" % (leftLen, rightLen)

    elif isinstance(node, BetaNode) and node.consequent:
        # rootMap[vertex] = 'true'
        peripheries = "2"
        stmts = []
        for s, p, o in node.consequent:
            stmts.append(
                " ".join(
                    [
                        str(namespace_manager.normalizeUri(s)),
                        str(namespace_manager.normalizeUri(p)),
                        str(namespace_manager.normalizeUri(o)),
                    ]
                )
            )

        rhsVertex = Node(BNode(), label='"' + "\\n".join(stmts) + '"', shape="plaintext")
        edge = Edge(vertex, rhsVertex)
        # edge.color = 'red'
        dot.add_edge(edge)
        dot.add_node(rhsVertex)
        if node.commonVariables:
            inst = node.network.instantiations.get(node, 0)
            label = str(
                "Terminal node\\n(%s)\\n%d instantiations" % (",".join(["?%s" % i for i in node.commonVariables]), inst)
            )
        else:
            label = "Terminal node"
        leftLen = node.memories[LEFT_MEMORY] and len(node.memories[LEFT_MEMORY]) or 0
        rightLen = len(node.memories[RIGHT_MEMORY])
        label += "\\n %s in left, %s in right memories" % (leftLen, rightLen)
        inst = node.network.instantiations[node]
        if inst:
            label += "\\n%s instantiations" % inst

    elif isinstance(node, BuiltInAlphaNode):
        peripheries = "1"
        shape = "plaintext"
        # label = '..Builtin Source..'
        label = repr(node.n3builtin)
        canonicalFunc = namespace_manager.normalizeUri(node.n3builtin.uri)
        canonicalArg1 = namespace_manager.normalizeUri(node.n3builtin.argument)
        canonicalArg2 = namespace_manager.normalizeUri(node.n3builtin.result)
        label = "%s(%s,%s)" % (canonicalFunc, canonicalArg1, canonicalArg2)

    elif isinstance(node, AlphaNode):
        peripheries = "1"
        shape = "plaintext"
        # widthMap[vertex] = '50em'
        label = " ".join(
            [isinstance(i, BNode) and i.n3() or str(namespace_manager.normalizeUri(i)) for i in node.triplePattern]
        )

    vertex.set_shape(shape)
    vertex.set_label('"%s"' % label)
    vertex.set_peripheries(peripheries)
    if root:
        vertex.set_root("true")
    return vertex
Пример #38
0
def get_node(name):
    # modify to accept orm_nodes
    node = GNode(cleanup(name))
    orm_node = Node.objects.select_related().get(name=name)
    node.set_URL('/node/'+name)
    tooltip = '/n'.join(orm_node.description.splitlines())    
    node.set_tooltip(tooltip)
    node.set_target('_parent')
    color = getattr(orm_node.node_type,"color","lightblue")
    shape = getattr(orm_node.node_type,"shape","box")    
    node.set_color(color)
    node.set_shape(shape)
    node.set_style('filled')
    return node
Пример #39
0
    def _get_dot(self, myndnode, style=False):
        assert type(myndnode) == MYndMapNode

        formatted_text = self._get_formatted_text(myndnode.rtf_note)

        dot = Node(formatted_text,
                   label=formatted_text,
                   shape=self._dot_config['shape'])

        if not self._dot_config['style'] is None:
            dot.add_style(self._dot_config['style'])

        if self._dot_config['color']:
            dot.set_color(myndnode.color)

        if self._dot_config['fillcolor']:
            dot.set_fillcolor(GraphVizPlot.LIGHT_COLORS[myndnode.color])

        if not self._dot_config['fontname'] is None:
            dot.set_fontname(self._dot_config['fontname'])

        if not self._dot_config['fontsize'] is None:
            dot.set_fontsize(self._dot_config['fontsize'])

        return dot
Пример #40
0
 def to_node(self):
     node = Node(self.uri)
     node.set_label( self.label_for_properties() )
     return node