Example #1
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
Example #2
0
    def generate_dot(self, graph_input):
        dot = Digraph("Traceable relationships",
                      comment="Traceable relationships")
        dot.body.append("rankdir=LR")
        dot.attr("graph", fontname="helvetica", fontsize="7.5")
        dot.attr("node", fontname="helvetica", fontsize="7.5")
        dot.attr("edge", fontname="helvetica", fontsize="7.5")

        # Group traceables by their category.
        categorized = {}
        for traceable in graph_input.traceables:
            category = traceable.attributes.get("category")
            categorized.setdefault(category, []).append(traceable)

        # Create subgraphs for each category so that its traceables lineup.
        for category, traceables in categorized.items():
            subgraph = Digraph(str(category))
            subgraph.body.append("rank=same")
            for traceable in traceables:
                self.add_dot_traceable(subgraph, traceable)
            dot.subgraph(subgraph)

        # Add the relationships between traceables.
        for relationship_info in graph_input.relationships:
            traceable1, traceable2, relationship, direction = relationship_info
            src = traceable1.tag if direction >= 0 else traceable2.tag
            dst = traceable2.tag if direction >= 0 else traceable1.tag
            reverse = self.storage.get_relationship_opposite(relationship)
            dot.edge(src, dst, headlabel=reverse, taillabel=relationship,
                     labelfontsize="7.0", labelfontcolor="#999999")

        return dot.source
Example #3
0
def nlp44(sentence: str) -> None:
    chunks = get_chunk_list(sentence)
    G = Digraph(format='png')
    G.attr('node', shape='circle')
    for i, chunk in enumerate(chunks):
        G.edge(chunk.join_morphs(), chunks[chunk.dst].join_morphs())
    G.render('cabocha_tree')
    return
Example #4
0
class BrainGraph:
    def __init__(self, brain, name='brain', typename='brain'):
        self.graph = Digraph(typename, filename=name, format='png')
        self.brain = brain

    def add_node(self, node_id, node_type, text):
        """
        Add node to graph
        @param node_id: id of node
        @param node_type: type of node
        @param text: text to show inside node
        """
        if node_type == 'Input':
            self.graph.attr('node', shape='circle')
        elif node_type == 'Oscillator':
            self.graph.attr('node', shape='square')
        self.graph.node(node_id, label=text)

    def add_edge(self, source_id, desitnation_id, label):
        """
        Add edge to graph
        @param source_id: id of source node
        @param destination_id: id of destination node
        @param label: label of edge
        """
        self.graph.edge(source_id, desitnation_id, label)

    def save_graph(self):
        """
        Save graph
        """
        self.graph.render()

    def brain_to_graph(self):
        """
        Export complete brain to graph
        """

        nodes = self.brain.nodes
        params = self.brain.params
        # belongs to TODO
        duplicates = fnmatch.filter(nodes, 'node*-*')
        for node in nodes:
            # TODO REMOVE condition WHEN duplicated nodes bug is fixed -- duplicated nodes end in '-[0-9]+' or '-core[0-9]+' (node2-2, node2-core1)
            if node not in duplicates:
                node_id = nodes[node].id
                text = node_id
                if node_id in params:
                    param = params[node_id]
                    text += '\n Oscillator {0} \n period: {1} \n phase_offset: {2} \n amplitude: {3}'.format(
                        nodes[node].part_id, params[node_id].period, params[node_id].phase_offset, params[node_id].amplitude)
                self.add_node(node_id, nodes[node].type, text)

        for connection in self.brain.connections:
            self.add_edge(str(connection.src), str(connection.dst), str(connection.weight))
Example #5
0
def make_graph_visualization(graph, f_name, methods_hash):
	dot = Digraph('Classes Graph')
	dot.attr('node', shape='box')
	for key in graph.keys():
		methods_str = '()\n'.join([methods_hash[x]['name'] for x in graph[key]['members'].split(' ')
							if x in methods_hash.keys()])
		dot.node(key, label=graph[key]['name'] + '\n_______\n' + methods_str + '()')
	for key in graph.keys():
		if graph[key]['children'] == '': continue
		for child in graph[key]['children'].split(' '):
			dot.edge(key, child)
	#print(dot.source)
	dot.render(f_name, None, True)
Example #6
0
def draw_causal_graph(result_order, result_matrix, observed_data_labels, output_name='graph', format='png'):
    G = Digraph(format=format, engine='dot')
    G.attr('node', shape='circle')
    for label in observed_data_labels:
        G.node(str(label), str(label))

    for i in result_order:
        for j in result_order:
            if result_matrix[i][j] != 0:
                G.edge(str(observed_data_labels[result_order[j]]), str(observed_data_labels[result_order[i]]), str(result_matrix[i][j]))

    G.render(output_name)
    return "{0}.{1}".format(output_name, format)
Example #7
0
 def plot(self, output_name="result", format="png", threshold=0.01, decimal=3):
     graph = Digraph(format=format)
     graph.attr("graph", layout="dot", splines="true", overlap="false")
     graph.attr("node", shape="box")
     for label in self.labels:
         graph.node(label)
     for i, m_i in enumerate(self.matrix):
         for j, m_i_j in enumerate(m_i):
             if np.abs(round(m_i_j, 3)) >= threshold:
                 graph.edge(self.labels[j],
                            self.labels[i],
                            str(round(m_i_j, decimal)))
     graph.render(output_name, cleanup=True)
     return graph
Example #8
0
	def visualize_it(self): #I'll give you somethin' to do
		f = Digraph('finite_state_machine', filename='fsm.gv')
		f.body.extend(['rankdir=LR', 'size="8,5"'])
		f.attr('node', shape='circle')
		#Iterate through each state
		for key, state in self._states.items():
			#Create a node for each state
			f.node(str(state.get_state_id()), label=state.get_field("description"))
			
			#Iterate over each transition in the state
			if state != None:
				for key, trans in state.get_transitions().items():
					if trans != None:
						print trans.get_end()
						for condition in trans.get_conditions():
							f.edge(str(state.get_state_id()), str(trans.to_dictionary()["end"]), label=str(condition))
		f.view()
Example #9
0
def draw_graph(centroid, graph):
    g = Digraph(centroid, engine="sfdp")
    g.attr("node", style="filled")
    g.node(centroid, color="crimson")
    for key in graph:
        g.node(key, color=("burlywood2" if key is not centroid else "crimson"))
    large_set = Queue()
    large_set.put(centroid)
    visited_from_graph = {}
    while not large_set.empty():
        key = large_set.get()
        if key in graph and key not in visited_from_graph:
            visited_from_graph[key] = True
            for keyword in graph[key]:
                g.edge(key, keyword, penwidth=str(float(graph[key][keyword]) / 50.0))
                large_set.put(keyword)
    g.view()
Example #10
0
 def plot(self, output_name="result", format="png", separate=False, decimal=3, threshold=0.01, integration=False):
     if integration:
         integration_matrix = self.matrixes.sum(axis=0)
         graph = Digraph(format=format)
         graph.attr("graph", layout="dot", splines="true", overlap="false")
         graph.attr("node", shape="box")
         for label in self.labels:
             graph.node(label)
         for i, m_i in enumerate(integration_matrix):
             for j, m_i_j in enumerate(m_i):
                 if np.abs(round(m_i_j, decimal)) >= threshold:
                     graph.edge(self.labels[j],
                                self.labels[i],
                                str(round(m_i_j, decimal)))
         graph.render(output_name, cleanup=True)
         return graph
     else:
         def generate_random_color():
             return "#{:X}{:X}{:X}".format(*[random.randint(0, 255) for i in range(3)])
         graph = Digraph(format=format)
         graph.attr("graph", layout="dot", splines="true", overlap="false")
         graph.attr("node", shape="box")
         legend = Digraph("cluster_legend")
         legend.attr("graph", rankdir="LR")
         legend.attr("node", style="invis")
         lags = ["t"] + ["t_{}".format(i) for i in range(1, len(self.matrixes))]
         for label in self.labels:
             graph.node(label)
         for lag, matrix in zip(lags, self.matrixes):
             color = generate_random_color()
             legend.edge("s_{}".format(lag),
                         "d_{}".format(lag),
                         lag,
                         color=color)
             for i, m_i in enumerate(matrix):
                 for j, m_i_j in enumerate(m_i):
                     if round(np.abs(m_i_j), decimal) >= threshold:
                         graph.edge(self.labels[j],
                                    self.labels[i],
                                    str(round(m_i_j, decimal)),
                                    color=color)
         graph.subgraph(legend)
         graph.render(output_name, cleanup=True)
         return graph
Example #11
0
	def __init__(self, tree):
		"""Construtor da classe DecisionTree"""

		super(DecisionTree, self).__init__()

		self.tree = tree

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

		# Contador do node para gerar nos diferentes com o mesmo label
		counter = 0

		# Chama o metodo de criacao da arvore de decisao
		self.build_tree(tree, counter)

		# Renderiza a arvore de decisao
		dot.render(view=False, cleanup=False)
    def generate_dot(self, graph_input):
        dot = Digraph("Traceable relationships",
                      comment="Traceable relationships")
        dot.body.append("rankdir=LR")
        dot.attr("graph", fontname="helvetica", fontsize="7.5")
        dot.attr("node", fontname="helvetica", fontsize="7.5")
        dot.attr("edge", fontname="helvetica", fontsize="7.5")

        for traceable in graph_input.traceables:
            self.add_dot_traceable(dot, traceable)
        for relationship_info in graph_input.relationships:
            traceable1, traceable2, relationship, direction = relationship_info
            src = traceable1.tag if direction >= 0 else traceable2.tag
            dst = traceable2.tag if direction >= 0 else traceable1.tag
            reverse = self.storage.get_relationship_opposite(relationship)
            dot.edge(src, dst, headlabel=reverse, taillabel=relationship,
                     labelfontsize="7.0", labelfontcolor="#999999")

        return dot.source
Example #13
0
def generate_graph(msgs, fn):
    dot = Digraph()
    dot.attr(rankdir="LR")
    for m in msgs.values():
        if m.typ == "start":
            dot.node(m.name, shape="box", color="blue")
        elif m.typ == "end":
            dot.node(m.name, shape="box", color="green3")
        elif m.typ == "auxstart":
            dot.node(m.name, shape="diamond", color="blue")
        elif m.typ == "auxend":
            dot.node(m.name, shape="diamond", color="green3")
        elif m.typ == "normal":
            dot.node(m.name)

    for m in msgs.values():
        for n in m.next:
            dot.edge(m.name, n)
    dot.render(fn)
Example #14
0
def create_dag(start, end, dictionary):
	print "gets here"
	f = Digraph(format='png')
	f.body.extend(['rankdir=LR', 'size="8,5"'])
	
	print "now here"
	f.attr('node', shape='doublecircle')
	f.node(start)
	f.node(end)

	f.attr('node', shape='circle')
	for cur1 in dictionary.keys():
		print cur1
		# if cur1 != start and cur1 != end:
		for cur2 in dictionary[cur1].keys():
			# if cur2 != start and cur2 != end: 
			print f
			f.edge(cur1, cur2, label=str(dictionary[cur1][cur2]))
# print "about to render"
	f.render('static/img/dag')
Example #15
0
 def save(self, name):
     g = Digraph('G', filename="{}.gv".format(name))#os.path.join(OUT, "graph.gv"))
     g.attr('node', shape='circle')
     for label in self.labels:
         if label != "":
             index = self.labels.index(label)
             n_label = "{} ({})".format(label, self.nodes[index+1].weight)
             g.node(n_label)
     for (n1,n2),cov in self.edges.items():
         n1_label = "{} ({})".format(self.labels[n1-1], self.nodes[n1].weight)
         n2_label = "{} ({})".format(self.labels[n2-1], self.nodes[n2].weight)
         g.edge(n1_label, n2_label, label=str(cov), color = "black")
     for (n1,n2),cov in self.new_edges.items():
         n1_label = "{} ({})".format(self.labels[n1-1], self.nodes[n1].weight)
         n2_label = "{} ({})".format(self.labels[n2-1], self.nodes[n2].weight)
         g.edge(n1_label, n2_label, label=str(cov), color = "red")
     for (n1,n2),cov in self.fake_edges.items():
         n1_label = "{} ({})".format(self.labels[n1-1], self.nodes[n1].weight)
         n2_label = "{} ({})".format(self.labels[n2-1], self.nodes[n2].weight)
         g.edge(n1_label, n2_label, label=str(cov), color = "black", style="dashed")
     g.render()
Example #16
0
    def diagram(self):
        from graphviz import Digraph
        from queue import Queue
        diagram=Digraph(comment='The Trie')

        i=0

        diagram.attr('node', shape='circle')
        diagram.node(str(i), self.root.getValue())

        q=Queue()
        q.put((self.root, i))
        
        while not q.empty():

            node, parent_index=q.get()

            for child in node.getChildren():
                i+=1
                if child.getEnding():
                    diagram.attr('node', shape='doublecircle')
                    diagram.node(str(i), child.getValue())
                    diagram.attr('node', shape='circle')
                else:
                    diagram.node(str(i), child.getValue())
                diagram.edge(str(parent_index), str(i))
                q.put((child, i))

        o=open('trie_dot.gv', 'w')
        o.write(diagram.source)
        o.close()
        diagram.render('trie_dot.gv', view=True)
        'trie_dot.gv.pdf'
Example #17
0
def plotCss(css):

    g_css = Digraph('structs', format='pdf',
                    filename=css['css_name'],
                    node_attr={'shape': 'record', 'height': '.1'})

    g_css.attr(rankdir='LR')

    css_line = ''

    with g_css.subgraph(name='cluster0') as c:
        c.graph_attr['rankdir'] = 'LR'

        last = len(css['members']) - 1

        for member in css['members']:
            index = css['members'].index(member)

            gv_line = ''
            css_line += '<{0}> {0}|'.format(member['partition'])
            for pattern in member['patterns']:
                if pattern[0] == '\\':
                    gv_line += '\\{0}|'.format(pattern)
                else:
                    gv_line += '{0}|'.format(pattern)

            c.node(member['partition'], '<{0}> {0}| {1}'.format(
                member['partition'], gv_line[:-1]))

            if index < last:
                nextitem = css['members'][index + 1]
                c.edge(
                    '%s:%s' %
                    (member['partition'],
                     member['partition']),
                    '%s:%s' %
                    (nextitem['partition'],
                     nextitem['partition']))

    return g_css
Example #18
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 #19
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 #20
0
	def print_graph(self):
		dot = Digraph()
		dot.attr('node', shape='circle')
		dot.attr('node', style='filled')
		dot.attr('node', fillcolor='white')
		for key in self.nodelist.keys():
			if key in self.path:
				dot.attr('node', fillcolor='green')
			node = dot.node(key)
			dot.attr('node', fillcolor='white')
				
		for key in self.edgelist.keys():
			edges = self.edgelist[key]
			dot.edge(key, edges[0].number)
			dot.edge(key, edges[1].number)
	
		print dot.source
		dot.render('test-output/g.gv', view=True)
Example #21
0
    def create_graph(self):
        g = Digraph('G')
        g.body.append('ranksep=0.7; splines=ortho')
        g.attr('node', shape='box')

        # add people nodes
        for generation, people_list in self.people_by_generation.iteritems():
            _g = Digraph('generation_%s' % generation)
            _g.attr('graph', rank='same')
            for people in people_list:
                if type(people) == Couple:
                    husband, wife = people.husband, people.wife
                    parent_id = people.get_id()
                    _g.node(parent_id, shape='point', height='0', color='invis')
                    _g.edge(husband, parent_id, dir='none', color='black:invis:black')
                    _g.edge(parent_id, wife, dir='none', color='black:invis:black')
                elif type(people) == Children:
                    children = people.children
                    for i in xrange(len(children)):
                        _g.node(children[i])
            g.subgraph(_g)

        # add children edges
        for generation, people_list in self.people_by_generation.iteritems():
            _g = None
            for people in [people for people in people_list if type(people) == Children]:
                child_ids = people.get_ids()
                children_id = people.get_id()
                if _g is None:
                    _g = Digraph('children_%s' % '/'.join(child_ids))
                    _g.attr('graph', rank='same')
                children = people.children
                children_nodes = [children_id]
                parent_id = people.parent.get_id()
                if len(children) > 1:
                    _g.node(children_id, shape='point', height='0.01')
                    for i in xrange(len(children)):
                        _g.node(child_ids[i], shape='point', height='0.01')
                        g.edge(child_ids[i], children[i], dir='none')
                        children_nodes.append(child_ids[i])
                    for i in xrange(1, len(children_nodes)):
                        _g.edge(children_nodes[i-1], children_nodes[i], dir='none', constraint='false')
                    g.edge(parent_id, children_id, dir='none')
                else:
                    g.edge(parent_id, children[0], dir='none')
            if _g is not None:
                g.subgraph(_g)
        return g
Example #22
0
    def asGraph(self, computation_counter):
        from graphviz import Digraph # @UnresolvedImport pylint: disable=F0401,I0021

        graph = Digraph("cluster_%d" % computation_counter, comment = "Graph for %s" % self.getName())
        graph.body.append("style=filled")
        graph.body.append("color=lightgrey")
        graph.body.append("label=Iteration_%d" % computation_counter)


        def makeTraceNodeName(variable_trace):
            return "%d/ %s %s %s" % (
                computation_counter,
                variable_trace.getVariable(),
                variable_trace.getVersion(),
                variable_trace.__class__.__name__
            )

        for function_body in self.active_functions:
            constraint_collection = function_body.constraint_collection

            for (_variable, _version), variable_trace in constraint_collection.getVariableTracesAll().items():
                node = makeTraceNodeName(variable_trace)

                previous = variable_trace.getPrevious()

                if variable_trace.hasDefiniteUsages():
                    graph.attr("node", style = "filled", color = "blue")
                elif variable_trace.hasPotentialUsages():
                    graph.attr("node", style = "filled", color = "yellow")
                else:
                    graph.attr("node", style = "filled", color = "red")

                graph.node(node)

                if type(previous) is tuple:
                    for previous in previous:
                        graph.edge(makeTraceNodeName(previous), node)
                elif previous is not None:
                    graph.edge(makeTraceNodeName(previous), node)

        return graph
Example #23
0
class Grafo:
    def __init__(self, ruta):
        self.ruta = ruta
        self.s = Digraph('structs',
                         filename='grafo.dot',
                         node_attr={'shape': 'plaintext'})
        self.s.attr(bgcolor='gray', fontcolor='white')
        self.tree = ET.parse(ruta)
        self.root = self.tree.getroot()

        self.i_de_tabla = '''<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">'''
        self.f_de_tabla = '''</TABLE>>'''
        self.i_de_fila = '<TR>'
        self.f_de_fila = '</TR>'
        self.i_de_columna = '<TD PORT="f0">'
        self.f_de_columna = '</TD>'

    # Va a retornar el numero de matrices que se pueden graficar
    def cantidad_de_matrices(self):
        tamano = 0
        for i in range(len(self.root)):
            tamano += 1
        return tamano

    # Muestra las matrices disponibles para graficar
    def mostrar_matrices_disponibles(self):
        tamano = 0
        for i in range(len(self.root)):
            print("     " + str(i + 1) + ". " + self.root[i].get("nombre"))
            tamano += 1
        return tamano

    # Como lo que voy a mostrar las matrices del documento, y cada una de ellas se les asocio un numero
    # cuando el usuario ingrese el numero, en realidad lo que esta mandando es la posicion de esa matriz dentro
    # del arbol
    def generar_grafo(self, opcion_grafo):

        self.s.node(
            'struct1', '''<
                <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" PORT="f0"><TR>
                    <TD>MATRICES</TD>
                </TR>
                </TABLE>>''')

        grafo = self.root[opcion_grafo]

        nombre = self.i_de_fila + self.i_de_columna + grafo.get(
            "nombre") + self.f_de_columna + self.f_de_fila
        tabla = self.i_de_tabla + nombre + self.f_de_tabla
        self.s.node('struct2', tabla)

        n = self.i_de_fila + self.i_de_columna + "n = " + grafo.get(
            "n") + self.f_de_columna + self.f_de_fila
        tabla = self.i_de_tabla + "n = " + n + self.f_de_tabla
        self.s.node('struct3', tabla)

        m = self.i_de_fila + self.i_de_columna + "m = " + grafo.get(
            "m") + self.f_de_columna + self.f_de_fila
        tabla = self.i_de_tabla + m + self.f_de_tabla
        self.s.node('struct4', tabla)

        n = int(grafo.get("n"))
        m = int(grafo.get("m"))
        datos = grafo.findall("dato")

        tabla = self.i_de_tabla
        for i in range(n):  # Recorriendo las filas
            tabla += self.i_de_fila + "\n"
            for j in range(m):  # Recorreindo las columnas
                for l in range(len(datos)):
                    x = int(datos[l].get("x"))
                    y = int(datos[l].get("y"))
                    if (x == (i + 1) and y == (j + 1)):
                        dato = datos[l].text
                        tabla += self.i_de_columna + dato + self.f_de_columna + "\n"
            tabla += self.f_de_fila + "\n"
        tabla += self.f_de_tabla + "\n"

        #print("El formato es ", tabla)

        self.s.node('struct5', tabla)

        self.s.edges([
            ('struct1:f0', 'struct2:f0'), ('struct2:f0', 'struct3:f0'),
            ('struct2:f0', 'struct4:f0'), ('struct2:f0', 'struct5:f0')
        ])

        #print("El nombre del filename es ", self.s.filename)
        self.s.view()
        archivo = render('dot', 'png', 'grafo.dot')
        #print(archivo)
        os.system(archivo)
Example #24
0
# -*- coding: utf-8 -*-
#@note: conda activate my-rdkit-env
#@note: https://www.rdkit.org/docs/GettingStartedInPython.html#drawing-molecules
#@note: https://www.rdkit.org/docs/Install.html#how-to-install-rdkit-with-conda

from graphviz import Digraph

#dot = Digraph(comment='workflow', format="png")
dot = Digraph(comment='workflow', format="svg")

dot.attr('node', shape='box')
dot.node('A', '整个纳米体系')

dot.node('B', '(嵌入)\n 分子片段一')
dot.node('C', '(嵌入)\n 分子片段二')
dot.node('D', '(嵌入)\n 分子片段三')

dot.node('E', '分子力学力场模型')
dot.node('F', '杂化模型')

dot.edges(['AB', 'AC', 'AD', 'BE', 'CE', 'DE', 'EF'])

# 在创建两圆点之间创建一条边
#dot.edge('B', 'C', 'test')

# 保存source到文件,并提供Graphviz引擎
dot.save('test-table.gv')  # 保存
dot.render('test-table.gv')
# dot.view()  # 显示

# 从保存的文件读取并显示
Example #25
0
    def set_ranks(self):
        pids = sorted(list(self.db.peoples.rows.keys()), reverse=False)
        p0000 = Digraph(name='0000-')
        p0000.attr(rank='same')
        #p0000.body.append("rankdir=LR")
        #p0000.attr(rankdir='LR')
        p1000 = Digraph(name='1000-')
        p1000.attr(rank='same')
        #p1000.attr(sortv="1")
        #p1000.body.append("rankdir=LR")
        #p1000.attr(rankdir='LR')
        p2000 = Digraph(name='2000-')
        p2000.attr(rank='same')
        #p2000.attr(sortv="2")
        #p2000.body.append("rankdir=LR")
        #p2000.attr(rankdir='LR')
        p3000 = Digraph(name='3000-')
        p3000.attr(rank='same')
        #p3000.attr(sortv="3")
        #p3000.body.append("rankdir=LR")
        #p3000.attr(rankdir='LR')
        p4000 = Digraph(name='4000-')
        p4000.attr(rank='same')
        #p4000.attr(sortv="1")
        #p4000.body.append("rankdir=LR")
        #p4000.attr(rankdir='LR')
        p5000 = Digraph(name='5000-')
        p5000.attr(rank='same')
        #p5000.body.append("rankdir=LR")
        #p5000.attr(sortv="1")
        for pid in pids:
            if pid > 0 and pid < 1000:
                p0000.node(str(pid))
            if pid >= 1000 and pid < 2000:
                p1000.node(str(pid))
            if pid >= 2000 and pid < 3000:
                p2000.node(str(pid))
            if pid >= 3000 and pid < 4000:
                p3000.node(str(pid))
            if pid >= 4000 and pid < 5000:
                p4000.node(str(pid))
            if pid >= 5000 and pid < 6000:
                p5000.node(str(pid))

        self.dot.subgraph(p0000)
        self.dot.subgraph(p1000)
        self.dot.subgraph(p2000)
        self.dot.subgraph(p3000)
        self.dot.subgraph(p4000)
        self.dot.subgraph(p5000)
Example #26
0
def plot_merge_class_arcs(arcs, class_to_idx, cfg, **kwargs):
    """ make DAG plot and save to file_path as .png """

    format = get_attr_kwargs(cfg, 'format', **kwargs)
    file_path = get_attr_kwargs(cfg, 'file_path', **kwargs)
    caption = get_attr_kwargs(cfg, 'caption', default=None, **kwargs)
    n_cells = get_attr_kwargs(cfg, 'n_cells', **kwargs)
    n_nodes_per_cell = get_attr_kwargs(cfg, 'n_nodes_per_cell', **kwargs)
    conv1x1_label = get_attr_kwargs(cfg, 'conv1x1_label', **kwargs)
    ops = get_attr_kwargs(cfg, 'ops', **kwargs)
    view = get_attr_kwargs(cfg, 'view', **kwargs)

    edge_attr = {'fontsize': '15', 'fontname': 'times'}
    node_attr = {
        'style': 'filled',
        # 'shape'   : 'circle',
        'shape': 'rect',
        'align': 'center',
        'fontsize': '15',
        'height': '0.5',
        'width': '0.5',
        'penwidth': '2',
        'fontname': 'times'
    }
    G = Digraph(filename=file_path,
                format=format,
                edge_attr=edge_attr,
                node_attr=node_attr,
                engine='dot')
    G.body.extend(['rankdir=LR'])

    n_edges_per_cell = len(arcs[0]) // n_cells
    assert n_edges_per_cell == (1 + n_nodes_per_cell) * n_nodes_per_cell // 2

    # for cell_idx in range(n_cells):
    #   with G.subgraph(name='subgraph_cell_idx' + str(cell_idx)) as s:
    #     s.attr(rank='same')
    #     for class_name, idx in class_to_idx.items():
    #       class_name = class_name.title()
    #       # UpSample node
    #       upsample_label = f"U{cell_idx}"
    #       upsample_name = class_name + upsample_label
    #       s.node(upsample_name, upsample_label, fillcolor='yellow')

    class_to_idx = list(reversed(list(class_to_idx.items())))
    G_ori = G
    for class_name, idx in class_to_idx:
        class_name = class_name.title()
        G = G_ori
        with G.subgraph(name=f'cluster_{idx}') as G:
            G.attr(color='blue', penwidth='3')
            # G.attr(label=class_name)
            G.attr(label=class_name,
                   overlap='false',
                   fontsize='25',
                   fontname='times')

            edge_idx = 0
            for cell_idx in range(n_cells):
                # UpSample node
                upsample_label = f"U{cell_idx}"
                upsample_name = class_name + upsample_label
                G.node(upsample_name, upsample_label, fillcolor='yellow')
                with G.subgraph(name=f'cluster_{class_name}_{cell_idx}') as g:
                    g.attr(color='black', penwidth='2')
                    g.attr(label=f'Cell {cell_idx}',
                           overlap='false',
                           fontsize='20',
                           fontname='times')

                    if cell_idx != 0:

                        cell_out_label = 'Out'
                        cell_out_name = class_name + f"{cell_idx-1}" + cell_out_label
                        G.edge(cell_out_name, upsample_name, fillcolor="white")
                    # C_in node
                    cell_in_label = 'In'
                    cell_in_name = class_name + f"{cell_idx - 1}" + cell_in_label
                    g.node(cell_in_name,
                           cell_in_label,
                           fillcolor='darkseagreen2')
                    G.edge(upsample_name,
                           cell_in_name,
                           label=conv1x1_label,
                           fillcolor="lightgray")

                    pre_nodes = [cell_in_name]
                    for node_idx in range(cell_idx * n_nodes_per_cell,
                                          (cell_idx + 1) * n_nodes_per_cell):
                        is_none_node = True
                        # Dense connection
                        for pre_node_idx in range(len(pre_nodes)):
                            pre_node_name = pre_nodes[pre_node_idx]
                            op_name = ops[arcs[idx][edge_idx]]
                            if op_name != 'None' and pre_node_name != 'None':
                                if is_none_node:
                                    node_label = str(node_idx)
                                    node_name = class_name + node_label
                                    g.node(node_name,
                                           node_label,
                                           fillcolor='lightblue')
                                g.edge(pre_node_name,
                                       node_name,
                                       label=op_name,
                                       fillcolor="black")
                                is_none_node = False
                            edge_idx += 1
                        if is_none_node:
                            pre_nodes.append('None')
                        else:
                            pre_nodes.append(node_name)

                    # output node
                    cell_out_label = 'Out'
                    cell_out_name = class_name + f"{cell_idx}" + cell_out_label
                    g.node(cell_out_name,
                           cell_out_label,
                           fillcolor='darkseagreen2')
                    # Replace C_in node
                    G.edge(upsample_name, cell_out_name, fillcolor="lightgray")
                    for pre_node in pre_nodes[1:]:
                        if pre_node != 'None':
                            g.edge(pre_node,
                                   cell_out_name,
                                   fillcolor="lightgray")

    # add image caption
    if caption:
        G_ori.attr(label=caption,
                   overlap='false',
                   fontsize='25',
                   fontname='times')

    if view:
        G_ori.view()
    else:
        G_ori.save()
Example #27
0
        'weight': '1',
        'fontsize': '11',
        'fontcolor': 'black',
        'len': '4'
    },
    graph_attr={
        'fixedsize': 'false',
        #'bgcolor':   'transparent'
        'bgcolor': 'white'
    },
    node_attr={'shape': 'plaintext'},
    directory='gv',
    filename='map',
    format='png')
#dot.attr(bgcolor='blue')
dot.attr(layout="neato")

dot.attr(nodesep='3')
dot.attr(ranksep='3')
dot.attr(size='5000,5000')

dot.node(
    'h1', '''<
<table ALIGN="CENTER" BORDER="0" CELLBORDER="1" CELLSPACING="0"><tr><td port="0">wlan0<br/>192.168.1.163<br/>DC:A6:32:27:D8:01<br/>Raspberry Pi Trading Ltd</td><td port="hostname" rowspan="2">raspberrypi</td><td port="1">lo<br/>127.0.0.1<br/>00:00:00:00:00:00<br/>XEROX CORPORATION</td></tr><tr><td port="2">eth0<br/>None<br/>DC:A6:32:27:D7:FF<br/>Raspberry Pi Trading Ltd</td><td port="3"></td></tr></table>
>''')

nodes = [
    '<table ALIGN="CENTER" BORDER="0" CELLBORDER="1" CELLSPACING="0"><tr port="0"><td>192.168.1.218<br/>18:cf:5e:56:d7:22<br/>Unknown</td></tr></table>',
    '<table ALIGN="CENTER" BORDER="0" CELLBORDER="1" CELLSPACING="0"><tr port="0"><td>192.168.1.205<br/>d4:11:a3:81:3f:8f<br/>Unknown</td></tr></table>',
    '<table ALIGN="CENTER" BORDER="0" CELLBORDER="1" CELLSPACING="0"><tr port="0"><td>192.168.1.146<br/>38:1a:52:28:32:e0<br/>Unknown</td></tr></table>',
    '<table ALIGN="CENTER" BORDER="0" CELLBORDER="1" CELLSPACING="0"><tr port="0"><td>192.168.1.143<br/>d8:31:34:88:9e:34<br/>Unknown</td></tr></table>',
Example #28
0
    def export_graphviz(self, filename='rfstree.gv'):
        """
        Export the dependency graph built in the fir phase
        as a graphviz document. It returns an object g representing the
        graph (e.g., you can visualize it by g.view())
        Args:
            filename (str): output file

        Returns:
            g (graphviz.Digraph): an object representing the graph

        """
        def apply_styles(graph, styles):
            graph.graph_attr.update(
                ('graph' in styles and styles['graph']) or {}
            )
            graph.node_attr.update(
                ('nodes' in styles and styles['nodes']) or {}
            )
            graph.edge_attr.update(
                ('edges' in styles and styles['edges']) or {}
            )
            return graph

        if not hasattr(self, 'nodes'):
            raise ValueError('Model must be trained.')

        from graphviz import Digraph

        g = Digraph('G', filename=filename)
        g.body.extend(['rankdir=BT'])
        g.attr('node', shape='circle')
        # BFS
        S = set()
        Q = [0]
        g.node('0', label='{}\nr2={:.4f}'.format(self.nodes[0].feature_name, self.nodes[0].data['r2score'][-1]))
        while len(Q) > 0:
            current_id = Q[0]
            current = self.nodes[current_id]
            Q = [Q[i] for i in range(1, len(Q))]

            # prepare visualization data
            keys = {}
            if 'r2score' in current.data.keys():
                diff_scores = np.ediff1d(current.data['r2score'], to_begin=current.data['r2score'][0])
                for cnt, el in enumerate(current.data['ordered_features']):
                    keys[el] = cnt
            else:
                diff_scores = None

            for node_id in current.children:
                if node_id not in S:
                    lfn = self.nodes[node_id].feature_name
                    if current.feature_name == self.nodes[node_id].feature_name:
                        # make self loop if parent feature is equal to the current one
                        g.edge(str(current_id), str(current_id),
                               label='r2={:.4f}'.format(diff_scores[keys[lfn]]) if diff_scores is not None else '')
                    else:
                        if 'r2score' in self.nodes[node_id].data.keys():
                            lbl = '{}\nr2={:.4f}'.format(lfn, self.nodes[node_id].data['r2score'][-1])
                        else:
                            lbl = '{}'.format(lfn)
                        g.node(str(node_id), label=lbl)
                        g.edge(str(node_id), str(current.id),
                               label='r2={:.4f}'.format(diff_scores[keys[lfn]]) if diff_scores is not None else '')
                    S.add(node_id)
                    Q.append(node_id)

        styles = {
            # 'graph': {
            #     'label': 'A Fancy Graph',
            #     'fontsize': '16',
            #     'fontcolor': 'black',
            #     'bgcolor': 'white',
            #     'rankdir': 'BT',
            # },
            # 'nodes': {
            #     'fontname': 'Helvetica',
            #     'shape': 'hexagon',
            #     'fontcolor': 'black',
            #     'color': 'black',
            #     'style': 'filled',
            #     'fillcolor': 'white',
            # },
            'edges': {
                # 'style': 'solid',
                # 'color': 'black',
                'arrowhead': 'open',
                # 'fontname': 'Courier',
                'fontsize': '12',
                'fontcolor': 'black',
            }
        }
        g = apply_styles(g, styles)
        # g.view()
        return g
Example #29
0
def to_graphviz(self):
    graph = Digraph(name='cluster' + str(self.id))
    label = self.name
    graph.attr(label=label)
    graph.subgraph(self.circuit.to_graphviz())
    return graph
Example #30
0
def build(name):
    path = f'{name}-new.dot'
    G = read_dot(path)

    d = {}
    for n in G.nodes:
        if not (n in d):
            d[n] = {
                'num_units': min(10, get_num_units(G, n)),
                'succ_str': list(G.successors(n))[:10]
            }

    g = Digraph('g', filename=f'{name}-build.gv')
    g.graph_attr.update(splines="false", nodesep='1', ranksep='2')
    g.attr(arrowShape="none")

    for e in d:
        with g.subgraph(name=f'cluster_{e}') as c:
            c.attr(color="white")

            for i in range(d[e]['num_units']):
                name_d = f'{e}_{i}'
                if 'Input' in e:
                    color = "#33cc33"
                    c.node(name_d,
                           shape="circle",
                           style="filled",
                           color=color,
                           fontcolor=color)
                elif 'Dropout' in e:
                    color = "#ffcc00"
                    c.node(name_d,
                           shape="rect",
                           style="filled",
                           color=color,
                           fontcolor=color)
                elif 'Concatenate' in e:
                    color = "#993300"
                    c.node(name_d,
                           shape="rect",
                           style="filled",
                           color=color,
                           fontcolor=color)
                elif len(d[e]['succ_str']) == 0:  # OUTPUT
                    color = "#ff0000"
                    c.node(name_d,
                           shape="circle",
                           style="filled",
                           color=color,
                           fontcolor=color)
                else:
                    color = "#3498db"
                    c.node(name_d,
                           shape="circle",
                           style="filled",
                           color=color,
                           fontcolor=color)
                for s in d[e]['succ_str']:
                    if 'Dense' in s:
                        for j in range(d[s]['num_units']):
                            name_a = f'{s}_{j}'
                            g.edge(name_d, name_a)
                    else:
                        for j in range(d[s]['num_units']):
                            name_a = f'{s}_{j}'
                            g.edge(name_d, name_a)
    g.view()
Example #31
0
for i in range(len(top_9)):
    top = []
    top.append(top_9[0][i].split("---|")[0])
    top.append(top_9[0][i].split("---|")[1].split("|--->")[0])
    top.append(top_9[0][i].split("---|")[1].split("|--->")[1])
    end.append(top)

# In[4]:

for i in range(len(end)):
    for j in range(len(end[0])):
        end[i][j] = end[i][j].replace(" ", "")

# In[5]:

from graphviz import Digraph

G = Digraph(format="png")
G.attr("node", shape="square", style="filled")
for i in range(len(end)):
    G.edge(end[i][0], end[i][2], label=end[i][1])
G.node("人口増減率", shape="circle", color="pink")
G.render("zenkoku")

# ### 付録

# In[12]:

lingam = LiNGAM()
lingam.fit(X, use_sklearn=True)
Example #32
0
# hello.py - http://www.graphviz.org/content/hello
import os

import cv2 as cv
from graphviz import Digraph

g = Digraph('G', filename='hello.gv')

g.attr('node', shape='record')

g.node('Hello', 'a|b|c|d|e')
g.edge('Hello', 'World')

filename = 'hello'
filepath = './run'
render_format = 'png'
#以png渲染生成文件
g.render(filename, filepath, view=False, cleanup=True, format=render_format)

img = cv.imread(filepath + '/' + filename + '.' + render_format)
#创建窗口并显示图像
cv.namedWindow("Image")
cv.imshow("Image", img)
cv.waitKey(0)
#释放窗口
cv.destroyAllWindows()

os.remove(filepath + '/' + filename + '.' + render_format)
for ii in range(len(start_nodes)):
    edges.append((start_nodes[ii], end_nodes[ii]))
#    edges.append((start_nodes[ii],end_nodes[ii],{'capacity': capacities[ii]},{'cost': costs[ii]}))
print("edges:", edges, "\n")

G = nx.DiGraph()
G.add_edges_from(edges)

H = nx.relabel_nodes(G, NodeDict)
pos = nx.spring_layout(H)
nx.draw(H, pos, with_labels=True)
plt.show()

#%%
f = Digraph('graphviz plot1', filename='transportation network viz')
f.attr(rankdir='LR', size='8,3')

for ii in range(len(start_nodes)):
    f.attr('node', shape='circle')
    node1 = edges[ii][0]
    node2 = edges[ii][1]
    title1 = NodeDict[node1]
    title2 = NodeDict[node2]
    f.edge(f'{title1}', f'{title2}', label = f'Capacity: {capacities[ii]} Cost: {unit_costs[ii]}')

f.view()
#%%

supply_nodes = []
supply_values = []
for index, row in data_supply.iterrows():
Example #34
0
if __name__ == "__main__":

    alfabeto = ['a', 'b', 'c']
    states = ['0', '1', '2', '3', '4', '5']  #, '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', '&', '4'), ('4', '&', '2'), ('2', '&', '5'),
             ('5', '&', '3'), ('3', '&', '6'), ('6', '&', '1'),
             ('4', 'a', '4'), ('5', 'b', '5')]
    final_states = ['1']

    grafo_q2(grafo, states, final_states)

    drawGraph = Digraph('Automatum', filename='automataq02d', 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 #35
0
# Traffic Light Behaviors
# Tung M. Phan
# July 8th, 2018
# California Institute of Technology

from graphviz import Digraph

simple_lights = Digraph(filename='simple_lights.gv', comment='This is a very simple traffic light model')
simple_lights.node_attr.update(color='green', style='filled', fixedsize='true', width='1')

simple_lights.attr('node', shape = 'circle')
simple_lights.node ('0', 'green', color='yellow')
simple_lights.node ('1', 'red', color='yellow')
simple_lights.attr('node', shape = 'circle')

simple_lights.edge('0', '1', label='t_walk == t_remaining / ?cross')
simple_lights.edge('0', '1', label='⊤ / #wait')
simple_lights.edge('0', '0', label='⊤ / #wait')
simple_lights.edge('1', '0', label='⊤ / #wait')
simple_lights.edge('1', '1', label='⊤ / #wait')
simple_lights.edge('0', '0', label='t_walk < t_remaining / ?cross')
simple_lights.view()

Example #36
0
# ## Derivation Trees

if __name__ == "__main__":
    print('\n## Derivation Trees')




if __name__ == "__main__":
    from graphviz import Digraph


if __name__ == "__main__":
    tree = Digraph("root")
    tree.attr('node', shape='plain')
    tree.node(r"\<start\>")


if __name__ == "__main__":
    tree


if __name__ == "__main__":
    tree.edge(r"\<start\>", r"\<expr\>")


if __name__ == "__main__":
    tree

Example #37
0
# condition = []
# stm = []
# start.append('start')
num = 0

scope2 = []
for i in new_indexing_result:
    scope2.append(i[0])

# print(scope2)
for i in new_indexing_result:
    # if num>0:
    #     fc.edge(str(num - 1), str(num))
    if i[1] in {'int', 'string', 'bool', 'char'}:
        # start.append(i[2])
        fc.attr('node', shape ='rectangle')
        fc.node(str(num), label=i[2])
        if num == 0:
            fc.attr('node', rankdir='LR')
            fc.node('start', shape='oval')
            fc.edge('start', str(num))
        if num > 0:
            fc.edge(str(num - 1), str(num))
        num += 1

    if i[1] in {'while', 'for', 'if', 'else if'}:
        # condition.append(i[2][1])
        # fc.attr('node', shape='diamond')
        fc.node(str(num), label=i[2][2], shape='diamond')
        if num > 0:
            fc.edge(str(num - 1), str(num))
Example #38
0
def cli(output_file, json_dir):

    print(f"Loading JSON files from {json_dir}")
    cfg_dir = os.path.join(json_dir, "data")
    files = [(fi) for fi in os.listdir(cfg_dir) if "_init" in fi]

    print("Creating main Digraph")
    conf = Digraph(name=json_dir)
    conf.graph_attr['rankdir'] = 'LR'

    netsenders = []
    netrecvrs = []
    nwconnections = {}
    nwconnectionnames = []
    nwtopicnames = []
    procname_to_host = {}
    j = {}
    filename = os.path.join(json_dir, "boot.json")
    with open(filename, "r") as jf:
        try:
            j = json.load(jf)
        except json.decoder.JSONDecodeError as e:
            raise RuntimeError(f"ERROR: failed to load {filename}") from e

        for app in j["apps"].keys():
            procname_to_host[app] = j["apps"][app]["host"]

    for file in files:
        procname = file[:-10]
        filename = os.path.join(cfg_dir, file)
        print(f"Parsing init file for process {procname}")
        j = {}
        with conf.subgraph(name=f"cluster_{procname}",
                           node_attr={'shape': 'box'}) as procconf:
            procconf.attr(label=f"{procname}")
            with open(filename, "r") as jf:
                try:
                    j = json.load(jf)
                except json.decoder.JSONDecodeError as e:
                    raise RuntimeError(
                        f"ERROR: failed to load {filename}") from e

            # NetworkManager connections should be the same for all processes
            if len(nwconnections) == 0:
                for nwconn in j["nwconnections"]:
                    name = nwconn["name"]
                    target = re.search(r"host_[^}]*",
                                       nwconn["address"]).group()
                    is_subscriber = len(nwconn["topics"]) != 0
                    print(
                        f"Adding NetworkManager connection with name {name}, target host {target}, and is_subscriber {is_subscriber}"
                    )
                    nwconnections[name] = {
                        "target": target,
                        "is_subscriber": is_subscriber,
                        "topics": nwconn["topics"]
                    }
                    nwconnectionnames.append(name)
                    if len(nwconn["topics"]) != 0:
                        nwtopicnames.extend(nwconn["topics"])

                    conf.node(name)

            # print("Parsing module configuration")
            qmap = {}
            for modcfg in j["modules"]:
                modinst = modcfg["inst"]
                modplug = modcfg["plugin"]

                if modplug == "NetworkToQueue":
                    netrecvrs.append(modinst)
                if modplug == "QueueToNetwork":
                    netsenders.append(modinst)

                for qcfg in modcfg["data"]["qinfos"]:
                    qinst = qcfg["inst"]
                    qdir = qcfg["dir"]

                    if qinst not in qmap:
                        qmap[qinst] = {"sinks": [], "sources": []}

                    if qdir == "input":
                        qmap[qinst]["sinks"].append(f"{procname}_{modinst}")
                    elif qdir == "output":
                        qmap[qinst]["sources"].append(f"{procname}_{modinst}")

                procconf.node(f"{procname}_{modinst}",
                              label=f"{modinst}\n{modplug}")

            # print("Creating queue links")
            for qinst in qmap:
                # print(f"Queue {qinst}")
                qcfg = qmap[qinst]
                procconf.node(f"{procname}_{qinst}",
                              shape="point",
                              width='0.01',
                              height='0.01',
                              xlabel=f"{qinst}")

                first = True
                for qsrc in qcfg["sources"]:
                    procconf.edge(qsrc, f"{procname}_{qinst}", dir="none")
                for qsin in qcfg["sinks"]:
                    procconf.edge(f"{procname}_{qinst}", qsin)

    netedges = {}

    files = [(fi) for fi in os.listdir(cfg_dir) if "_conf" in fi]
    for file in files:
        procname = file[:-10]
        filename = os.path.join(cfg_dir, file)
        print(f"Parsing conf file for process {procname}")
        j = {}
        with open(filename, "r") as jf:
            try:
                j = json.load(jf)
            except json.decoder.JSONDecodeError as e:
                raise RuntimeError(f"ERROR: failed to load {filename}") from e

        for modcfg in j["modules"]:
            modname = modcfg["match"]
            if modname in netrecvrs:
                print(f"{modname} is a NetworkToQueue instance!")
                conn_name = modcfg["data"]["receiver_config"]["name"]
                netedge = f"{procname}_{modname}_{conn_name}"

                print(
                    f"Setting sink of network edge {netedge} to {procname}_{modname}"
                )
                netedges[netedge] = {
                    "src": conn_name,
                    "sink": f"{procname}_{modname}",
                    "label": f"{modname}\n{modcfg['data']['msg_module_name']}",
                    "color": "green"
                }
            elif modname in netsenders:
                print(f"{modname} is a QueueToNetwork instance!")
                conn_name = modcfg["data"]["sender_config"]["name"]
                netedge = f"{procname}_{modname}_{conn_name}"

                print(
                    f"Setting src of network edge {netedge} to {procname}_{modname}"
                )
                netedges[netedge] = {
                    "sink": conn_name,
                    "src": f"{procname}_{modname}",
                    "label": f"{modname}\n{modcfg['data']['msg_module_name']}",
                    "color": "green"
                }
            else:

                def add_nwedge(conn_name):
                    netedge = f"{procname}_{modname}_{conn_name}"
                    is_receiver = (nwconnections[conn_name]["target"] == procname_to_host[procname] and not nwconnections[conn_name]["is_subscriber"]) or \
                                  (nwconnections[conn_name]["is_subscriber"] and nwconnections[conn_name]["target"] != procname_to_host[procname])

                    print(
                        f"Found NetworkManager connection {conn_name} in {procname}_{modname}, is_receiver: {is_receiver}"
                    )
                    if is_receiver:
                        netedges[netedge] = {
                            "src": conn_name,
                            "sink": f"{procname}_{modname}",
                            "color": "blue",
                            "label": f"{modname}"
                        }
                    else:
                        netedges[netedge] = {
                            "src": f"{procname}_{modname}",
                            "sink": conn_name,
                            "color": "blue",
                            "label": f"{modname}"
                        }

                # We need to search for NetworkManager connections now
                def search_nwconnection(obj_to_search):
                    if type(obj_to_search) == type(dict()):
                        for key in obj_to_search.keys():
                            if type(obj_to_search[key]) == type(""):
                                if obj_to_search[
                                        key] in nwconnectionnames and not "reply_connection_name" in key:
                                    add_nwedge(obj_to_search[key])
                                elif obj_to_search[
                                        key] in nwtopicnames and not "timesync_connection_name" in obj_to_search.keys(
                                        ):
                                    topic_name = obj_to_search[key]
                                    for nwconn in nwconnections:
                                        if topic_name in nwconnections[nwconn][
                                                "topics"]:
                                            add_nwedge(nwconn)

                            else:
                                search_nwconnection(obj_to_search[key])
                    elif type(obj_to_search) == type([]):
                        for key in obj_to_search:
                            if type(key) == type(""):
                                if key in nwconnectionnames:
                                    add_nwedge(key)
                                elif key in nwtopicnames:
                                    topic_name = key
                                    for nwconn in nwconnections:
                                        if topic_name in nwconnections[nwconn][
                                                "topics"]:
                                            add_nwedge(nwconn)
                            else:
                                search_nwconnection(key)

                if "data" in modcfg:
                    search_nwconnection(modcfg["data"])

    for netedge in netedges:
        src = netedges[netedge]["src"]
        sink = netedges[netedge]["sink"]
        label = netedges[netedge]["label"]
        color = netedges[netedge]["color"]
        print(f"Setting up {netedge} to connect {src} to {sink}")

        conf.attr('edge', color=color)
        conf.edge(src, sink, label=f"{label}")

    print("Writing output dot")
    with open(output_file, 'w') as dotfile:
        dotfile.write(conf.source)
Example #39
0
    def start(self, only_blocks=False, combined=False):
        self.only_blocks = only_blocks
        self.combined = combined
        name = 'cluster_CFG' if self.combined else 'CFG'
        dot = Digraph(name=name)
        if not self.combined:
            dot.attr('graph', fontname='helvetica')
            dot.attr('graph', splines='spline')
            dot.attr('graph', compound='true')

            dot.attr('node', fontname='helvetica')
            dot.attr('node', style='filled', fillcolor='white')

            dot.attr('edge', fontname='helvetica')

        for node in (self.root if isinstance(self.root, list) else [self.root]):
            subgraph = Digraph()
            self.draw(node, subgraph)
            dot.subgraph(subgraph)

        for link in self.missing_links:
            dot.edge(**link)

        return dot
Example #40
0
M.transition(T25)
M.transition(T26)

M.transition(T35)
M.transition(T36)
M.transition(T46)
M.transition(T51)

#****************************************
#      ausfuehrung 
#****************************************
p = [1,0, 0 ,0, 0, 0]
matrix = M.createMatrix()
print("==================================")
print("        markov-matrix             ")
print("===================================")
print(matrix)
prob = M.probability(p, matrix)
print("==================================")
print("Wahrscheinlichkeit eines Zustandes")
print("===================================")
print(prob)

#****************************************
#          graph
#****************************************
g = Digraph(comment='Markov')
g.attr('node', shape='circle')
M.graph(g)
g.view()
Example #41
0
def ann_viz(model,
            view=True,
            filename="network.gv",
            title="My Neural Network"):
    """Vizualizez a Sequential model.

    # Arguments
        model: A Keras model instance.

        view: whether to display the model after generation.

        filename: where to save the vizualization. (a .gv file)

        title: A title for the graph
    """
    from graphviz import Digraph
    import keras
    from keras.models import Sequential
    from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten
    import json
    input_layer = 0
    hidden_layers_nr = 0
    layer_types = []
    hidden_layers = []
    output_layer = 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")
            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")
        last_layer_nodes = input_layer
        nodes_up = input_layer
        if (type(model.layers[0]) != keras.layers.core.Dense):
            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.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")
        for i in range(0, 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")
        if view == True:
            g.view()
Example #42
0
class Frequency_graph():
    """
    DataFrame - с 3 столбцами ['case_name', 'transact', 'time_diff'].
    count_treshold - принимает на вход:
        - string: "All" (отрисовываются ребра любой частотности)
        - integer: 0, 10, 123,... (отрисовываются ребра с частотой до или с заданного диапазона,
                                    указывается совместно с параметром less_or_more) 
    less_or_more - принимает на вход:
        - string: "<" или ">" (указывается для задания необходимого порога, если параметр 
                                count_treshold принимает значение integer)
    Функция возвращает граф, где цифрами обозначена частота перехода между двумя событиями.
                             Чем ярче и толще линия, тем чаще встречается данный переход.
    """
    def __init__(self, DataFrame, filename=None):
        self.df = DataFrame
        self.name = filename
        self.counts = None
        self.graph = None

    def check_colon(self):
        name_processes = tuple(self.df['transact'].unique())
        counts = [1 for i in name_processes if ':' in i]
        if len(counts) != 0:
            print(
                """В именах событий содержится двоеточие, данный вывод некорректен, 
                     перед отрисовкой графа необходимо заменить двоеточие на тире"""
            )

    def graph_init(self):
        if self.name is None:
            curr_time = datetime.now().strftime("%H:%M:%S").replace(':', '-')
            self.graph = Digraph('finite_state_machine',
                                 filename=f'Graph_{curr_time}')
        else:
            self.graph = Digraph('finite_state_machine', filename=self.name)
        self.graph.attr(rankdir='T', size='8,5')
        self.graph.attr('node',
                        shape='box',
                        style='filled',
                        color='deepskyblue')
        self.graph.node('Start Log',
                        shape='doublecircle',
                        color='deepskyblue1')
        self.graph.node('Log End', shape='doublecircle', color='brown3')
        self.graph.attr('node', shape='box', color='lightblue')

    def count_transact(self, count_method):
        if count_method == "uniq":
            counts = self.df.groupby("transact")["case_name"]\
                           .agg("nunique")\
                           .sort_values(ascending=False)\
                           .reset_index()
        else:
            counts = pd.DataFrame(
                self.df['transact'].value_counts()).reset_index()
        counts.columns = ['transact', 'counts']
        return counts

    def stat_calculate(cls, count_treshold, less_or_more, count_method):
        if count_treshold == 'All':
            cls.counts = cls.count_transact(count_method)
        else:
            try:
                if less_or_more == "<":
                    counts = cls.count_transact(count_method)
                    cls.counts = counts[counts['counts'] < count_treshold]
                elif less_or_more == ">":
                    counts = cls.count_transact(count_method)
                    cls.counts = counts[counts['counts'] > count_treshold]
                else:
                    return 'Недопустимое значение для параметра less_or_more или неправильно указано значение All'
            except Exception as e:
                print(e)
                print(
                    """Параметр count_treshold принимает либо значение All, либо  должно иметь тип integer,\
                совместно с параметром less_or_more, который принимает одно из следующих значений: "<" или ">" """
                )

    @staticmethod
    def change_color_freq(count_transact, stat):
        if count_transact <= 100:  ## <= stat[0]
            color = 'brown'  #'brown'
        elif (count_transact > 100) and (
                count_transact <= 500):  ## stat[0] > count_transact <= stat[1]
            color = 'coral1'  #'coral1'
        elif (count_transact > 500) and (count_transact <= 1000):  ## etc
            color = 'goldenrod'  #'goldenrod'
        elif (count_transact > 1000) and (count_transact <= 2000):
            color = 'deepskyblue1'
        elif count_transact > 2000:
            color = 'cyan'
        return color

    @staticmethod
    def change_width_freq(count_transact, stat):
        if count_transact <= 100:  ## <= stat[0]
            width = '1'
        elif (count_transact > 100) and (
                count_transact <= 500):  ## stat[0] > count_transact <= stat[1]
            width = '1'  #'2'
        elif (count_transact > 500) and (count_transact <= 1000):  ## etc
            width = '1'  #'3'
        elif (count_transact > 1000) and (count_transact <= 2000):
            width = '4'
        elif count_transact > 2000:
            width = '5'
        return width

    @staticmethod
    def get_stat_freq(freq_to_int):
        percent_25 = int(np.percentile(freq_to_int, 25))
        percent_50 = int(np.percentile(freq_to_int, 50))
        percent_75 = int(np.percentile(freq_to_int, 75))
        percent_95 = int(np.percentile(freq_to_int, 95))
        stat_percent = [percent_25, percent_50, percent_75, percent_95]
        return stat_percent

    def draw_freq(cls,
                  count_treshold='All',
                  less_or_more=None,
                  count_method="uniq"):
        cls.stat_calculate(count_treshold, less_or_more, count_method)
        cls.graph_init()
        cls.check_colon()

        transact = cls.counts['transact'].values
        countss = cls.counts['counts'].values

        for c in range(len(transact)):
            stat_percent = cls.get_stat_freq(countss)
            tr = transact[c]
            count = int(countss[c])
            start = tr.split('-->')[0]
            end = tr.split('-->')[1]
            cls.graph.edge('{0}'.format(start),
                           '{0}'.format(end),
                           label='{0}'.format(count),
                           arrowhead='vee',
                           penwidth=cls.change_width_freq(count, stat_percent),
                           color=cls.change_color_freq(count, stat_percent),
                           fontcolor=cls.change_color_freq(
                               count, stat_percent))
        cls.graph.view()
Example #43
0
from Optimizacion.reporteOptimizacion import *

# variables.ventana = Tk()
variables.ventana.geometry("1200x650")
variables.ventana.resizable(False, False)
variables.ventana.config(bg="gray25")  # color de fondo, background
variables.ventana.config(cursor="pirate")  # tipo de cursor (arrow defecto)
variables.ventana.config(relief="sunken")  # relieve del root
variables.ventana.config(bd=12)  # tamaño del borde en píxeles

global tablaSym
tablaSym = Digraph("TablaSym", node_attr={'shape': 'record'})

global ErroresS
ErroresS = Digraph("reporte", node_attr={'shape': 'record'})
ErroresS.attr(style='rounded', color='#4b8dc5')
contenidoE: str = ""

global ReporteO
ReporteO= Digraph("reporteOp", node_attr={'shape': 'record'})
ReporteO.attr(style='rounded', color='#4b8dc5')
contenidoO: str = ""

def send_data():
    print("Analizando Entrada:")
    print("==============================================")
    # reporteerrores = []
    contenido = Tentrada.get(1.0, 'end')
    variables.consola.delete("1.0", "end")
    variables.consola.configure(state='normal')
Example #44
0
def draw_vector(V, name='', rankdir='LR', ioff=0, joff=0):
    g = Digraph(name)
    g.attr(rankdir=rankdir, ranksep='1')
    for i, v in V:
        g.node(str(i + ioff), label='%s:%s' % (str(i), str(v)))
    return g
Example #45
0
    def print_coupling_dot_LR(self, update, context):
        if self.operation_count == 0:
            self.print_entity_db(update)
            update.message.reply_text("Type name of Entity")
            self.operation_count += 1
        elif self.operation_count == 1:
            if update.message.text in self.model_db.keys():
                self.selected = update.message.text
                self.load_entity(self.selected)
                command = Digraph(comment=self.entity.entity_name)
                command.attr(rankdir='LR')
                # command.node('externalIn', "External Input", shape="invhouse", color="red")
                # command.node('externalOut', "External Output", shape="invhouse", color="skyblue")
                # command.node('R', self.entity.entity_name, shape="box", style="bold")
                entity_height = "0.3"
                entity_width = "1"
                entity_fontsize = "15"
                port_height = "0.1"
                port_width = "0.1"
                ex_port_height = "0.3"
                ex_port_width = "0.3"
                port_shape = "point"
                port_fontsize = "1.5"

                if self.aft_msa.entity_list is not None:
                    for item in self.aft_msa.entity_list:
                        if item[2]:
                            command.node(item[0],
                                         item[0],
                                         shape="box",
                                         style="bold",
                                         height=entity_height,
                                         width=entity_width,
                                         fontsize=entity_fontsize)
                        else:
                            command.node(item[0],
                                         item[0],
                                         shape="box",
                                         style="bold",
                                         height=entity_height,
                                         width=entity_width,
                                         fontsize=entity_fontsize)

                if self.aft_msa.external_input_map is not None:
                    i = 0
                    for keys, values in self.aft_msa.external_input_map.items(
                    ):
                        command.node(keys + "exin" + str(i),
                                     "",
                                     shape="invhouse",
                                     style='filled',
                                     color='plum1',
                                     height=ex_port_height,
                                     width=ex_port_width)
                        j = 0
                        for item in values:
                            # item[1]
                            command.node(keys + item[1] + "in" + str(j),
                                         "",
                                         shape=port_shape,
                                         height=port_height,
                                         width=port_width)
                            command.edge(keys + "exin" + str(i),
                                         keys + item[1] + "in" + str(j),
                                         label=" " + keys)
                            command.edge(keys + item[1] + "in" + str(j),
                                         item[0],
                                         label=" " + item[1])
                            j += 1
                        i += 1

                if self.aft_msa.internal_coupling_map_tuple is not None:
                    i = 0
                    for keys, values in self.aft_msa.internal_coupling_map_tuple.items(
                    ):
                        # keys[1]
                        j = 0
                        for item in values:
                            command.node(keys[1] + "internalOut" + str(i) +
                                         str(j),
                                         "",
                                         shape=port_shape,
                                         height=port_height,
                                         width=port_width)
                            # item[1]
                            # command.node(keys[1] + item[1] +"internalIn"+str(i)+str(j), item[1], shape=port_shape,
                            #             height=port_height, width=port_width)
                            command.edge(keys[0],
                                         keys[1] + "internalOut" + str(i) +
                                         str(j),
                                         style="dotted",
                                         label=" " + keys[1])
                            # command.edge(keys[1] + "internalOut"+str(i),
                            #             keys[1] + item[1] +"internalIn"+str(i)+str(j), style="dotted")
                            command.edge(keys[1] + "internalOut" + str(i) +
                                         str(j),
                                         item[0],
                                         label=" " + item[1])
                            j += 1
                        i += 1

                if self.aft_msa.external_output_map is not None:
                    i = 0
                    for keys, values in self.aft_msa.external_output_map.items(
                    ):
                        # keys
                        command.node(keys + "exout" + str(i),
                                     "",
                                     shape="invhouse",
                                     style='filled',
                                     color='skyblue',
                                     height=ex_port_height,
                                     width=ex_port_width)
                        j = 0
                        for item in values:
                            # item1
                            command.node(keys + item[1] + "out" + str(j),
                                         "",
                                         shape=port_shape,
                                         height=port_height,
                                         width=port_width)
                            command.edge(item[0],
                                         keys + item[1] + "out" + str(j),
                                         style="dotted",
                                         label=" " + keys)
                            command.edge(keys + item[1] + "out" + str(j),
                                         keys + "exout" + str(i),
                                         style="dotted",
                                         label=" " + item[1])
                            j += 1
                        i += 1

                self.send_dot_telegram(command, update, context)
                self.clear_system()
            else:
                update.message.reply_text("[ERR] Entity Not Found")
                update.message.reply_text("Type name of Entity")
Example #46
0
class GraphDrawer:
    def __init__(self, db=0, rengine='dot'):
        self.db = db
        self.dot = Digraph(
            comment='The Round Table',
            node_attr={
                'color': 'lightblue2',
                'style': 'filled'
            },
            engine=rengine
        )  #node_attr={'color': 'lightblue2', 'style': 'filled'},
        self.dot.attr(newrank='true')
        #self.dot.attr(rankdir='TB')
        self.dot.attr(pad="0.5")
        self.dot.attr(ranksep="1")
        #self.dot.attr(nodesep="2.0")

        self.dot.attr(ratio="auto")
        self.dot.attr(remincross="false")
        self.dot.attr(label="FAMILY TREE")

        self.fill_nodes()
        self.set_ranks()
        self.fill_relations()
        #self.set_rel_ranks()
        self.dot.format = 'svg'
        self.dot.render(view=True)  #('round-table.gv', view=True)

    def set_ranks(self):
        pids = sorted(list(self.db.peoples.rows.keys()), reverse=False)
        p0000 = Digraph(name='0000-')
        p0000.attr(rank='same')
        #p0000.body.append("rankdir=LR")
        #p0000.attr(rankdir='LR')
        p1000 = Digraph(name='1000-')
        p1000.attr(rank='same')
        #p1000.attr(sortv="1")
        #p1000.body.append("rankdir=LR")
        #p1000.attr(rankdir='LR')
        p2000 = Digraph(name='2000-')
        p2000.attr(rank='same')
        #p2000.attr(sortv="2")
        #p2000.body.append("rankdir=LR")
        #p2000.attr(rankdir='LR')
        p3000 = Digraph(name='3000-')
        p3000.attr(rank='same')
        #p3000.attr(sortv="3")
        #p3000.body.append("rankdir=LR")
        #p3000.attr(rankdir='LR')
        p4000 = Digraph(name='4000-')
        p4000.attr(rank='same')
        #p4000.attr(sortv="1")
        #p4000.body.append("rankdir=LR")
        #p4000.attr(rankdir='LR')
        p5000 = Digraph(name='5000-')
        p5000.attr(rank='same')
        #p5000.body.append("rankdir=LR")
        #p5000.attr(sortv="1")
        for pid in pids:
            if pid > 0 and pid < 1000:
                p0000.node(str(pid))
            if pid >= 1000 and pid < 2000:
                p1000.node(str(pid))
            if pid >= 2000 and pid < 3000:
                p2000.node(str(pid))
            if pid >= 3000 and pid < 4000:
                p3000.node(str(pid))
            if pid >= 4000 and pid < 5000:
                p4000.node(str(pid))
            if pid >= 5000 and pid < 6000:
                p5000.node(str(pid))

        self.dot.subgraph(p0000)
        self.dot.subgraph(p1000)
        self.dot.subgraph(p2000)
        self.dot.subgraph(p3000)
        self.dot.subgraph(p4000)
        self.dot.subgraph(p5000)

    def set_rel_ranks(self, rels):
        pids = sorted([int(key) for key in rels.keys() if '_im' not in key],
                      reverse=False)
        print(pids)
        p0000 = Digraph(name='0000-')
        p0000.attr(rank='same')
        #p0000.body.append("rankdir=LR")
        #p0000.attr(rankdir='LR')
        p1000 = Digraph(name='1000-')
        p1000.attr(rank='same')
        #p1000.attr(sortv="1")
        #p1000.body.append("rankdir=LR")
        #p1000.attr(rankdir='LR')
        p2000 = Digraph(name='2000-')
        p2000.attr(rank='same')
        #p2000.attr(sortv="2")
        #p2000.body.append("rankdir=LR")
        #p2000.attr(rankdir='LR')
        p3000 = Digraph(name='3000-')
        p3000.attr(rank='same')
        #p3000.attr(sortv="3")
        #p3000.body.append("rankdir=LR")
        #p3000.attr(rankdir='LR')
        p4000 = Digraph(name='4000-')
        p4000.attr(rank='same')
        #p4000.attr(sortv="1")
        #p4000.body.append("rankdir=LR")
        #p4000.attr(rankdir='LR')
        p5000 = Digraph(name='5000-')
        p5000.attr(rank='same')
        #p5000.body.append("rankdir=LR")
        #p5000.attr(sortv="1")
        for pid in pids:
            if pid > 0 and pid < 1000:
                p0000.node(rels[str(pid)])
            if pid >= 1000 and pid < 2000:
                p1000.node(rels[str(pid)])
            if pid >= 2000 and pid < 3000:
                p2000.node(rels[str(pid)])
            if pid >= 3000 and pid < 4000:
                p3000.node(rels[str(pid)])
            if pid >= 4000 and pid < 5000:
                p4000.node(rels[str(pid)])
            if pid >= 5000 and pid < 6000:
                p5000.node(rels[str(pid)])

        self.dot.subgraph(p0000)
        self.dot.subgraph(p1000)
        self.dot.subgraph(p2000)
        self.dot.subgraph(p3000)
        self.dot.subgraph(p4000)
        self.dot.subgraph(p5000)

    def fill_nodes(self):
        pids = sorted(list(self.db.peoples.rows.keys()), reverse=False)
        for pid in pids:
            people = self.db.get_people(pid)
            text, color_rel = self.get_people_info(pid)

            photo_ids = self.db.get_all_photo_ids(pid)
            image_path = self.db.get_photo_path(
                pid, photo_ids[0]) if photo_ids and type(photo_ids) == type(
                    []) and len(photo_ids) > 0 else ''
            image_mini_path = os.path.join(
                os.path.join('photos', 'miniatures'),
                str(pid) + '_001.png')
            if image_path != '' and os.path.exists(
                    image_path) and not os.path.exists(image_mini_path):
                print(pid)
                gm = GalleryMiniature(pid, image_path)
                gm.exec()

            shape = 'doublecircle'
            #else:
            #    shape = 'doubleoctagon'
            node_text = str(people['pid'])
            node_image = str(people['pid']) + '_im'
            node_tooltip = str('День рождения: ' + str(people['birthday']) +
                               '' if 'birthday' in people.keys()
                               and str(people['birthday']) != '' else '')
            node_image_tooltip = r'<img src="photos/miniatures/4009_001.png" width="189" height="255">'
            #node_tooltip = node_tooltip + node_tooltip
            self.dot.node(node_text,
                          text,
                          shape='box',
                          color=color_rel,
                          fontcolor='white',
                          width="3",
                          height="2",
                          fixedsize="true",
                          fontsize="36",
                          tooltip=node_tooltip)  #image="f.png",'''
            if os.path.exists(image_mini_path):
                self.dot.node(node_image,
                              '',
                              shape=shape,
                              color=color_rel,
                              fontcolor='white',
                              tooltip=node_image_tooltip,
                              image=image_mini_path,
                              imagescale="true",
                              width="3",
                              height="3",
                              fixedsize="true",
                              fontsize="36")  #image="f.png",'''
            else:
                self.dot.node(node_image,
                              '',
                              shape=shape,
                              color=color_rel,
                              fontcolor='white',
                              width="3",
                              height="3",
                              fixedsize="true",
                              fontsize="36")  #image="f.png",'''

            self.dot.edge(node_image, node_text, weigth="1400")

    def get_people_info(self, pid):
        people = self.db.get_people(int(pid))
        text_formatter = lambda x: x if x == '' else '\n'.join(
            str(x).split(' ')) + '\n'
        text = text_formatter(people['surname']) + str(
            '' if people['maiden'] == '' else '(' + people['maiden'] +
            ')\n') + text_formatter(people['name']) + text_formatter(
                people['midname'])
        pol = people['pol'] if 'pol' in people.keys() else ''
        if pol == '':
            color_rel = "/dark28/" + str(2)
        if len(pol) > 0 and pol[0].lower() == 'м':
            #text = text_formatter(self.mans_surnames[random.randint(0, len(self.mans_surnames)-1)]) +  text_formatter(self.mans_names[random.randint(0, len(self.mans_names)-1)])
            color_rel = "#ad66d5"  #"/dark28/"+str(3)
        if len(pol) > 0 and pol[0].lower() == 'ж':
            #text = text_formatter(self.womans_surnames[random.randint(0, len(self.womans_surnames)-1)]) +  text_formatter(self.womans_names[random.randint(0, len(self.womans_names)-1)])
            color_rel = "#e667af"  #"/dark28/"+str(8)
        #is_alive = people['deathday'] if 'deathday' in people.keys() else ''

        return (text, color_rel)

    def have_parents(self, pid):
        relations = self.db.get_relations(int(pid))
        rel_keys = sorted([typeid
                           for typeid in relations]) if relations else []
        if 1 in rel_keys or 2 in rel_keys:
            return True
        return False

    def fill_relations(self):
        pids = sorted(list(self.db.peoples.rows.keys()), reverse=True)
        #print(pids)
        rel_nodes = {}
        pids_added = []
        for pid in pids:
            relations = self.db.get_relations(pid)
            rel_keys = sorted([typeid
                               for typeid in relations]) if relations else []
            #print(relations)
            for key in rel_keys:
                if key > 2:
                    #print(relations[key])
                    people_pid1 = str(relations[key]['ppid'])
                    people_pid2 = str(relations[key]['pid'])
                    people_pid_im1 = str(relations[key]['ppid']) + '_im'
                    people_pid_im2 = str(relations[key]['pid']) + '_im'
                    #print((people_pid1,people_pid2))
                    if people_pid2 in rel_nodes.keys():
                        node_need_add = False
                    else:
                        node_need_add = True
                        rel_nodes[
                            people_pid1] = people_pid1 + '_' + people_pid2
                        rel_nodes[
                            people_pid2] = people_pid1 + '_' + people_pid2
                        rel_nodes[
                            people_pid_im1] = people_pid1 + '_' + people_pid2
                        rel_nodes[
                            people_pid_im2] = people_pid1 + '_' + people_pid2

                    #rel_nodes[people_pid_im1] = people_pid_im1 + people_pid_im2
                    #rel_nodes[people_pid_im2] = people_pid_im1 + people_pid_im2
                    #print(rel_nodes)
                    if node_need_add:
                        self.dot.node(rel_nodes[people_pid2],
                                      '',
                                      shape='invtriangle',
                                      color=str("/dark28/" + str(2)),
                                      width="0.7",
                                      height="0.7",
                                      fixedsize="true")
                        #self.dot.node(rel_nodes[people_pid_im2], '', shape='invtriangle', color=str("/dark28/"+str(2)), width="1.5", height="1.5", fixedsize="true")
                        #self.dot.edge(people_pid2, people_pid1, color="#e1004c")
                    self.dot.edge(people_pid2,
                                  rel_nodes[people_pid2],
                                  color="#e1004c",
                                  weigth="5000")
                    self.dot.edge(people_pid_im2,
                                  rel_nodes[people_pid_im2],
                                  style="invis",
                                  constraint="false",
                                  weigth="5000")  #style="invis"
                    self.dot.edge(people_pid2,
                                  rel_nodes[people_pid2],
                                  style="invis",
                                  weigth="5000")

        #print(rel_nodes)
        #print(rel_keys)

        print(rel_nodes)
        for pid in pids:
            relations = self.db.get_relations(pid)
            #print(relations)
            rel_keys = sorted([typeid
                               for typeid in relations]) if relations else []
            for key in rel_keys:
                if key == 1 or key == 2:
                    if str(relations[key]['ppid']) in rel_nodes.keys():
                        self.dot.edge(rel_nodes[str(relations[key]['ppid'])],
                                      str(relations[key]['pid']),
                                      color="#3714b0",
                                      weigth="10000")  #color="#7908aa")
                        #self.dot.edge(rel_nodes[str(relations[key]['ppid'])], str(relations[key]['ppid']), color="#3714b0", weigth="10000")
                        #self.dot.edge(rel_nodes[str(relations[key]['ppid'])], str(relations[key]['pid']), style="invis", weigth="10000")
                        break
                    self.dot.edge(str(relations[key]['ppid']),
                                  str(relations[key]['pid']),
                                  color="#3714b0",
                                  weigth="1000")
Example #47
0
def plot(data=None, output=None):
    components = [
        "fs", "ipc", "mm", "net", "security", "block", "sched", "time", "irq",
        "locking"
    ]

    dot = Digraph(comment='Linux graph plot')
    dot.attr(ratio="compress")
    dot.attr(ranksep="0")
    dot.attr(concentrate="true")
    dot.attr(size="50,20")
    dot.attr(rankdir="LR")

    dot.attr("node",
             fontname="Helvetica",
             fontcolor="black",
             fontsize="80",
             shape="box")
    dot.attr("edge", fontname="Helvetica", fontcolor="blue", fontsize="35")

    adj_list = {}

    for i in components:
        adj_list[i] = {}
        for line in open(os.path.join(data, i) + ".deps", "r"):
            if "linux" in line:

                comp = ""

                for w in components:
                    if w in line:
                        comp = w
                        break

                if comp == "":
                    continue

                j = comp

                if j == i or j == "ukdebug":
                    continue

                if j not in adj_list[i]:
                    adj_list[i][j] = 0

                adj_list[i][j] = adj_list[i][j] + 1

    for i in components:
        for j in adj_list[i]:
            if j in components:
                dot.edge(i, j, label=str(adj_list[i][j]))

    dot.render(output)
Example #48
0
def plot(arc, cfg, **kwargs):
    """ make DAG plot and save to file_path as .png """

    format = get_attr_kwargs(cfg, 'format', **kwargs)
    file_path = get_attr_kwargs(cfg, 'file_path', **kwargs)
    caption = get_attr_kwargs(cfg, 'caption', default=None, **kwargs)
    n_cells = get_attr_kwargs(cfg, 'n_cells', **kwargs)
    n_nodes_per_cell = get_attr_kwargs(cfg, 'n_nodes_per_cell', **kwargs)
    conv1x1_label = get_attr_kwargs(cfg, 'conv1x1_label', **kwargs)
    ops = get_attr_kwargs(cfg, 'ops', **kwargs)
    view = get_attr_kwargs(cfg, 'view', **kwargs)

    edge_attr = {'fontsize': '15', 'fontname': 'times'}
    node_attr = {
        'style': 'filled',
        # 'shape'   : 'circle',
        'shape': 'rect',
        'align': 'center',
        'fontsize': '15',
        'height': '0.5',
        'width': '0.5',
        'penwidth': '2',
        'fontname': 'times'
    }
    G = Digraph(format=format,
                edge_attr=edge_attr,
                node_attr=node_attr,
                engine='dot')
    G.body.extend(['rankdir=LR'])

    # intermediate nodes
    n_edges_per_cell = len(arc) // n_cells
    assert n_edges_per_cell == (1 + n_nodes_per_cell) * n_nodes_per_cell // 2

    edge_idx = 0
    for cell_idx in range(n_cells):
        # UpSample node
        G.node(f"U{cell_idx}", fillcolor='yellow')
        with G.subgraph(name=f'cluster_{cell_idx}') as g:
            g.attr(color='black')
            g.attr(label=f'Cell {cell_idx}',
                   overlap='false',
                   fontsize='20',
                   fontname='times')

            if cell_idx != 0:
                G.edge(f"C{cell_idx-1}_{{out}}",
                       f"U{cell_idx}",
                       fillcolor="white")
            # C_in node
            g.node(f"C{cell_idx}_{{in}}", fillcolor='darkseagreen2')
            G.edge(f"U{cell_idx}",
                   f"C{cell_idx}_{{in}}",
                   label=conv1x1_label,
                   fillcolor="lightgray")

            pre_nodes = [f"C{cell_idx}_{{in}}"]
            for node_idx in range(cell_idx * n_nodes_per_cell,
                                  (cell_idx + 1) * n_nodes_per_cell):
                is_none_node = True
                # Dense connection
                for pre_node_idx in range(len(pre_nodes)):
                    pre_node_name = pre_nodes[pre_node_idx]
                    op_name = ops[arc[edge_idx]]
                    if op_name != 'None' and pre_node_name != 'None':
                        if is_none_node:
                            g.node(str(node_idx), fillcolor='lightblue')
                        g.edge(pre_node_name,
                               str(node_idx),
                               label=op_name,
                               fillcolor="black")
                        is_none_node = False
                    edge_idx += 1
                if is_none_node:
                    pre_nodes.append('None')
                else:
                    pre_nodes.append(str(node_idx))

            # output node
            g.node(f"C{cell_idx}_{{out}}", fillcolor='darkseagreen2')
            # Replace C_in node
            G.edge(f"U{cell_idx}",
                   f"C{cell_idx}_{{out}}",
                   fillcolor="lightgray")
            for pre_node in pre_nodes[1:]:
                if pre_node != 'None':
                    g.edge(pre_node,
                           f"C{cell_idx}_{{out}}",
                           fillcolor="lightgray")

    #
    # # output node
    # g.node("c_{k}", fillcolor='palegoldenrod')
    # for i in range(n_nodes):
    #     g.edge(str(i), "c_{k}", fillcolor="gray")

    # add image caption
    if caption:
        G.attr(label=caption, overlap='false', fontsize='25', fontname='times')

    G.render(file_path, view=view)
Example #49
0
def graphviz_visualization(net,
                           image_format="png",
                           initial_marking=None,
                           final_marking=None,
                           decorations=None,
                           debug=False,
                           set_rankdir=None):
    """
    Provides visualization for the petrinet

    Parameters
    ----------
    net: :class:`pm4py.entities.petri.petrinet.PetriNet`
        Petri net
    image_format
        Format that should be associated to the image
    initial_marking
        Initial marking of the Petri net
    final_marking
        Final marking of the Petri net
    decorations
        Decorations of the Petri net (says how element must be presented)
    debug
        Enables debug mode
    set_rankdir
        Sets the rankdir to LR (horizontal layout)

    Returns
    -------
    viz :
        Returns a graph object
    """
    if initial_marking is None:
        initial_marking = Marking()
    if final_marking is None:
        final_marking = Marking()
    if decorations is None:
        decorations = {}

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Digraph(net.name,
                  filename=filename.name,
                  engine='dot',
                  graph_attr={'bgcolor': 'transparent'})
    if set_rankdir:
        viz.graph_attr['rankdir'] = set_rankdir
    else:
        viz.graph_attr['rankdir'] = 'LR'

    # transitions
    viz.attr('node', shape='box')
    # add transitions, in order by their (unique) name, to avoid undeterminism in the visualization
    trans_sort_list = sorted(list(net.transitions),
                             key=lambda x:
                             (x.label
                              if x.label is not None else "tau", x.name))
    for t in trans_sort_list:
        if t.label is not None:
            if t in decorations and "label" in decorations[
                    t] and "color" in decorations[t]:
                viz.node(str(id(t)),
                         decorations[t]["label"],
                         style='filled',
                         fillcolor=decorations[t]["color"],
                         border='1')
            else:
                viz.node(str(id(t)), str(t.label))
        else:
            if debug:
                viz.node(str(id(t)), str(t.name))
            elif t in decorations and "color" in decorations[
                    t] and "label" in decorations[t]:
                viz.node(str(id(t)),
                         decorations[t]["label"],
                         style='filled',
                         fillcolor=decorations[t]["color"],
                         fontsize='8')
            else:
                viz.node(str(id(t)), "", style='filled', fillcolor="black")

    # places
    viz.attr('node', shape='circle', fixedsize='true', width='0.75')
    # add places, in order by their (unique) name, to avoid undeterminism in the visualization
    places_sort_list_im = sorted(
        [x for x in list(net.places) if x in initial_marking],
        key=lambda x: x.name)
    places_sort_list_fm = sorted([
        x for x in list(net.places)
        if x in final_marking and not x in initial_marking
    ],
                                 key=lambda x: x.name)
    places_sort_list_not_im_fm = sorted([
        x for x in list(net.places)
        if x not in initial_marking and x not in final_marking
    ],
                                        key=lambda x: x.name)
    # making the addition happen in this order:
    # - first, the places belonging to the initial marking
    # - after, the places not belonging neither to the initial marking and the final marking
    # - at last, the places belonging to the final marking (but not to the initial marking)
    # in this way, is more probable that the initial marking is on the left and the final on the right
    places_sort_list = places_sort_list_im + places_sort_list_not_im_fm + places_sort_list_fm

    for p in places_sort_list:
        if p in initial_marking:
            viz.node(str(id(p)),
                     str(initial_marking[p]),
                     style='filled',
                     fillcolor="green")
        elif p in final_marking:
            viz.node(str(id(p)), "", style='filled', fillcolor="orange")
        else:
            if debug:
                viz.node(str(id(p)), str(p.name))
            else:
                if p in decorations and "color" in decorations[
                        p] and "label" in decorations[p]:
                    viz.node(str(id(p)),
                             decorations[p]["label"],
                             style='filled',
                             fillcolor=decorations[p]["color"],
                             fontsize='6')
                else:
                    viz.node(str(id(p)), "")

    # add arcs, in order by their source and target objects names, to avoid undeterminism in the visualization
    arcs_sort_list = sorted(list(net.arcs),
                            key=lambda x: (x.source.name, x.target.name))
    for a in arcs_sort_list:
        if a in decorations and "label" in decorations[
                a] and "penwidth" in decorations[a]:
            viz.edge(str(id(a.source)),
                     str(id(a.target)),
                     label=decorations[a]["label"],
                     penwidth=decorations[a]["penwidth"])
        elif a in decorations and "color" in decorations[a]:
            viz.edge(str(id(a.source)),
                     str(id(a.target)),
                     color=decorations[a]["color"])
        else:
            viz.edge(str(id(a.source)), str(id(a.target)))
    viz.attr(overlap='false')
    viz.attr(fontsize='11')

    viz.format = image_format

    return viz
Example #50
0
def graphviz_visualization(activities_count,
                           dfg,
                           image_format="png",
                           measure="frequency",
                           max_no_of_edges_in_diagram=100000,
                           start_activities=None,
                           end_activities=None,
                           soj_time=None,
                           font_size="12"):
    """
    Do GraphViz visualization of a DFG graph

    Parameters
    -----------
    activities_count
        Count of attributes in the log (may include attributes that are not in the DFG graph)
    dfg
        DFG graph
    image_format
        GraphViz should be represented in this format
    measure
        Describes which measure is assigned to edges in direcly follows graph (frequency/performance)
    max_no_of_edges_in_diagram
        Maximum number of edges in the diagram allowed for visualization
    start_activities
        Start activities of the log
    end_activities
        End activities of the log
    soj_time
        For each activity, the sojourn time in the log

    Returns
    -----------
    viz
        Digraph object
    """
    if start_activities is None:
        start_activities = {}
    if end_activities is None:
        end_activities = {}

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Digraph("",
                  filename=filename.name,
                  engine='dot',
                  graph_attr={'bgcolor': 'transparent'})

    # first, remove edges in diagram that exceeds the maximum number of edges in the diagram
    dfg_key_value_list = []
    for edge in dfg:
        dfg_key_value_list.append([edge, dfg[edge]])
    # more fine grained sorting to avoid that edges that are below the threshold are
    # undeterministically removed
    dfg_key_value_list = sorted(dfg_key_value_list,
                                key=lambda x: (x[1], x[0][0], x[0][1]),
                                reverse=True)
    dfg_key_value_list = dfg_key_value_list[
        0:min(len(dfg_key_value_list), max_no_of_edges_in_diagram)]
    dfg_allowed_keys = [x[0] for x in dfg_key_value_list]
    dfg_keys = list(dfg.keys())
    for edge in dfg_keys:
        if edge not in dfg_allowed_keys:
            del dfg[edge]

    # calculate edges penwidth
    penwidth = assign_penwidth_edges(dfg)
    activities_in_dfg = set()
    activities_count_int = copy(activities_count)

    for edge in dfg:
        activities_in_dfg.add(edge[0])
        activities_in_dfg.add(edge[1])

    # assign attributes color
    activities_color = get_activities_color(activities_count_int)

    # represent nodes
    viz.attr('node', shape='box')

    if len(activities_in_dfg) == 0:
        activities_to_include = sorted(list(set(activities_count_int)))
    else:
        # take unique elements as a list not as a set (in this way, nodes are added in the same order to the graph)
        activities_to_include = sorted(list(set(activities_in_dfg)))

    activities_map = {}

    for act in activities_to_include:
        if "frequency" in measure and act in activities_count_int:
            viz.node(str(hash(act)),
                     act + " (" + str(activities_count_int[act]) + ")",
                     style='filled',
                     fillcolor=activities_color[act],
                     fontsize=font_size)
            activities_map[act] = str(hash(act))
        else:
            viz.node(str(hash(act)),
                     act + " (" + human_readable_stat(soj_time[act]) + ")",
                     fontsize=font_size)
            activities_map[act] = str(hash(act))

    # make edges addition always in the same order
    dfg_edges = sorted(list(dfg.keys()))

    # represent edges
    for edge in dfg_edges:
        if "frequency" in measure:
            label = str(dfg[edge])
        else:
            label = human_readable_stat(dfg[edge])
        viz.edge(str(hash(edge[0])),
                 str(hash(edge[1])),
                 label=label,
                 penwidth=str(penwidth[edge]),
                 fontsize=font_size)

    start_activities_to_include = [
        act for act in start_activities if act in activities_map
    ]
    end_activities_to_include = [
        act for act in end_activities if act in activities_map
    ]

    if start_activities_to_include:
        viz.node("@@startnode",
                 "@@S",
                 style='filled',
                 shape='circle',
                 fillcolor="#32CD32",
                 fontcolor="#32CD32")
        for act in start_activities_to_include:
            label = str(start_activities[act]) if isinstance(
                start_activities, dict) else ""
            viz.edge("@@startnode",
                     activities_map[act],
                     label=label,
                     fontsize=font_size)

    if end_activities_to_include:
        viz.node("@@endnode",
                 "@@E",
                 style='filled',
                 shape='circle',
                 fillcolor="#FFA500",
                 fontcolor="#FFA500")
        for act in end_activities_to_include:
            label = str(end_activities[act]) if isinstance(
                end_activities, dict) else ""
            viz.edge(activities_map[act],
                     "@@endnode",
                     label=label,
                     fontsize=font_size)

    viz.attr(overlap='false')

    viz.format = image_format

    return viz
Example #51
0
    "palegreen4", "paleturquoise1", "paleturquoise3", "paleturquoise4",
    "palevioletred1", "palevioletred3", "palevioletred4", "peachpuff1",
    "peachpuff3", "peachpuff4", "peru", "pink1", "pink3", "plum1", "plum3",
    "plum4", "purple1", "purple3", "red1", "red3", "red4", "rosybrown",
    "rosybrown4", "royalblue1", "royalblue3", "saddlebrown", "salmon1",
    "salmon3", "sandybrown", "seashell3", "seashell4", "sienna1", "sienna3",
    "skyblue4", "slateblue1", "slateblue3", "slategray2", "slategray3",
    "slategrey", "snow3", "springgreen1", "springgreen3", "springgreen4",
    "steelblue1", "steelblue3", "steelblue4", "tan", "tan1", "tan3", "tan4",
    "thistle2", "thistle3", "thistle4", "tomato1", "tomato3", "tomato4",
    "turquoise", "turquoise1", "turquoise3", "turquoise4", "violet",
    "violetred", "violetred1", "wheat1", "wheat3", "yellow1", "yellow3",
    "yellowgreen", "skyblue1", "skyblue3", "seagreen3", "seagreen4", "navy",
    "seagreen1"
]

for i in range(len(q)):
    #if(IS[i] == -1 or (players[i] == 1 and q[i] == 1)):
    # if(b[i] == "leaf"):
    #     continue
    dot.attr('node', style='filled', color=colors[IS[i]])
    dot.node(str(i), b[i])
    if (i > 0):
        if (q[i] == 1):
            dot.edge(str(parents[i]),
                     str(i),
                     minlen=str((i - parents[i] - 1) * 0.1 + 1))
        else:
            dot.edge(str(parents[i]), str(i))
dot.render('tree', view=True)
Example #52
0
def plot_graph(mdp, graph_size='10,10', s_node_size='1,5',
               a_node_size='0,5', rankdir='LR', ):
    """
    Function for pretty drawing MDP graph with graphviz library.
    Requirements:
    graphviz : https://www.graphviz.org/
    for ubuntu users: sudo apt-get install graphviz
    python library for graphviz
    for pip users: pip install graphviz
    :param mdp:
    :param graph_size: size of graph plot
    :param s_node_size: size of state nodes
    :param a_node_size: size of action nodes
    :param rankdir: order for drawing
    :return: dot object
    """
    s_node_attrs = {'shape': 'doublecircle',
                    'color': '#85ff75',
                    'style': 'filled',
                    'width': str(s_node_size),
                    'height': str(s_node_size),
                    'fontname': 'Arial',
                    'fontsize': '24'}

    a_node_attrs = {'shape': 'circle',
                    'color': 'lightpink',
                    'style': 'filled',
                    'width': str(a_node_size),
                    'height': str(a_node_size),
                    'fontname': 'Arial',
                    'fontsize': '20'}

    s_a_edge_attrs = {'style': 'bold',
                      'color': 'red',
                      'ratio': 'auto'}

    a_s_edge_attrs = {'style': 'dashed',
                      'color': 'blue',
                      'ratio': 'auto',
                      'fontname': 'Arial',
                      'fontsize': '16'}

    graph = Digraph(name='MDP')
    graph.attr(rankdir=rankdir, size=graph_size)
    for state_node in mdp._transition_probs:
        graph.node(state_node, **s_node_attrs)

        for posible_action in mdp.get_possible_actions(state_node):
            action_node = state_node + "-" + posible_action
            graph.node(action_node,
                       label=str(posible_action),
                       **a_node_attrs)
            graph.edge(state_node, state_node + "-" +
                       posible_action, **s_a_edge_attrs)

            for posible_next_state in mdp.get_next_states(state_node,
                                                          posible_action):
                probability = mdp.get_transition_prob(
                    state_node, posible_action, posible_next_state)
                reward = mdp.get_reward(
                    state_node, posible_action, posible_next_state)

                if reward != 0:
                    label_a_s_edge = 'p = ' + str(probability) + \
                                     '  ' + 'reward =' + str(reward)
                else:
                    label_a_s_edge = 'p = ' + str(probability)

                graph.edge(action_node, posible_next_state,
                           label=label_a_s_edge, **a_s_edge_attrs)
    return graph
Example #53
0
    def dessinerArbre(self, montrerThemes=False):
        """
        Permet de dessiner l'arbre d'annotations d'une personne, à l'aide de Graphviz. 
        L'objet retourné est un Digraph Graphviz. Il peut être enregistré comme suit :
        dot = annot.dessinerArbre()
        dot.format = 'png' # si on veut changer le format d'enregistrement
        dot.render()

        montrerThemes: boolean qui indique si on doit afficher les boîtes thématiques ou pas
        return: graphviz.Digraph
        """
        nom = self.texte.nom+'_-_'+self.annotateur.id
        dot = Digraph(name=nom, node_attr={'shape':'box','style':'filled'})
        dot.attr(newrank="true") # pour que ça affiche les clusters au bon endroit

        dot.node("zero", style="invis") # Le noeud d'origine du dessin
        # Ajout des unités
        for u in self.texte.unites:
            if u.name[0] == "A":
                dot.node(u.name, u.name + " : " + u.txt, fillcolor='wheat')
            elif u.name[0] == "B":
                dot.node(u.name, u.name + " : " + u.txt, fillcolor='skyblue')
            else:
                dot.node(u.name, u.name + " : " + u.txt)       

        # Ajout des relations
        typesRel = self.annotateur.campagne.typesRelations
        debut = self.texte.unites[0].name
        dot.edge("zero", debut, label="", style="invis") #On relie le début à l'origine
        for rel in self.relations:
            if typesRel[rel.type] == "horizontale":
                ## On n'utilise au final pas les sous-graphes car ils ne permettent pas d'afficher aussi les thèmes (on ne peut pas faire des clusters et sous-graphes qui se chevauchent)
                # with dot.subgraph() as sub:
                #     sub.attr(rank="same")
                #     sub.node(rel.dest.name)
                #     sub.node(rel.origine.name)
                #     sub.edge(rel.dest.name, rel.origine.name, label=rel.type, dir="none")
                

                ## A la place on va relier les membres d'une relation horizontale au noeud situé au-dessus, de manière invisible
                # Pour ça il faut donc chercher le parent qui est situé au dessus : ce n'est pas forcément le parent immédiat car on peut avoir un enchainement de relations horizontales
                relParent = rel.type
                noeudParent = rel.dest.name
                while typesRel[relParent] == "horizontale" and noeudParent != debut: #on cherche jusqu'à arriver à une relation verticale, ou au début
                    mat = self.matrice()[:,noeudParent,:] # matrice (destination, typeRel) binaire présentant toutes les relations qui partent du parent
                    ligne = ""
                    colonne = ""
                    where = np.argwhere(mat.as_matrix()) # On cherche l'index de la case où il y a un 1, c'est à dire celle qui correspond à la relation qui part de cette unité
                    if(len(where)>0): # Si on a bien trouvé une case (normalement il n'y en a qu'une)
                        ligne, colonne = where[0] 
                        # On transforme cet index numérique en le nom de l'unité et le type de relation
                        noeudParent = mat.index[ligne]
                        relParent = mat.columns[colonne]
                    else: # Sinon c'est qu'on est arrivé au début (il n'a pas de parent) ou que l'annotateur a oublié de relier cette unité
                        noeudParent = debut
                #Si on est arrivé au début il faut se raccrocher à l'origine invisible comme parent vertical
                if noeudParent == debut:
                    noeudParent = "zero"
                #On ajoute ensuite une relation verticale invisible vers le noeud au-dessus, afin de contraindre notre noeud dans la hiérarchie du graphe : il doit forcément être placé sous noeudParent
                dot.edge(noeudParent, rel.origine.name, style="invis", weight="1") # On met un poids de 1 (faible) car cette relation n'est pas importante et peut-être penchée. Les vraies relations verticales en revanche auront un poids plus élevées pour être dessinées le plus verticalement possible
                # On dessine enfin la relation horizontale. constraint=false permet d'indiquer que cette relation n'intervient pas dans la hiérarchie du graphe : les deux noeuds doivent être dessinés au même niveau.
                dot.edge(rel.dest.name, rel.origine.name, label=rel.type, dir="none", constraint="false")
            else:
                dot.edge(rel.dest.name, rel.origine.name, label=rel.type, dir="none", weight="2") # On met un poids de 2 pour que cette relation soit prioritaire sur les relations invisibles : elle doit être dessinée le plus verticalement possible.


        # Ajout des thèmes
        if montrerThemes:
            colorsThemes = dict()
            i = 0
            colors=["violetred", "olivedrab", "red", "burlywood4", "blue", "peru", "seagreen4", "mediumorchid", "royalblue", "darkorange"]
            for theme, unites in self.getThemesUnitsList():
                if theme not in colorsThemes:
                    colorsThemes[theme] = colors[i]
                with dot.subgraph(name="cluster_"+str(i)) as c:
                    c.attr(label="<<B>"+theme+"</B>>")
                    c.attr(color=colorsThemes[theme])
                    c.attr(fontcolor=str(colorsThemes[theme]))
                    for u in unites:
                        c.node(u.name)
                i += 1 

        return dot
Example #54
0
 def initialize_graph(graph: Digraph):
     graph.attr('node', shape='record')
Example #55
0
    def get_cluster_graph(self, engine="fdp", graph_attr=None, node_attr=None, edge_attr=None):
        """
        Generate directory graph in the DOT language. Directories are shown as clusters

        .. warning::

            This function scans the entire directory tree starting from top so the resulting
            graph can be really big.

        Args:
            engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage']
            graph_attr: Mapping of (attribute, value) pairs for the graph.
            node_attr: Mapping of (attribute, value) pairs set for all nodes.
            edge_attr: Mapping of (attribute, value) pairs set for all edges.

        Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph>
        """
        # https://www.graphviz.org/doc/info/
        from graphviz import Digraph
        g = Digraph("directory", #filename="flow_%s.gv" % os.path.basename(self.relworkdir),
            engine=engine) # if engine == "automatic" else engine)

        # Set graph attributes.
        #g.attr(label="%s@%s" % (self.__class__.__name__, self.relworkdir))
        g.attr(label=self.top)
        #g.attr(fontcolor="white", bgcolor='purple:pink')
        #g.attr(rankdir="LR", pagedir="BL")
        #g.attr(constraint="false", pack="true", packMode="clust")
        g.node_attr.update(color='lightblue2', style='filled')
        #g.node_attr.update(ranksep='equally')

        # Add input attributes.
        if graph_attr is not None:
            fg.graph_attr.update(**graph_attr)
        if node_attr is not None:
            fg.node_attr.update(**node_attr)
        if edge_attr is not None:
            fg.edge_attr.update(**edge_attr)

        def node_kwargs(path):
            return dict(
                #shape="circle",
                #shape="none",
                #shape="plaintext",
                #shape="point",
                shape="record",
                #color=node.color_hex,
                fontsize="8.0",
                label=os.path.basename(path),
            )

        edge_kwargs = dict(arrowType="vee", style="solid", minlen="1")
        cluster_kwargs = dict(rankdir="LR", pagedir="BL", style="rounded", bgcolor="azure2")

        # TODO: Write other method without clusters if not walk.
        exclude_top_node = False
        for root, dirs, files in os.walk(self.top):
            if exclude_top_node and root == self.top: continue
            cluster_name = "cluster_%s" % root
            #print("root", root, cluster_name, "dirs", dirs, "files", files, sep="\n")

            with g.subgraph(name=cluster_name) as d:
                d.attr(**cluster_kwargs)
                d.attr(rank="source" if (files or dirs) else "sink")
                d.attr(label=os.path.basename(root))
                for f in files:
                    filepath = os.path.join(root, f)
                    d.node(filepath, **node_kwargs(filepath))
                    if os.path.islink(filepath):
                        # Follow the link and use the relpath wrt link as label.
                        realp = os.path.realpath(filepath)
                        realp = os.path.relpath(realp, filepath)
                        #realp = os.path.relpath(realp, self.top)
                        #print(filepath, realp)
                        #g.node(realp, **node_kwargs(realp))
                        g.edge(filepath, realp, **edge_kwargs)

                for dirname in dirs:
                    dirpath = os.path.join(root, dirname)
                    #head, basename = os.path.split(dirpath)
                    new_cluster_name = "cluster_%s" % dirpath
                    #rank = "source" if os.listdir(dirpath) else "sink"
                    #g.node(dirpath, rank=rank, **node_kwargs(dirpath))
                    #g.edge(dirpath, new_cluster_name, **edge_kwargs)
                    #d.edge(cluster_name, new_cluster_name, minlen="2", **edge_kwargs)
                    d.edge(cluster_name, new_cluster_name, **edge_kwargs)
        return g
# finalcgv.py - Curriculum Graph Visualizer

from graphviz import Digraph

c = Digraph('test_ie', filename='test_ie.gv')
c.attr('graph', fontname="Helvetica")
c.attr('node', fontname="Helvetica")
# c.attr('fontname="Arial"')

# legend
c0 = Digraph('cluster_0')
c0.body.append('label = "LEGEND"')
c0.body.append('color=lightgrey')
c0.node_attr.update(style='filled', color='white')
c0.edge_attr.update(color='white')
c0.node('Semester 6', color='plum')
c0.node('Semester 7', color='crimson')
c0.node('Semester 3', color='peachpuff')
c0.node('Semester 4', color='darkseagreen')
c0.node('Semester 5', color='lightblue')
c0.node('Completed', color='grey')
c0.node('Semester 1', color='pink')
c0.node('Semester 2', color='lightsalmon')
c0.node('Semester 8', color='chocolate')
c0.edge('Semester 6', 'Semester 7')
c0.edge('Semester 7', 'Semester 8')
c0.edge('Semester 7', 'Semester 8')
c0.edge('Semester 3', 'Semester 4')
c0.edge('Semester 4', 'Semester 5')
c0.edge('Completed', 'Semester 1')
c0.edge('Semester 1', 'Semester 2')
Example #57
0
import chunks
from graphviz import Digraph

sentences = chunks.get_sentences_as_chunks()


def get_chunk_and_dst(chunk, chunks_for_sentence):
    return (chunk, chunks_for_sentence[chunk.dst] if chunk.dst > 0 else None)


relates = list(map(lambda chunks_for_sentence: list(map(lambda chunk: get_chunk_and_dst(chunk, chunks_for_sentence), chunks_for_sentence)), sentences))
sentence = relates[7]

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

for index, relate in enumerate(sentence):
    graph.node(str(index), relate[0].get_surfaces_without_symbol())

for index, relate in enumerate(sentence):
    if relate[1] != None:
        graph.edge(str(index), str(relate[0].dst))

graph.render('output')
Example #58
0
from graphviz import Digraph
import numpy as np

f = Digraph('Markov_Chain_Diagram', format = 'png')
f.body.extend(['rankdir=LR', 'size="10, 10"'])

A = np.loadtxt('../model/modelnhidden5groupAtrans.txt')

f.attr('node', shape='doublecircle')
f.node('START')
f.node('END')

DIM = A.shape[0] - 2

f.attr('node', shape='circle')

for it in range(DIM):
	if(A[-2,it]>1e-4): # plot the edge only the probability is greater than 1e-4
		f.edge('START', '{0}'.format(it), label= str(round(A[-2, it], 3)))

for it in range(DIM):
	if(A[it,-1]>1e-4):
		f.edge('{0}'.format(it), 'END', label= str(round(A[it, -1], 3)))

for outer_it in range(DIM):
		for inner_it in range(DIM):
			if(A[outer_it,inner_it]>1e-4):
				f.edge('{0}'.format(outer_it), '{0}'.format(inner_it), label= str(round(A[outer_it,inner_it], 3)))

f.render(filename = 'HiddenMarkov{0}'.format(DIM), view = True)
Example #59
-1
def generateGraph( facts, input, output ):
	dot = Digraph(comment='expert_system')
	dot.strict = True

	for fact in sorted(facts):
		dot.attr('node', shape='circle')
		dot.node(fact)
		for rule in facts[fact].getRules():
			dot.attr('node', shape='box')
			dot.node(rule.getRule())

	for fact in sorted(facts):
		for rule in facts[fact].getRules():
			dot.edge(rule.getRule(),fact)
			for factFromRule in rule.getFacts():
				dot.edge(factFromRule, rule.getRule())


	dot.render('output', view=True)
Example #60
-14
	def draw(self):
		g = Digraph(filename='./temp/tmp.gv', format='png')
		g.body.extend(['rankdir=LR'])

		# accepting states
		g.attr('node', shape='doublecircle')
		for state in self.acceptingStates:
			g.node(str(state))

		# other states
		g.attr('node', shape='circle')
		for state in self.states:
			if not state in self.acceptingStates:
				g.node(str(state))

		# transitions
		for transition in self.transitions:
			g.edge(str(transition.fromState), str(transition.toState), str(transition.symbol))

		# Initial state initialization
		g.attr('node', shape='plaintext')
		g.node('')
		g.edge('', str(self.initialState))

		g.view()