def render(self, filename): g = AGraph(strict=False, directed=True) # create nodes for frame_id, node in self.callers.items(): label = "{ %s }" % node g.add_node(frame_id, shape='Mrecord', label=label, fontsize=13, labelfontsize=13) # create edges for frame_id, node in self.callers.items(): child_nodes = [] for child_id in node.child_methods: child_nodes.append(child_id) g.add_edge(frame_id, child_id) # order edges l to r if len(child_nodes) > 1: sg = g.add_subgraph(child_nodes, rank='same') sg.graph_attr['rank'] = 'same' prev_node = None for child_node in child_nodes: if prev_node: sg.add_edge(prev_node, child_node, color="#ffffff") prev_node = child_node g.layout() g.draw(path=filename, prog='dot') print("callviz: rendered to %s" % filename) self.clear()
def draw(self): tree = self.to_tree() A = AGraph(tree) if not self.filename: self.filename = input('Please input a filename:') A.draw('temp/{}.jpg'.format(self.filename), format='jpg', prog='fdp')
def run_graph(dot): """ Runs graphviz to see if the syntax is good. """ graph = AGraph() graph = graph.from_string(dot) extension = 'png' graph.draw(path='output.png', prog='dot', format=extension) sys.exit(0)
def dot_to_graph(dot, output_path): """ Render by calling graphviz the figure on the output path. :param dot: str with the :param output_path: :return: """ from pygraphviz import AGraph graph = AGraph().from_string(dot) graph.draw(path=output_path, prog='dot')
def draw_workflow(filename, workflow): dot = AGraph(directed=True, strict=False) # (comment="Computing scheme") for i, n in workflow.nodes.items(): dot.add_node(i, label="{0} \n {1}".format(n.foo.__name__, _format_arg_list(n.bound_args.args, None))) for i in workflow.links: for j in workflow.links[i]: dot.add_edge(i, j[0], j[1].name) # , headlabel=j[1].name, labeldistance=1.8) dot.layout(prog="dot") dot.draw(filename)
def __call__(self): self.request.response.setHeader('Content-Type', 'image/svg+xml') self.request.response.setHeader('Content-Disposition', 'inline; filename=%s.svg' % \ self.context.getId()) tfile = tempfile.NamedTemporaryFile(suffix='.svg') gv = generate_gv(self.context) ag = AGraph(string=gv) ag.layout() ag.draw(path=tfile, format='svg', prog='dot') tfile.seek(0) return tfile.read()
def draw_workflow(filename, workflow): dot = AGraph(directed=True) # (comment="Computing scheme") for i, n in workflow.nodes.items(): dot.add_node(i, label="{0} \n {1}".format( n.foo.__name__, _format_arg_list(n.bound_args.args, None))) for i in workflow.links: for j in workflow.links[i]: dot.add_edge(i, j[0]) dot.layout(prog='dot') dot.draw(filename)
def render_local(self, filename): """Renders the OBST image locally using pygraphviz.""" # Get the graph information node_list, edge_list = self.__generate_image() # Generate the graph from pygraphviz import AGraph G=AGraph(strict=True,directed=True) # Create a graph for node in node_list: G.add_node(node) for edge in edge_list: G.add_edge(edge[0], edge[1]) G.layout('dot') # Set hierarchical layout G.draw(filename) # Save the image.
def to_dot(self, filename, edges): from pygraphviz import AGraph dot = AGraph(directed=True) for n in edges.keys(): dot.add_node(str(n)) if lib.qcgc_arena_get_blocktype(ffi.cast("cell_t *", n)) not in [ lib.BLOCK_BLACK, lib.BLOCK_WHITE]: node = dot.get_node(str(n)) node.attr['color'] = 'red' for n in edges.keys(): if edges[n] is not None: dot.add_edge(str(n), str(edges[n])) dot.layout(prog='dot') dot.draw(filename)
def run(self): options = self.options filename = self.arguments[0] if self.content: content = u'\n'.join(self.content) ofilename = filename + '.' + self.outputformat else: content = open(filename).read().decode(options.get('encoding','utf-8')) ofilename = os.path.splitext(filename)[0] + '.' + self.outputformat g = AGraph(string=content) g.layout(prog='dot') opath = os.path.join(OUTPUT_DIR, ofilename) g.draw(opath, 'png') self.arguments[0] = opath return super(GraphvizBlock, self).run()
def render_image(self, filename): """Renders the graph image locally using pygraphviz.""" # Create a graph G=AGraph(directed=False) # Add nodes for node in self.nodes: G.add_node(node) # Add edges for edge in self.edges: G.add_edge(edge[0], edge[1], color='blue') # Give layout and draw. G.layout('circo') G.draw(filename) # Save the image. # Display the output image. os.system("gwenview %s&" % filename)
def graph(self, filename, reachable=True): from pygraphviz import AGraph # NOTE - LIS machines do not have pygraphviz graph = AGraph(strict=True, directed=True) for vertex in self.vertices.values(): for connector in vertex.connectors: if not reachable or (vertex.reachable and connector.reachable): graphviz_connect(graph, vertex, connector) for connector in self.connectors.values(): for edge in connector.edges: if not reachable or (connector.reachable and edge.reachable): graphviz_connect(graph, connector, edge) for edge in self.edges.values(): for _, sink_vertex in edge.mappings: if not reachable or (edge.reachable and sink_vertex.reachable): graphviz_connect(graph, edge, sink_vertex) graph.draw(filename, prog='dot')
def render_image(node_list, edge_list): # Generate the graph from pygraphviz import AGraph G=AGraph(strict=False,directed=True) # Create a graph for node in node_list: G.add_node(node) for edge in edge_list: G.add_edge(edge[0], edge[1]) G.layout('dot') # Set hierarchical layout filename = str(time()) postfix = 0 while exists(filename+str(postfix)+".png"): postfix+=1 filename += str(postfix) + ".png" G.draw(filename) # Save the image. with open(filename, "rb") as handle: return xmlrpclib.Binary(handle.read())
def write_graph(probs, path): graph = AGraph(directed=True) next_label = 0 labels = {} for from_state, to_states in probs.iteritems(): if from_state not in labels: labels[from_state] = next_label next_label += 1 for to_state in to_states: if to_state not in labels: labels[to_state] = next_label next_label += 1 for label in xrange(next_label): graph.add_node(label, fillcolor="blue", label="", style="filled") for from_state, to_states in probs.iteritems(): for to_state, prob in to_states.iteritems(): graph.add_edge(labels[from_state], labels[to_state], label="%.2g" % prob) # prog: neato (default), dot, twopi, circo, fdp or nop. graph.layout() graph.draw(path)
__author__ = """Aric Hagberg ([email protected])""" from pygraphviz import AGraph A = AGraph() # set some default node attributes A.node_attr['style'] = 'filled' A.node_attr['shape'] = 'circle' A.node_attr['fixedsize'] = 'true' A.node_attr['fontcolor'] = '#FFFFFF' # make a star in shades of red for i in range( 16 ): A.add_edge( 0, i ) n = A.get_node( i ) n.attr['fillcolor'] = "#%2x0000" % ( i * 16 ) n.attr['height'] = "%s" % ( i / 16.0 + 0.5 ) n.attr['width'] = "%s" % ( i / 16.0 + 0.5 ) print A.string() # print to screen A.write( "star.dot" ) # write to simple.dot print "Wrote star.dot" A.draw( 'star.png', prog="circo" ) # draw to png using circo print "Wrote star.png" import matplotlib.pyplot as plt a = plt.imread( 'star.png' ) plt.imshow( a ) plt.show()
def dot_layout(cy_elements): """ Get a CyElements object and augment it (in-place) with positions, widths, heights, and spline data from a dot based layout. Returns the object. """ elements = cy_elements.elements g = AGraph(directed=True, strict=False) # make transitive relations appear top to bottom # TODO: make this not specific to leader example elements = list(elements) nodes_by_id = dict( (e["data"]["id"], e) for e in elements if e["group"] == "nodes" ) order = [ (nodes_by_id[e["data"]["source"]], nodes_by_id[e["data"]["target"]]) for e in elements if e["group"] == "edges" and e["data"]["obj"] in ('reach', 'le') ] elements = topological_sort(elements, order, lambda e: e["data"]["id"]) # add nodes to the graph for e in elements: if e["group"] == "nodes": g.add_node(e["data"]["id"], label=e["data"]["label"].replace('\n', '\\n')) # TODO: remove this, it's specific to leader_demo weight = { 'reach': 10, 'le': 10, 'id': 1, } constraint = { 'pending': False, } # add edges to the graph for e in elements: if e["group"] == "edges": g.add_edge( e["data"]["source"], e["data"]["target"], e["data"]["id"], weight=weight.get(e["data"]["obj"], 0), #constraint=constraint.get(e["data"]["obj"], True), ) # add clusters clusters = defaultdict(list) for e in elements: if e["group"] == "nodes" and e["data"]["cluster"] is not None: clusters[e["data"]["cluster"]].append(e["data"]["id"]) for i, k in enumerate(sorted(clusters.keys())): g.add_subgraph( name='cluster_{}'.format(i), nbunch=clusters[k], ) # now get positions, heights, widths, and bsplines g.layout(prog='dot') for e in elements: if e["group"] == "nodes": attr = g.get_node(e["data"]["id"]).attr e["position"] = _to_position(attr['pos']) e["data"]["width"] = 72 * float(attr['width']) e["data"]["height"] = 72 * float(attr['height']) elif e["group"] == "edges": attr = g.get_edge(e["data"]["source"], e["data"]["target"], e["data"]["id"]).attr e["data"].update(_to_edge_position(attr['pos'])) g.draw('g.png') return cy_elements
def main(): usage= 'usage: %prog [options] midis' parser= OptionParser(usage=usage) parser.add_option('--n-measures', dest='n_measures', default=1, type='int', help='if the partition algorithm is MEASURE, especifies the number of measures to take as a unit') parser.add_option('-o', dest='outfname', help='the output file') options, args= parser.parse_args(argv[1:]) if len(args) < 1: parser.error('not enaught args') outfname= options.outfname if outfname is None: parser.error('missing outfname') infnames= args[:] parser= MidiScoreParser() models= [] for infname in infnames: score= parser.parse(infname) if not score: import ipdb;ipdb.set_trace() # por que podria devolver None? ######### # AJUSTES DE PARSING notes= score.get_first_voice() notes= [n for n in notes if n.duration > 0] instr= score.notes_per_instrument.keys()[0] patch= instr.patch channel= instr.channel score.notes_per_instrument= {instr:notes} ######### interval_size= measure_interval_size(score, options.n_measures) algorithm= HarmonyHMM(interval_size, instrument=patch, channel=channel) algorithm.train(score) algorithm.create_model() models.append(algorithm.model) def sim(m1, m2): """ calcula H(m1|m2) """ from math import log ans= 0 for s1 in m2.state_transition: for s2, prob in m1.state_transition.get(s1, {}).iteritems(): ans+= m2.pi[s1]*prob*log(prob) return -ans from os import path def get_node_name(ticks): n_quarters= 0 while ticks >= score.divisions: ticks-= score.divisions n_quarters+= 1 if ticks > 0: f= Fraction(ticks, score.divisions) if n_quarters > 0: return "%s + %s" % (n_quarters, f) else: return repr(f) return "%s" % n_quarters for i, m in enumerate(models): m.pi= m.calc_stationationary_distr() from pygraphviz import AGraph from utils.fraction import Fraction g= AGraph(directed=True, strict=False) for n1, adj in m.state_transition.iteritems(): n1_name= get_node_name(n1) for n2, prob in adj.iteritems(): n2_name= get_node_name(n2) g.add_edge(n1_name, n2_name) e= g.get_edge(n1_name, n2_name) e.attr['label']= str(prob)[:5] model_fname= path.basename(infnames[i]).replace('mid', 'png') g.draw(model_fname, prog='dot', args='-Grankdir=LR') sims= defaultdict(dict) for i, m1 in enumerate(models): for j in xrange(i+1, len(models)): m2= models[j] sims[path.basename(infnames[i])][path.basename(infnames[j])]= sim(m1, m2) sims[path.basename(infnames[j])][path.basename(infnames[i])]= sim(m2, m1) import csv f= open(outfname, 'w') writer= csv.writer(f) head= sorted(sims) head.insert(0, "-") writer.writerow(head) for (k, row) in sorted(sims.iteritems(), key=lambda x:x[0]): row= sorted(row.iteritems(), key=lambda x:x[0]) row= [t[1] for t in row] row.insert(0, k) writer.writerow(row) f.close() return from pygraphviz import AGraph from utils.fraction import Fraction g= AGraph(directed=True, strict=False) for infname1, adj in sims.iteritems(): for infname2, sim in adj.iteritems(): if sim>0.2 and sim!=0: continue g.add_edge(infname1, infname2) e= g.get_edge(infname1, infname2) e.attr['label']= str(sim)[:5] g.draw(outfname, prog='dot')
def draw_graph(sparse, f): g = AGraph(directed=True) g.add_edges_from(sparse.todok().keys()) g.draw(f, prog='neato')
class UmlPygraphVizDiagram: """ Creates a diagram similar to the class diagrams and objects diagrams from UML using pygraphviz """ def __init__(self): logging.basicConfig() self.graph = AGraph(directed=True, strict=False) self.graph.node_attr["shape"] = "record" self.graph.graph_attr["fontsize"] = "8" self.graph.graph_attr["fontname"] = "Bitstream Vera Sans" self.graph.graph_attr["label"] = "" self.connected_nodes = set() self.described_nodes = set() def _add_node(self, node_id, node_label): self.graph.add_node(node_id, label=node_label) def add_class_node(self, class_name, attributes): self.described_nodes.add(class_name) label = "<{<b>%s</b> | %s }>" % ( class_name, "<br align='left'/>".join(attributes).strip() + "<br align='left'/>", ) self.subgraph.add_node(graphviz_id(class_name), label=label) def add_object_node(self, object_name, class_name, attributes): self.described_nodes.add(object_name) if class_name: label = "<{<b><u>%s (%s)</u></b>| %s }>" % ( object_name, class_name, "<br align='left'/>".join(attributes) + "<br align='left'/>", ) else: label = "<{<b><u>%s</u></b>| %s }>" % ( object_name, "<br align='left'/>".join(attributes) + "<br align='left'/>", ) self.subgraph.add_node(graphviz_id(object_name), label=label) def add_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open") def add_cardinality_edge(self, src, dst, name, card): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel=card + "..." + card, labelangle=-65.0, ) def add_min_cardinality_edge(self, src, dst, name, card): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel=card + "...*", labelangle=-65.0, ) def add_max_cardinality_edge(self, src, dst, name, card): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel="0..." + card, labelangle=-65.0, ) def add_min_max_cardinality_edge(self, src, dst, name, min, max): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel=min + "..." + max, labelangle=-65.0, ) def add_list_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowtail="ediamond", dir="back", headlabel="0...*", labeldistance=2.0, labelfontcolor="black", labelangle=-65.0, ) # self.graph.add_edge(graphviz_id(src), graphviz_id(dst),label=name,arrowtail="ediamond", dir="back",headlabel="0...*", taillabel=(dst.split(":")[1])+"s",labeldistance=2.0,labelfontcolor="black") def add_symmetric_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="none") def add_functional_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", headlabel="1...1", taillabel="0...*", labeldistance=2.0, labelfontcolor="black", labelangle=-65.0, ) def add_inversefunctional_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", headlabel="0...*", taillabel="1...1", labeldistance=2.0, labelfontcolor="black", labelangle=-65.0, ) def add_equivalentclass_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label="\<\<equivalentClass\>\>", arrowhead="none", style="dashed" ) def add_unionof_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label="\<\<unionOf\>\>", arrowhead="open", style="dashed" ) def add_oneof_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge( graphviz_id(src), graphviz_id(dst), label="\<\<instanceOf\>\>", arrowhead="open", style="dashed", dir="back" ) def add_subclass_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), arrowhead="empty") def set_label(self, label): self.graph.graph_attr["label"] = label def start_subgraph(self, graph_name): self.subgraph = self.graph.add_subgraph(name="cluster_%s" % graphviz_id(graph_name)) self.subgraph.graph_attr["label"] = graph_name def add_undescribed_nodes(self): s = self.connected_nodes - self.described_nodes for node in s: self.graph.add_node(graphviz_id(node), label=node) def write_to_file(self, filename_dot): f = open(filename_dot, "w") f.write(self.graph.string()) print("dot file created: " + filename_dot) def visualize(self, filename, namespaceList=None): self.graph.layout(prog="dot") self.graph.draw(filename) if filename.endswith(".svg"): self._add_links_to_svg_file(filename, namespaceList) print("graphic file created: " + filename) def _add_links_to_svg_file(self, output, namespaceList=None): # SVG Datei anpassen svg_string = open(output).read() # Titel der SVG Datei anpassen svg_string = svg_string.replace("%3", output) # Hyperlinks mit den Internetseiten hinzufügen for ns in namespaceList: namespace = str(ns[0]) # Präfix des Namespaces url = str(ns[1]) # URL des Namespaces regex_str = """%s:(\w+)""" % namespace regex = re.compile(regex_str) svg_string = regex.sub("""<a xlink:href='%s\\1'>%s:\\1</a>""" % (url, namespace), svg_string) # Datei schreiben svg_file = open(output, "w") svg_file.write(svg_string) svg_file.close()
def draw_graph(): G = AGraph(dg.edges, directed=True, rankdir="LR") G.draw(graph_image_name,prog="dot") image_file = open(graph_image_name) return image_file
def draw_graph(input_file, out, ref_chain=[], aim_chain=[], freq_min=1, draw_all=False): ps = AGraph(directed=True) ps.graph_attr['rankdir'] = 'LR' ps.graph_attr['mode'] = 'hier' nodes = delete_nodes(ref_chain, input_file[1], freq_min) print('Number of nodes: ', end='') if draw_all == False: print(len(nodes)) elif draw_all == True: print(len(input_file[1])) cluster_main = ps.add_subgraph() cluster_main.graph_attr['rank'] = '0' for i in range(len(ref_chain)): shape = 'circle' if ref_chain[i] in aim_chain: cluster_main.add_node(ref_chain[i], shape=shape, color='red') else: cluster_main.add_node(ref_chain[i], shape=shape, color='pink') for i in input_file[0]: if 'PATH' in i: shape = 'box' if i in aim_chain or i in ref_chain: continue if i in nodes: ps.add_node(str(i)) continue else: if draw_all == True: ps.add_node(str(i), color='grey') continue for i in input_file[1]: color = 'black' try: if ref_chain.index(i[1]) - ref_chain.index(i[0]) == 1: color = 'red' ps.add_edge(str(i[0]), str(i[1]), color=color, penwidth=str(math.sqrt(i[2]))) continue except ValueError: pass if i[2] < freq_min: if draw_all == True: ps.add_edge(str(i[0]), str(i[1]), color='grey', penwidth=str(math.sqrt(i[2])), constraint='false') continue elif i[0] in nodes and i[1] in nodes: ps.add_edge(str(i[0]), str(i[1]), color=color, penwidth=str(math.sqrt(i[2]))) elif draw_all == True: ps.add_edge(str(i[0]), str(i[1]), color='grey', penwidth=str(math.sqrt(i[2])), constraint='false') ps.draw(out + '.ps', prog='dot') ps.write(out + '.dot')
class Plugin: def __init__(self, title="System"): self.schematic = AGraph( directed=True, label=title, rankdir='LR', splines='true' ) self.nodes = [] self.edges = [] self.outputs = {} self.ip_outputs = {} #sources def write_stimulus(self, stream): self.nodes.append((id(stream), "Stimulus", "ellipse")) def write_repeater(self, stream): self.nodes.append( (id(stream), "Repeater : {0}".format(stream.value), "ellipse") ) def write_counter(self, stream): self.nodes.append( ( id(stream), "Counter : {0}, {1}, {2}".format( stream.start, stream.stop, stream.step ), "ellipse" ) ) def write_in_port(self, stream): self.nodes.append( ( id(stream), "InPort : {0} {1}".format( stream.name, stream.bits ), "ellipse" ) ) def write_serial_in(self, stream): self.nodes.append( ( id(stream), "SerialIn : {0}".format( stream.name ), "ellipse" ) ) #sinks def write_response(self, stream): self.nodes.append((id(stream), "Response", "box")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_out_port(self, stream): self.nodes.append( ( id(stream), "OutPort : {0}".format( stream.name ), "box" ) ) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_serial_out(self, stream): self.nodes.append( ( id(stream), "SerialOut : {0}".format( stream.name ), "box" ) ) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_svga(self, stream): self.nodes.append((id(stream), "SVGA", "box")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_console(self, stream): self.nodes.append((id(stream), "Console", "box")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_asserter(self, stream): self.nodes.append((id(stream), "Asserter", "box")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) #combinators def write_binary(self, stream): labels = { 'add' : '+', 'sub' : '-', 'mul' : '*', 'div' : '//', 'mod' : '%', 'and' : '&', 'or' : '|', 'xor' : '^', 'sl' : '<<', 'sr' : '>>', 'eq' : '==', 'ne' : '!=', 'lt' : '<=', 'le' : '<', 'gt' : '>', 'ge' : '>=' } self.nodes.append((id(stream), labels[stream.function], "circle")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "nw" ) ) self.edges.append( ( id(stream.b), id(stream), stream.b.get_bits(), "sw" ) ) def write_unary(self, stream): labels = { 'abs' : 'abs', 'not' : '!', 'invert' : '~', 'sln' : '<<', 'srn' : '>>', } self.nodes.append((id(stream), labels[stream.function], "circle")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "nw" ) ) self.edges.append( ( id(stream.b), id(stream), stream.b.get_bits(), "sw" ) ) def write_lookup(self, stream): self.nodes.append((id(stream), "Lookup", "ellipse")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_array(self, stream): self.nodes.append((id(stream), "Array", "ellipse")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "nw" ) ) self.edges.append( ( id(stream.b), id(stream), stream.b.get_bits(), "w" ) ) self.edges.append( ( id(stream.c), id(stream), stream.c.get_bits(), "sw" ) ) def write_decoupler(self, stream): self.nodes.append( ( id(stream), "Decoupler", "ellipse" ) ) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_resizer(self, stream): self.nodes.append((id(stream), "Resizer", "ellipse")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_printer(self, stream): self.nodes.append((id(stream), "Printer", "ellipse")) self.edges.append( ( id(stream.a), id(stream), stream.a.get_bits(), "w" ) ) def write_output(self, stream): self.outputs[id(stream)] = id(stream.process) def write_process(self, p): self.nodes.append((id(p), "Process", "ellipse")) for i in p.inputs: self.edges.append((id(i), id(p), i.get_bits(), "centre")) def write_external_ip(self, ip): for i in ip.output_streams: self.ip_outputs[id(i)]=id(ip) self.nodes.append((id(ip), ip.definition.name, "ellipse")) for i in ip.input_streams: self.edges.append((id(i), id(ip), i.get_bits(), "centre")) def write_chip(self, *args): pass #System VHDL Generation and external tools def draw(self, filename): for ident, label, shape in self.nodes: self.schematic.add_node( str(ident), shape=shape, label=str(label) ) for from_node, to_node, bits, headport in self.edges: if from_node in self.outputs: self.schematic.add_edge( str(self.outputs[from_node]), str(to_node), label=str(bits), headport=headport ) elif from_node in self.ip_outputs: self.schematic.add_edge( str(self.ip_outputs[from_node]), str(to_node), label=str(bits), headport=headport ) else: self.schematic.add_edge( str(from_node), str(to_node), label=str(bits) ) self.schematic.layout(prog='dot') self.schematic.draw(filename)
def recalculate(user): # remove old ranking RankedTeam.objects.filter(team__user = user).delete() for pic in RankingPicture.objects.all(): pic.image.delete() pic.delete() color_index = 0 team_graph = Graph() gvfull = AGraph(directed = True) for team in user.teams.all(): gvfull.add_node(asciiname(team), label = team.name) team_graph.add_node(team) for game in Game.objects.filter(team_1__user = user, team_2__user = user): team_graph.add_edge(game.winner(), game.loser(), game.jugg_diff()) for source, dest, weight in team_graph.edges(): gvfull.add_edge(asciiname(source), asciiname(dest), label = str(weight)) current_place = 1 gvcircles = AGraph(directed = True) gvtiebreaker = AGraph(directed = True) for place in team_graph.topological_sort(): place_list = [] relevant_teams = set() for circle in place: relevant_teams |= circle if len(circle) == 1: continue color_index, current_color = getcolor(color_index) for team in circle: gvcircles.add_node(asciiname(team), label = team.name, color = current_color, fontcolor = current_color) gvfull.get_node(asciiname(team)).attr['color'] = current_color gvfull.get_node(asciiname(team)).attr['fontcolor'] = current_color for source, dest, weight in team_graph.edges(): if source in circle and dest in circle: gvcircles.add_edge(asciiname(source), asciiname(dest), label = str(weight), color = current_color, fontcolor = current_color) gvfull.get_edge(asciiname(source), asciiname(dest)).attr['color'] = current_color gvfull.get_edge(asciiname(source), asciiname(dest)).attr['fontcolor'] = current_color place = [[(team.normalized_jugg_diff(relevant_teams), team.name, team) for team in circle] for circle in place] for circle in place: circle.sort(reverse = True) while place: place_list.append(set()) i = 0 while i < len(place): circle = place[i] jd = circle[0][0] while circle and circle[0][0] == jd: place_list[-1].add(circle.pop(0)) if not circle: place.remove(circle) else: i += 1 for same_place_set in place_list: # tie breaker if len(same_place_set) > 1: # teams that everyone on this place played against relevant_teams = team_graph.nodes() for circ_jugg_diff, name, team in same_place_set: opponents = set() for game in team.games(): if game.team_1 == team: opponents.add(game.team_2) else: opponents.add(game.team_1) relevant_teams &= opponents if len(relevant_teams) > 0: color_index, current_color_a = getcolor(color_index) color_index, current_color_b = getcolor(color_index) for team in relevant_teams: gvtiebreaker.add_node("b-" + asciiname(team), label = team.name, color = current_color_b, fontcolor = current_color_b) for void, void, team in same_place_set: gvtiebreaker.add_node("a-" + asciiname(team), label = team.name, color = current_color_a, fontcolor = current_color_a) for game in team.games(): if game.team_1 == team and game.team_2 in relevant_teams: if game.winner() == team: gvtiebreaker.add_edge("a-" + asciiname(team), "b-" + asciiname(game.team_2), label = game.jugg_diff(), color = current_color_a, fontcolor = current_color_a) else: gvtiebreaker.add_edge("b-" + asciiname(game.team_2), "a-" + asciiname(team), label = game.jugg_diff(), color = current_color_b, fontcolor = current_color_b) elif game.team_2 == team and game.team_1 in relevant_teams: if game.winner() == team: gvtiebreaker.add_edge("a-" + asciiname(team), "b-" + asciiname(game.team_1), label = game.jugg_diff(), color = current_color_a, fontcolor = current_color_a) else: gvtiebreaker.add_edge("b-" + asciiname(game.team_1), "a-" + asciiname(team), label = game.jugg_diff(), color = current_color_b, fontcolor = current_color_b) # jugg differences against relevant teams rel_jugg_diffs = set() for team_tuple in same_place_set: rel_jugg_diffs.add((team_tuple, team_tuple[2].normalized_jugg_diff(relevant_teams))) # pop all teams, highest relevant jugg difference first while rel_jugg_diffs: # current maximum max_rel_jugg_diff = None # teams with maximum jugg difference to_remove = None for team_tuple, rel_jugg_diff in rel_jugg_diffs: # new maximum if max_rel_jugg_diff is None or rel_jugg_diff > max_rel_jugg_diff[0]: max_rel_jugg_diff = (rel_jugg_diff, {team_tuple}) to_remove = {(team_tuple, rel_jugg_diff)} # same as maximum elif rel_jugg_diff == max_rel_jugg_diff[0]: max_rel_jugg_diff[1].add(team_tuple) to_remove.add((team_tuple, rel_jugg_diff)) # remove teams with maximum jugg difference rel_jugg_diffs -= to_remove # add teams to listing for (circ_jugg_diff, name, team), rel_jugg_diff in to_remove: RankedTeam.objects.create(place = current_place, team = team) current_place += 1 else: circ_jugg_diff, name, team = same_place_set.pop() RankedTeam.objects.create(place = current_place, team = team) current_place += 1 with tempfile.NamedTemporaryFile(suffix = ".png") as tmp: gvfull.draw(tmp, "png", "dot") pic = RankingPicture(user = user, image = File(tmp), title = "Full Team Graph") pic.save() with tempfile.NamedTemporaryFile(suffix = ".png") as tmp: gvcircles.draw(tmp, "png", "dot") pic = RankingPicture(user = user, image = File(tmp), title = "Circles") pic.save() with tempfile.NamedTemporaryFile(suffix = ".png") as tmp: gvtiebreaker.draw(tmp, "png", "dot") pic = RankingPicture(user = user, image = File(tmp), title = "Tie Breaker") pic.save()
if __name__ == '__main__': M1 = FSM(G7) M2 = FSM(G8) D1 = M1.get_DFA() D2 = M2.get_DFA() args = [(M1.get_dot_data(), u"НДКА первой грамматики"), (M2.get_dot_data(), u"НДКА второй грамматики"), (D1.get_dot_data(), u"ДКА первой грамматики"), (D2.get_dot_data(), u"ДКА второй грамматики")] # threads = [Process(target=show_graph, args=a) for a in args] # map(Process.start, threads) # map(Process.join, threads) from pygraphviz import AGraph for data, name in args: G = AGraph(data) G.draw(name + '.png', prog='dot') with open("test.txt") as f: chains = f.read().replace(" ", "").split('\n') chains1 = [] chains2 = [] chains_no_one = [] for c in chains: if D1.check_chain(c): chains1.append(c) elif D2.check_chain(c): chains2.append(c) else: chains_no_one.append(c)
class UiGraphio(QMainWindow): """ Main window for application """ def __init__(self): """ Constructor """ QMainWindow.__init__(self) self.ui = graphio.Ui_MainWindow() self.ui.setupUi(self) self.scene_graph = QGraphicsScene() self.ui.graphicsView.setScene(self.scene_graph) self.ui.graphicsView.update() self.graph = AGraph(strict=True, directed=True) self.graph.layout(prog='dot') ##################################################### # View update ##################################################### def update_adj_matrix(self): count = self.graph.number_of_nodes() self.ui.tw_adjmatrix.setRowCount(count) self.ui.tw_adjmatrix.setColumnCount(count) self.ui.tw_adjmatrix.setHorizontalHeaderLabels(self.graph.nodes()) self.ui.tw_adjmatrix.setVerticalHeaderLabels(self.graph.nodes()) for (i, u) in enumerate(self.graph.nodes()): for (j, v) in enumerate(self.graph.nodes_iter()): if self.graph.has_edge(u, v): self.ui.tw_adjmatrix.setItem( i, j, QTableWidgetItem( self.graph.get_edge(u, v).attr['label'])) else: self.ui.tw_adjmatrix.setItem(i, j, QTableWidgetItem(str(0))) def update_matrix_incidence(self): nodes = self.graph.nodes() edges = self.graph.edges() self.ui.tw_incmatrix.setRowCount(len(nodes)) self.ui.tw_incmatrix.setColumnCount(len(edges)) self.ui.tw_incmatrix.setHorizontalHeaderLabels( [str(node) for node in self.graph.edges()]) self.ui.tw_incmatrix.setVerticalHeaderLabels(self.graph.nodes()) for (i, u) in enumerate(nodes): for (j, edg) in enumerate(edges): value = 0 if (u == edg[0]): value = 1 elif (u == edg[1]): value = -1 self.ui.tw_incmatrix.setItem(i, j, QTableWidgetItem(str(value))) def update_list_edges(self): edges = self.graph.edges() self.ui.tw_edges.setRowCount(len(edges)) for (i, edge) in enumerate(edges): self.ui.tw_edges.setItem(i, 0, QTableWidgetItem(edge[0])) self.ui.tw_edges.setItem(i, 1, QTableWidgetItem(edge[1])) def update_adj_list(self): nodes = self.graph.nodes() self.ui.tw_adjlist.setRowCount(self.graph.number_of_nodes()) self.ui.tw_adjlist.setVerticalHeaderLabels(nodes) for (i, node) in enumerate(nodes): value = '' for adj in self.graph.out_edges(node): value += adj[1] + ', ' self.ui.tw_adjlist.setItem(i, 0, QTableWidgetItem(value[:-2])) ##################################################### # Reset editors ##################################################### def add_cb_item(self, label): n = self.ui.cb_nodes.count() i = 0 while i < n: itext = self.ui.cb_nodes.itemText(i) if label == itext: return elif label < itext: break i += 1 # insert item to lists self.ui.cb_nodes.insertItem(i, label) self.ui.cb_starting_node.insertItem(i, label) self.ui.cb_ending_node.insertItem(i, label) @pyqtSlot(bool, name='on_bt_add_node_clicked') @pyqtSlot(bool, name='on_bt_del_node_clicked') @pyqtSlot(bool, name='on_bt_add_edge_clicked') @pyqtSlot(bool, name='on_bt_del_edge_clicked') def reset_editors(self): self.ui.cb_nodes.clearEditText() self.ui.cb_starting_node.clearEditText() self.ui.cb_ending_node.clearEditText() self.ui.sb_weight_edge.setMinimum() def redraw(self): self.graph.draw('graph', 'png', 'dot') self.scene_graph.clear() self.scene_graph.addItem(QGraphicsPixmapItem(QPixmap('graph'))) self.ui.graphicsView.update() ##################################################### # Buttons actions ##################################################### @pyqtSlot() def on_bt_add_node_clicked(self): """ Slot when click on Add node button """ label = self.ui.cb_nodes.currentText() if not self.graph.has_node(label): self.add_cb_item(label) self.graph.add_node(label) self.redraw() @pyqtSlot() def on_bt_del_node_clicked(self): """ Slot when click on Delete node button """ index = self.ui.cb_nodes.currentIndex() label = self.ui.cb_nodes.currentText() if index > -1 and self.graph.has_node(label): self.graph.remove_node(label) self.redraw() self.ui.cb_nodes.removeItem(index) self.ui.cb_starting_node.removeItem(index) self.ui.cb_ending_node.removeItem(index) @pyqtSlot() def on_bt_add_edge_clicked(self): """ Slot when click on Add branch button """ start = self.ui.cb_starting_node.currentText() end = self.ui.cb_ending_node.currentText() weight = self.ui.sb_weight_edge.value() if start and end: self.add_cb_item(start) self.add_cb_item(end) self.graph.add_edge(start, end, label=weight) self.redraw() @pyqtSlot() def on_bt_del_edge_clicked(self): """ Slot when click on Delete branch button """ start = self.ui.cb_starting_node.currentText() end = self.ui.cb_ending_node.currentText() weight = self.ui.sb_weight_edge.value() if start and end and self.graph.has_edge(start, end): self.graph.remove_edge(start, end) self.redraw() @pyqtSlot(int) @pyqtSlot(bool, name='on_bt_add_node_clicked') @pyqtSlot(bool, name='on_bt_del_node_clicked') @pyqtSlot(bool, name='on_bt_add_edge_clicked') @pyqtSlot(bool, name='on_bt_del_edge_clicked') def on_toolbox_view_currentChanged(self, index): index = self.ui.toolbox_view.currentIndex() if index == 0: self.update_adj_matrix() elif index == 1: self.update_matrix_incidence() elif index == 2: self.update_list_edges() elif index == 3: self.update_adj_list()
def this_layer_plus_one(list_of_task_dicts: list, list_of_subtasks: list, output_filename: str, recursive_depth: int, parent: str) -> None: """ recursively create hyperlinked SVGs using GraphViz input data structure is a list of dicts """ # need the filename prefix for both this file and the child files fnamel = "layer_plus_one_" + str(recursive_depth) + "_" fnamel1 = "layer_plus_one_" + str(recursive_depth + 1) + "_" # initialize a new graph for this layer use_case = AGraph(directed=True, comment=output_filename) #, compound=True) use_case.clear() use_case.graph_attr.update(compound="true") for task in list_of_subtasks: #print(task) for this_dict in list_of_task_dicts: if list(this_dict.keys())[0] == task: #unique_subgraph_name = task_without_spaces#+"_"+str(random.randint(1000,9999)) if (task_has_children_in_list_of_task_dicts( task, list_of_task_dicts)): sg = use_case.subgraph(name="cluster_" + smush(task), label=with_spaces(task), href=fnamel1 + smush(task) + ".svg") else: # no href to SVG because there are no child nodes sg = use_case.subgraph(name="cluster_" + smush(task), label=with_spaces(task)) sg.add_node(smush(task), style="invis") #print(task) #print(list(this_dict.keys())[0]) subitem_list = list(this_dict.values())[0] # print(subitem_list) if len(subitem_list) < 2: # no edges to connect if (task_has_children_in_list_of_task_dicts( subitem_list[0], list_of_task_dicts)): sg.add_node(smush(task) + smush(subitem_list[0]), label=with_spaces(subitem_list[0]), href=fnamel1 + smush(task) + ".svg", color="blue", shape="rectangle") else: sg.add_node(smush(task) + smush(subitem_list[0]), label=with_spaces(subitem_list[0]), shape="rectangle") sg.add_edge(smush(task) + smush(subitem_list[0]), smush(task), style="invis") else: for index, subitem in enumerate(subitem_list[1:]): #print(' ',subitem) if (task_has_children_in_list_of_task_dicts( subitem_list[index], list_of_task_dicts)): sg.add_node(smush(task) + smush(subitem_list[index]), label=with_spaces(subitem_list[index]), href=fnamel1 + smush(task) + ".svg", color="blue", shape="rectangle") else: # no children to link to sg.add_node(smush(task) + smush(subitem_list[index]), label=with_spaces(subitem_list[index]), shape="rectangle") if (task_has_children_in_list_of_task_dicts( subitem, list_of_task_dicts)): sg.add_node(smush(task) + smush(subitem), label=with_spaces(subitem), href=fnamel1 + smush(task) + ".svg", color="blue", shape="rectangle") else: sg.add_node(smush(task) + smush(subitem), label=with_spaces(subitem), shape="rectangle") # every sequence of tasks is ordered, so link task with prior task sg.add_edge( smush(task) + smush(subitem_list[index]), smush(task) + smush(subitem)) if index == len( subitem_list ): # last item links to invisible node in order to force invisible node to bottom of subgraph sg.add_edge(smush(task) + smush(subitem_list[index]), smush(task), style="invis") for index, task_tup in enumerate(list_of_subtasks[1:]): # use_case.add_node(smush(list_of_subtasks[index]),label=with_spaces(task_tup),shape="rectangle") # use_case.add_node(smush(task_tup),label=with_spaces(task_tup),shape="rectangle") use_case.add_edge(smush(list_of_subtasks[index]), smush(task_tup), ltail="cluster_" + smush(list_of_subtasks[index]), lhead="cluster_" + smush(task_tup)) if recursive_depth > 0: use_case.add_node("zoom out", href=parent + ".svg", color="red", shape="triangle") #use_case.write() use_case.draw(fnamel + output_filename + ".svg", format="svg", prog="dot") #print("drew SVG for ", output_filename) for task_tuple in list_of_subtasks: for index, this_dict in enumerate(list_of_task_dicts): if task_tuple in this_dict.keys(): this_layer_plus_one(list_of_task_dicts, list_of_task_dicts[index][task_tuple], smush(task_tuple), recursive_depth + 1, fnamel + output_filename) return
def show(self, filename='AST.png'): g = AGraph() g.graph_attr['label'] = 'AST' AST_DFS(self, g) g.layout(prog='dot') g.draw(filename)
def create_graph(filename, layout="dot", use_singularity=False): """ :param filename: should end in .png or .svg or .dot If extension is .dot, only the dot file is created. This is useful if you have issues installing graphviz. If so, under Linux you could use our singularity container see github.com/cokelaer/graphviz4all """ from bioconvert.core.registry import Registry rr = Registry() try: if filename.endswith(".dot") or use_singularity is True: raise from pygraphviz import AGraph dg = AGraph(directed=True) for a, b in rr.get_conversions(): dg.add_edge(a, b) dg.layout(layout) dg.draw(filename) except: dot = """ strict digraph{ node [label="\\N"]; """ nodes = set([item for items in rr.get_conversions() for item in items]) for node in nodes: dot += "\"{}\";\n".format(node) for a, b in rr.get_conversions(): dot+="\"{}\" -> \"{}\";\n".format(a, b) dot += "}\n" from easydev import TempFile from bioconvert import shell dotfile = TempFile(suffix=".dot") with open(dotfile.name, "w") as fout: fout.write(dot) dotpath = "" if use_singularity: from bioconvert.core.downloader import download_singularity_image singfile = download_singularity_image( "graphviz.simg", "shub://cokelaer/graphviz4all:v1", "4288088d91c848e5e3a327282a1ab3d1") dotpath = "singularity run {} ".format(singfile) on_rtd = environ.get('READTHEDOCS', None) == 'True' if on_rtd: dotpath = "" ext = filename.rsplit(".", 1)[1] cmd = "{}dot -T{} {} -o {}".format(dotpath, ext, dotfile.name, filename) try: shell(cmd) except: import os os.system(cmd)
class UmlPygraphVizDiagram(): """ Creates a diagram similar to the class diagrams and objects diagrams from UML using pygraphviz """ def __init__(self): logging.basicConfig() self.graph = AGraph(directed=True, strict=False) self.graph.node_attr['shape'] = 'record' self.graph.graph_attr['fontsize'] = '8' self.graph.graph_attr['fontname'] = "Bitstream Vera Sans" self.graph.graph_attr['label'] = "" self.connected_nodes = set() self.described_nodes = set() def _add_node(self, node_id, node_label): self.graph.add_node(node_id, label=node_label) def add_class_node(self, class_name, attributes): self.described_nodes.add(class_name) label = "<{<b>%s</b> | %s }>" % ( class_name, "<br align='left'/>".join(attributes).strip() + "<br align='left'/>") self.subgraph.add_node(graphviz_id(class_name), label=label) def add_object_node(self, object_name, class_name, attributes): self.described_nodes.add(object_name) if class_name: label = "<{<b><u>%s (%s)</u></b>| %s }>" % ( object_name, class_name, "<br align='left'/>".join(attributes) + "<br align='left'/>") else: label = "<{<b><u>%s</u></b>| %s }>" % ( object_name, "<br align='left'/>".join(attributes) + "<br align='left'/>") self.subgraph.add_node(graphviz_id(object_name), label=label) def add_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open") def add_cardinality_edge(self, src, dst, name, card): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel=card + "..." + card, labelangle=-65.0) def add_min_cardinality_edge(self, src, dst, name, card): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel=card + "...*", labelangle=-65.0) def add_max_cardinality_edge(self, src, dst, name, card): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel="0..." + card, labelangle=-65.0) def add_min_max_cardinality_edge(self, src, dst, name, min, max): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", labeldistance=2.0, headlabel=min + "..." + max, labelangle=-65.0) def add_list_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowtail="ediamond", dir="back", headlabel="0...*", labeldistance=2.0, labelfontcolor="black", labelangle=-65.0) # self.graph.add_edge(graphviz_id(src), graphviz_id(dst),label=name,arrowtail="ediamond", dir="back",headlabel="0...*", taillabel=(dst.split(":")[1])+"s",labeldistance=2.0,labelfontcolor="black") def add_symmetric_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="none") def add_functional_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", headlabel="1...1", taillabel="0...*", labeldistance=2.0, labelfontcolor="black", labelangle=-65.0) def add_inversefunctional_edge(self, src, dst, name): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label=name, arrowhead="open", headlabel="0...*", taillabel="1...1", labeldistance=2.0, labelfontcolor="black", labelangle=-65.0) def add_equivalentclass_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label="\<\<equivalentClass\>\>", arrowhead="none", style="dashed") def add_unionof_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label="\<\<unionOf\>\>", arrowhead="open", style="dashed") def add_oneof_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), label="\<\<instanceOf\>\>", arrowhead="open", style="dashed", dir="back") def add_subclass_edge(self, src, dst): self.connected_nodes.add(src) self.connected_nodes.add(dst) self.graph.add_edge(graphviz_id(src), graphviz_id(dst), arrowhead="empty") def set_label(self, label): self.graph.graph_attr['label'] = label def start_subgraph(self, graph_name): self.subgraph = self.graph.add_subgraph(name="cluster_%s" % graphviz_id(graph_name)) self.subgraph.graph_attr['label'] = graph_name def add_undescribed_nodes(self): s = self.connected_nodes - self.described_nodes for node in s: self.graph.add_node(graphviz_id(node), label=node) def write_to_file(self, filename_dot): f = open(filename_dot, 'w') f.write(self.graph.string()) print("dot file created: " + filename_dot) def visualize(self, filename, namespaceList=None): self.graph.layout(prog='dot') self.graph.draw(filename) if filename.endswith(".svg"): self._add_links_to_svg_file(filename, namespaceList) print("graphic file created: " + filename) def _add_links_to_svg_file(self, output, namespaceList=None): # SVG Datei anpassen svg_string = open(output).read() # Titel der SVG Datei anpassen svg_string = svg_string.replace("%3", output) # Hyperlinks mit den Internetseiten hinzufügen for ns in namespaceList: namespace = str(ns[0]) # Präfix des Namespaces url = str(ns[1]) # URL des Namespaces if namespace: regex_str = """%s:(\w+)""" % namespace regex = re.compile(regex_str) svg_string = regex.sub( """<a xlink:href='%s\\1'>%s:\\1</a>""" % (url, namespace), svg_string) # Datei schreiben svg_file = open(output, "w") svg_file.write(svg_string) svg_file.close()
def pdf_export(self, id, **kw): app = DBSession.query(Application).get(id) log.info("pdf_export: id=%s" % (id)) action_by_id = {} for a in DBSession.query(Action): action_by_id[a.action_id] = asterisk_string(a.name) prev_context = None nodes = [] edges = [] label = [] for s in ( DBSession.query(Scenario).filter(Scenario.app_id == id).order_by(Scenario.context).order_by(Scenario.step) ): if prev_context is None: # First loop log.debug(" * * * First context") prev_context = s.context elif prev_context != s.context: # Next context log.debug(" * * * Write context %s" % prev_context) nodes.append(mk_label(label, action_by_id)) label = [] prev_context = s.context edges += mk_edges(s) label.append(s) log.debug(" * * * Write last %s" % prev_context) nodes.append(mk_label(label, action_by_id)) dir_tmp = mkdtemp() dot = open(dir_tmp + "/graphviz.dot", "w") dot.write("digraph g {\n") for n in nodes: dot.write(asterisk_string(n)) log.debug("edges: %s" % edges) for e in edges: dot.write(asterisk_string(e)) dot.write("}\n") dot.close() fn = "%s/%s.pdf" % (dir_tmp, app.name) from pygraphviz import AGraph g = AGraph(dir_tmp + "/graphviz.dot") log.debug(" * * * AGraph encoding %s" % g.encoding) g.layout(prog="dot") g.draw(fn) import os try: st = os.stat(fn) f = open(fn) except: flash(u"Erreur à la génération du fichier PDF", "error") redirect("") rh = response.headers rh["Pragma"] = "public" # for IE rh["Expires"] = "0" rh["Cache-control"] = "must-revalidate, post-check=0, pre-check=0" # for IE rh["Cache-control"] = "max-age=0" # for IE rh["Content-Type"] = "application/pdf" rh["Content-Disposition"] = str( (u'attachment; filename="%s.pdf"; size=%d;' % (app.name, st.st_size)).encode("utf-8") ) rh["Content-Transfer-Encoding"] = "binary" return f.read()
def create_graph(filename, layout="dot", use_singularity=False, color_for_disabled_converter='red'): """ :param filename: should end in .png or .svg or .dot If extension is .dot, only the dot file is created. This is useful if you have issues installing graphviz. If so, under Linux you could use our singularity container see github.com/cokelaer/graphviz4all """ from bioconvert.core.registry import Registry rr = Registry() try: if filename.endswith(".dot") or use_singularity is True: raise Exception() from pygraphviz import AGraph dg = AGraph(directed=True) url = "https://bioconvert.readthedocs.io/en/master/formats.html#{}" for a, b, s in rr.get_all_conversions(): if len(a) == 1 and len(b) == 1: dg.add_node(a[0], shape="rectangle", style="filled", url=url.format(a[0].upper())) dg.add_node(b[0], shape="rectangle", style="filled", url=url.format(b[0].upper())) dg.add_edge( a[0], b[0], color='black' if s else color_for_disabled_converter) else: and_node = "_".join(a) + "_and_" + "_".join(b) dg.add_node(and_node, label="", fillcolor="black", width=.1, height=.1, styled="filled", fixedsize=True, shape="circle") for this in a: dg.add_edge( this, and_node, color="black" if s else color_for_disabled_converter) for this in b: dg.add_edge( and_node, this, color="black" if s else color_for_disabled_converter) for name in dg.nodes(): if dg.degree(name) < 5: dg.get_node(name).attr["fillcolor"] = "white" elif dg.degree(name) < 10: # yellow dg.get_node(name).attr["fillcolor"] = "yellow" elif dg.degree(name) < 20: # orange dg.get_node(name).attr["fillcolor"] = "orange" else: # red dg.get_node(name).attr["fillcolor"] = "red" dg.layout(layout) dg.draw(filename) dg.write("conversion.dot") print(list(dg.get_node("FASTQ").attr.values())) except Exception as e: _log.error(e) dot = """ strict digraph{ node [label="\\N"]; """ nodes = set([ item for items in rr.get_all_conversions() for item in items[0:1] ]) for node in nodes: dot += "\"{}\";\n".format(node) for a, b, s in rr.get_all_conversions(): dot += "\"{}\" -> \"{}\";\n".format(a, b) dot += "}\n" from easydev import TempFile from bioconvert import shell dotfile = TempFile(suffix=".dot") with open(dotfile.name, "w") as fout: fout.write(dot) dotpath = "" if use_singularity: from bioconvert.core.downloader import download_singularity_image singfile = download_singularity_image( "graphviz.simg", "shub://cokelaer/graphviz4all:v1", "4288088d91c848e5e3a327282a1ab3d1") dotpath = "singularity run {} ".format(singfile) on_rtd = environ.get('READTHEDOCS', None) == 'True' if on_rtd: dotpath = "" ext = filename.rsplit(".", 1)[1] cmd = "{}dot -T{} {} -o {}".format(dotpath, ext, dotfile.name, filename) print(dotfile.name) try: shell(cmd) except: import os os.system(cmd)