def generate_table_mapping_diagram(mapping_config):
    graph = Digraph("Imposm Mapping", format="png", graph_attr={"rankdir": "LR", "ranksep": "3"})

    for table in find_tables(mapping_config):
        graph.subgraph(generate_mapping_subgraph(table))

    graph.render(filename="mapping_graph", view=True)
Example #2
0
def visualize(content, target):
    parser = AstParser()
    ast = parser.parse(content, rule_name='ast')
    graph = Digraph(comment=argv[1])
    handle_node(ast, graph)
    handle_edges(ast.edges, graph)
    graph.render(target, view=False)
Example #3
0
def main(argv):

    print("Generating graph...")

    parser = argparse.ArgumentParser(description='Create a dot representation of the give mistral workflow file')
    parser.add_argument('--file', required=True, help='Path to workflow file')
    parser.add_argument('--output', required=True, help='Path to output file')
    parser.add_argument('--format', required=False, help='Format of output file', default="png")

    args = parser.parse_args()

    with open(args.file, "r") as f:
        workflow = yaml.load(f)

    tasks = workflow["workflows"]["main"]["tasks"]

    dot = Digraph(comment='Workflow description', format=args.format)
    for key in tasks:
        task = tasks[key]
        dot.node(key)
        add_success_edges(dot, key, task)
        add_error_edges(dot, key, task)
        add_on_complete_edges(dot, key, task)

    dot.render(args.output)
Example #4
0
 def getDotObject(self):
     dot = Digraph(format=self.outputFormat)
     for node in self.programProcessor.allNodes:
         dot.node(node.name, node.text,shape=node.shape)
     for edge in self.programProcessor.allEdges:
         dot.edge(edge.frm, edge.to,color=edge.color,label=edge.label)
     self.dot = dot
Example #5
0
def generateGraph(items):
    """
    Generates and renders a dependency graph for the class items being passed in
    TODO Handle equivalencies nicely, currently just ignoring
    TODO Generate subgraphs with same rank for semesters and have an invisible edge between them
         to force vertical alignment
    """
    nodes = []
    edges = []
    for item in items:
        if not item["completed"]:
            for prereqs in item["prereqs"]:
                for prereq in prereqs["codes"]:
                    edges.append(((prereq, item["code"]), {"weight": "4", "penwidth": "1"}))
            for coreqs in item["coreqs"]:
                for coreq in coreqs["codes"]:
                    edges.append(((coreq, item["code"]), {"style": "dashed", "constraint": "false", "weight": "6", "penwidth": "1"}))
        found = False
        for node in nodes:
            if node[0] == item["code"]:
                found = True
        if not found:
            if INCLUDE_DESC:
                if item["completed"]:
                    nodes.append((item["code"], {"label": item["code"] + ' ' + item["name"] + '\n' +  item["description"] 
                                                                   + ' ' + str(item["hours"]) + " semester hours.",
                                                 "fillcolor": "gray", "style": "filled", "fontsize": "24", "height": "1.5",
                                                 "width": "8.5", "fixedsize": "shape"}))
                else:
                    nodes.append((item["code"], {"label": item["code"] + ' ' + item["name"] + '\n' +  item["description"] 
                                                                   + ' ' + str(item["hours"]) + " semester hours.",
                                                 "fontsize": "12"}))
            else:
                if item["completed"]:
                    nodes.append((item["code"], {"label": item["code"] + ' ' + item["name"], "fillcolor": "gray",
                                                 "style": "filled", "fontsize": "11"}))
                else:
                    nodes.append((item["code"], {"label": item["code"] + ' ' + item["name"], "fontsize": "11"}))
    courseList = sortGraph(items, edges)
    dot = Digraph(format="pdf",graph_attr = {"splines": "ortho", "autosize": "false", "size": "17,11", "scale": "1.0", "dpi": "300", 
                                             "landscape": "true", "fontsize": "24", 
                                             "page": "8.5,11", "ranksep": str(30/float(len(courseList)))+" equally", "margin": "0.1",
                                             "pad": "0.1", "conentrate": "false", "voro_margin": "0.0"})
    for i,courses in enumerate(courseList):
        tNodes = []
        tDot = Digraph("cluster_"+str(i), graph_attr={"rank": "same", "label": "Semester "+str(i+START_SEMESTER), "style": "rounded", "penwidth": "3"})
        #tDot = Digraph(graph_attr={"rank": "same", "label": "Semester "+str(i+START_SEMESTER), "style": "rounded", "penwidth": "3"})
        for node in nodes:
            for course in courses:
                if course == node[0]:
                    tNodes.append(node)
        tDot = add_nodes(tDot, tNodes)
        dot.subgraph(tDot)
        #dot = add_nodes(dot, tNodes)
        if i > 0:
            edges.append(((courseList[i-1][0], courseList[i][0]), {"style": "invis", "weight": "100"}))
    dot = add_edges(dot, edges)
    with open("DegreePlan.dot", 'w') as dotOut:
        print(dot.source, file=dotOut)
    dot.render(view=True)
def init_graph():
    "init the graph and image panel"
    dot = Digraph()
    dot.name = "topology"
    dot.format = "gif"
    dot.filename = "zigbee_topology"
    return dot
Example #7
0
def plot_trail(trail):

    graph = Digraph()
    graph.attr('node', shape='box', fontsize='12', penwidth='1.0', color='#888888', style='rounded')
    
    c = count()

    def _make_graph(trail):
        if isinstance(trail, Call):
            # We need to make a node
            node = str(c.next())
            graph.node(node, format_args(trail))

            for a in trail.args:
                if isinstance(a, Call):
                    parent = _make_graph(a)
                    graph.edge(parent, node)

            for v in trail.kwargs.values():
                if isinstance(v, Call):
                    parent = _make_graph(v)
                    graph.edge(parent, node)

            return node

    _make_graph(trail)
    return graph
def proc(file_path):
    fp = open(file_path, 'r')
    cont = fp.read()
    fp.close()
    cont_dict = json.loads(cont)
    calls = cont_dict["calls"]
    calls_filter = []
    for i in calls:
        if i["category"] == "system":
            pass
        else:
            calls_filter.append(i["api"])

    dot = Digraph(comment="cuckoolog")
    last = None
    j = 0
    edges = set()
    for i in calls_filter:
        if last == None:
            last = i
        else:
            if last+i in edges:
                pass
            else:
                edges.add(last+i)
                dot.edge(last,i,label=str(j))
                j += 1
            last = i

    dot.render("cfg/"+file_path+'.gv', view=False)
Example #9
0
 def render(self, filename):
     '''Create a PDF image of the tree.'''
     dot = Digraph()
     self.root.render(dot)
     dot.render(filename)
     os.remove(filename)
     os.rename(filename + '.pdf', filename)
def build_visualization():
    print('Building schema documentation...')

    # Load directory tree info
    bin_dir = os.path.dirname(os.path.realpath(__file__))
    root_dir = os.path.join(os.path.abspath(
        os.path.join(bin_dir, os.pardir, os.pardir)))

    # Create graph
    dot = Digraph(
        comment="High level graph representation of GDC data model", format='pdf')
    dot.graph_attr['rankdir'] = 'RL'
    dot.node_attr['fillcolor'] = 'lightblue'
    dot.node_attr['style'] = 'filled'

    # Add nodes
    for node in m.Node.get_subclasses():
        label = node.get_label()
        print label
        dot.node(label, label)

    # Add edges
    for edge in m.Edge.get_subclasses():
        if edge.__dst_class__ == 'Case' and edge.label == 'relates_to':
            # Skip case cache edges
            continue

        src = m.Node.get_subclass_named(edge.__src_class__)
        dst = m.Node.get_subclass_named(edge.__dst_class__)
        dot.edge(src.get_label(), dst.get_label(), edge.get_label())

    gv_path = os.path.join(root_dir, 'docs', 'viz', 'gdc_data_model.gv')
    dot.render(gv_path)
    print('graphviz output to {}'.format(gv_path))
Example #11
0
def build_graph(args):
    stream = open(os.path.dirname(__file__)+"/diagram.yml", "r")
    conf_diagram = yaml.safe_load(stream)
    dia = Digraph('webdevops', filename=args.filename, format=args.format, directory=args.path)
    dia = apply_styles(dia,conf_diagram['diagram']['styles'])
    dia.body.append(r'label = "\n\nWebdevops Images\n at :%s"' % get_current_date() )

    # Create subgraph
    for group, group_attr in conf_diagram['diagram']['groups'].items():
        SUBGRAPH[group] = Digraph("cluster_"+group);
        SUBGRAPH[group].body.append(r'label = "%s"' % group_attr['name'] )
        SUBGRAPH[group] = apply_styles(SUBGRAPH[group],group_attr['styles'] )
    for image, base in CONTAINERS.items():
        graph_image = get_graph(conf_diagram, dia, image)
        graph_base = get_graph(conf_diagram, dia, base)
        if "webdevops" in base:
            if graph_image == graph_base:
                graph_image.edge(base, image)
            else:
                graph_image.node(image)
                EDGES[image] = base
            if args.all :
                attach_tag(graph_image, image)
        else:
            graph_image.node(image)

    for name, subgraph in SUBGRAPH.items():
        dia.subgraph(subgraph)

    for image, base in EDGES.items():
        dia.edge(base, image)
    return dia
Example #12
0
    def generate_graph(self, rule_links, out_file):
        graph_label = 'Rule based visualizer'

        graph_attr = {
            'rankdir': 'TD',
            'labelloc': 't',
            'fontsize': '15',
            'label': graph_label
        }
        node_attr = {}
        dot = Digraph(comment='Rule based links visualization',
                      node_attr=node_attr, graph_attr=graph_attr, format='png')

        nodes = set()
        for _, rule_link in rule_links:
            print(rule_link._source_action_ref)
            if rule_link._source_action_ref not in nodes:
                nodes.add(rule_link._source_action_ref)
                dot.node(rule_link._source_action_ref, rule_link._source_action_ref)
            if rule_link._dest_action_ref not in nodes:
                nodes.add(rule_link._dest_action_ref)
                dot.node(rule_link._dest_action_ref, rule_link._dest_action_ref)
            dot.edge(rule_link._source_action_ref, rule_link._dest_action_ref, constraint='true',
                     label=rule_link._rule_ref)
        output_path = os.path.join(os.getcwd(), out_file)
        dot.format = 'png'
        dot.render(output_path)
Example #13
0
 def get_formatted_fields(self, type_name: str, schema: dict, group: Digraph) -> list:
     resulting_fields = []
     for field in self.get_fields(schema, schema_name=type_name):
         name = field['name']
         if 'reference' in field:
             if field['type'] == 'list':
                 head_label = '*' if field['attr']['Required'] else '1..*'
             else:
                 head_label = '1' if field['attr']['Required'] else '0..1'
             group.edge(type_name, field['reference'], headlabel=head_label, taillabel='*', label=field['name'])
         else:
             field['name'] = '*' + name if field['attr']['Unique'] else name
             resulting_field = '+ {}'.format(field['name'])
             if len(field['attr']['Allowed'] or []) > 0:
                 enum_name = '{}Enum'.format(name)
                 group.node(enum_name, '{{{}Enum\lEnum|{}}}'.format(name, '\l'.join(map(str, field['attr']['Allowed']))))
                 resulting_field += ': {}'.format(enum_name)
             else:
                 resulting_field += ': {}'.format(field['type'])
             resulting_field += ' [0..1]' if not field['attr']['Required'] else ''
             resulting_field += ' (write-only)' if field['attr']['Write only'] else ''
             resulting_field += ' (read-only)' if field['attr']['Read only'] else ''
             resulting_fields.append((resulting_field, field['attr']['Sink']))
     resulting_fields.sort(key=Doc.get_sink, reverse=True)
     return [resulting_field[0] for resulting_field in resulting_fields]
Example #14
0
def render_forest(trees):
    """
    Renders a (parse) tree forest using graphiz
    Args:
        trees: list of recursive tree structure: tuple (node_label, children_nodes)
               for non-terminals or a string for terminals.

    Returns:
        the Digraph object representing the forest. Can be rendered in notebook.
    """
    nodes = []
    edges = []

    def collect_graph(current):
        if isinstance(current, tuple):
            children = [collect_graph(child) for child in current[1]]
            node_id = str(len(nodes))
            nodes.append((node_id, current[0]))
            for child_id, _ in children:
                edges.append((node_id, child_id))
        else:
            node_id = str(len(nodes))
            nodes.append((node_id, current))
        return nodes[-1]

    for tree in trees:
        collect_graph(tree)
    dot = Digraph(comment='The Round Table')
    for node_id, node_label in nodes:
        dot.node(node_id, node_label)
    for arg1_id, arg2_id in edges:
        dot.edge(arg1_id, arg2_id)

    return dot
Example #15
0
    def generate_graph(self, seed, render):
        """ Create graph by connecting adjacent nodes """

        self.sensored_cnt = 0

        # Ensure the generated file indicates nsfw or not
        filename = seed + '_d' + str(self.depth)
        filename = os.path.join(self.output_path, filename)
        if self.nsfw:
            filename += '_nsfw'

        g = Digraph('G', format='png', filename=filename + '.gv')

        sub = self.query_db(seed)
        if not sub:
            return ('Failure', 'Subreddit not in database, please try another subreddit')
        seed_cnt = sub['subscribers']

        if sub['up_links'] != []:
            g = self.add_edges(g, seed, self.depth, up=True, reverse=False)

        self.msg("Traversing up, then down")
        up_links = sub['up_links']
        for item in up_links:
            # Ignore if a referrer does not have 20% subscribers
            # Prevent very small subs from clustering about a huge one
            # subreddit = self.query_db(item)
            # if subreddit['subscribers'] < (seed_cnt * 0.2):
            #     continue
            g = self.add_edges(g, item, self.depth - 1, up=True, reverse=True)

        self.msg("Travsering straight down")
        if sub['down_links'] != []:
            g = self.add_edges(g, seed, self.depth)

        if not len(self.edges):
            return ('Failure', 'Graph is empty, please try another subreddit')

        if self.censored_cnt >= 1:
            self.msg('# of NSFW nodes removed: ' + str(self.censored_cnt))

        # Draw graphviz graph
        if render:
            # Save graphviz file
            g.save()
            g.render(view=True)

        # Save json for D3
        filename = filename + '.json'
        with open(filename, "wt") as d3:
            print('{"nodes":[', end="", file=d3)
            print(', '.join(self.d3_node_list), end="", file=d3)
            print('], "links":[', end="", file=d3)
            print(', '.join(self.d3_edges), end="", file=d3)
            print(']}', end="", file=d3)

        self.cleanup()

        return ('Success', filename)
Example #16
0
def make_graph(url, pages, include_resources=False):
    g = Digraph(comment='Site map generated from {!r}'.format(url))
    for page_url, page in pages.items():
        if isinstance(page, Exception):
            g.node(page_url, label='{} {}'.format(page_url, page), color='red')
        else:
            _process_page(g, page, include_resources)
    return g
Example #17
0
 def createDigraph(self):
      dot = Digraph(comment='The Round Table', \
      node_attr={"shape":"circle"})
     
      dot.append("rankdir=LR;")
      dot.append('size="8,5"')
      
      return dot
Example #18
0
class search_tree():
    def __init__(self):
        self.graph = Digraph()

    def addEdge(self, source, action, target):
        self.graph.edge(source, target, action)

    def getDot(self):
        return self.graph
Example #19
0
 def main(self, args):
     args = self.parse_args(args)
     logging.basicConfig(level=args.loglevel, stream=sys.stdout)
     self._logger.debug("Start graphing...")
     dot = Digraph(node_attr={'shape': 'plaintext'}, comment='Loaded Classes')
     self.graphClassload(dot, args.raw, args.filter, args.abrv)
     self.addLegend(dot)
     dot.render(args.dest, view=True)
     self._logger.info("Ends here")
Example #20
0
 def render(self, filename=None):
     from graphviz import Digraph
     dot = Digraph()
     if self.tree is not None:
         dot.node(str(id(self.tree)), self.tree.obj)
         self._recursive_render(dot, str(id(self.tree)), self.tree)
     if filename is not None:
         dot.render(filename)
     return dot
Example #21
0
    def dibujar(arbol):
        '''
        Construye una representacion grafica del arbol en formato .png
        '''

        dot = Digraph(format='png')

        Dibujante.subDibujar(arbol, dot)
        dot.render('output2.png', view=True)
def main():
  dataset = {
      u'users' : parse_csv('data/user_edges.csv')
  }
  g = Digraph(format='svg')
  for key in dataset:
    draw_graph(key, dataset, g)
    g = apply_styles(g, styles)
    g.render('graph')
Example #23
0
	def generateGraph(self):

		graph = Digraph(comment = 'Case Tress')

		rootNode = CaseNode(self.nodeNumberCounter, [3, 1, 5, 8], 0)

		self._generateGraph(graph, rootNode, 0)

		graph.render(self.filePath)
def generate_table_mapping_diagram(mapping_config):
    graph = Digraph('Imposm Mapping', format='png', graph_attr={
        'rankdir': 'LR',
        'ranksep': '3'
    })

    for table in find_tables(mapping_config):
        graph.subgraph(generate_mapping_subgraph(table))

    graph.render(filename='mapping_graph', view=True)
Example #25
0
def _make_graph(libs):
    graph = Digraph()
    for lib in libs:
        graph.node(lib.name, weight=str(len(lib.dependencies)))

    for lib in libs:
        for dependency in lib.dependencies:
            graph.edge(lib.name, dependency)

    return graph
Example #26
0
def main() :
    if(len(sys.argv) != 2) :
        print "usage:  dir2pic.py PATH"
        return

    dot = Digraph()

    path = sys.argv[1]
    dirwalk(dot,path)
    dot.render("out.gv")
Example #27
0
    def handle(self, *args, **options):
        """ Main command handler. """

        dot = Digraph(name='Job Graph', comment='Job Graph', format='svg',
                      engine='twopi')

        def status_to_color(status):
            return {Job.NEW: 'lightgray',
                    Job.QUEUED: 'yellow',
                    Job.RUNNING: 'lightblue',
                    Job.COMPLETE: 'lightgreen',
                    Job.ERROR: 'red'}[status]

        for job in Job.objects.all():

            jobinfo = "%s&#10;Created: %s" % (str(job.table), job.created)

            dot.node('J-%d' % job.id,
                     style='filled', color=status_to_color(job.status),
                     tooltip=jobinfo)

            if job.parent:
                dot.edge('J-%d' % job.parent.id, 'J-%d' % job.id)

            if job.master:
                dot.edge('J-%d' % job.id, 'J-%d' % job.master.id,
                         style='dashed')

        outfile = options['outfile']
        if outfile.endswith('.svg'):
            outfile = outfile[:-4]
        dot.render(outfile)
        print "Rendered to %s.svg" % outfile
Example #28
0
def visualize_users(quora_data):
    dot = Digraph(comment='Users subgraph', engine='sfdp')
    seen_users = set()
    for document in quora_data:
        username = _get_username(document)
        # Checking if user was already added to the graph
        if username not in seen_users:
            # Adding user to graph as node
            dot.node(username, label=username)
            seen_users.add(username)

    for document in quora_data:
        username = _get_username(document)
        # Traversing over following users and adding edge
        for following in document[username]['following']:
            following_sanitized = _sanitize_username(following)
            if following_sanitized in seen_users:
                dot.edge(username, following_sanitized)
        # Traversing over user's followers
        for follower in document[username]['followers']:
            follower_sanitized = _sanitize_username(follower)
            if follower_sanitized in seen_users:
                dot.edge(follower_sanitized, username)

    dot = _apply_styles(dot, styles)
    # print dot.source
    dot.render(os.path.join('images', 'users.gv'), view=True)
Example #29
0
def display_variant_graph_as_SVG(graph,svg_output,output):
        # create new Digraph
        dot = Digraph(format="svg", graph_attr={'rankdir': 'LR'})
        # add nodes
        counter = 0
        mapping = {}
        for n in graph.graph.nodes():
            counter += 1
            mapping[n] = str(counter)
            # dot.node(str(n), nodedata["label"])
            if output == "svg_simple":
                label = n.label
                if label == '':
                    label = '#'
                dot.node( mapping[n], label )
            else:
                readings = ["<TR><TD ALIGN='LEFT'><B>" + n.label + "</B></TD><TD ALIGN='LEFT'><B>Sigla</B></TD></TR>"]
                reverseDict = defaultdict(list)
                for key,value in n.tokens.items():
                    reverseDict["".join(item.token_data["t"] for item in value)].append(key)
                for key,value in sorted(reverseDict.items()):
                    reading = ("<TR><TD ALIGN='LEFT'><FONT FACE='Bukyvede'>{}</FONT></TD><TD ALIGN='LEFT'>{}</TD></TR>").format(key,', '.join(value))
                    readings.append(reading)
                dot.node(mapping[n], '<<TABLE CELLSPACING="0">' + "".join(readings) + '</TABLE>>',{'shape': 'box'})
        # add edges
        for u,v,edgedata in graph.graph.edges_iter(data=True):
            dot.edge(str(mapping[u]), str(mapping[v]), edgedata["label"])
        # render the dot graph to SVG
        # Note: this creates a file
        if svg_output:
            svg = dot.render(svg_output,'svg_output')
        else:
            svg = dot.render()
        # display using the IPython SVG module
        return display(SVG(svg))
def cli(url, include):
    token = zign.api.get_existing_token('test')
    access_token = token['access_token']

    r = requests.get(url + '/accounts', headers={'Authorization': 'Bearer {}'.format(access_token)})
    accounts = r.json()

    def get_label(account_region):
        parts = account_region.split('/')
        name = accounts.get(parts[0], {}).get('name', parts[0])
        return name

    r = requests.get(url + '/account-connections',
                     params={'include': include},
                     headers={'Authorization': 'Bearer {}'.format(access_token)}, timeout=180)
    data = r.json()
    max_score = 0
    for dest, sources in data.items():
        for row in sources:
            if row['score'] > max_score:
                max_score = row['score']

    graph = Digraph(comment='Account Graph', engine='circo', format='svg')
    for dest, sources in data.items():
        graph.node(dest, label=get_label(dest), style='filled')
        for row in sources:
            source = row['source']
            graph.node(source, label=get_label(source), style='filled')
            graph.edge(source, dest, weight=str(int(row['score'])), penwidth=str(max(0.5, 5 * row['score']/max_score)))

    graph.render('account-graph')
 def get_graph(self, filename):
     g = Digraph('G', filename=filename, format='pdf')
     self.root_node.add_edge(g, "0")
     return g
Example #32
0
    def lnfa_to_dfa(self):
        print("The lambda-NFA statements: ")
        print(states_list)
        print(" \n The symbols: ")
        print(symbols_list)

        self.lnfa = []
        for i in range(states):
            self.lnfa.append(f.readline().split())

        # ----------------------------------------

        # AFISARE
        print("\nThe lambda-NFA table: \n")
        print("States |", *symbols_list, sep='\t')
        print("--------------------------------")
        for i in range(states):
            print(states_list[i] + "      | ", *self.lnfa[i], sep='\t')
        print()
        print("=========================================================")
        # -------------------------------------------------------------

        # lambda closures

        for i in range(states):
            lambda_closures[states_list[i]] = set()
            lambda_closures[states_list[i]].add(states_list[i])

        for i in range(states):
            self.closure(i, i)

        print("\n The lambda-closures: ")
        print(lambda_closures)

        # ---------------------------------------------------------

        # primele n linii ale tabelului

        table = [[set() for j in range(symbols - 1)] for i in range(states)]

        for i in range(states):
            for j in range(symbols - 1):
                adiacent = set()
                for x in lambda_closures[states_list[i]]:
                    if self.lnfa[states_list.index(x)][j] != "-":
                        for k in self.lnfa[states_list.index(x)][j]:
                            adiacent.add(k)
                # print(adiacent)
                new = set()
                for x in adiacent:
                    new = new.union(lambda_closures[x])
                # print(new)
                # print("\n")
                for x in new:
                    table[i][j].add(x)

        symbols_list.pop()
        print()
        print("The intermediate table:")
        print("States |", *symbols_list, sep='                   ')
        print("-------------------------------------------------------------------------------------------")
        for i in range(states):
            print(states_list[i] + "      | ", *table[i], sep='\t')
        print()
        # ------------------------------------------

        # dfa

        dfa = [[]]
        new_states = []
        new_start_state = lambda_closures[start_state]
        new_end_states = []
        current = []

        # print(start_state)
        # print(lambda_closures[start_state])

        new_states.append(lambda_closures[start_state])  # nodul de start

        for i in range(symbols - 1):
            aux = set()
            for x in lambda_closures[start_state]:
                aux = aux.union(table[states_list.index(x)][i])
            if aux != lambda_closures[start_state]:
                dfa[0].append(aux)
                if len(aux) > 0:
                    current.append(aux)
                    new_states.append(aux)
                    # print(aux)

        print("=======================")

        j = 0
        while len(current) > 0:
            j += 1
            dfa.append([])
            for i in range(symbols - 1):
                aux = set()
                # print(current[0])
                for x in current[0]:
                    aux = aux.union(table[states_list.index(x)][i])
                dfa[j].append(aux)
                if aux not in new_states and len(aux) > 0:
                    new_states.append(aux)
                    current.append(aux)
            current.pop(0)

        for x in new_states:
            for y in x:
                if y in end_states:
                    new_end_states.append(x)

        # ----------------------------------------------------------------------



        # Afisare

        print()

        print("THE DFA IS:  ")
        print("New States                       |", *symbols_list, sep='                   ')
        print("-------------------------------------------------------------------------------------------")

        for i in range(j + 1):
            print(new_states[i], "  ->  ", end="")
            print(*dfa[i], sep="      ")

        print()
        print("The start state:  ", new_start_state)
        print("The end states:   ", *new_end_states)
        print()
        print(new_states)
        print(end_states)
        # Grafica

        g = Digraph('DFA', filename='fsm.gv')
        g.attr(rankdir='LR', size='10')
        if new_start_state not in new_end_states:
            g.attr('node', shape='circle', fillcolor="green", style="filled")
            g.node(str(new_states.index(new_start_state)))
        else:
            g.attr('node', shape='doublecircle', fillcolor="green", style="filled")
            g.node(str(new_states.index(new_start_state)))

        g.attr('node', shape='doublecircle', fillcolor="red", style="filled")
        for o in new_end_states:
            g.node(str(new_states.index(o)))

        g.attr('node', shape='circle', fillcolor="white", style="filled")
        for x in new_states:
            if x not in new_end_states and x != new_start_state:
                g.node(str(new_states.index(x)))

        for i in range(j + 1):
            for x in range(len(symbols_list)):
                if dfa[i][x] != set():
                    g.edge(str(i), str(new_states.index(dfa[i][x])), label=symbols_list[x], color="blue", style="filled")

        g.view()
Example #33
0
from graphviz import Digraph

dot = Digraph(comment='The Round Table', format="png", filename="nusa_structure")
dot.edge("NuSA","core")
dot.edge("NuSA","element")
dot.edge("NuSA","model")
dot.edge("NuSA","lib")
dot.edge("NuSA","io")
dot.render()
Example #34
0
def make_dot(var, params=None):
    """ Produces Graphviz representation of PyTorch autograd graph.

    Blue nodes are the Variables that require grad, orange are Tensors
    saved for backward in torch.autograd.Function

    Args:
        var: output Variable
        params: dict of (name, Variable) to add names to node that
            require grad (TODO: make optional)
    """
    if params is not None:
        assert all(isinstance(p, Variable) for p in params.values())
        param_map = {id(v): k for k, v in params.items()}

    node_attr = dict(style='filled',
                     shape='box',
                     align='left',
                     fontsize='12',
                     ranksep='0.1',
                     height='0.2')
    dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
    seen = set()

    def size_to_str(size):
        return '(' + (', ').join(['%d' % v for v in size]) + ')'

    output_nodes = (var.grad_fn, ) if not isinstance(var, tuple) else tuple(
        v.grad_fn for v in var)

    def username(x):
        return f"{x.username if hasattr(x, 'username') else ''}"

    def add_nodes(var):
        if var not in seen:
            if torch.is_tensor(var):
                # note: this used to show .saved_tensors in pytorch0.2, but stopped
                # working as it was moved to ATen and Variable-Tensor merged
                dot.node(str(id(var)),
                         f"{username(var)}\n{size_to_str(var.size())}",
                         fillcolor='orange')
            elif hasattr(var, 'variable'):
                u = var.variable
                name = param_map.get(
                    id(u), username(u)) if params is not None else username(u)
                node_name = '%s\n %s' % (name, size_to_str(u.size()))
                dot.node(str(id(var)), node_name, fillcolor='lightblue')
            elif var in output_nodes:
                dot.node(str(id(var)),
                         str(type(var).__name__),
                         fillcolor='darkolivegreen1')
            else:
                dot.node(str(id(var)), str(type(var).__name__))
            seen.add(var)
            if hasattr(var, 'next_functions'):
                for u in var.next_functions:
                    if u[0] is not None:
                        dot.edge(str(id(u[0])), str(id(var)))
                        add_nodes(u[0])
            if hasattr(var, 'saved_tensors'):
                for t in var.saved_tensors:
                    dot.edge(str(id(t)), str(id(var)))
                    add_nodes(t)
            if hasattr(var, 'grad_fn'):
                dot.edge(str(id(var.grad_fn)), str(id(var)))
                add_nodes(var.grad_fn)

    # handle multiple outputs
    if isinstance(var, tuple):
        for v in var:
            add_nodes(v.grad_fn)
    else:
        add_nodes(var)

    resize_graph(dot)

    return dot
Example #35
0
def _build_graph_simple_model(model, filename, title):

    input_layer = 0
    hidden_layers_nr = 0
    layer_types = []
    hidden_layers = []
    output_layer = 0
    input_count = 0
    for layer in model.layers:
        if (layer == model.layers[0]):
            input_layer = int(str(layer.input_shape).split(",")[1][1:-1])
            hidden_layers_nr += 1
            if (type(layer) == keras.layers.core.Dense):
                hidden_layers.append(
                    int(str(layer.output_shape).split(",")[1][1:-1]))
                layer_types.append("Dense")
            elif (type(layer) == keras.engine.input_layer.InputLayer):
                hidden_layers.append(
                    int(str(layer.output_shape).split(",")[1][1:-1]))
                input_count += 1
                layer_types.append("Dense")
            else:
                hidden_layers.append(1)
                if (type(layer) == keras.layers.convolutional.Conv2D):
                    layer_types.append("Conv2D")
                elif (type(layer) == keras.layers.pooling.MaxPooling2D):
                    layer_types.append("MaxPooling2D")
                elif (type(layer) == keras.layers.core.Dropout):
                    layer_types.append("Dropout")
                elif (type(layer) == keras.layers.core.Flatten):
                    layer_types.append("Flatten")
                elif (type(layer) == keras.layers.core.Activation):
                    layer_types.append("Activation")
        else:
            if (layer == model.layers[-1]):
                output_layer = int(
                    str(layer.output_shape).split(",")[1][1:-1])
            else:
                hidden_layers_nr += 1
                if (type(layer) == keras.layers.core.Dense):
                    hidden_layers.append(
                        int(str(layer.output_shape).split(",")[1][1:-1]))
                    layer_types.append("Dense")
                else:
                    hidden_layers.append(1)
                    if (type(layer) == keras.layers.convolutional.Conv2D):
                        layer_types.append("Conv2D")
                    elif (type(layer) == keras.layers.pooling.MaxPooling2D):
                        layer_types.append("MaxPooling2D")
                    elif (type(layer) == keras.layers.core.Dropout):
                        layer_types.append("Dropout")
                    elif (type(layer) == keras.layers.core.Flatten):
                        layer_types.append("Flatten")
                    elif (type(layer) == keras.layers.core.Activation):
                        layer_types.append("Activation")
                    elif (type(layer) == keras.engine.input_layer.InputLayer):
                        input_count += 1
        last_layer_nodes = input_layer
        nodes_up = input_layer

        if input_count > 1:
            raise ValueError(
                "Model contains multiple input layers, enable multi_input")

        if (type(model.layers[0]) != keras.layers.core.Dense) and (type(
                model.layers[0]) != keras.engine.input_layer.InputLayer):
            last_layer_nodes = 1
            nodes_up = 1
            input_layer = 1

    g = Digraph('g', filename=filename)
    n = 0
    g.graph_attr.update(splines="false", nodesep='1', ranksep='2')
    #Input Layer
    with g.subgraph(name='cluster_input') as c:
        if (type(model.layers[0]) == keras.layers.core.Dense):
            the_label = title + '\n\n\n\nInput Layer'
            if (int(str(model.layers[0].input_shape).split(",")[1][1:-1]) >
                    10):
                the_label += " (+" + str(
                    int(str(model.layers[0].input_shape).split(",")[1][1:-1]) -
                    10) + ")"
                input_layer = 10
            c.attr(color='white')
            for i in range(0, input_layer):
                n += 1
                c.node(str(n))
                c.attr(label=the_label)
                c.attr(rank='same')
                c.node_attr.update(color="#2ecc71",
                                   style="filled",
                                   fontcolor="#2ecc71",
                                   shape="circle")

        elif (type(model.layers[0]) == keras.engine.input_layer.InputLayer):
            the_label = title + '\n\n\n\nInput Layer'
            if (int(str(model.layers[0].input_shape).split(",")[1][1:-1]) >
                    10):
                the_label += " (+" + str(
                    int(str(model.layers[0].input_shape).split(",")[1][1:-1]) -
                    10) + ")"
                input_layer = 10
            c.attr(color='white')
            for i in range(0, input_layer):
                n += 1
                c.node(str(n))
                c.attr(label=the_label)
                c.attr(rank='same')
                c.node_attr.update(color="#2ecc71",
                                   style="filled",
                                   fontcolor="#2ecc71",
                                   shape="circle")

        elif (type(model.layers[0]) == keras.layers.convolutional.Conv2D):
            #Conv2D Input visualizing
            the_label = title + '\n\n\n\nInput Layer'
            c.attr(color="white", label=the_label)
            c.node_attr.update(shape="square")
            pxls = str(model.layers[0].input_shape).split(',')
            clr = int(pxls[3][1:-1])
            if (clr == 1):
                clrmap = "Grayscale"
                the_color = "black:white"
            elif (clr == 3):
                clrmap = "RGB"
                the_color = "#e74c3c:#3498db"
            else:
                clrmap = ""
            c.node_attr.update(fontcolor="white",
                               fillcolor=the_color,
                               style="filled")
            n += 1
            c.node(str(n),
                   label="Image\n" + pxls[1] + " x" + pxls[2] + " pixels\n" +
                   clrmap,
                   fontcolor="white")
        else:
            raise ValueError(
                "ANN Visualizer: Layer not supported for visualizing: {}".
                format(layer))
    for i in range(1, hidden_layers_nr):
        with g.subgraph(name="cluster_" + str(i + 1)) as c:
            if (layer_types[i] == "Dense"):
                c.attr(color='white')
                c.attr(rank='same')
                #If hidden_layers[i] > 10, dont include all
                the_label = ""
                if (int(str(model.layers[i].output_shape).split(",")[1][1:-1])
                        > 10):
                    the_label += " (+" + str(
                        int(
                            str(model.layers[i].output_shape).split(",")[1]
                            [1:-1]) - 10) + ")"
                    hidden_layers[i] = 10
                c.attr(labeljust="right", labelloc="b", label=the_label)
                for j in range(0, hidden_layers[i]):
                    n += 1
                    c.node(str(n),
                           shape="circle",
                           style="filled",
                           color="#3498db",
                           fontcolor="#3498db")
                    for h in range(nodes_up - last_layer_nodes + 1,
                                   nodes_up + 1):
                        g.edge(str(h), str(n))
                last_layer_nodes = hidden_layers[i]
                nodes_up += hidden_layers[i]
            elif (layer_types[i] == "Conv2D"):
                c.attr(style='filled', color='#5faad0')
                n += 1
                kernel_size = str(model.layers[i].get_config(
                )['kernel_size']).split(',')[0][1] + "x" + str(
                    model.layers[i].get_config()['kernel_size']).split(
                        ',')[1][1:-1]
                filters = str(model.layers[i].get_config()['filters'])
                c.node("conv_" + str(n),
                       label="Convolutional Layer\nKernel Size: " +
                       kernel_size + "\nFilters: " + filters,
                       shape="square")
                c.node(str(n),
                       label=filters + "\nFeature Maps",
                       shape="square")
                g.edge("conv_" + str(n), str(n))
                for h in range(nodes_up - last_layer_nodes + 1, nodes_up + 1):
                    g.edge(str(h), "conv_" + str(n))
                last_layer_nodes = 1
                nodes_up += 1
            elif (layer_types[i] == "MaxPooling2D"):
                c.attr(color="white")
                n += 1
                pool_size = str(model.layers[i].get_config()
                                ['pool_size']).split(',')[0][1] + "x" + str(
                                    model.layers[i].get_config()
                                    ['pool_size']).split(',')[1][1:-1]
                c.node(str(n),
                       label="Max Pooling\nPool Size: " + pool_size,
                       style="filled",
                       fillcolor="#8e44ad",
                       fontcolor="white")
                for h in range(nodes_up - last_layer_nodes + 1, nodes_up + 1):
                    g.edge(str(h), str(n))
                last_layer_nodes = 1
                nodes_up += 1
            elif (layer_types[i] == "Flatten"):
                n += 1
                c.attr(color="white")
                c.node(str(n),
                       label="Flattening",
                       shape="invtriangle",
                       style="filled",
                       fillcolor="#2c3e50",
                       fontcolor="white")
                for h in range(nodes_up - last_layer_nodes + 1, nodes_up + 1):
                    g.edge(str(h), str(n))
                last_layer_nodes = 1
                nodes_up += 1
            elif (layer_types[i] == "Dropout"):
                n += 1
                c.attr(color="white")
                c.node(str(n),
                       label="Dropout Layer",
                       style="filled",
                       fontcolor="white",
                       fillcolor="#f39c12")
                for h in range(nodes_up - last_layer_nodes + 1, nodes_up + 1):
                    g.edge(str(h), str(n))
                last_layer_nodes = 1
                nodes_up += 1
            elif (layer_types[i] == "Activation"):
                n += 1
                c.attr(color="white")
                fnc = model.layers[i].get_config()['activation']
                c.node(str(n),
                       shape="octagon",
                       label="Activation Layer\nFunction: " + fnc,
                       style="filled",
                       fontcolor="white",
                       fillcolor="#00b894")
                for h in range(nodes_up - last_layer_nodes + 1, nodes_up + 1):
                    g.edge(str(h), str(n))
                last_layer_nodes = 1
                nodes_up += 1

    with g.subgraph(name='cluster_output') as c:
        if (type(model.layers[-1]) == keras.layers.core.Dense):
            c.attr(color='white')
            c.attr(rank='same')
            c.attr(labeljust="1")
            for i in range(1, output_layer + 1):
                n += 1
                c.node(str(n),
                       shape="circle",
                       style="filled",
                       color="#e74c3c",
                       fontcolor="#e74c3c")
                for h in range(nodes_up - last_layer_nodes + 1, nodes_up + 1):
                    g.edge(str(h), str(n))
            c.attr(label='Output Layer', labelloc="bottom")
            c.node_attr.update(color="#2ecc71",
                               style="filled",
                               fontcolor="#2ecc71",
                               shape="circle")

    g.attr(arrowShape="none")
    g.edge_attr.update(arrowhead="none", color="#707070")
    return g
Example #36
0
def main(metadata_path, output_path, print_source=False):
    metadata_path = os.path.abspath(metadata_path)
    metadata_dir = os.path.dirname(metadata_path)

    meta_loader = MetaLoader()
    data = meta_loader.load(metadata_path)

    action_name = data["name"]
    entry_point = data["entry_point"]

    workflow_metadata_path = os.path.join(metadata_dir, entry_point)
    chainspec = meta_loader.load(workflow_metadata_path)

    chain_holder = ChainHolder(chainspec, "workflow")

    graph_label = "%s action-chain workflow visualization" % (action_name)

    graph_attr = {
        "rankdir": "TD",
        "labelloc": "t",
        "fontsize": "15",
        "label": graph_label,
    }
    node_attr = {}
    dot = Digraph(
        comment="Action chain work-flow visualization",
        node_attr=node_attr,
        graph_attr=graph_attr,
        format="png",
    )
    #  dot.body.extend(['rankdir=TD', 'size="10,5"'])

    # Add all nodes
    node = chain_holder.get_next_node()
    while node:
        dot.add_node(node.name)
        node = chain_holder.get_next_node(curr_node_name=node.name)

    # Add connections
    node = chain_holder.get_next_node()
    processed_nodes = set([node.name])
    nodes = [node]
    while nodes:
        previous_node = nodes.pop()
        success_node = chain_holder.get_next_node(
            curr_node_name=previous_node.name, condition="on-success")
        failure_node = chain_holder.get_next_node(
            curr_node_name=previous_node.name, condition="on-failure")

        # Add success node (if any)
        if success_node:
            dot.add_edge(
                previous_node.name,
                success_node.name,
                constraint="true",
                color="green",
                label="on success",
            )
            if success_node.name not in processed_nodes:
                nodes.append(success_node)
                processed_nodes.add(success_node.name)

        # Add failure node (if any)
        if failure_node:
            dot.add_edge(
                previous_node.name,
                failure_node.name,
                constraint="true",
                color="red",
                label="on failure",
            )
            if failure_node.name not in processed_nodes:
                nodes.append(failure_node)
                processed_nodes.add(failure_node.name)

    if print_source:
        print(dot.source)

    if output_path:
        output_path = os.path.join(output_path, action_name)
    else:
        output_path = output_path or os.path.join(os.getcwd(), action_name)

    dot.format = "png"
    dot.render(output_path)

    print("Graph saved at %s" % (output_path + ".png"))
Example #37
0
File: wit.py Project: imimouni/wit
def graph():
    letters_to_show = 6
    wit = valid_wit(os.getcwd())
    if not wit:
        return
    references_path = os.path.join(wit, "references.txt")
    head = get_head(references_path)
    parent = get_parent(wit=wit, commit_id=head)
    commit_graph = Digraph()

    commit_graph.node('HEAD', head[:letters_to_show], shape='circle')
    current = 'HEAD'

    while parent != 'None':
        commit_graph.node(parent, parent[:letters_to_show], shape='circle')
        commit_graph.edge(current, parent, constraint='false')
        current = parent
        parent = get_parent(wit=wit, commit_id=parent)
    commit_graph.format = 'png'
    commit_graph.render('graph.gv', view=True, directory=wit, cleanup=True)
Example #38
0
def visualize_edges(graph, out_file, control_edges, dep_edges):
    nodes = graph.nodes
    dot = Digraph(comment='Graph')
    #nodes = []
    row_height = 50
    indent_len = 50
    max_height = len(nodes) * row_height

    known_nodes = []

    def get_height(row_num):
        return max_height - row_num * row_height

    for edges, is_control in [(graph.control_edges, True),
                              (graph.dep_edges, False)]:
        for edge in edges:
            if (is_control and control_edges) or (not is_control
                                                  and dep_edges):
                x, y = edge.from_, edge.to
                # x_node = pydot.Node("Node B", style="filled", fillcolor="green")
                if x not in known_nodes:
                    dot.node(str(x),
                             nodes[x].statement,
                             color="black",
                             pos="%d,%d" %
                             (nodes[x].indent * indent_len, get_height(x)))
                # print nodes[x].statement
                if y < len(nodes):
                    if y not in known_nodes:
                        dot.node(str(y),
                                 nodes[y].statement,
                                 pos="%d,%d" %
                                 (nodes[y].indent * indent_len, get_height(y)))
                    if not is_control:
                        dot.edge(str(x), str(y), color="green", style="dashed")
                    elif edge.jmp_true is None:
                        dot.edge(str(x), str(y), color="black")
                    elif edge.jmp_true is True:
                        dot.edge(str(x), str(y), color="blue")
                    else:
                        dot.edge(str(x), str(y), color="red")
    # apply_styles(dot, styles)
    dot.engine = "neato"
    dot.save(out_file, None)

    cmd = "neato.exe -Tpdf -O -n2 -Goverlap=false -Gsplines=true " + out_file

    try:
        returncode = subprocess.Popen(cmd).wait()
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise RuntimeError('failed to execute %r, '
                               'make sure the Graphviz executables '
                               'are on your systems\' path' % cmd)
        else:
            raise
Example #39
0
def make_dot(var, params=None):
    """ Produces Graphviz representation of PyTorch autograd graph.

    Blue nodes are the Variables that require grad, orange are Tensors
    saved for backward in torch.autograd.Function

    Args:
        var: output Variable
        params: dict of (name, Variable) to add names to node that
            require grad (TODO: make optional)
    """
    if params is not None:
        assert all(isinstance(p, Variable) for p in params.values())
        param_map = {id(v): k for k, v in params.items()}

    node_attr = dict(style='filled',
                     shape='box',
                     align='left',
                     fontsize='12',
                     ranksep='0.1',
                     height='0.2')
    dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
    seen = set()

    def size_to_str(size):
        return '(' + ('x').join(['%d' % v for v in size]) + ')'

    output_nodes = (var.grad_fn, ) if not isinstance(var, tuple) else tuple(
        v.grad_fn for v in var)

    from collections import defaultdict
    info_nodes = {}
    tail2head_edges = defaultdict(set)
    head2tail_edges = defaultdict(set)
    lazy_node_registration = []
    lazy_edge_registration = []

    def add_nodes(var):
        if var not in seen:
            if torch.is_tensor(var):
                # note: this used to show .saved_tensors in pytorch0.2, but stopped
                # working as it was moved to ATen and Variable-Tensor merged
                nid = str(id(var))
                name = size_to_str(var.size())
                kwargs = {"fillcolor": "orange"}
                dot.node(nid, name, fillcolor='orange')
                info_nodes[str(id(var))] = {
                    "name": str(id(var)),
                    "size": var.size(),
                    "kwargs": kwargs
                }
            elif hasattr(var, 'variable'):
                # variable node
                u = var.variable
                name = param_map[id(u)] if params is not None else ''
                node_name = '%s\n %s' % (name, size_to_str(u.size()))
                nid = str(id(var))
                dot.node(nid, node_name, fillcolor='lightblue')
                info_nodes[str(id(var))] = {
                    "name": node_name,
                    "size": u.size()
                }
            elif var in output_nodes:
                # final output
                nid = str(id(var))
                node_name = str(type(var).__name__)
                dot.node(str(id(var)), node_name, fillcolor='darkolivegreen1')
                info_nodes[str(id(var))] = {
                    "name": str(type(var).__name__),
                    "size": None
                }
            else:
                # other output(s)
                dot.node(str(id(var)), str(type(var).__name__))
                info_nodes[str(id(var))] = {
                    "name": str(type(var).__name__),
                    "size": None
                }

            seen.add(var)
            if hasattr(var, 'next_functions'):
                for u in var.next_functions:
                    if u[0] is not None:
                        tail_name = str(id(u[0]))
                        head_name = str(id(var))
                        # dot.edge(tail_name, head_name, )
                        tail2head_edges[tail_name].add(head_name)
                        head2tail_edges[head_name].add(tail_name)
                        add_nodes(u[0])

            if hasattr(var, 'saved_tensors'):
                for t in var.saved_tensors:
                    tail_name = str(id(t))
                    head_name = str(id(var))
                    # dot.edge(tail_name, head_name)
                    tail2head_edges[tail_name].add(head_name)
                    head2tail_edges[head_name].add(tail_name)
                    add_nodes(t)

    # handle multiple outputs`
    if isinstance(var, tuple):
        for v in var:
            add_nodes(v.grad_fn)
    else:
        add_nodes(var.grad_fn)

    for key, value in info_nodes.items():
        in_edges = len(head2tail_edges[key])
        dot.node(key,
                 value["name"] + "\tid:%s" % key + "\t in_edges:%d" % in_edges)

    # topologic sort to infer the shape
    from queue import Queue
    zero_edges = Queue()
    edges_count = {}
    for key, value in info_nodes.items():
        in_edges = len(head2tail_edges[key])
        edges_count[key] = in_edges
        if in_edges == 0:
            zero_edges.put(key)

    while not zero_edges.empty():
        tail = zero_edges.get()
        print(tail)
        for head in tail2head_edges[tail]:
            dot.edge(tail, head, label=size_to_str(info_nodes[tail]["size"]))
            # define by op here
            if "inputs" not in info_nodes[head]:
                info_nodes[head]["inputs"] = list()
            info_nodes[head]["inputs"].append(info_nodes[tail]["size"])
            edges_count[head] -= 1
            if edges_count[head] == 0:
                # all inputs ready
                input_list = info_nodes[head]["inputs"]
                node_name = info_nodes[head]["name"]
                d_size = torch.Size([-1])
                if "MulBackward" in node_name:
                    dsize = input_list[0]
                elif "AddBackward" in node_name:
                    d_size = input_list[0]
                elif "TBackward" in node_name:
                    d_size = input_list[0][::-1]
                elif "ThresholdBackward" in node_name:
                    d_size = input_list[0]
                elif "MmBackward" in node_name:
                    s1, s2 = input_list
                    if s1[1] == s2[0]:
                        d_size = torch.Size([s1[0], s2[1]])
                    else:
                        d_size = torch.Size([s2[0], s1[1]])

                info_nodes[head]["size"] = d_size
                zero_edges.put(head)

    resize_graph(dot)

    return dot, info_nodes, tail2head_edges, head2tail_edges
Example #40
0
        # render HTML template and add node
        template_ctx = {
            'component_name': component_name,
            'consumer_ports': consumer_ports,
            'has_consumer_ports': len(consumer_ports) > 0,
            'provider_ports': provider_ports,
            'has_provider_ports': len(provider_ports) > 0
        }

        g.node(component_name, label=chevron.render(component_template, data=template_ctx))

    filename = args.output
    if args.component:
        filename += '-' + args.component

    g = Digraph(engine='dot', filename=filename + '.gv', format=args.format)
    g.attr('node', shape='plaintext')
    g.attr('graph', rankdir='LR')
    g.attr('graph', ranksep='3')
    g.attr('graph', splines='polyline')
    g.attr('graph', concentrate='true')

    for name in components_to_draw:
        add_component(g, name, rt._components[name])

    for provider_name, consumer_name in edges_to_draw:
        pc = provider_name.split('/')[0]
        cc = consumer_name.split('/')[0]
        g.edge('{}:{}:e'.format(pc, provider_name), '{}:{}:w'.format(cc, consumer_name))

    g.view()
            robot_list[robot_num].vision_sensor)

        if (obj_list != None):
            # Remove the robot itself from the list
            obj_list = [
                i for i in obj_list if i.name != robot_list[robot_num].name
            ]

        # Print detected objects of the vision sensor
        print(robot_list[robot_num].name,
              robot_list[robot_num].vision_sensor.name, obj_list)

        #############################################
        # generate scene graph
        #############################################
        dot = Digraph(comment='warehouse', format='svg')
        dot.node_attr['shape'] = 'record'
        robot_velocity = get_velocity(robot_list[robot_num])
        i = robot_list[robot_num]
        # print(i.bbox_min[0], i.bbox_min[1], i.bbox_max[0], i.bbox_max[1])
        # robot_label = '{%s|%s|velocity: %.2f|orientation: %.2f}'%(robot[robot_num].name, robot[robot_num].vision_sensor.name, robot_velocity, robot[robot_num].ori[2]*180/pi)
        robot_label = '{%s|type: 0|%s|velocity: %.2f}' % (
            robot_list[robot_num].name,
            robot_list[robot_num].vision_sensor.name, robot_velocity)

        # robot_label = '{%s|%s}'%(robot[robot_num].name, robot[robot_num].vision_sensor.name)

        dot.node('robot', label=robot_label)
        dot.node('warehouse', label='warehouse')
        dot.node('floor', label='{floor|size: 25*25}')
        dot.edge('warehouse', 'floor')
Example #42
0
                sys.exit()
            options["filetype"]: arg
        elif opt in ('-o', "--output"):
            if not Path(arg).is_dir(
            ):  #different locales might have a problem here!
                print(arg + " is not a valid directory\n")
                sys.exit()
            options["output"] = Path(PurePath(arg)).absolute()
    return options


# this is the path of Graphviz in Windows OS, you can change it accordingly
# linux users should be good from the get-go ( sudo apt-get install graphviz )
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

graph = Digraph('G', filename='graph')
graph.attr(rankdir='LR', dpi="300")


class Graph:
    def __init__(self, data, startingNode, options):
        self.style = options["style"]
        self.counter = 0
        self.startingNode = startingNode
        self.data = data
        self.superGraph = graph

        if "execute" in data:
            if not data["execute"]:
                for entry in data["globalProcesses"]:
                    self.counter += 1
Example #43
0
def generarAutomataGrafico(gramatica):
    try:
        f = Digraph('Automata de pila',
                    filename='AP_' + gramatica.Nombre + '.gv',
                    format='jpg')

        f.attr('node', shape='box')
        f.attr(rankdir='UD')
        inicio = """<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">\n"""
        inicio += '<TR>\n'
        inicio += '<TD> Nombre: </TD>\n'
        inicio += '<TD> AP_' + gramatica.Nombre + '</TD>\n'
        inicio += '</TR>'
        pila = ','.join(gramatica.terminales + gramatica.no_Terminales + ["#"])
        inicio += '<TR>\n'
        inicio += '<TD>Alfabeto de pila: </TD>\n'
        inicio += '<TD>{' + pila + '}</TD>\n'
        inicio += '</TR>'

        inicio += '<TR>\n'
        inicio += '<TD> Estados: </TD>\n'
        inicio += '<TD> {i,p,q,f}</TD>\n'
        inicio += '</TR>'

        inicio += '<TR>\n'
        inicio += '<TD> Estado inicial: </TD>\n'
        inicio += '<TD> {i}</TD>\n'
        inicio += '</TR>'

        inicio += '<TR>\n'
        inicio += '<TD> Estado de aceptacion: </TD>\n'
        inicio += '<TD> {f}</TD>\n'
        inicio += '</TR>'
        inicio += '</TABLE>>\n'

        f.node("datos", inicio)

        f.attr(rankdir='LR')
        f.attr('node', shape='circle')
        f.node('i')
        f.node('p')
        f.node('q')

        producNoTerminales = []
        producTerminales = []
        for produccion in gramatica.producciones:
            # entrada ; desapilar ; apilar1
            for derivacion in produccion.derivaciones:
                apilar = ""
                for simbolo in derivacion:
                    apilar = apilar + simbolo.valor

                texto = "λ," + produccion.nombre + ';' + apilar
                producNoTerminales.append(texto)

        for terminal in gramatica.terminales:
            texto = terminal + ',' + terminal + ';λ'
            producTerminales.append(texto)

        # prods1 = producNoTerminales+producTerminales
        prods1 = '\\n'.join(producNoTerminales)
        prods2 = '\\n'.join(producTerminales)
        f.edge('i', 'p', label='λ,λ;#')
        f.edge('p', 'q', label=('λ,λ;' + gramatica.inicial))
        f.edge('q:n', 'q:n', label=prods1)
        f.edge('q:s', 'q:s', label=prods2)
        f.attr('node', shape='doublecircle')
        f.node('f')
        f.edge('q', 'f', label='λ,#,λ')

        f.view()

    except Exception as e:
        print('Ha ocurido un error: ' + str(e))
Example #44
0
def _build_graph_multi_input_model(model,
                                   filename,
                                   title,
                                   max_nodes=5,
                                   colours=None,
                                   node_size=None):

    input_layers = []
    layers = OrderedDict()
    if node_size is None:
        node_size = {"width": str(2), "height": str(2)}
    if colours is None:
        colours = {
            "Dense": "#3498db",
            "Input": "#2ecc71",
            "Concatenation": "#ffa500",
            "Output": "#e74c3c",
            "Mixed_Dense": "#551a8b"
        }

    for layer in model.layers:
        cf = layer.get_config()
        name = cf['name']
        # get name of input layer
        if "merge" in name:
            inputs = [re.split('/|:', a.name)[0] for a in layer.input]
        else:
            inputs = re.split('/|:', layer.input.name)[0]
        if layer == model.layers[-1]:
            nodes = cf["units"]
            layer_type = "Output"
        else:
            if type(layer) == keras.engine.input_layer.InputLayer:
                nodes = int(str(layer.output_shape).split(",")[1][1:-1])
                layer_type = "Input"
            elif type(layer) == keras.layers.Dense:
                nodes = int(cf["units"])
                layer_type = "Dense"
            else:
                nodes = 1
                if (type(layer) == keras.layers.convolutional.Conv2D):
                    layer_type = "Conv2D"
                elif (type(layer) == keras.layers.pooling.MaxPooling2D):
                    layer_type = "MaxPooling2D"
                elif (type(layer) == keras.layers.core.Dropout):
                    layer_type = "Dropout"
                elif (type(layer) == keras.layers.core.Flatten):
                    layer_type = "Flatten"
                elif (type(layer) == keras.layers.core.Activation):
                    layer_type = "Activation"
                elif (type(layer) == keras.layers.merge.Concatenate):
                    layer_type = "Concatenation"
        if (nodes > max_nodes):
            nodes = max_nodes
        d = {
            "name": name,
            "inputs": inputs,
            "type": layer_type,
            "nodes": nodes
        }
        layers[name] = d
        if layer_type == "Input":
            input_layers.append(d)

    g = Digraph('g', filename=filename)
    g.graph_attr.update(splines="false", nodesep='1', ranksep='2')

    for layer in input_layers:
        name = "cluster_" + layer["name"].split("_")[0] + "_input"
        with g.subgraph(name=name) as c:
            c.attr(color='white')
            c.attr(rank='same')
            c.attr(labeljust="right", labelloc="b", label="")
            for i in range(0, layer["nodes"]):
                c.node(layer["name"] + str(i),
                       color="#2ecc71",
                       style="filled",
                       fontcolor="#2ecc71",
                       shape="circle",
                       label="",
                       **node_size)
                c.attr(rank='same')

    for layer in layers.values():
        # input layers already added
        if layer in input_layers:
            continue
        # name for layer in the Diagraph
        name = "cluster_" + layer["name"]
        # get the colour for the nodes in layer
        if "mix" in name:
            colour = colours["Mixed_Dense"]
        else:
            colour = colours[layer["type"]]
        # merge layers have multiple inputs
        if "merge" in layer["name"]:
            input_name = [layers[l]["name"] for l in layer["inputs"]]
            layer["nodes"] = [layers[l]["nodes"] for l in layer["inputs"]]
            # make list of nodes that input into merge layer
            input_nodes = [[inp + str(n) for n in range(N)]
                           for inp, N in zip(input_name, layer["nodes"])]
            input_nodes = list(itertools.chain.from_iterable(input_nodes))
            layer["nodes"] = sum(layer["nodes"])
        else:
            input_name = [layers[layer["inputs"]]["name"]]
            nodes = layer["nodes"]
        # make subgraph
        with g.subgraph(name=name) as c:
            c.attr(color='white')
            c.attr(rank='same')
            for i in range(0, layer["nodes"]):
                c.node(layer["name"] + str(i),
                       color=colour,
                       style="filled",
                       fontcolor=colour,
                       shape="circle",
                       label="",
                       **node_size)
                if "merge" in layer["name"]:
                    g.edge(input_nodes[i], layer["name"] + str(i))
                else:
                    for inp in input_name:
                        for j in range(0, layers[inp]["nodes"]):
                            g.edge(inp + str(j), layer["name"] + str(i))

    g.attr(arrowShape="none")
    g.edge_attr.update(arrowhead="none", color="#707070")
    return g
Example #45
0
from pudzu.charts import *
from pudzu.sandbox.bamboo import *
from graphviz import Digraph

df = pd.read_csv("datasets/etymgreek.csv").sort_values("language").set_index(
    "language")
flags = pd.read_csv("datasets/countries.csv").split_columns(
    'country', "|").explode('country').set_index('country')['flag']

g = Digraph('G', filename='cache/etymgreek.gv', format="png")
g.attr(newrank="True")

default_img = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/No_flag.svg/1024px-No_flag.svg.png"


def make_flag(language):
    url = get_non(df.flag, language, default_img)
    if not url.startswith("http"): url = flags[url]
    icon = Image.from_url_with_cache(url).to_rgba().resize(
        (160, 100)).pad(1 if language != "Nepal" else 0, "grey")
    label = Image.from_text(language, sans(20), align="center")
    flag = Image.from_column([icon, label], padding=2)
    flag.save(f"cache/icons/{language}.png")


for language, row in df.iterrows():
    make_flag(language)
    g.node(language, image=f"icons/{language}.png", shape="none", label="")
    if get_non(df.greek, language):
        for to in row.greek.split("|"):
            g.edge(language, to, label="           ")
Example #46
0
from graphviz import Digraph

g = Digraph('unix',
            filename='unix.gv',
            node_attr={
                'color': 'lightblue2',
                'style': 'filled'
            })
g.attr(size='6,6')
g.edge('1', '2')
g.edge('1', '3')
g.edge('2', '4')
g.edge('2', '5')
g.edge('3', '6')
g.edge('3', '7')
g.edge('4', '8')
g.edge('4', '9')
g.edge('5', '10')
g.edge('5', '11')
g.edge('6', '12')
g.edge('6', '13')
g.edge('7', '14')
g.edge('7', '15')
# g.edge('8', '9')
# g.edge('8', '10')
# g.edge('8', '11')
# g.edge('9', '11')
g.view()
Example #47
0
def _to_graphviz(tree_info,
                 show_info,
                 feature_names,
                 name=None,
                 comment=None,
                 filename=None,
                 directory=None,
                 format=None,
                 engine=None,
                 encoding=None,
                 graph_attr=None,
                 node_attr=None,
                 edge_attr=None,
                 body=None,
                 strict=False):
    """Convert specified tree to graphviz instance.

    See:
      - http://graphviz.readthedocs.io/en/stable/api.html#digraph
    """
    try:
        from graphviz import Digraph
    except ImportError:
        raise ImportError('You must install graphviz to plot tree.')

    def add(root, parent=None, decision=None):
        """recursively add node or edge"""
        if 'split_index' in root:  # non-leaf
            name = 'split' + str(root['split_index'])
            if feature_names is not None:
                label = 'split_feature_name:' + str(
                    feature_names[root['split_feature']])
            else:
                label = 'split_feature_index:' + str(root['split_feature'])
            label += '\nthreshold:' + str(root['threshold'])
            for info in show_info:
                if info in {'split_gain', 'internal_value', 'internal_count'}:
                    label += '\n' + info + ':' + str(root[info])
            graph.node(name, label=label)
            if root['decision_type'] == '<=':
                l_dec, r_dec = '<=', '>'
            elif root['decision_type'] == '==':
                l_dec, r_dec = 'is', "isn't"
            else:
                raise ValueError('Invalid decision type in tree model.')
            add(root['left_child'], name, l_dec)
            add(root['right_child'], name, r_dec)
        else:  # leaf
            name = 'leaf' + str(root['leaf_index'])
            label = 'leaf_index:' + str(root['leaf_index'])
            label += '\nleaf_value:' + str(root['leaf_value'])
            if 'leaf_count' in show_info:
                label += '\nleaf_count:' + str(root['leaf_count'])
            graph.node(name, label=label)
        if parent is not None:
            graph.edge(parent, name, decision)

    graph = Digraph(name=name,
                    comment=comment,
                    filename=filename,
                    directory=directory,
                    format=format,
                    engine=engine,
                    encoding=encoding,
                    graph_attr=graph_attr,
                    node_attr=node_attr,
                    edge_attr=edge_attr,
                    body=body,
                    strict=strict)
    add(tree_info['tree_structure'])

    return graph
Example #48
0
            k = k+1

if __name__ == "__main__":

    alfabeto = ['a']
    states = ['0', '1', '2', '3', '4']#, '6']
    #grafo = [('0', '&', '5'), ('5', '&', '2'), ('2', 'b', '3'), ('3', 'b', '4'), ('4', '&', '6'), ('6', '&', '1'),
     #       ('5', 'a', '5'), ('6', 'a', '6'), ('5', 'b', '5'), ('6', 'b', '6')]
    #grafo = [('0', '&', '2'), ('2', '&', '1'), ('2', 'a', '3'), ('3', 'b', '2'), ('3', 'c', '2')]
    #grafo = [('0','&','4'), ('0','&','5'), ('4','&','2'), ('5','&','3'), ('2','b','1'), ('3','a','1'), ('4','a','4'),
     #       ('5', 'b', '5')]
    grafo = [('0','&','2'), ('2','&','1'), ('2','a','4'), ('4','a','3'), ('3', 'a', '2')]
    final_states = ['1']

    grafo_q2(grafo, states, final_states)

    drawGraph = Digraph('Automatum', filename='automataq02ex', format='jpg')
    drawGraph.attr(rankdir='LR', size='8,5')
    drawGraph.attr('node', shape='doublecircle')
    for x in final_states:
        drawGraph.node(x)
    drawGraph.attr('node', shape='circle')
    for element in grafo:
        init = str(element[0])
        final = str(element[2])
        label = ""
        for symbol in element[1]:
            label += (symbol)
        drawGraph.edge(init, final, label=label)
    drawGraph.view()
Example #49
0
                    variavel.initializer = ir.Constant(ir.FloatType(), 0.0)
                    variavel.linkage = "common"
                    variavel.align = 4
                self.lista_ponteiros_variaveis.append(variavel)

    def llvm_declaracao_variavel_local(self, filho, builder):
        tipo = filho.child[0].value
        for filhos in filho.child[1].child: 
            if tipo == "inteiro":
                variavel = builder.alloca(ir.IntType(32), name=filhos.value)
                variavel.align = 4
            elif tipo == "flutuante":
                variavel = builder.alloca(ir.FloatType(), name=filhos.value)
                variavel.align = 4
            self.lista_ponteiros_variaveis.append(variavel)

if __name__ == '__main__':
    now = datetime.now()
    root = Syn()                        # Chama o analisador Sintatico
    Run(root.ps)                        # Poda a arvore
    dot = Digraph(comment='TREE')       # Abaixo é o processo de impressão
    Gerador = Gerador_TOP()

    NomeProg = sys.argv[1]
    modulo = ir.Module(NomeProg)

    Gerador.andar(root.ps, modulo)
    arquivo = open(NomeProg+'.ll','w')
    arquivo.write(str(modulo))
    arquivo.close()
    print(modulo)
Example #50
0
def graph(workflow):
    g = Digraph(workflow.name)
    g.node_attr.update(color='lightblue2', style='filled')
    g.edge("x","z")
    g.edge("x", "y")
    g.view()
Example #51
0
    def visualize(self, name, comment, pro_do=lambda dot, tree: None, **kwargs):
        """Visualize the graph by using graphviz package and dot language.

        Args:
            name (str): Name of the dot graph.
            comment (str): Comment on the dot graph.
            pro_do (function): Higher-order function that will be called right
                before rendering. It gets 'dot' and 'tree' objects as an
                argument and it is useful for the inherited subclasses to
                override this method by adding more things to the final rendered
                graph.

        kwargs:
            filename (str): Name of the output file (default='tree').
            fmt (str): File format of the output (default='svg').
            hl_nodes ([Tree *]): List of highlighted nodes (default=[]). These
                nodes (corresponding subtrees) are highlighted in the rendered
                graph.
            graph_attr (dict): Graph attributes. Default attributes are:
                    For graph: ratio=1
                    For nodes: shape=circle, margin=0.2
                    For edges: fontsize=10
            leaves_attr (dict): Leaves attributes. Default attributes are:
                    style=filled
                    fillcolor=lightgrey
            hl_nodes_attr (dict): Highlighted nodes attributes. Default
                attributes are:
                    style=filled
                    fillcolor=red

            Remaining options passed to dot.render() function. such as:
                'directory':
                    (Sub)directory for source saving and rendering.
                'view':
                    Open the rendered result with the default application.
                'cleanup':
                    Delete the source file after rendering.

                See the full list at:
                    http://graphviz.readthedocs.io/en/latest/api.html#graphviz.Digraph.render
        """
        filename = kwargs.pop('filename', 'tree')
        fmt = kwargs.pop('fmt', 'svg')
        hl_nodes = kwargs.pop('hl_nodes', [])

        graph_attr = {
            'graph_attr': {'ratio': '1'},
            'node_attr': {'shape': 'circle',
                          'margin': '0.2'},
            'edge_attr': {'fontsize': '10'}
        }
        graph_attr = kwargs.pop('graph_attr', graph_attr)

        leaves_attr = {
            'style': 'filled',
            'fillcolor': 'lightgray'
        }
        leaves_attr = kwargs.pop('leaves_attr', leaves_attr)

        hl_nodes_attr = {
            'style': 'filled',
            'fillcolor': 'red'
        }
        hl_nodes_attr = kwargs.pop('hl_nodes_attr', hl_nodes_attr)

        # Create a dot graph by given name, comment, and attributes.
        dot = Digraph(name, comment, **graph_attr)

        # Traverse the tree by DFS.
        for node in self.dfs():
            attributes = {}
            if node.is_leaf():
                attributes = leaves_attr
            if node in hl_nodes:
                attributes = hl_nodes_attr  # Overriding leave attributes.

            # Add the node to dot graph.
            dot.node(str(node.root_id), str(node), **attributes)
            if node != self:  # If node is not the caller, add its parent edge.
                # Add parent edge to the dot graph.
                dot.edge(str(node.parent_edge.src.root_id), str(node.root_id),
                         label=str(node.parent_edge))

        # Do more by subclasses' overrided visualize function!
        pro_do(dot, self)

        dot.format = fmt
        # Rendering... . Remaining kwargs will be passed to the render function.
        dot.render(filename, **kwargs)
Example #52
0
    def toGraph(self):
        states = self.states
        # print(len(states))
        edges = []
        for s in states:
            # edges format = (from, to, label)
            for t in s.transitions:
                tmp = []
                tmp.append(s.name)
                tmp.append(s.transitions[t].name)
                tmp.append(t)
                edges.append(tmp)
            for e in s.epsilon:
                tmp = []
                tmp.append(s.name)
                tmp.append(e.name)
                tmp.append("epsilon")
                edges.append(tmp)
        # print(edges)
        g = Digraph('G', filename='eNFA_graph.gv', directory='graphs')
        g.attr(rankdir='LR')  # orientation Left to Right

        # start arrow
        g.attr('node', shape='point')
        g.node('sa')

        # final state
        g.attr('node', shape='doublecircle')
        for s in states:
            if s.is_end:
                g.node(s.name)

        # else
        g.attr('node', shape='circle')
        g.edge('sa', states[0].name)
        for e in edges:
            g.edge(e[0], e[1], label=e[2])

        # view in viewer
        g.view()
Example #53
0
        def make_dot(output_var, state_dict=None):
            """
            Produces Graphviz representation of Pytorch autograd graph.
            Blue nodes are the Variables that require grad, orange are Tensors
            saved for backward in torch.autograd.Function.

            Args:
                output_var: output Variable
                state_dict: dict of (name, parameter) to add names to node that require grad
            """
            from graphviz import Digraph

            if state_dict is not None:
                # assert isinstance(params.values()[0], Variable)
                param_map = {id(v): k for k, v in state_dict.items()}

            node_attr = dict(style='filled',
                             shape='box',
                             align='left',
                             fontsize='12',
                             ranksep='0.1',
                             height='0.2')
            dot = Digraph(node_attr=node_attr,
                          graph_attr=dict(size="12,12"),
                          format="svg")
            seen = set()

            def size_to_str(size):
                return '(' + (', ').join(['%d' % v for v in size]) + ')'

            def add_nodes(var):
                if var not in seen:
                    if torch.is_tensor(var):
                        dot.node(str(id(var)),
                                 size_to_str(var.size()),
                                 fillcolor='orange')
                    elif hasattr(var, 'variable'):
                        u = var.variable
                        if state_dict is not None and id(u.data) in param_map:
                            node_name = param_map[id(u.data)]
                        else:
                            node_name = ""
                        node_name = '%s\n %s' % (node_name,
                                                 size_to_str(u.size()))
                        dot.node(str(id(var)),
                                 node_name,
                                 fillcolor='lightblue')
                    else:
                        node_name = str(type(var).__name__)
                        if node_name.endswith("Backward"):
                            node_name = node_name[:-8]
                        dot.node(str(id(var)), node_name)
                    seen.add(var)
                    if hasattr(var, 'next_functions'):
                        for u in var.next_functions:
                            if u[0] is not None:
                                dot.edge(str(id(u[0])), str(id(var)))
                                add_nodes(u[0])
                    if hasattr(var, 'saved_tensors'):
                        for t in var.saved_tensors:
                            dot.edge(str(id(t)), str(id(var)))
                            add_nodes(t)

            add_nodes(output_var.grad_fn)
            return dot
# read csv data for Tennis data set
csv_data = pd.read_csv('Tennis.csv')
data = csv_data.drop(columns=['Day'])
data = data.to_dict('index')
# set the target name
target = 'PlayTennis'

# rearrange the data set for later processing
(data_set, attributes) = rearrange_data(data, 'PlayTennis')

# Invoke the function for Task 2.2.2, print the result, find the best attribute to become the root
for i in range(0, 4):
    print("Gain(S, ", attributes[i], "): ", information_gain(data_set, i))

(root_attribute, root_ig) = choose_best_attribute(data_set, [0, 1, 2, 3])

print('The root is ', attributes[root_attribute], '. The I.G is ', root_ig)
print('==============================')

print('Generating Decision Tree...')
t = id3(data_set, [0, 1, 2, 3])

index = 0
root_name = t.attribute + ' I.G= ' + str(round(t.ig, 4))
dot = Digraph(format='png')
nodes_to_edge(t, root_name)
print(dot.source)

dot.render('tennis', view=True)
Example #55
0
def _to_graphviz(tree_info,
                 show_info,
                 feature_names,
                 precision=3,
                 constraints=None,
                 **kwargs):
    """Convert specified tree to graphviz instance.

    See:
      - https://graphviz.readthedocs.io/en/stable/api.html#digraph
    """
    if GRAPHVIZ_INSTALLED:
        from graphviz import Digraph
    else:
        raise ImportError('You must install graphviz to plot tree.')

    def add(root, total_count, parent=None, decision=None):
        """Recursively add node or edge."""
        if 'split_index' in root:  # non-leaf
            l_dec = 'yes'
            r_dec = 'no'
            if root['decision_type'] == '<=':
                lte_symbol = "&#8804;"
                operator = lte_symbol
            elif root['decision_type'] == '==':
                operator = "="
            else:
                raise ValueError('Invalid decision type in tree model.')
            name = 'split{0}'.format(root['split_index'])
            if feature_names is not None:
                label = '<B>{0}</B> {1} '.format(
                    feature_names[root['split_feature']], operator)
            else:
                label = 'feature <B>{0}</B> {1} '.format(
                    root['split_feature'], operator)
            label += '<B>{0}</B>'.format(
                _float2str(root['threshold'], precision))
            for info in [
                    'split_gain', 'internal_value', 'internal_weight',
                    "internal_count", "data_percentage"
            ]:
                if info in show_info:
                    output = info.split('_')[-1]
                    if info in {
                            'split_gain', 'internal_value', 'internal_weight'
                    }:
                        label += '<br/>{0} {1}'.format(
                            _float2str(root[info], precision), output)
                    elif info == 'internal_count':
                        label += '<br/>{0}: {1}'.format(output, root[info])
                    elif info == "data_percentage":
                        label += '<br/>{0}% of data'.format(
                            _float2str(
                                root['internal_count'] / total_count * 100, 2))

            fillcolor = "white"
            style = ""
            if constraints:
                if constraints[root['split_feature']] == 1:
                    fillcolor = "#ddffdd"  # light green
                if constraints[root['split_feature']] == -1:
                    fillcolor = "#ffdddd"  # light red
                style = "filled"
            label = "<" + label + ">"
            graph.node(name,
                       label=label,
                       shape="rectangle",
                       style=style,
                       fillcolor=fillcolor)
            add(root['left_child'], total_count, name, l_dec)
            add(root['right_child'], total_count, name, r_dec)
        else:  # leaf
            name = 'leaf{0}'.format(root['leaf_index'])
            label = 'leaf {0}: '.format(root['leaf_index'])
            label += '<B>{0}</B>'.format(
                _float2str(root['leaf_value'], precision))
            if 'leaf_weight' in show_info:
                label += '<br/>{0} weight'.format(
                    _float2str(root['leaf_weight'], precision))
            if 'leaf_count' in show_info:
                label += '<br/>count: {0}'.format(root['leaf_count'])
            if "data_percentage" in show_info:
                label += '<br/>{0}% of data'.format(
                    _float2str(root['leaf_count'] / total_count * 100, 2))
            label = "<" + label + ">"
            graph.node(name, label=label)
        if parent is not None:
            graph.edge(parent, name, decision)

    graph = Digraph(**kwargs)
    graph.attr("graph", nodesep="0.05", ranksep="0.3", rankdir="LR")
    if "internal_count" in tree_info['tree_structure']:
        add(tree_info['tree_structure'],
            tree_info['tree_structure']["internal_count"])
    else:
        raise Exception("Cannot plot trees with no split")

    if constraints:
        # "#ddffdd" is light green, "#ffdddd" is light red
        legend = """<
            <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4">
             <TR>
              <TD COLSPAN="2"><B>Monotone constraints</B></TD>
             </TR>
             <TR>
              <TD>Increasing</TD>
              <TD BGCOLOR="#ddffdd"></TD>
             </TR>
             <TR>
              <TD>Decreasing</TD>
              <TD BGCOLOR="#ffdddd"></TD>
             </TR>
            </TABLE>
           >"""
        graph.node("legend", label=legend, shape="rectangle", color="white")
    return graph
Example #56
0
from graphviz import Digraph

g = Digraph(comment='')


def new_block(scale, origin, address, length, label, ref):
    with g.subgraph(name='cluster_' + str(address),
                    node_attr={'shape': 'record'}) as a:

        a.attr(label=label)
        for i in range(0, length):
            a.node(
                str(address + i),
                label='<{{X={0} | W<sub>x</sub> = {1:.4f} | Buf {2} | Ref {3}}}>'
                .format(i, ((i - 1) * scale + origin) *
                        (not (i == 0 or i == length - 1)), address + i,
                        ref[i]),
                style="filled",
                fillcolor=('green' if i == 0 or i == length - 1 else 'white'))

        a.body.append('{rank=same;' +
                      ';'.join([str(address + i)
                                for i in range(0, length)]) + '}')
        a.body.append(' -> '.join([str(address + i)
                                   for i in range(0, length)]) +
                      '[style=invis,weight=100,len=0,K=0]')


def block_indices(address, ref, name, formatter):
    with g.subgraph(name='cluster_' + str(address),
                    node_attr={'shape': 'record'}) as a:
Example #57
0
from graphviz import Digraph
from analizer.reports.Nodo import Nodo

dot = Digraph(comment="AST")


class AST:
    def __init__(self):
        self.count = 0

    def makeAst(self, root):
        self.defineTreeNodes(root)
        self.joinTreeNodes(root)
        self.drawGraph()

    def defineTreeNodes(self, root):
        root.setId(str(self.count))
        dot.node(str(self.count), root.getVal())
        self.count += 1
        for node in root.getLista():
            self.defineTreeNodes(node)

    def joinTreeNodes(self, root):
        for node in root.getLista():
            dot.edge(root.getId(), node.getId())
            self.joinTreeNodes(node)

    def drawGraph(self):
        global dot
        dot.render("test-output/round-table.gv", view=True)
        "test-output/round-table.gv.jpg"
Example #58
0
from collections import Counter

from graphviz import Digraph
from litman import LitMan
from litman.litman import load_config, ItemNotFound

dot = Digraph('papers')

_, conf = load_config()
lm = LitMan(conf['litman_dir'])

l0_mag_items = lm.get_items(has_mag=True, level=0)
lm1_mag_items = lm.get_items(has_mag=True, level=-1)

added_items = Counter()

for item in l0_mag_items:
    for ref_item_name in item.cites:
        try:
            ref_item = lm.get_item(ref_item_name)
        except ItemNotFound:
            continue
        if ref_item.level == 0:
            if item.name not in added_items:
                added_items[item.name] += 1
                dot.node(item.name, item.name)
            if ref_item.name not in added_items:
                added_items[ref_item.name] += 1
                dot.node(ref_item.name, ref_item.name)

            dot.edge(item.name, ref_item.name)
Example #59
0
from knock41 import func41, Chunk
"""
edges = [(1,2),(1,3),(1,4),(3,4)]
g = pydot.graph_from_edges(edges)
g.write_jpeg('graph_from_edges_dot.jpg',prog = 'dot')
"""
"""
b(class Chunk) in line下で
掛かり先のChunkの表層形:ingword = b.getSurword()
掛かり元のChunkの表層形:edword = line[b.getDst()].getSurword()

Digraph:有向グラフ
Graph:無向グラフ
"""

g = Digraph(format='png')
g.attr('node', shape='circle')

N = 15
counter = 0
#for line in range(N):
for line in func41():
    if counter > N:
        break
    for b in line:
        ingword = b.getSurword()
        edword = line[b.getDst()].getSurword()
        if len(ingword) > 0 and len(edword) > 0:
            if b.getDst() != -1:
                g.edge(ingword, edword)
Example #60
0
def plot_network(symbol, title="plot", shape=None):
    """convert symbol to dot object for visualization

    Parameters
    ----------
    title: str
        title of the dot graph
    symbol: Symbol
        symbol to be visualized
    shape: dict
        dict of shapes, str->shape (tuple), given input shapes
    Returns
    ------
    dot: Diagraph
        dot object of symbol
    """
    # todo add shape support
    try:
        from graphviz import Digraph
    except:
        raise ImportError("Draw network requires graphviz library")
    if not isinstance(symbol, Symbol):
        raise TypeError("symbol must be Symbol")
    draw_shape = False
    if shape != None:
        draw_shape = True
        interals = symbol.get_internals()
        _, out_shapes, _ = interals.infer_shape(**shape)
        if out_shapes == None:
            raise ValueError("Input shape is incompete")
        shape_dict = dict(zip(interals.list_outputs(), out_shapes))
    conf = json.loads(symbol.tojson())
    nodes = conf["nodes"]
    heads = set(conf["heads"][0])  # TODO(xxx): check careful
    node_attr = {
        "shape": "box",
        "fixedsize": "true",
        "width": "1.3",
        "height": "0.8034",
        "style": "filled"
    }
    dot = Digraph(name=title)
    # color map
    cm = ("#8dd3c7", "#fb8072", "#ffffb3", "#bebada", "#80b1d3", "#fdb462",
          "#b3de69", "#fccde5")

    # make nodes
    for i in range(len(nodes)):
        node = nodes[i]
        op = node["op"]
        name = node["name"]
        # input data
        attr = copy.deepcopy(node_attr)
        label = op

        if op == "null":
            if i in heads:
                label = node["name"]
                attr["fillcolor"] = cm[0]
            else:
                continue
        elif op == "Convolution":
            label = "Convolution\n%sx%s/%s, %s" % (
                _str2tuple(node["param"]["kernel"])[0],
                _str2tuple(node["param"]["kernel"])[1],
                _str2tuple(
                    node["param"]["stride"])[0], node["param"]["num_filter"])
            attr["fillcolor"] = cm[1]
        elif op == "FullyConnected":
            label = "FullyConnected\n%s" % node["param"]["num_hidden"]
            attr["fillcolor"] = cm[1]
        elif op == "BatchNorm":
            attr["fillcolor"] = cm[3]
        elif op == "Activation" or op == "LeakyReLU":
            label = "%s\n%s" % (op, node["param"]["act_type"])
            attr["fillcolor"] = cm[2]
        elif op == "Pooling":
            label = "Pooling\n%s, %sx%s/%s" % (
                node["param"]["pool_type"], _str2tuple(
                    node["param"]["kernel"])[0],
                _str2tuple(node["param"]["kernel"])[1],
                _str2tuple(node["param"]["stride"])[0])
            attr["fillcolor"] = cm[4]
        elif op == "Concat" or op == "Flatten" or op == "Reshape":
            attr["fillcolor"] = cm[5]
        elif op == "Softmax":
            attr["fillcolor"] = cm[6]
        else:
            attr["fillcolor"] = cm[7]

        dot.node(name=name, label=label, **attr)

    # add edges
    for i in range(len(nodes)):
        node = nodes[i]
        op = node["op"]
        name = node["name"]
        if op == "null":
            continue
        else:
            inputs = node["inputs"]
            for item in inputs:
                input_node = nodes[item[0]]
                input_name = input_node["name"]
                if input_node["op"] != "null" or item[0] in heads:
                    attr = {"dir": "back", 'arrowtail': 'open'}
                    # add shapes
                    if draw_shape:
                        if input_node["op"] != "null":
                            key = input_name + "_output"
                            shape = shape_dict[key][1:]
                            label = "x".join([str(x) for x in shape])
                            attr["label"] = label
                        else:
                            key = input_name
                            shape = shape_dict[key][1:]
                            label = "x".join([str(x) for x in shape])
                            attr["label"] = label
                    dot.edge(tail_name=name, head_name=input_name, **attr)

    return dot