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 networkx(self): d = self.graph() # FIXME deduplicate from pygraphviz import AGraph import networkx as nx dot = AGraph(strict=True, directed=True) def rec(nodes, parent): for d in nodes: if not isinstance(d, dict): if '(dirty)' in d: d = d.replace('(dirty)', '') dot.add_node(d, label=d, color='red') dot.add_edge(d, parent, color='red') else: dot.add_node(d, label=d) dot.add_edge(d, parent) else: for k in d: if '(dirty)' in k: k = k.replace('(dirty)', '') dot.add_node(k, label=k, color='red') rec(d[k], k) dot.add_edge(k, parent, color='red') else: dot.add_node(k, label=k) rec(d[k], k) dot.add_edge(k, parent) for k in d: dot.add_node(k, label=k) rec(d[k], k) return nx.nx_agraph.from_agraph(dot)
def gen_op_insts(rf_allocs: List[RFallocation], dfg: AGraph, fu: AGraph, input_map: Dict[str, int]) -> List[ATAI]: assembly = [] instructions: List[Instruction] = [] for instruction in fu.nodes(): instructions.append(parse_instruction(instruction)) for instruction in instructions: n = dfg.get_node(instruction.name) nodes = dfg.predecessors(n) input_type0 = inst_input_type(rf_allocs, fu, nodes[0]) if len(nodes) > 1: input_type1 = inst_input_type(rf_allocs, fu, nodes[1]) else: input_type1 = input_type0 # This should never occur but we check for it anyways if input_type0 == OpInput and input_type1 == OpInput: if nodes[0] != nodes[1]: raise DoubleUnidenticalOPInputException # TODO: find scheduling for fetch ops might need to be swapped to fit? if input_type0 == RFInput: # If the data is in the RF we need to generate fetch instructions assembly.append( generate_fetch(rf_allocs, instruction, nodes[0], ATAFetch.REG.REG0)) input0 = RFInput() elif input_type0 == OpInput: input0 = OpInput() else: n = input_map[nodes[0].get_name()] if n is None: raise FUinputException( 'Cannot find FU from which predecessing node originates in map' ) input0 = FUinput(n) if input_type1 == RFInput: assembly.append( generate_fetch(rf_allocs, instruction, nodes[1], ATAFetch.REG.REG1)) input1 = RFInput() elif input_type1 == OpInput: input1 = OpInput() else: n = input_map[nodes[1].get_name()] if n is None: raise FUinputException( 'Cannot find FU from which predecessing node originates in map' ) input1 = FUinput(n) assembly.append(ATAOp(input0, input1, instruction.cycle)) return assembly
def __init__(self): self.evolution = [] # List[str] self._evaluating = None # Dict[Candidate, Set[Requirement]] self._dependencies = defaultdict(set) # Dict[Candidate.name, Counter[Requirement]] self._active_requirements = defaultdict(Counter) self._node_names = {} self._counter = count() self.graph = AGraph( directed=True, rankdir="LR", labelloc="top", labeljust="center", nodesep="0", concentrate="true", ) self.graph.add_node("root", label=":root:", shape="Mdiamond") self._node_names[self._key(None)] = "root" del self.graph.node_attr["label"] self.graph.edge_attr.update({ "arrowhead": "empty", "style": "dashed", "color": "#808080" })
def get_graphviz(self, triple_args_function=None, ignore_properties=VIS_IGNORE_PROPERTIES): """ Create a pygraphviz graph from the tree """ def _id(node): return node.uri.split("/")[-1] g = AGraph(directed=True) triples = list(self.get_triples()) nodeset = set(chain.from_iterable((t.subject, t.object) for t in triples)) for n in nodeset: label = "%s: %s" % (n.id, n.word) for k, v in n.__dict__.iteritems(): if k not in ignore_properties: label += "\\n%s: %s" % (k, v) g.add_node(_id(n), label=label) # create edges for triple in triples: kargs = (triple_args_function(triple) if triple_args_function else {}) if 'label' not in kargs: kargs['label'] = triple.predicate g.add_edge(_id(triple.subject), _id(triple.object), **kargs) # some theme options g.graph_attr["rankdir"] = "BT" g.node_attr["shape"] = "rect" g.edge_attr["edgesize"] = 10 g.node_attr["fontsize"] = 10 g.edge_attr["fontsize"] = 10 return g
def toSVG(B, name): if B: graph = AGraph(toDot(B)) layout = graph.layout(prog="dot") draw = graph.draw("{}.svg".format(name)) else: print("Give me a better tree")
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 __init__(self, filename): self.G = AGraph(filename) xs = [(nodo, nodo.attr.get("initial", None)) for nodo in self.G.iternodes()] xs = [x for x in xs if x[1]] if len(xs) == 0: raise BadInputGraph("Missing 'initial' node") elif len(xs) > 1: raise BadInputGraph("Cannot have two initial nodes") if not any(nodo.attr.get("goal", None) for nodo in self.G.iternodes()): raise BadInputGraph("Missing a goal state '[goal=\"1\"]'") super(DotGraphSearchProblem, self).__init__(xs[0][0]) self.initial_state.attr["shape"] = "doublecircle" for node in self.G.iternodes(): if self.is_goal(node): node.attr["shape"] = "hexagon" node.attr["color"] = "blue" self.seen = set() self.visit(self.initial_state) for edge in self.G.iteredges(): edge.attr["style"] = "dotted" x = edge.attr.get("weight", None) if x: x = int(x) else: x = 1 edge.attr["weight"] = x edge.attr["label"] = x
def graphviz_to_firebase(dirname,filename): """ since several chars must be escaped from firebase keys, (see #http://stackoverflow.com/questions/19132867/adding-firebase-data-dots-and-forward-slashes we can't directly use them as keys so: - we use integer i as key, - "nodes" dict maps node name to i to preserve edges coherency - node name is kept as default node label """ f=os.path.join(dirname, filename) graph=filename.split('.')[0] print('processing %s'%f), agraph=AGraph(f) nodes={} for i,node in enumerate(agraph.iternodes()): nodes[node]=i attrs={} attrs.update(agraph.node_attr) attrs['label']=node #default label is node id attrs.update(node.attr) key='%s/node/%d'%(graph,i) ref.patch(key,attrs) print('.'), for i,edge in enumerate(agraph.iteredges()): attrs={} attrs.update(agraph.edge_attr) attrs.update(edge.attr) attrs['source']=nodes[edge[0]] attrs['target']=nodes[edge[1]] #edges are added as attributes of their destination node key='%s/edge/%d'%(graph,i) ref.patch(key,attrs) print('-'), logging.info('ok')
def convert(graph_to_convert, layout_prog="dot"): if isinstance(graph_to_convert, AGraph): graph = graph_to_convert else: try: graph = AGraph(graph_to_convert) except BaseException as e: raise ValueError( "graph_to_convert must be one of a string, file, or AGraph object" ) from e graph_edges = { e[0] + "->" + e[1]: list37(e.attr.iteritems()) for e in list37(graph.edges_iter()) } graph_nodes = { n: list37(n.attr.iteritems()) for n in list37(graph.nodes_iter()) } svg_graph = graph.draw(prog=layout_prog, format="svg") nodes, edges = SvgParser(svg_graph).get_nodes_and_edges() [e.enrich_from_graph(graph_edges[e.gid]) for e in edges] [n.enrich_from_graph(graph_nodes[n.gid]) for n in nodes.values()] mx_graph = MxGraph(nodes, edges) return mx_graph.value()
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 build_graph(ts): g = AGraph(directed=True) g.add_edges_from(ts.ts.todok().keys()) g.graph_attr['overlap'] = 'scalexy' for n, s in zip(g.nodes(), ts._pwa.states): n.attr['label'] = s return g
def user_trace(graph: pgv.AGraph, quantities: List[Quantity]): def request_value(quantity: Quantity) -> Tuple[str,str]: print('Values for {}:'.format(quantity.name)) mag = input("Magnitude? (out of [{}])\n".format(','.join(quantity.magnitude._member_names_))) if mag == "": mag = quantity.magnitude._member_names_[0] drv = input("Derivative? (out of [{}])\n".format(','.join(quantity.derivative._member_names_))) if drv == "": drv = quantity.derivative._member_names_[1] return (mag,drv) print('Enter start node for trace:') start = str(tuple(request_value(q) for q in quantities)) if not graph.has_node(start): print('START NODE NOT IN GRAPH') return print('\n\nEnter end node for trace:') end = str(tuple(request_value(q) for q in quantities)) if not graph.has_node(end): print('END NODE NOT IN GRAPH') return shgraph = trace(graph, start, end) shgraph.draw('trace.pdf', prog='dot')
def path_graph(nodes): graph = AGraph(directed=True) for node in nodes: graph.add_node(node, shape='rectangle') graph.add_path(nodes) return graph
def plan_library_to_graphviz(planlibrary): """Converts a plan library into a graphviz data structure""" G = AGraph() for a in planlibrary: G.add_edge(a.path[0], a.path[1]) return G
def __init__(self, finite_states): self.states = finite_states nodes = { state : [] for state in finite_states } self.graph = AGraph(nodes, directed=True, strict=False) self.edgesize = len(nodes) / 5.0
def draw(diagram: 'Diagram', output_file: 'str') -> None: G = AGraph(**GRAPH_OPTIONS) for node in diagram.components.values(): G.add_node(node.name, label=node.render(), **COMPONENT_OPTIONS) for node in diagram.sections.values(): G.add_node(node.name, label=node.render(), **SECTION_OPTIONS) add_edges(G, diagram) G.write() G.draw(output_file, prog=LAYOUT)
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 processLines(self): if len(self.lines) == 0: return self.identifier = self.lines[0][2:] s = '\n'.join(self.lines) A = AGraph() G = A.from_string(s) self.processGraph(G)
def dot_to_plan_library(filename): G = AGraph() G.read(filename) planlib = set([]) for edge in G.edges(): a = Action(list(edge)) planlib.add(a) log.info("Loaded graph: " + str(planlib)) return planlib
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 from_agraph(cls, A: AGraph, lambdas): """ Construct a ProgramAnalysisGraph from an AGraph """ self = cls(nx.DiGraph()) for n in A.nodes(): if n.attr["node_type"] in ("LoopVariableNode", "FuncVariableNode"): self.add_variable_node(n) for n in A.nodes(): if n.attr["node_type"] == "ActionNode": self.add_action_node(A, lambdas, n) for n in self.nodes(data=True): n_preds = len(n[1]["pred_fns"]) if n_preds == 0: del n[1]["pred_fns"] elif n_preds == 1: n[1]["update_fn"], = n[1].pop("pred_fns") else: n[1]["choice_fns"] = n[1].pop("pred_fns") def update_fn(n, **kwargs): cond_fn = n[1]["condition_fn"] sig = signature(cond_fn) ind = 0 if cond_fn(**kwargs) else 1 return n[1]["choice_fns"][ind](**kwargs) n[1]["update_fn"] = partial(update_fn, n) isolated_nodes = [ n for n in self.nodes() if len(list(self.predecessors(n))) == len(list(self.successors(n))) == 0 ] for n in isolated_nodes: self.remove_node(n) # Create lists of all input function and all input variables self.input_variables = list() self.input_functions = list() for n in self.nodes(): if self.nodes[n].get("init_fn") is not None: self.input_functions.append(n) if ( self.nodes[n]["node_type"] in ("LoopVariableNode", "FuncVariableNode") and len(list(self.predecessors(n))) == 0 ): self.input_variables.append(n) return self
def add_graph(g: AGraph, layer_graph: tx.Graph, cluster): for node in layer_graph.nodes: # HTML for record nodes https://graphviz.org/doc/info/shapes.html#top g.add_node(f"{cluster}_{node.name}", shape="none", margin=0, label=tx.utils.vizstyle(node)) for node in layer_graph.nodes: for other_node in layer_graph.edges_out[node]: g.add_edge(f"{cluster}_{node.name}", f"{cluster}_{other_node.name}")
def startGraph(): # We maintain this globally to make it accessible, pylint: disable=global-statement global graph if Options.shallCreateGraph(): try: from pygraphviz import AGraph # pylint: disable=I0021,import-error graph = AGraph(name = "Optimization", directed = True) graph.layout() except ImportError: warning("Cannot import pygraphviz module, no graphing capability.")
def gen_add_input2( dfg: AGraph, fu: AGraph, input_map: Dict[str, int]) -> Tuple[List[Input], List[Output]]: outputs: List[Output] = [] inputs: List[Input] = [] nodes: List[Instruction] = [] for node in fu.nodes(): nodes.append(parse_instruction(node)) nodes.sort() prev_o = 0 for node in nodes: preds = dfg.predecessors(node.name) parent0 = parse_instruction(preds[0]) parent1 = parse_instruction(preds[1]) if parent0.name in input_map: label = dfg.get_node(parent0.name).attr['label'] if 'mul' in label: latency = 2 else: latency = 1 i0 = prev_o + 1 inputs.append( Input(i0, input_map[parent0.name], parent0.cycle + latency)) else: for output in outputs: if output.cycle == parent0.cycle + 1: i0 = output.val break if parent1.name in input_map: label = dfg.get_node(parent1.name).attr['label'] if 'mul' in label: latency = 2 else: latency = 1 i1 = prev_o + 1 inputs.append( Input(i1, input_map[parent1.name], parent1.cycle + latency)) else: for output in outputs: if output.cycle == parent1.cycle + 1: i1 = output.val break expected = i0 + i1 prev_o = expected outputs.append(Output(expected, node.cycle + 1)) inputs.sort() return inputs, outputs
def _render(self, costs=False, word_probs=False, highlight_best=False): from pygraphviz import AGraph graph = AGraph(directed=True) for node_id, node_label in self.nodes.iteritems(): attributes = self._node_attr(node_id, costs=costs, word_probs=word_probs) graph.add_node(node_id, **attributes) for (parent_node_id, child_node_id) in self.edges: graph.add_edge(parent_node_id, child_node_id) self.graph = graph if highlight_best: self._highlight_best()
def remove_bad_edges(graph: AGraph, collections: Iterable[Iterable[str]]): for from_node, to_node in graph.edges(): from_group = None to_group = None for i, group in enumerate(collections): if from_node in group: from_group = i if to_node in group: to_group = i if from_group is None or to_group is None or from_group < to_group: graph.delete_edge(from_node, to_node)
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 startGraph(): # We maintain this globally to make it accessible, pylint: disable=global-statement global graph if Options.shallCreateGraph(): try: from pygraphviz import AGraph # pylint: disable=I0021,import-error graph = AGraph(name="Optimization", directed=True) graph.layout() except ImportError: warning("Cannot import pygraphviz module, no graphing capability.")
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 trace(graph: pgv.AGraph, start: str, end: str) -> pgv.AGraph: nxgraph = nx.nx_agraph.from_agraph(graph) assert(start in nxgraph and end in nxgraph) shortest = nx.shortest_path(nxgraph, start, end) shgraph = pgv.AGraph(directed=True,overlap=False,rankdir='LR') for e in range(len(shortest)-1): label = graph.get_edge(shortest[e], shortest[e+1]).attr['label'] shgraph.add_edge(shortest[e], shortest[e+1], label=label) for n in shgraph.nodes_iter(): n.attr['label'] = graph.get_node(n).attr['label'] n.attr['style'] = graph.get_node(n).attr['style'] n.attr['fillcolor'] = graph.get_node(n).attr['fillcolor'] return shgraph
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 __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')
def _construct_graph(graph: gz.AGraph, state): graph.add_node( state.id_nr, label=_state_to_node(state), shape="record", ) for move, next_state in state.next_states.items(): if next_state: _construct_graph(graph, next_state) graph.add_edge(u=state.id_nr, v=next_state.id_nr, key="l", label=str(move))
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 crear_grafo_invocaciones(datos_csv): '''[Autor: Ivan Litteri] [Ayuda: crea grafo.svg y grafo.png]''' g = AGraph(directed=True, rankdir='LR') for funcion in datos: g.add_node(funcion) for i in datos[funcion]["invocaciones"]: g.add_edge((funcion, i)) g.layout(prog='dot') g.draw('grafo.svg') g.draw('grafo.png')
def draw_finite_state_machine(finite_state_machine: FiniteStateMachine, path: str): """Creates a directed non-strict multi graph image representation of the FSM.""" from pygraphviz import AGraph graph = AGraph(strict=False, directed=True) graph.add_nodes_from(finite_state_machine.state_set) for initial_state in finite_state_machine.initial_states: graph.get_node(initial_state).attr["color"] = "green" for element, transitions in finite_state_machine.transitions.items(): for from_state, to_states in transitions.items(): for to_state in to_states: graph.add_edge(from_state, to_state, label=element) for final_state in finite_state_machine.final_states: graph.get_node(final_state).attr["color"] = "red" graph.draw(path, prog="dot")
def jupyter_draw(ppdot_str, format='png', prog='dot'): from pygraphviz import AGraph from IPython.display import Image # convert ppdot to dot format dot_str = process_string(ppdot_str) # create graph and render image graph = AGraph(string=dot_str) data = graph.draw(format=format, prog=prog) # pass image to IPython/Jupyter image = Image(data=data) return image
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 main(): """ The entrypoint for the program. """ global _MESHINERY_GRAPH global _MESHINERY_ARGS # Register the keyboard interrupt and SIGTERM handler signal.signal(signal.SIGINT, handle_sigint) signal.signal(signal.SIGTERM, handle_sigint) args = docopt(USAGE) _MESHINERY_ARGS = args if args['--verbose']: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.info('Starting') logging.debug('Args:\n{}'.format(pformat(args))) agraph = AGraph(args['DOT_GRAPH_FILE']) graph = nx.Graph(agraph) _MESHINERY_GRAPH = graph # We intentionally don't take a fresh copy if args['--clean']: clean(graph, dry_run=args['--dry-run'], instance_id=args['--id'], strays=args['--strays']) if args['clean']: return # Arrange network namespaces and crate veth bridges prepare_namespaces(graph, dry_run=args['--dry-run'], instance_id=args['--id']) # Run commands associated with each node try: graph = execute(graph, dry_run=args['--dry-run'], instance_id=args['--id']) _MESHINERY_GRAPH = graph except Exception as e: logging.error('Per-node command execution failed, cleaning up...') logging.debug('Caught exception {} in main(): {}'.format(type(e), e)) clean(graph, dry_run=args['--dry-run'], instance_id=args['--id']) sys.exit(1) logging.info("Meshinery is ready. Press any key to clean up and exit.") input() clean(graph, dry_run=args['--dry-run'], instance_id=args['--id'], strays=args['--strays']) logging.info('Bye!')
def process_nodes(g: pgv.AGraph) -> Tuple[Node, bool]: nodes = {str(gvnode): from_label(gvnode) for gvnode in g.nodes()} root_node = None for gvn, ndata in nodes.items(): if 'this/RootNode' in ndata[1]: root_node = gvn break else: print("Error: cannot find root node\n") sys.exit(-1) def walk(rn: pgv.Node) -> Tuple[Node, bool]: args_dict = {} correctness_holds = True for n in g.successors(rn): e = pgv.Edge(g, rn, n) m = re.match('^args\\s+\\[(\\d+)\\]$', e.attr['label']) assert m arg_idx = int(m.group(1)) assert arg_idx not in args_dict args_dict[arg_idx], have_correctness = walk(n) if not have_correctness: correctness_holds = False args = [args_dict[idx] for idx in range(len(args_dict))] new_node = Node(*nodes[rn], args=args) if correctness_holds: correctness_holds = 'this/CorrectnessHolds' in new_node.sets return new_node, correctness_holds return walk(root_node)
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 build_graph(score): corpus= create_corpus(score) calc_tf_idf(corpus, log_tf, log_idf) #corpus= group_corpus(corpus, log_tf, log_idf) g= AGraph(strict=False) for i, d1 in enumerate(corpus): d1_name= str(d1) edges= [(d2, d2.similarity(d1)) for d2 in corpus[i+1:]] edges.sort(key=lambda x:x[1], reverse=True) edges= edges[:5] for d2, weight in edges: d2_name= str(d2) g.add_edge(d1_name, d2_name) e= g.get_edge(d1_name, d2_name) e.attr['label']= str(weight)[:5] #import ipdb;ipdb.set_trace() return g
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 __init__(self, title="System"): self.schematic = AGraph( directed=True, label=title, rankdir='LR', splines='true' ) self.nodes = [] self.edges = [] self.outputs = {} self.ip_outputs = {}
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)
class DotRenderer(GraphRenderer): """Renderer fox dot.""" """The AGraph used for rendering.""" _graph = None def __init__(self, settings, reporter): GraphRenderer.__init__(self, settings, reporter) if not pygraphvizAvail: self.reporter.severe("Can not render dot format because module `pygraphviz` cannot be loaded") def prepare(self): self._graph = AGraph(strict=False, directed=True, name=self._visitor.sourceName) def finish(self): # TODO The ordering of nodes seems to be rather random in the output; # however, the node ordering is used for the layout of the graph # at least by `dot` and by `neato`; there should be a way to # determine the ordering r = self._graph.string() self._graph = None return r def renderAnchor(self, anchor): self._graph.add_node(anchor.id(), label=anchor.name()) def renderReference(self, reference): if reference.fromAnchor is None: # No anchor to start edge from # TODO Should result in a warning return fromId = reference.fromAnchor.id() toId = reference.toAnchor.id() if self._doReverse: (fromId, toId) = (toId, fromId) self._graph.add_edge(fromId, toId)
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)
def igraph_from_dot(file): """numbered_graph(file) -> graph Input: file: the name of the dot-file Output: graph: igraph.Graph object. Verticies has the attribute "name". """ print("Step 1/3: Reading from dot.") a=AGraph(file) vertices = a.nodes() edges = a.edges() numbered_edges = [] print("Step 2/3: To numbered graph. Be patient...") for x, y in edges: xx = vertices.index(x) yy = vertices.index(y) numbered_edges.append((xx,yy)) print("Step 3/3: To igraph.") g=igraph.Graph(len(vertices), numbered_edges) g.vs["name"]=vertices return g
def as_graph(self, to=None): from pygraphviz import AGraph g = AGraph(directed=True) for a in self.activities.values(): g.add_node(a.title, label=a.title) for t in self.transitions.values(): g.add_edge(t.input.title, t.output.title, label=t.name) if to: g.write(to) else: return str(g)
def get_dot(self, labeller=None): self.labeller = labeller a_graph = AGraph(directed=True) nx_graph = self.graph.nx_graph # TODO: Add some default stuff? # a_graph.graph_attr.update(N.graph.get('graph',{})) # a_graph.node_attr.update(N.graph.get('node',{})) # a_graph.edge_attr.update(N.graph.get('edge',{})) structural_nodes = [] output_nodes = [] input_nodes = [] # First, add nodes for node in nx_graph.nodes(): name, attrs = self.get_node_attributes(node) if self.graph.is_input(node): input_nodes.append(name) elif self.graph.is_structural(node): structural_nodes.append(name) elif self.graph.is_output(node): output_nodes.append(name) # Keep a reference to the original node a_graph.add_node(name, **attrs) # We need to add subgraphs to cluster stuff on rank sub = a_graph.add_subgraph(input_nodes, name='input') sub.graph_attr['rank'] = 'source' sub = a_graph.add_subgraph(structural_nodes, name='structural') sub.graph_attr['rank'] = 'same' sub = a_graph.add_subgraph(output_nodes, name='output') sub.graph_attr['rank'] = 'sink' # Now add edges for u, v, edgedata in nx_graph.edges_iter(data=True): attrs = {} a_graph.add_edge(self.graph.node_to_name(u), self.graph.node_to_name(v), **attrs) return a_graph
def cm_json_to_graph(im_json): """Return pygraphviz Agraph from Kappy's contact map JSON. Parameters ---------- im_json : dict A JSON dict which contains a contact map generated by Kappy. Returns ------- graph : pygraphviz.Agraph A graph representing the contact map. """ cmap_data = im_json['contact map']['map'] # Initialize the graph graph = AGraph() # In this loop we add sites as nodes and clusters around sites to the # graph. We also collect edges to be added between sites later. edges = [] for node_idx, node in enumerate(cmap_data): sites_in_node = [] for site_idx, site in enumerate(node['node_sites']): # We map the unique ID of the site to its name site_key = (node_idx, site_idx) sites_in_node.append(site_key) graph.add_node(site_key, label=site['site_name'], style='filled', shape='ellipse') # Each port link is an edge from the current site to the # specified site if not site['site_type'] or not site['site_type'][0] == 'port': continue for port_link in site['site_type'][1]['port_links']: edge = (site_key, tuple(port_link)) edges.append(edge) graph.add_subgraph(sites_in_node, name='cluster_%s' % node['node_type'], label=node['node_type']) # Finally we add the edges between the sites for source, target in edges: graph.add_edge(source, target) return graph