def init_graph():
    "init the graph and image panel"
    dot = Digraph()
    dot.name = "topology"
    dot.format = "gif"
    dot.filename = "zigbee_topology"
    return dot
Example #2
0
    def draw( self, vec, contentMatrix, fig_coment,K = 0, filter_lonelyRoot = False, filter_noRequest = True):
        self.find_lonely(vec)
#        dot = Digraph(comment=fig_coment, engine='dot')
#        dot = Digraph(comment=fig_coment, engine='neato')
        dot = Digraph(comment=fig_coment, engine='fdp')
#        dot = Digraph(comment=fig_coment, engine='twopi')
        dot.format = 'svg'
#        dot.body.extend(['rankdir=LR']) # set vertical layout
        if K >0:
            time_consuming = self.most_timeConsuming(contentMatrix['wait_interval'],K)
        else:
            time_consuming = []
#        dot.body.append('center=ture')
#        dot.node_attr.update(color='lightblue2', style='filled',width='0.04',height='0.04')
        for i in range(0,len(vec)):
            if (filter_lonelyRoot and (i in self.lonely)) or vec[i]<0:
                continue
            if i in time_consuming:
                if contentMatrix['wait_interval'][i] != -1:
                    dot.node(str(i+1),"("+str(i+1)+")\n"+contentMatrix['mimeType'][i].split(';')[0].split('/')[-1]+':'+str(contentMatrix['wait_interval'][i]),color='tomato2', style='filled')
                elif not filter_noRequest:
                    dot.node(str(i+1),"("+str(i+1)+")\n"+"no request", style='filled')
            else:
                if contentMatrix['wait_interval'][i] != -1:
                    dot.node(str(i+1),"("+str(i+1)+")\n"+contentMatrix['mimeType'][i].split(';')[0].split('/')[-1]+':'+str(contentMatrix['wait_interval'][i]),color='lightblue2', style='filled')
                elif not filter_noRequest:
                    dot.node(str(i+1),"("+str(i+1)+")\n"+"no request", style='filled')
            if vec[i] != 0 and ((not filter_noRequest) or contentMatrix['wait_interval'][i] != -1):
                dot.edge(str(vec[i]), str(i+1))#,constraint='false')
        dot.render(fig_coment+'_treeplot.dot', view=True)
        return dot
Example #3
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 #4
0
def draw(FA, adj, output):
	newAlpha = list(FA[1])
	if newAlpha[-1] == EPS:
		newAlpha.pop();
	sigma = ', '.join(newAlpha)
	gr = Digraph();
	gr.engine = 'dot'
	gr.format = 'pdf'

	gr.attr('node', style = 'invis');
	gr.node('myStarting');
	
	gr.attr('node', style = '', shape = 'doublecircle');
	for u in FA[-1]:
		gr.node(str(u));
	
	gr.attr('node', shape = 'circle');
	for u in FA[0]:
		if u not in FA[-1]:
			gr.node(str(u))
	
	gr.edge('myStarting', str(FA[2]), 'Start');
	for u, v in adj.keys():
		if adj[u, v] == sigma:
			gr.edge(str(u), str(v), 'Sigma')
		else:
			gr.edge(str(u), str(v), adj[u, v])

	gr.render(output, view = True);
Example #5
0
def dumpgraph(request,descl, comment,rankdir="RL", student=None,ALL=True):
	dot = Digraph(comment=comment)
	dot.format='svg'
	dot.graph_attr['rankdir'] = rankdir
	if student != None:
		student = get_object_or_404(Student,student_id=student)

	s=set()
	for l in descl:
		s.add(l.ascendant)
		s.add(l.descendant)
	for x in s:
		if student != None and student.knowsConcept(x.name) :
			cc = student.conceptlevel(x.name)
			l= ['red','green','orange','yellow']
			cc=l[min(cc,len(l)-1)]
			dot.node(x.name,URL=x.makeUrl(),color=cc,style="filled",shape="box")
		else:
			if ALL :
				dot.node(x.name,URL=x.makeUrl(),color="red",style="filled",shape="box")

	for l in descl:
		if ALL:
			dot.edge(l.descendant.name,l.ascendant.name)
		else:
			if student != None and student.knowsConcept(l.descendant.name) and student.knowsConcept(l.ascendant.name):
				dot.edge(l.descendant.name,l.ascendant.name)
	dot.render('concept/templates/concept/graph')
Example #6
0
 def generate_graph(self, graph: Digraph, sub_graphs: tuple, name):
     graph.format = self.img_format
     graph.directory = self.directory
     for sub_graph in sub_graphs:
         graph.subgraph(sub_graph)
     graph.render('{} {}'.format(self.file_prefix, name), None, False)
     print('Class diagram {} written.'.format(name))
Example #7
0
def render_block_graph(qmp, filename, format='png'):
    '''
    Render graph in text (dot) representation into "@filename" and
    representation in @format into "@filename.@format"
    '''

    bds_nodes = qmp.command('query-named-block-nodes')
    bds_nodes = {n['node-name']: n for n in bds_nodes}

    job_nodes = qmp.command('query-block-jobs')
    job_nodes = {n['device']: n for n in job_nodes}

    block_graph = qmp.command('x-debug-query-block-graph')

    graph = Digraph(comment='Block Nodes Graph')
    graph.format = format
    graph.node('permission symbols:\l'
               '  w - Write\l'
               '  r - consistent-Read\l'
               '  u - write - Unchanged\l'
               '  g - Graph-mod\l'
               '  s - reSize\l'
               'edge label scheme:\l'
               '  <child type>\l'
               '  <perm>\l'
               '  <shared_perm>\l', shape='none')

    for n in block_graph['nodes']:
        if n['type'] == 'block-driver':
            info = bds_nodes[n['name']]
            label = n['name'] + ' [' + info['drv'] + ']'
            if info['drv'] == 'file':
                label += '\n' + os.path.basename(info['file'])
            shape = 'ellipse'
        elif n['type'] == 'block-job':
            info = job_nodes[n['name']]
            label = info['type'] + ' job (' + n['name'] + ')'
            shape = 'box'
        else:
            assert n['type'] == 'block-backend'
            label = n['name'] if n['name'] else 'unnamed blk'
            shape = 'box'

        graph.node(str(n['id']), label, shape=shape)

    for e in block_graph['edges']:
        label = '%s\l%s\l%s\l' % (e['name'], perm(e['perm']),
                                  perm(e['shared-perm']))
        graph.edge(str(e['parent']), str(e['child']), label=label)

    graph.render(filename)
Example #8
0
    def draw(self, name, output_dir):
        # Cria grafo direcionado e define o estilo padrao dos nos
        dot = Digraph(name = name)
        dot.graph_attr['rankdir'] = 'LR'
        dot.graph_attr['pad'] = '0.5,0.5'
        dot.node_attr['shape'] = 'circle'
        dot.node_attr['style'] = 'filled'
        dot.node_attr['fillcolor'] = 'aquamarine4'
        dot.format = 'png'

        # Obtem os rotulos dos estados e os coloca em ordem alfabetica
        states = list(self.states.keys())
        states.sort()

        # Adicionana cada estado como um no do grafo
        for state in states:
            # Estilo do estado inicial
            if state == self.initial_state:
                # Estilo diferenciado caso o estado inicial seja tambem final
                if state in self.marked_states:
                    dot.node(state, shape = 'doublecircle', fillcolor = 'cornflowerblue', color = 'cornflowerblue')
                else:
                    dot.node(state, fillcolor = 'cornflowerblue')
            elif state in self.marked_states:
                # Estili diferenciado para os estados finais
                dot.node(state, shape = 'doublecircle', fillcolor = 'brown1', color = 'brown1')
            else:
                # Adiciona estados com o estilo padrao
                dot.node(state)

        # Adiciona no que aponta para o estado inicial
        dot.node('', shape = 'point', fillcolor = '#000000')
        dot.edge('', self.initial_state)

        # Adciona os eventos
        for state_label, state in self.states.items():
            for event, edges in state.edges.items():
                for edge in edges:
                    dot.edge(state_label, edge, label = event)

        # Verifica se o diretoria output existe, caso nao exista ele e criado
        if not os.path.exists(output_dir) or not os.path.isdir(output_dir):
            os.mkdir(output_dir)

        # Renderiza a imagem do automato
        dot.render(output_dir + os.sep + name)

        # Remove os arquivos desnecessarios apos renderizacao
        os.remove(output_dir + os.sep + name)
    def __init__(self, tree, name='Arvore_QueensPuzzle'):
        """Contrutor da classe DrawTree"""
        super(DrawTree, self).__init__()
        # Cópia da árvore
        self.tree = copy.deepcopy(tree)

        global dot
        # Cria grafo direcionado
        dot = Digraph(name = name)
        dot.format = 'png'

        # Desenha árvore
        self.draw(self.tree)

        # Visualiza a imagem da árvore
        dot.view()
Example #10
0
def display_tree(root,**kwargs):
    max_depth = 5
    dot = Digraph(comment='MCTS Tree')
    fringe = [(None,0,root)]
    while fringe:
        (parent_hash,d,child) = fringe.pop()
        child_str = str(child)
        child_hash = str(hash(child))

        if child.is_leaf():
            dot.attr('node',shape='box',style='')
        else:
            dot.attr('node',shape='ellipse',style='')
        dot.node(child_hash,child_str)
            
        if parent_hash:
            label = str(child.state)
            dot.edge(parent_hash,
                     child_hash,
                     label=label)        

        # Add new nodes
        for a_id in child.children:
            if d < max_depth:
                dot.attr('node',shape='diamond',style='filled')
                child_aid_hash = child_hash + str(a_id)
                dot.node(child_aid_hash,'')
            else:
                dot.attr('node',shape='box',style='filled')
                child_aid_hash = child_hash + str(a_id)
                dot.node(child_aid_hash,'...')

            label = '{0},{1:0.2f},{2}'.format(a_id,
                                         child.get_ucb(a_id),
                                         child.costs[a_id])
            dot.edge(child_hash,
                     child_aid_hash,
                     label=label)
            if d < max_depth:
                for gc in child.children[a_id]:
                    fringe.append((child_aid_hash,d+1,gc))
    dot.format='png'
    dot.render('data/test.gv')
    img = mpimg.imread('data/test.gv.png')
    plt.imshow(img)
    plt.title(kwargs.get('title',''))
    plt.show()
Example #11
0
def render_graph(nodes, filename):
    dot = Digraph(name='windbg_graph', node_attr={'shape': 'box', 'fontname' : 'Lucida Console'}, graph_attr={'splines':'polyline'})

    for anode in nodes:
        if(anode.has_color()):
            dot.node(anode.get_nodeName(),anode.get_dotformat_label(), _attributes={'style':'filled', 'fillcolor':'gray'})
        else:
            dot.node(anode.get_nodeName(),anode.get_dotformat_label())
        connections = anode.get_connections()
        for connection in connections:
            dot.edge(anode.get_nodeName(),connection)

    #print(dot.source)
    dot.format = outputformat
    graph_file = dot.render(filename, view=False)
    os.unlink(filename)
    return  graph_file
 def graph(self):
     dot = Digraph(comment='Lista Canciones')
     dot.format = 'png'
     actual = self.head
     i = 0
     while actual:
         dot.node(str(i), actual.getNombre())
         actual = actual.getSiguiente()
         i += 1
         if actual == self.head:
             break
         dot.edge(str(i - 1), str(i), constraint='false')
         dot.edge(str(i), str(i - 1), constraint='false')
     dot.edge(str(i - 1), str(0), constraint='false')
     dot.edge(str(0), str(i - 1), constraint='false')
     dot.render(filename="listaCanciones",
                directory="C:\\Graphs\\",
                view=True,
                cleanup=True)
Example #13
0
def render_graph(system, user_query):
    dot = Digraph(
        node_attr=dict(shape='box', style='rounded, filled'),
        graph_attr=dict(splines='ortho'),
    )

    # Nodes
    render_nodes(dot, system, '#deebff')
    render_nodes(dot, user_query, '#ffebcc')

    # Edges
    render_edges(dot, system)
    render_edges(dot, user_query)

    file = "chatbot-design"
    file_format = 'svg'
    dot.format = file_format
    dot.render(file, cleanup=True, view=False)
    return f"{file}.{file_format}"
Example #14
0
def display_history_png(instance_id):
    instance = InstanceStory.query.get_or_404(instance_id)
    if not is_obj_of_current_user(instance):
        return abort(403)
    histories = instance.history.order_by(HistoryInstance.timestamp.asc()).all()
    res = Response()
    g = Digraph(instance.story.name)
    step_ids = []
    for history in histories:
        if history.from_step_id and not history.from_step_id in step_ids:
            step_ids.append(history.from_step_id)
        if history.to_step_id and not history.to_step_id in step_ids:
            step_ids.append(history.to_step_id)

    steps_tmp = Step.query.filter(Step.id.in_(step_ids))
    steps = {}
    for step in steps_tmp:
        steps[step.id] = step

    for history in histories:
        if history.from_step_id and not history.from_step_id in steps:
            step = Step.query.get(history.from_step_id)
            steps[history.from_step_id] = step
        if history.to_step_id and not history.to_step_id in steps:
            step = Step.query.get(history.to_step_id)
            steps[history.to_step_id] = step
    for step_id in steps:
        step = steps[step_id]
        if step.final:
            g.node('step_%d' % step.id, label=step.name, color="lightblue2", style="filled")
        else:
            g.node('step_%d' % step.id, label=step.name)

    index = 1
    for history in histories:
        if history.from_step_id:
            g.edge('step_%d' % history.from_step_id, 'step_%d' % history.to_step_id, label = "%d. %s" % (index, history.choice_text))
            index += 1

    g.format = 'png'
    res.content_type = "image/png"
    res.data = g.pipe()
    return res
Example #15
0
def visualize(ts, parameters=None):
    if parameters is None:
        parameters = {}

    image_format = parameters["format"] if "format" in parameters else "png"
    show_labels = parameters[
        "show_labels"] if "show_labels" in parameters else True
    show_names = parameters[
        "show_names"] if "show_names" in parameters else True
    force_names = parameters[
        "force_names"] if "force_names" in parameters else None

    if force_names:
        nts = copy(ts)
        for index, state in enumerate(nts.states):
            state.name = state.name + " (%.2f)" % (force_names[state])
        ts = nts

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Digraph(ts.name, filename=filename.name, engine='dot')

    # states
    viz.attr('node')
    for s in ts.states:
        if show_names:
            viz.node(str(s.name))
        else:
            viz.node(str(s.name), "")
    # arcs
    for t in ts.transitions:
        if show_labels:
            viz.edge(str(t.from_state.name),
                     str(t.to_state.name),
                     label=t.name)
        else:
            viz.edge(str(t.from_state.name), str(t.to_state.name))

    viz.attr(overlap='false')
    viz.attr(fontsize='11')

    viz.format = image_format

    return viz
def visualize(ts, parameters=None, value=None, aggregation_measure=None):
    if parameters is None:
        parameters = {}

    image_format = parameters["format"] if "format" in parameters else "png"
    show_labels = parameters[
        "show_labels"] if "show_labels" in parameters else True
    show_names = parameters[
        "show_names"] if "show_names" in parameters else True
    show_value = False if aggregation_measure is None else True

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Digraph(ts.name, filename=filename.name, engine='dot')

    # states
    viz.attr('node')
    for s in ts.states:
        if show_names:
            viz.node(str(s.name))
        else:
            viz.node(str(s.name), "")
    # arcs
    for t in ts.transitions:
        if show_value:
            aggr_stat = aggregate_stats(t.data[value], aggregation_measure)
            #aggr_stat_hr = human_readable_stat(aggr_stat)
            viz.edge(str(t.from_state.name),
                     str(t.to_state.name),
                     label=str(aggr_stat))
        elif show_labels:
            viz.edge(str(t.from_state.name),
                     str(t.to_state.name),
                     label=t.name)
        else:
            viz.edge(str(t.from_state.name), str(t.to_state.name))

    viz.attr(overlap='false')
    viz.attr(fontsize='11')

    viz.format = image_format

    return viz
Example #17
0
    def render_current_generation(self, folder_name: str):
        """
        this function render the current generation in PNG format with some extra information
        :param folder_name:
        :return:
        """
        g = Digraph()
        g.format = 'png'
        g.directory = folder_name + "/Generation " + str(self.generation)
        counter = 1

        for tree in self.population:
            g.clear()
            info = '"00_comment_00" [label="G : {0}\nF : {1}\nD : {2}\nW : {3}\nn : {4}" , shape="box" , color="white"]'.format(
                self.generation, tree.fitness, tree.depth, tree.width,
                tree.number_of_nodes_in_tree)
            g.body.append(info)
            g.body.append(tree.print_graph())
            g.render("Individual {0}".format(counter))
            counter += 1
Example #18
0
 def graficar(self):
     self.text = ""
     g = Digraph('G', filename='graficaListaUsuarios.gv')
     g.body.append('rankdir=LR')
     g.attr('node', shape='box', color='blue')
     aux = self.first
     if aux == None:
         print "Lista vacia"
         g.body.append('"Lista Vacia"')
     else:
         while True:
             g.body.append('"'+str(aux.nombre)+str(aux.pasword)+'"'+' [label="'+str(aux.nombre)+'\\n'+str(aux.pasword)+'"];\n')
             g.edge(str(aux.nombre)+str(aux.pasword), str(aux.next.nombre)+str(aux.next.pasword))
             g.body.append('[dir=both arrowhead=halfopen color=darkgreen]')
             aux = aux.next
             if (aux == self.last.next):
                 break
     g.body.append('label = "Lista Doblemente Enlazada de Usuarios"; \n')
     g.format = 'png'
     g.render('test-output/Lista-Usuario/graficaListaUsuarios.gv', view=True)
Example #19
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 #20
0
def dot(layers, edges):
    g = Digraph(
        "dag",
        graph_attr={"dpi": str(600)},
        node_attr={
            "fontname": "Courier New",
            "shape": "box"
        },
        edge_attr={"fontname": "Courier New"},
    )
    g.format = "png"

    for layer, width in layers.items():
        g.node(layer, label="{}\n{}".format(layer, width))

    for parents, children in edges:
        for parent, child in itertools.product(parents, children):
            g.edge(parent, child)

    return g
def generate_bn_image(bn):
    """
    Auxiliary function for generating the image of a BN, as model
    methods are not available in migrations.
    """
    dot = Digraph(comment=bn.name)
    nodes = bn.nodes.all()
    for node in nodes:
        dot.node(name=node.name, label=node.name)
    edges = bn.edges.all()
    for edge in edges:
        dot.edge(str(edge.parent.name),
                 str(edge.child.name))
    dot.format = "png"
    contentfile = ContentFile(dot.pipe())
    image_name = "{0}/{1}".format(
        os.path.join("django_ai", "bayesian_networks"),
        bn.name + ".png")
    bn.image.save(image_name, contentfile)
    bn.save()
Example #22
0
def genDag(name, tree):
    dot = Digraph(comment='Dag')

    i = 0
    for triangle in tree:
        addr = triangle['addr']
        valid = triangle["valid"]
        dot.node(addr,'{}({})'.format(addr, valid))
        i += 1

    for triangle in tree:
        addr = triangle['addr']
        children = triangle['children']
        for c in children:
            if None != c:
                dot.edge(addr, c)

    dot.format = 'png'
    dot.render(name)
    return name
Example #23
0
    def doit_each(namelist, dotoption):

        dottree = Digraph("caus")
        dottree.graph_attr["rankdir"] = "TB"
        dottree.graph_attr["concentrate"] = str(dotoption["concentrate"])+";"

        for filename in namelist:

            basename, ext = os.path.splitext(filename)
            print("doit_each, basename", basename)

            with open(filename) as f:
                dataall = yaml.safe_load(f)

            fdtree = FDTree(basename, dottree, dotoption=dotoption)
            dottree = fdtree.apply(dataall, basename=basename, make_png=False)

        dottree.format = "png"
        dottree.render(view=False)
        print("done")
Example #24
0
def plot_node_structure_as_directed_graph(node_structure,
                                          file_prefix='',
                                          drawing_name='tmp_.png',
                                          popup=True,
                                          node_dic=None):
    pure_leaves, admix_leaves, pure_coalescence, admix_coalescence, root, edges, inner_node_colors = node_structure_to_networkx(
        node_structure, node_dic)
    print pure_leaves, admix_leaves, pure_coalescence, admix_coalescence, root, edges, inner_node_colors
    filename, image_format = drawing_name.split('.')
    G = Digraph('G', filename=filename)

    leaves_graph = Digraph('l')
    leaves_graph.node_attr.update(style='filled', color='cadetblue1')
    for leaf in pure_leaves:
        leaves_graph.node(leaf)

    aleaves_graph = Digraph('l')
    aleaves_graph.node_attr.update(style='filled', color='slateblue1')
    for leaf in admix_leaves:
        aleaves_graph.node(leaf)

    admixture_graph = Digraph()
    admixture_graph.node_attr.update(style='filled',
                                     fillcolor='coral1',
                                     shape='box')
    for adm_n in admix_coalescence:
        admixture_graph.node(adm_n, fillcolor=inner_node_colors[adm_n])

    coalescence_graph = Digraph()
    coalescence_graph.node_attr.update(style='filled', fillcolor='greenyellow')
    for cn in pure_coalescence:
        coalescence_graph.node(cn, fillcolor=inner_node_colors[cn])

    G.subgraph(leaves_graph)
    G.subgraph(aleaves_graph)
    G.subgraph(admixture_graph)
    G.subgraph(coalescence_graph)
    G.node('r', shape='egg', color='black', style='filled', fontcolor='white')
    G.edges(edges)
    G.format = image_format
    G.render(view=popup)
def resource_tracker_graph(request):
    dot = Digraph(comment='Graph')
    dot.attr(bgcolor=COLORS["transparent"])
    dot.name = 'Resource Tracker Graph'
    dot.attr('node', shape='plaintext')

    tags = Tag.objects.all()
    resource_graph_filtered = GraphFilter(request.GET, queryset=tags)

    display_graph = False

    if "tag" in request.GET:
        tag_list = request.GET.getlist("tag")
        resource_pool_queryset = ResourcePool.objects.filter(tags__name__in=tag_list)
        resource_group_queryset = ResourceGroup.objects.filter(tags__name__in=tag_list)
    else:
        resource_pool_queryset = ResourcePool.objects.all()
        resource_group_queryset = ResourceGroup.objects.all()

    for resource_pool in resource_pool_queryset:
        dot.node(f'{get_graph_name(resource_pool)}', label=create_resource_pool_svg(resource_pool))
        display_graph = True
    for resource_group in resource_group_queryset:
        display_graph = True
        dot.node(f'{get_graph_name(resource_group)}', label=create_resource_group_svg(resource_group))
        for attribute in resource_group.attribute_definitions.filter():
            rg = f'{get_graph_name(resource_group)}:{attribute.name}'
            if attribute.consume_from:
                dot.edge(f'{get_graph_name(attribute.consume_from.resource_pool)}:{attribute.consume_from.name}', rg,
                         color=COLORS['provider'])
            if attribute.produce_for:
                dot.edge(rg, f'{get_graph_name(attribute.produce_for.resource_pool)}:{attribute.produce_for.name}',
                         color=COLORS['consumer'])

    dot.format = 'svg'
    svg = mark_safe(dot.pipe().decode('utf-8'))

    return render(request, 'resource_tracking/graph/resource-tracker-graph.html',
                  context={'svg': svg,
                           'display_graph': display_graph,
                           'resource_graph': resource_graph_filtered})
Example #26
0
 def make_sub_graph(self, function_object):
     all_calls_address = []
     all_funcs = []
     all_function_address = []
     sub_graph = Digraph(
         "cluster_" + function_object.get_extra_string(),
         graph_attr={"label": function_object.get_extra_string()})
     sub_graph.format = 'svg'
     function_object.mark_visited()
     for f in function_object.get_sub_functions():
         if not f.has_visited(
         ) and f.get_sub_function_type() != eSubFunctionType.Unknown:
             sub_graph.subgraph(self.make_sub_graph(f))
         else:
             all_function_address.append(f.get_start_address())
             all_funcs.append(f)
             all_calls_address.extend(f.get_calls())
     for n in all_function_address:
         # string = "{:4X}".format(n)
         string = Regenerator.Regenerator_getLabelForAddr(n)
         sub_graph.node(string)
     for address in all_calls_address:
         # string = "{:4X}".format(address)
         string = Regenerator.Regenerator_getLabelForAddr(address)
         sub_graph.node(string, shape='cds')
     for f in all_funcs:
         for jump in f.get_jumps():
             # stringA = "{:4X}".format(f.getStartAddr())
             string_a = Regenerator.Regenerator_getLabelForAddr(
                 f.get_start_address())
             # stringB = "{:4X}".format(jump)
             string_b = Regenerator.Regenerator_getLabelForAddr(jump)
             sub_graph.edge(string_a, string_b)
         for call in f.get_calls():
             # stringA = "{:4X}".format(f.getStartAddr())
             string_a = Regenerator.Regenerator_getLabelForAddr(
                 f.get_start_address())
             # stringB = "{:4X}".format(call)
             string_b = Regenerator.Regenerator_getLabelForAddr(call)
             sub_graph.edge(string_a, string_b, color='red')
     return sub_graph
Example #27
0
def generate_png(story_id):
    story = Story.query.get_or_404(story_id)
    res = Response()
    g = Digraph(story.name)
    for step in story.steps:
        if step.final:
            g.node('step_%d' % step.id, label=step.name, color="lightblue2", style="filled")
        else:
            g.node('step_%d' % step.id, label=step.name)
        if step.first_choice_step_id:
            g.edge('step_%d' % step.id, 'step_%d' % step.first_choice_step_id, label = step.first_choice)
        if step.second_choice_step_id:
            g.edge('step_%d' % step.id, 'step_%d' % step.second_choice_step_id, label = step.second_choice)
    if str(request.url_rule).endswith('dot'):
        res.content_type = "text/plain"
        res.data = g.source
    elif str(request.url_rule).endswith('png'):
        g.format = 'png'
        res.content_type = 'image/png'
        res.data = g.pipe()
    return res
Example #28
0
 def graph(self):
     dot = Digraph(comment='Cola Circular de Canciones')
     dot.format = 'png'
     actual = self.primero
     if self.size == 1:
         dot.node(
             str(0), 'Artista - ' + actual.getDatos().getArtista() +
             '\nCancion: ' + actual.getDatos().getCancion())
         dot.edge(str(0), str(0), constraint='false')
     elif self.size == 2:
         i = 0
         while actual:
             dot.node(
                 str(i), 'Artista - ' + actual.getDatos().getArtista() +
                 '\nCancion: ' + actual.getDatos().getCancion())
             actual = actual.getSiguiente()
             i += 1
             if actual == self.primero:
                 break
             dot.edge(str(i), str(i - 1), constraint='false')
         dot.edge(str(0), str(i - 1), constraint='false')
     elif self.size > 2:
         i = 0
         while actual:
             dot.node(
                 str(i), 'Artista - ' + actual.getDatos().getArtista() +
                 '\nCancion: ' + actual.getDatos().getCancion())
             actual = actual.getSiguiente()
             i += 1
             if actual == self.primero:
                 break
             dot.edge(str(i - 1), str(i), constraint='false')
             dot.edge(str(i), str(i - 1), constraint='false')
         dot.edge(str(i - 1), str(0), constraint='false')
         dot.edge(str(0), str(i - 1), constraint='false')
     dot.render(filename="colaCanciones",
                directory="C:\\Graphs\\",
                view=True,
                cleanup=True)
     print dot
Example #29
0
    def makeGraphviz(self):
        """générer l'objet graphviz
        :rtype: None
        """
        dot = Digraph(comment="graphe MPM",
                      node_attr={"shape":"plaintext"})
        dot.attr("graph", rankdir="LR")
        dot.format = "png"
        # création des sous-graphes par niveau
        NIVtmp = list(set(self.niveaux.values()))
        NIV = sorted(NIVtmp)

        for N in NIV:
            with dot.subgraph(name=f"cluster_{N}",
                              node_attr={'rank': 'same'}) as c:
                c.attr(style="invis") # désactivation du cadre de cluster
                if self.show_level:
                    c.node(f"niv{N}")
                for k, n in self.sommets.items(): # key, noeud
                    if self.niveaux[k] == N:
                        c.node(str(k), f"<{n.noeud}>")
                        # la str html doit être encadrée de <>

        # branchement du nœud de départ:
        dot.node("debut", self.titre_debut, shape='ellipse')
        for k, n in self.sommets.items(): # key, noeud
            if self.niveaux[k] == NIV[0]:
                dot.edge("debut", k)

        # création des autres arcs, pondérés
        for k, L in self.successeurs.items():
            for i in list(L):
                dot.edge(k, i, label=str(self.ponderation[k]),
                         tailport="here", headport="here") # from to
        # création des liaisons de titres de niveaux
        if self.show_level:
            for N in NIV[:-1]:
                dot.edge(f"niv{N}", f"niv{N+1}", style='invis')

        self.gv = dot
Example #30
0
 def generate_class_diagram(self, output_file_name=None):
     if output_file_name is None:
         output_file_name = self.output_class_diagram
     try:
         dot = Digraph(comment='UML Class Diagram')
         dot.node_attr['shape'] = "record"
         dot.format = "dot"
         if len(self.components) > 0:
             for comp in self.components:
                 attributes = self._build_attributes_string(
                     comp.get_attributes())
                 functions = ""
                 for funct in comp.get_functions():
                     functions += funct + "\\n"
                 record = "{"
                 record += "{name} | {attribs} |{functs}".format(
                     name=comp.get_name(),
                     attribs=attributes,
                     functs=functions)
                 record += "}"
                 dot.node(comp.get_name(), record)
                 for parent in comp.get_parents():
                     dot.edge(parent.get_name(), comp.get_name())
                     dot.edge_attr.update(dir="back")
                     dot.edge_attr.update(arrowtail='empty')
             dot.render(output_file_name, view=False)
             self.write_dot_to_png(dot_file=output_file_name)
             if path.exists(output_file_name):
                 remove(output_file_name)
             if path.exists(output_file_name + ".dot"):
                 remove(output_file_name + ".dot")
         else:
             print("no components were found")
     except ExecutableNotFound:
         print(
             "Graphviz executable not found, please check it is properly installed."
         )
     except (CalledProcessError, RuntimeError) as err:
         print("An unexpected error occurred")
         print(err)
Example #31
0
def draw_fa(fa, final, start, file_name="my_first"):
    dot = Digraph('finite_state_machine')
    dot.attr(rankdir='LR', size='8,5')
    dot.format = 'png'
    edges_ls = []

    for n in fa:
        if n in final:
            dot.attr('node', shape='doublecircle')
            dot.node(str(n))
        elif n == start:
            dot.attr('node', shape="Mcircle")
            dot.node(str(n))
        else:
            dot.attr('node', shape="ellipse")
            dot.node(str(n))

    for node in fa:
        dot.node(str(node), str(node))
        if len(fa[node]) == 0:
            pass
        else:
            for symbol in fa[node]:
                try:
                    for s in fa[node][symbol]:
                        edges_ls.append([str(node), str(s), str(symbol)])
                except:
                    edges_ls.append(
                        [str(node),
                         str(fa[node][symbol]),
                         str(symbol)])

    for e in edges_ls:
        dot.edge(e[0], e[1], label=e[2])
    dot.view()
    isSave = input("Do you want to save this[Y/N] ")
    if isSave == 'Y':
        f_name = input("Enter the file name to save the nfa in png ")
        dot.render('output/' + f_name, view=True)
        print("File saved at output/" + f_name + '.png')
Example #32
0
    def graph_by_epics(self) -> None:
        output = self.config['output']['epics']
        graph_file = output['graph']
        logger.info(f"generating {graph_file}")
        graph = Digraph(comment = f"Generated on {self.config['generated']}", graph_attr = {'rankdir': 'LR', 'splines': 'ortho'}, node_attr = {'shape': 'none'})

        for epic in self.jira.sorted_by_key(self.jira.epics.values()):
            self.add_node(graph, epic)

            for story in self.jira.sorted_by_key(epic.stories):
                self.add_node(graph, story)
                self.add_edge(graph, epic, story)
                for risk in self.jira.sorted_by_key(story.risks):
                    self.add_node(graph, risk)
                    self.add_edge(graph, story, risk)
                for test in self.jira.sorted_by_key(story.tests):
                    self.add_node(graph, test)
                    self.add_edge(graph, story, test)

        graph.engine = output['engine']
        graph.format = output['format']
        graph.render(filename = graph_file, cleanup = False, view = False)
Example #33
0
  def graph(self):
    dot = Digraph(comment='chem', engine='neato')

    label = ['OUT LEFT', 'OUT RIGHT', 'FOOD', 'WATER']

    for i, chem in enumerate(self.controller.chemicals):
      atts = { 'fontsize': '10'}
      if i < len(label):
        dot.node(chem.formula, shape='rectangle', fillcolor='gold', style='filled', label=f'<<b>{label[i]}</b><br/>{chem.formula}>', **atts)
      else:
        dot.node(chem.formula, shape='rectangle', label=f'<{chem.formula}>', **atts)
    
    for rxn in self.controller.reactions:
      atts = {'fontsize' : '10'}
      dot.node(str(rxn), shape='plaintext', label=f'<<b>{str(rxn)}</b><br/>>', **atts)
      for lhs_chem in rxn.lhs:
        dot.edge(str(rxn), lhs_chem.formula)
      for rhs_chem in rxn.rhs:
        dot.edge(str(rxn), rhs_chem.formula)

    dot.format = 'png'
    dot.render('plot-graph')
    def graficar(self):
        dot = Digraph(node_attr={'shape': 'record'})
        i = 0
        st = ""
        while i < len(self.tabla):
            if len(self.tabla[i].cont) > 0:
                if self.tabla[i].cont[0].bandera == False:
                    if i == len(self.tabla) - 1:
                        st = st + "<" + str(i) + "N" + "0" + "> " + str(
                            i) + "." + str(self.tabla[i].cont[0].usuario)
                    else:
                        st = st + "<" + str(i) + "N" + "0" + "> " + str(
                            i) + "." + str(
                                self.tabla[i].cont[0].usuario) + " |"

                    if len(self.tabla[i].cont) > 1:
                        j = 1
                        while (j < len(self.tabla[i].cont)):
                            if self.tabla[i].cont[j].bandera == False:
                                dot.node(
                                    str(i) + "N" + str(j),
                                    str(self.tabla[i].cont[j].usuario))
                                if j + 1 <= len(self.tabla[i].cont) - 1:
                                    dot.edge(
                                        str(i) + "N" + str(j),
                                        str(i) + "N" + str(j + 1))
                            j = j + 1
                        dot.edge("tabla:" + str(i) + "N" + "0",
                                 str(i) + "N" + str(1))
                else:
                    st = st + "<" + str(i) + "N" + "0" + "> " + str(
                        i) + "." + str("Vacio") + " |"
            else:
                st = st + "<" + str(i) + "N" + "0" + "> " + str(i) + "." + str(
                    "Vacio") + " |"
            i = i + 1
        dot.node("tabla", st)
        dot.format = 'png'
        dot.render("hashprro")
Example #35
0
def plot_as_directed_graph(tree,
                           file_prefix='',
                           drawing_name='tmp.png',
                           popup=True,
                           plot_edge_lengths=False):

    leaves, admixture_nodes, coalescence_nodes, root, edges, edge_lengths = to_networkx_format(
        tree)
    filename, image_format = drawing_name.split('.')
    G = Digraph('G', filename=filename)

    leaves_graph = Digraph('l')
    leaves_graph.node_attr.update(style='filled', color='cadetblue1')
    for leaf in leaves:
        leaves_graph.node(leaf)

    admixture_graph = Digraph()
    admixture_graph.node_attr.update(style='filled',
                                     fillcolor='coral1',
                                     shape='box')
    for adm_n in admixture_nodes:
        admixture_graph.node(adm_n)

    coalescence_graph = Digraph()
    coalescence_graph.node_attr.update(style='filled', fillcolor='greenyellow')
    for cn in coalescence_nodes:
        coalescence_graph.node(cn)

    G.subgraph(leaves_graph)
    G.subgraph(admixture_graph)
    G.subgraph(coalescence_graph)
    G.node('r', shape='egg', color='black', style='filled', fontcolor='white')
    if plot_edge_lengths:
        for (to_node, from_node), label in zip(edges, edge_lengths):
            G.edge(to_node, from_node, label=label)
    else:
        G.edges(edges)
    G.format = image_format
    G.render(view=popup)
Example #36
0
    def graficar(self,usuario):
        #self.verify()
        g = Digraph('G', filename='graficaColaCircular.gv')
        g.body.append('rankdir=LR')
        g.attr('node', shape='Mdiamond', color='blue')

        aux = self.front
        if aux == None:
            g.edge(usuario,str('Cola esta vacia'))
        else:
            g.body.append('"'+usuario+'"->"'+str(aux.nombre)+'"')
            g.body.append('subgraph cluster_0 {')
            g.body.append('style=filled; color=lightgrey; node [style=filled,color=white];')
            while True:
                g.edge(str(aux.nombre), str(aux.next.nombre))
                aux = aux.next
                if (aux == self.front):
                    break
            g.body.append('}')
            g.body.append('label = "Play List del Usuario";')
        g.format = 'png'
        g.render('test-output/Cola-PlayList/graficaColaCircular.gv', view=True)
Example #37
0
    def drawStockTree(self, N=10):
        graph = Digraph(name='Stock Price Tree')
        deltat = self.T / N
        u = np.exp(self.sigma * np.sqrt(deltat))
        d = 1 / u
        a = np.exp(self.r * deltat)
        p = (a - d) / (u - d)

        # 計算出各節點之值並放入點中
        for i in range(N + 1):
            for j in range(i + 1):
                graph.node('S{},{}'.format(i, j),
                           '{:0.2f}'.format(self.S * u**j * d**(i - j)))

        # 連接點跟點
        for i in range(N):
            for j in range(i + 1):
                graph.edge('S{},{}'.format(i, j), 'S{},{}'.format(i + 1, j))
                graph.edge('S{},{}'.format(i, j),
                           'S{},{}'.format(i + 1, j + 1))
        graph.format = 'png'
        graph.render('C:/Users/User/Desktop/PriceTree{}'.format(N))
Example #38
0
    def print_state_diagram(self):
        print('model_print_state_diagram')
        dot = Digraph()
        states = []
        transitions = []

        for s in self.states:
            if s in self.accept:
                label = (str(s), {'label': "q_accept"})
            elif s in self.reject:
                label = (str(s), {'label': "q_reject"})
            else:
                label = (str(s), {'label': str(s)})

            if s == self.currstate[0]:
                label[1]['color'] = 'red'
                label[1]['weight'] = '5'

            states += [label]

        for preimage, image in self.delta.iteritems():
            if preimage[1]:
                label = u'%s \u2192 ' % (max(preimage[1], ''))

                if image[1]:
                    label += u'%s,' % (max(image[1], ''))

                if image[2] > 0:
                    label += u'R'
                elif image[2] == 0:
                    label += u'S'
                elif image[2] < 0:
                    label += u'L'

                key = str(preimage[0]), str(image[0])
                transitions += [((key), {'label': label})]

        dot.format = 'gif'
        add_edges(add_nodes(dot, states), transitions).render('imgs/temp')
Example #39
0
    def viz_search_tree(self, viz_file):
        G = Digraph('G', filename=viz_file)
        G.attr(rankdir='LR')
        G.attr('node', shape='box')
        G.format = 'pdf'

        node_queue = Queue()
        node_queue.put((self.root, None))
        while not node_queue.empty():
            node, parent = node_queue.get()

            if node.open:
                color = 'lightgrey'
            else:
                color = 'aquamarine'

            if hasattr(node, 'mol'):
                shape = 'box'
            else:
                shape = 'rarrow'

            if node.succ:
                color = 'lightblue'
                if hasattr(node, 'mol') and node.is_known:
                    color = 'lightyellow'

            G.node(node.serialize(), shape=shape, color=color, style='filled')

            label = ''
            if hasattr(parent, 'mol'):
                label = '%.3f' % node.cost
            if parent is not None:
                G.edge(parent.serialize(), node.serialize(), label=label)

            if node.children is not None:
                for c in node.children:
                    node_queue.put((c, node))

        G.render()
Example #40
0
    def save_graph(self,
                   out_prefix,
                   out_format='pdf',
                   title=None,
                   passage_labels=True,
                   link_labels=False,
                   remove_singletons=False,
                   char_limit=80):
        """Saves a graph representation of the story to a file."""
        comment = title if title is not None else out_prefix
        dot = Digraph(comment=comment)

        # Find singletons
        if remove_singletons:
            pids_linked = set()
            for passage in self.story["passages"]:
                if passage["links"]:
                    pids_linked.add(passage["pid"])
                for link in passage["links"]:
                    pids_linked.add(link["destination"]["pid"])

        # Determine node name for each passage and create nodes
        for passage in self.story["passages"]:
            if remove_singletons and passage["pid"] not in pids_linked:
                continue
            label = self._trim_text(passage["name"],
                                    char_limit) if passage_labels else None
            dot.node(str(passage["pid"]), label)

        # Create edges for passages
        for passage in self.story["passages"]:
            for link in passage["links"]:
                label = self._trim_text(link["text"],
                                        char_limit) if link_labels else None
                dot.edge(str(passage["pid"]), str(link["destination"]["pid"]),
                         label)
        dot.format = out_format
        dot.render(f"{out_prefix}.gv")
Example #41
0
    def graphviz(self):
        d = self.graph()

        from graphviz import Digraph
        dot = Digraph(self._name, strict=True)
        dot.format = 'png'

        def rec(nodes, parent):
            for d in nodes:
                if not isinstance(d, dict):
                    if '(dirty)' in d:
                        dot.node(d.replace('(dirty)', ''), color='red')
                        dot.edge(d.replace('(dirty)', ''),
                                 parent.replace('(dirty)', ''),
                                 color='red')
                    else:
                        dot.node(d)
                        dot.edge(d, parent.replace('(dirty)', ''))
                else:
                    for k in d:
                        if '(dirty)' in k:
                            dot.node(k.replace('(dirty)', ''), color='red')
                            rec(d[k], k)
                            dot.edge(k.replace('(dirty)', ''),
                                     parent.replace('(dirty)', ''),
                                     color='red')
                        else:
                            dot.node(k)
                            rec(d[k], k)
                            dot.edge(k, parent.replace('(dirty)', ''))

        for k in d:
            if '(dirty)' in k:
                dot.node(k.replace('(dirty)', ''), color='red')
            else:
                dot.node(k)
            rec(d[k], k)
        return dot
Example #42
0
    def visualize(dag, view_immediately=False, filename="dag"):
        dot = Digraph(name='DAG', node_attr={
            'shape':'box',\
            'style': "rounded"})
        dot.attr(rankdir='RL')
        links = []

        max_block_number = max(dag.blocks_by_number.keys())
        for number in range(max_block_number + 1):
            block_list_by_number = dag.blocks_by_number.get(number, [])

            with dot.subgraph() as sub:
                sub.attr(rank='same')

                #place number
                sub.node(str(number), shape="plain")
                if number != 0:
                    dot.edge(str(number), str(number - 1), style="invis")

                #add blocks on this level if any
                for block in block_list_by_number:
                    links += block.block.prev_hashes
                    blockhash = block.get_hash()
                    color = 'black'
                    if blockhash == dag.genesis_block().get_hash():
                        color = 'blue'
                    sub.node(blockhash.hex()[:SUFFIX_LEN], color=color)

        for _, signed_block in dag.blocks_by_hash.items():
            block_hash = signed_block.get_hash()
            for prev_hash in signed_block.block.prev_hashes:
                dot.edge(block_hash.hex()[:SUFFIX_LEN],
                         prev_hash.hex()[:SUFFIX_LEN],
                         constraint='true')
        #set view to True to instantly render and open pdf
        #Note, that you will need 'graphviz' package installed
        dot.format = "png"
        dot.render('visualization/' + filename + '.dot', view=view_immediately)
Example #43
0
def plot_graph_bfs(g, vertex_count, depth=5):
    s, t = 0, vertex_count - 1
    used = [False for _ in range(vertex_count)]
    used[s] = True

    d = Digraph()

    q_cur = [s]
    q_next = []
    for _ in range(depth):
        print('q_cur', len(q_cur))
        for u in q_cur:
            for v in g[u]:
                if not used[v]:
                    used[v] = True
                    d.edge(str(u), str(v))
                    q_next.append(v)
        q_cur = q_next
        q_next = []

    name = f'bfs_prefix_{depth}'
    d.format = 'png'
    d.render(f'output/graphviz/{name}.gv', view=True)
Example #44
0
def GraphViz(f_wrap, name='Graph'):
    d = Graph(f_wrap)
    from graphviz import Digraph
    dot = Digraph(name, strict=True)
    dot.format = 'png'

    def rec(nodes, parent):
        for d in nodes:
            if not isinstance(d, dict):
                dot.node(d)
                dot.edge(d, parent)

            else:
                for k in d:
                    dot.node(k)
                    rec(d[k], k)
                    dot.edge(k, parent)

    for k in d:
        dot.node(k)
        rec(d[k], k)

    return dot
Example #45
0
    def toGraphvizSource(self):
        """
        Generate graphviz code that can be used to draw the automaton.

        :return: graphviz code
        """
        dot = Digraph(engine="neato")
        dot.graph_attr.update(size="4,4")

        for v_idx in range(len(self.vertices)):
            vertex_style = "doublecircle" if len(self.vertices[v_idx].output_fun) > 0 else "circle"
            if v_idx == 0: vertex_style = "point"
            dot.node(str(v_idx), str(v_idx), shape=vertex_style)

        for v_idx in range(len(self.vertices)):
            for c in self.vertices[v_idx].next:
                to_idx = self.vertices[v_idx].next[c]
                dot.edge(str(v_idx), str(to_idx), label=c, constraint="false")

        dot.format = "png"
        dot.render('automaton')

        return dot.source
Example #46
0
# encoding: utf8
from graphviz import Digraph, Graph

graph = Digraph(comment='Test')
graph.format = 'png'

graph1 = Digraph('S1')
graph1.node('A')
graph1.node('Test1')
graph1.node('Test2')

graph2 = Digraph('S2')
graph2.node('B')
graph2.node('C')

graph.subgraph(graph1)
graph.subgraph(graph2)

graph.edge(head_name='S1', tail_name='S2')

graph.render('test')
Example #47
0
      if num_cycle==cycle_max:
         redoGen=True
         break

   if(redoGen==True):
      genSuccess=False
      continue
   else:
      genSuccess=True
      break

labeled_trans = num_to_labels(nodematrix, num_nodes)


f = Digraph('finite_state_machine', filename='tmp/fsm')
f.format='pdf'
f.attr('graph',overlap='false',size="7,8!")
f.attr('node', shape='circle')
f.attr('edge',overlap='false')

node_names=[]
for i in range(0,num_nodes):
    if(i==0):
        node_names.append("START")
    else:
        node_names.append("S{0}".format(i-1))

for i in range (0, num_nodes, 1):
      for j in range(0, num_nodes, 1):
         if nodematrix[i][j] > 0:
            f.edge(node_names[i], node_names[j]," "+ labeled_trans[i][j]+ "  ")
Example #48
0
def drawDiagram(modelXbrl, diagramFile, diagramNetwork=None, viewDiagram=False):
    if diagramNetwork not in diagramNetworks:
        modelXbrl.error("objectmaker:diagramNetwork",
                        "Diagram network %(diagramNetwork)s not recognized, please specify one of %(recognizedDiagramNetworks)s",
                        modelXbrl=modelXbrl, diagramNetwork=diagramNetwork, recognizedDiagramNetworks=", ".join(diagramNetworks))
        return
        
    try:
        from graphviz import Digraph, backend
    except ImportError:
        modelXbrl.error("objectmaker:missingLibrary",
                        "Missing library, please install graphviz for python importing",
                        modelXbrl=modelXbrl)
        return
    
    isUML = diagramNetwork == "uml"
    isBaseSpec = diagramNetwork in ("pre", "cal", "def")
    graphName = os.path.splitext(modelXbrl.modelDocument.basename)[0]
    mdl = Digraph(comment=graphName)
    mdl.attr("graph")
    mdl.node('node_title', graphName, shape="none", fontname="Bitstream Vera Sans")
    mdl.attr('node', shape="record")
    mdl.attr('node', fontname="Bitstream Vera Sans")
    mdl.attr('node', fontsize="8")
    
    if isUML:
        arcroleName = "http://xbrl.us/arcrole/Property"
        propertiesRelationshipSet = modelXbrl.relationshipSet(arcroleName)
        if not propertiesRelationshipSet:
            modelXbrl.modelManager.addToLog(_("no relationships for {0}").format(arcroleName))
            return False

    def node(mdl, id, modelObject):
        if modelObject is not None:
            mdl.attr("node", style="") # white classes
            if isUML:
                _properties = "".join("+{} {}\l".format(rel.toModelObject.qname.localName, rel.toModelObject.niceType)
                                                        for rel in propertiesRelationshipSet.fromModelObject(modelObject)
                                                        if rel.toModelObject is not None)
                mdl.node(id, "{{{}|{}}}".format(modelObject.qname.localName, _properties))
            elif isBaseSpec and isinstance(modelObject, ModelConcept):
                concept = modelObject
                if concept.isHypercubeItem:
                    _properties = "Hypercube"
                elif concept.isExplicitDimension:
                    _properties = "Dimension, Explicit"
                elif concept.isExplicitDimension:
                    _properties = "Dimension, Typed ({} {})".format(typedDomainElement.qname, typedDomainElement.niceType)
                elif concept.isEnumeration:
                    _properties = "Enumeration ({})".format(concept.enumDomain.qname)
                else:
                    _properties = "{}{}".format("Abstract " if modelObject.isAbstract else "",
                                                modelObject.niceType)
                mdl.node(id, "{{{}|{}}}".format(modelObject.qname.localName, _properties))
            elif isinstance(modelObject, ModelDocument.ModelDocument):
                mdl.node(id, "{{{}|{}}}".format(modelObject.basename, modelObject.gettype()))
            elif isinstance(modelObject, str): # linkrole definition
                mdl.node(id, "{{{}}}".format(modelObject))
            else:
                mdl.node(id, "{{{}}}".format(modelObject.qname.localName))
    
    nodes = set()
    edges = set()
    arcroles = diagramNetworks[diagramNetwork]

    lang = None # from parameter for override

    # sort URIs by definition
    linkroleUris = set()
    if isBaseSpec:
        for arcrole in arcroles:
            graphRelationshipSet = modelXbrl.relationshipSet(arcrole)
            for linkroleUri in graphRelationshipSet.linkRoleUris:
                modelRoleTypes = modelXbrl.roleTypes.get(linkroleUri)
                if modelRoleTypes:
                    roledefinition = (modelRoleTypes[0].genLabel(lang=lang, strip=True) or modelRoleTypes[0].definition or linkroleUri)                    
                else:
                    roledefinition = linkroleUri
                linkroleUris.add((roledefinition, linkroleUri))
    else:
        linkroleUris.add((None, None))

    for roledefinition, linkroleUri in sorted(linkroleUris):
        for arcrole in arcroles:
            relationshipType = arcrole.rpartition("/")[2].lower()
            edgeType = networkEdgeTypes[diagramNetwork][relationshipType]
            graphRelationshipSet = modelXbrl.relationshipSet(arcrole, linkroleUri)    
            roleprefix = (linkroleUri.replace("/","_").replace(":","_") + "_") if linkroleUri else ""
            if not graphRelationshipSet:
                continue
            if linkroleUri is not None:
                node(mdl, roleprefix, roledefinition or roleUri)
                for rootConcept in graphRelationshipSet.rootConcepts:
                    childName = roleprefix + rootConcept.qname.localName
                    node(mdl, childName, rootConcept)
                    nodes.add(childName)
                    mdl.edge(roleprefix, childName, 
                             dir=edgeType.get("dir"), arrowhead=edgeType.get("arrowhead"), arrowtail=edgeType.get("arrowtail"))
            for rel in graphRelationshipSet.modelRelationships:
                parent = rel.fromModelObject
                parentName = roleprefix + parent.qname.localName
                child = rel.toModelObject
                if child is None:
                    continue
                childName = roleprefix + child.qname.localName
                if parentName not in nodes:
                    node(mdl, parentName, parent)
                    nodes.add(parentName)
                if childName not in nodes:
                    node(mdl, childName, child)
                    nodes.add(childName)
                edgeKey = (relationshipType, parentName, childName)
                if edgeKey not in edges:
                    edges.add(edgeKey)
                    mdl.edge(parentName, childName, 
                             dir=edgeType.get("dir"), arrowhead=edgeType.get("arrowhead"), arrowtail=edgeType.get("arrowtail"))
    
    if diagramNetwork == "dts":
        def viewDtsDoc(modelDoc, parentDocName, grandparentDocName):
            docName = modelDoc.basename
            docType = modelDoc.gettype()
            if docName not in nodes:
                node(mdl, docName, modelDoc)
            if parentDocName:
                edgeKey = (parentDocName, docType, docName)
                if edgeKey in edges:
                    return
                edges.add(edgeKey)
                edgeType = networkEdgeTypes[diagramNetwork]["all-types"]
                mdl.edge(parentDocName, docName, 
                         dir=edgeType.get("dir"), arrowhead=edgeType.get("arrowhead"), arrowtail=edgeType.get("arrowtail"))
            for referencedDoc in modelDoc.referencesDocument.keys():
                if referencedDoc.basename != parentDocName: # skip reverse linkbase ref
                    viewDtsDoc(referencedDoc, docName, parentDocName)
            
        viewDtsDoc(modelXbrl.modelDocument, None, None)
            
    mdl.format = "pdf"
    try:
        mdl.render(diagramFile.replace(".pdf", ".gv"), view=viewDiagram)
    except backend.ExecutableNotFound as ex:
        modelXbrl.warning("objectmaker:graphvizExecutable",
                        "Diagram saving requires installation of graphviz, error: %(error)s:",
                        modelXbrl=modelXbrl, error=ex)
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.node(node.name, node.name)
        node = chain_holder.get_next_node(curr_node_name=node.name)

    # Add connections
    node = chain_holder.get_next_node()
    processed_nodes = sets.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.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.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 #50
0
import simplejson
import sys
import pydot
from graphviz import Digraph

dot = Digraph(comment='Ceph Crush Map')
dot.graph_attr['size'] = '100,500'
dot.graph_attr['resolution'] = '200'
dot.graph_attr['bb'] = '0,0,4,8'
dot.format = 'png'
m = sys.argv[1]

data_file = open(m)

cm = simplejson.load(data_file)

print (str(cm)+'\n')

print (str(cm.keys())+'\n')
print (str(cm['devices'])+'\n')

graph = pydot.Dot('ceph_crushmap', graph_type='digraph')

for i in range(len(cm['devices'])):
  dot.node(str(cm['devices'][i]['id']), 'device: '+cm['devices'][i]['name'], {'style':'filled','fillcolor':'Yellow'}) 

for i in range(len(cm['buckets'])):
  dot.node(str(cm['buckets'][i]['id']), cm['buckets'][i]['type_name']+': '+cm['buckets'][i]['name'], {'style':'filled','fillcolor':'Red'}) 

for i in range(len(cm['rules'])):
  dot.node('rule'+str(i), str(cm['rules'][i]), {'style':'filled','shape':'box', 'fillcolor':'Blue'})