def write_dot(self, file_basename): """Writes graph into a file in Graphviz DOT format. Args: file_basename: The output file name without extension. """ write_dot(self.digraph, file_basename + '.dot')
def get_patches(self, selection): """ Obtains names and patch info for a modified residue in a selection. Identifies which amino acid is patched by finding which amino acid this one is a maximal subgraph of. Then, builds a library of graphs representing all valid patches applied to this amino acid. Note that this does NOT handle multiple-residue patches such as disulfides! Args: selection (VMD atomsel): Selection that is patched Returns: (str, str, dict) resname matched, patch applied, name translation dictionary """ resname = selection.get('resname')[0] rgraph = self.parse_vmd_graph(selection)[0] # Check this residue against all possible patches applied to the for names in self.known_pres.keys(): graph = self.known_pres[names] matcher = isomorphism.GraphMatcher(rgraph, graph, \ node_match=super(CharmmMatcher, self)._check_atom_match) if matcher.is_isomorphic(): logger.info("Detected patch %s", names[1]) return (names[0], names[1], next(matcher.match())) logger.error("Couldn't find a patch for resname '%s'. Dumping as 'rgraph.dot'", resname) write_dot(rgraph, "rgraph.dot") return (None, None, None)
def dag(recipe_folder, config, packages="*", format='gml', hide_singletons=False): """ Export the DAG of packages to a graph format file for visualization """ dag, name2recipes = graph.build(utils.get_recipes(recipe_folder, "*"), config) if packages != "*": dag = graph.filter(dag, packages) if hide_singletons: for node in nx.nodes(dag): if dag.degree(node) == 0: dag.remove_node(node) if format == 'gml': nx.write_gml(dag, sys.stdout.buffer) elif format == 'dot': write_dot(dag, sys.stdout) elif format == 'txt': subdags = sorted(map(sorted, nx.connected_components(dag.to_undirected()))) subdags = sorted(subdags, key=len, reverse=True) singletons = [] for i, s in enumerate(subdags): if len(s) == 1: singletons += s continue print("# subdag {0}".format(i)) subdag = dag.subgraph(s) recipes = [ recipe for package in nx.topological_sort(subdag) for recipe in name2recipes[package]] print('\n'.join(recipes) + '\n') if not hide_singletons: print('# singletons') recipes = [recipe for package in singletons for recipe in name2recipes[package]] print('\n'.join(recipes) + '\n')
def generateGraph(cdata,dMatchBlocks,rid): dependencies = True try: from networkx.drawing.nx_pydot import write_dot import networkx as nx except ImportError: print("Cannot find networkx. Please install pydot and networkx.") print("Output file will be created without images.") dependencies = False return False if dependencies: G = nx.DiGraph() # populate Graph object with triggers G = addTriggersToGraph(cdata,G) for x in dMatchBlocks: G.add_node(x, color=dMatchBlocks[x]['shapecol'],style='filled',fillcolor=dMatchBlocks[x]['shapecol'],shape='box') G.add_edge(dMatchBlocks[x]['parent'],x) # write dot file for Graphviz out to file system write_dot(G,'file.dot') # execute 'dot' as os command, generate png file from dot file try: check_call(['dot','-Tpng','-Grankdir=LR','file.dot','-o',imagepath + '/' + rid +'.png']) except OSError as e: dependencies = False print("'dot' could not be found. Please install pydot.") return True
def main(): """The main function.""" args = parse_args() # Set the logging level numeric_log_level = getattr(logging, args.loglevel.upper(), None) if not isinstance(numeric_log_level, int): raise ValueError('Invalid log level: %s' % args.loglevel) logging.basicConfig(level=numeric_log_level, format='[%(asctime)s] %(levelname)s: %(message)s') # Load all of the control flow graphs (CFG) cfg, entry_pts = create_cfg(args.jsons, args.entry, args.module) # Output to DOT dot_path = args.dot logging.info('Writing CFG to %s', dot_path) write_dot(cfg, dot_path) if not args.stats: return # Depending on how the target was compiled and the CFGToJSON pass run, there # may be multiple entry points (e.g., multiple driver programs, each with # their own main function). # # Thus, iterate over each entry point and reduce the CFG to only those nodes # reachable from the entry point. This allows us to calculate eccentricity, # because the CFG is now connected. if not entry_pts: print_stats(cfg) else: for entry_node in entry_pts: print_stats(cfg, entry_node)
def _plot_trackers(sender_ids: List[Union[Text, List[Event]]], output_file: Optional[Text], endpoint: EndpointConfig, unconfirmed: Optional[List[Event]] = None ): """Create a plot of the trackers of the passed sender ids. This assumes that the last sender id is the conversation we are currently working on. If there are events that are not part of this active tracker yet, they can be passed as part of `unconfirmed`. They will be appended to the currently active conversation.""" if not output_file or not sender_ids: # if there is no output file provided, we are going to skip plotting # same happens if there are no sender ids return None event_sequences = _fetch_events(sender_ids, endpoint) if unconfirmed: event_sequences[-1].extend(unconfirmed) graph = visualize_neighborhood(event_sequences[-1], event_sequences, output_file=None, max_history=2) from networkx.drawing.nx_pydot import write_dot write_dot(graph, output_file)
def to_ruledag(self): cnfG = nx.DiGraph() n = len(self.rules) basic = {} for rule in self.rules: if not isinstance(rule, And): continue conds = rule.args m = len(conds) for i in range(m): cond1 = conds[i] a = cond1.atoms() assert (len(a) == 1) a = list(a)[0] if a not in basic: basic[a] = set() basic[a].add(cond1) for j in range(i + 1, m): cond2 = conds[j] cnfG.add_edge(cond1, cond2) print(cond1, cond2) for a in basic: if len(basic[a]) == 2: b = list(basic[a]) cnfG.add_edge(*b, style="dashed") pos = nx.nx_agraph.graphviz_layout(cnfG) nx.draw(cnfG, pos=pos) write_dot(cnfG, self.name + ".cnf.dot")
def main(): words = load_wordlist("words.txt") words = filter_words(words) G = build_graph(words) paths = nx.all_shortest_paths(G, "arty", "elks") g = paths_to_digraph(paths) write_dot(g, "paths.dot")
def _show_dot(G): import io from networkx.drawing.nx_pydot import write_dot dot_file = io.StringIO() write_dot(G, dot_file) return dot_file.getvalue()
def visualize_graph(graph): """ Save the positions of the nodes to a file. Can be visualized using Gephi """ pos = nx.nx_agraph.graphviz_layout(graph) nx.draw(graph, pos=pos) write_dot(graph, 'graph.dot')
def visualize(self, edgelabel=None, draw='pydot', save_path=None, dot_file_name="g", svg_file_name="file"): """ Visualizes a LOMAP system model """ if draw == 'pygraphviz': nx.view_pygraphviz(self.g, edgelabel) # elif draw == 'matplotlib': # pos = nx.spring_layout(self.g) # nx.draw(self.g, pos=pos) # nx.draw_networkx_labels(self.g, pos=pos) # plt.savefig('path.png') elif draw == 'pydot': if save_path is None: write_dot(self.g, dot_file_name + ".dot") os.system('dot -Tsvg ' + dot_file_name + '.dot -o ' + svg_file_name + '.svg') else: dot_file_path = os.path.join(save_path, dot_file_name + ".dot") svg_file_path = os.path.join(save_path, svg_file_name + '.svg') write_dot(self.g, dot_file_path) os.system('dot -Tsvg ' + dot_file_path + ' -o ' + svg_file_path) else: raise ValueError('Expected parameter draw to be either:' + '"pygraphviz" or "matplotlib" or "pydot"!')
def save_graph(g, path): g = g.copy() for v in g.nodes: g.nodes[v]['label'] = f'{v};{g.nodes[v]["weight"]}' for e in g.edges: g.edges[e]['label'] = g.edges[e]['weight'] write_dot(g, path)
def _write_dot(self): """ Write a dot file with the pipeline graph :param f: file to write :return: None """ if self.dot_file: write_dot(self.graph, self.dot_file)
def save_and_open_pdf_of_scheme_graph(graph, filename): """ Writes tree graph to pdf and dot file with given filename """ write_dot(graph, filename + ".dot") os.environ['PATH'] += ":" + "/usr/local/bin" check_call(["dot", "-T", "pdf", filename + ".dot", "-o", filename + ".pdf"]) os.system("open " + filename + ".pdf")
def __call__(self, paths=None, filename_output=None, excludes=[]): resources = expand_paths(paths, predicate=lambda r: isinstance(r, Resource)) graph = nx.Graph() # For each provided resources, a edge is created from this # resource to all of its refs, back_refs and parent. for r in resources: print "%s %s" % (short_name(r.path.name), r.path) r.fetch() graph.add_node(r.path, _node_rendering(r.path, r)) paths = [t.path for t in itertools.chain(r.refs, r.back_refs)] try: paths.append(r.parent.path) except ResourceMissing: pass for p in paths: if p.base in excludes: continue print "%s %s" % (short_name(p.name), p) graph.add_node(p, _node_rendering(p)) graph.add_edge(r.path, p) print "Dot file written to %s" % filename_output write_dot(graph, filename_output)
def render_all_nodetypes(filename): digraph = nx.MultiDiGraph() counter = defaultdict(int) def typenodename(typ): counter[typ] += 1 return typ.__name__ + str(counter[typ]) for nodetype in ALL_NODETYPES: name = nodetype.__name__ digraph.add_node(name) for intype in nodetype.INTYPES: typename = typenodename(intype) digraph.add_node(typename, label=intype.__name__) digraph.add_edge(typename, name) for outtype in nodetype.OUTTYPES: typename = typenodename(outtype) digraph.add_node(typename, label=outtype.__name__) digraph.add_edge(name, typename) LOGGER.info("Writing to %s", filename) write_dot(digraph, 'multi.dot') os.system("""dot -Nshape=box -T png multi.dot > {0}""".format(filename)) os.remove("multi.dot")
def visualize(graphs, viz_path, args_viz_format): import matplotlib from networkx.drawing.nx_agraph import graphviz_layout meta_graph = networkx.Graph() for graph in graphs: add_graph(meta_graph, graph) pos = graphviz_layout(meta_graph) networkx.draw(meta_graph, pos) if viz_path: ext = os.path.splitext(viz_path)[1] if ext == '.dot': viz_format = 'graphviz' elif ext == '.png': viz_format = 'png' else: viz_format = args_viz_format if viz_format == 'graphviz': from networkx.drawing.nx_pydot import write_dot assert viz_path is not None, 'Must provide a filename to --visualize if using --viz-format "graphviz".' base_path = os.path.splitext(viz_path) write_dot(meta_graph, base_path+'.dot') run_command('dot', '-T', 'png', '-o', base_path+'.png', base_path+'.dot') logging.info('Wrote image of graph to '+base_path+'.dot') elif viz_format == 'png': if viz_path is None: matplotlib.pyplot.show() else: matplotlib.pyplot.savefig(viz_path)
def debug_get_graph_png(graph: nx.Graph, postfix, dot=False): dot_name = "{}_{}.dot".format(graph.graph["name"], postfix) cfg_name = "{}_{}.png".format(graph.graph["name"], postfix) nx_dot.write_dot(graph, dot_name) subprocess.check_call(["dot", "-Tpng", dot_name, "-o", cfg_name]) if dot is False: os.remove(dot_name)
def print_results(G_refGraph): result_count = 1 for align in sorted(top_alignments, key=lambda x: x.score, reverse=True): print "Result %d - score: %f" % (result_count, align.score) print print "Matches: (query \ corresponding vertex)" list_nodes = [] for w in align.correspVertices: print "%s \t %s" % (w.queryVertex, w.name) list_nodes.append(w.name) print print "Edges:" for i in range(0, len(align.query_edges)): print "%s\t--\t%s\t\t" % (align.query_edges[i][0], align.query_edges[i][1]), for j in range(0, len(align.ref_edges[i]) - 1): print "%s\t--\t" % align.ref_edges[i][j], print align.ref_edges[i][len(align.ref_edges[i]) - 1] #Adding indel vertices to a list for getting the G subgraph ready for i in align.indelVertices: list_nodes.append(i) result = nx.subgraph(G_refGraph, list_nodes) for n in result.node: if n in align.indelVertices: result.node[n]['color'] = 'red' else: result.node[n]['color'] = 'blue' output_str = "result" + str(result_count) + ".dot" write_dot(result, output_str) result_count += 1 print
def plot_network(parameters, output_path): network_description = parameters.network_description vnf_requests = parameters.vnf_requests G = nx.MultiDiGraph() node_list = [] for domain_name, nodes in network_description["domain_nodes"].items(): for node in nodes: G.add_node(node) node_list.append(node) for request_id, request in vnf_requests.items(): if request['ingress_domain'] == domain_name and request['ingress'] not in node_list: G.add_node(request['ingress']) node_list.append(request['ingress']) if request['egress_domain'] == domain_name and request['egress'] not in node_list: G.add_node(request['egress']) node_list.append(request['egress']) for path_id, path in network_description[key_intra_domain_paths].items(): if path['domain'] == domain_name: G.add_edge(path['src'], path['dst'], label=path_id) for edge_id, edge in network_description[key_inter_domain_edges].items(): G.add_edge(edge['src'], edge['dst'], label=edge_id) write_dot(G, "{0}/graph.dot".format(output_path))
def get_patches(self, selection): """ Obtains names and patch info for a modified residue in a selection. Identifies which amino acid is patched by finding which amino acid this one is a maximal subgraph of. Then, builds a library of graphs representing all valid patches applied to this amino acid. Note that this does NOT handle multiple-residue patches such as disulfides! Args: selection (VMD atomsel): Selection that is patched Returns: (str, str, dict) resname matched, patch applied, name translation dictionary """ resname = selection.get('resname')[0] rgraph = self.parse_vmd_graph(selection)[0] # Check this residue against all possible patches applied to the for names in self.known_pres.keys(): graph = self.known_pres[names] matcher = isomorphism.GraphMatcher(rgraph, graph, \ node_match=super(CharmmMatcher, self)._check_atom_match) if matcher.is_isomorphic(): logger.info("Detected patch %s", names[1]) return (names[0], names[1], next(matcher.match())) logger.error( "Couldn't find a patch for resname '%s'. Dumping as 'rgraph.dot'", resname) write_dot(rgraph, "rgraph.dot") return (None, None, None)
def _graph_to_dot(self): file_name = ".".join([self.file_name, "dot"]) file_path = os.path.join(FSM_OUTPUT_DIR, file_name) if not self.built: raise Exception("`graph_to_dot` was called before graph was built!") write_dot(self.graph, file_path)
def render(self, ontol, **args): g = ontol.get_graph() _, fn = tempfile.mkstemp(suffix='dot') write_dot(g, fn) f = open(fn, 'r') s = f.read() f.close() return s
def compute_graph(self): self.cmd_graph.set_source(self.textedit.toPlainText()) write_dot(self.cmd_graph.graph, "grid.dot") (graph, ) = pydot.graph_from_dot_file('grid.dot') graph.write_png('somefile.png') self.label.setPixmap(QPixmap("somefile.png"))
def bpmn_diagram_to_dot_file(bpmn_diagram, file_name): """ Convert diagram graph to dot file :param bpmn_diagram: an instance of BPMNDiagramGraph class, :param file_name: name of generated file. """ g = bpmn_diagram.diagram_graph write_dot(g, file_name + ".dot")
def save_graph(nodes, edges, filename, to_undirected=True): graph = Data(x=nodes, edge_index=edges) nx_graph = to_networkx(graph, node_attrs=["x"], to_undirected=to_undirected) write_dot(nx_graph, filename) # dot_graph = to_pydot(nx_graph) # dot_graph.write(filename) pass
def gen_G(self, filename='G.dot'): """ Recursively print the nodes of tree. """ import networkx as nx from networkx.drawing.nx_pydot import write_dot G = nx.DiGraph() if(self.root != None): self._gen_G(self.root, G, None) write_dot(G, filename)
def write_graph_to_file(graph): pydot_graph = nx_pydot.to_pydot(graph) png_str = pydot_graph.create_png(prog='dot') #write the png to disk with open("/tmp/output.png", "w") as text_file: text_file.write(png_str) #write the dot to disk nx_pydot.write_dot(graph, '/tmp/output.graph')
def export_to_dot(self, filename=None): try: # test pydot is importable (optionally installed) import pydot # noqa: F401 except ImportError: raise ImportError("Package 'pydot' is not installed") from networkx.drawing.nx_pydot import write_dot filename = filename or (self.filename + '.dot') write_dot(self.dep_graph, filename)
def __write_dot(self, target, commands, outs, filename): import networkx from networkx.drawing.nx_pydot import write_dot _, edges = self.__build_graph(target, commands, outs) edges = [edge[::-1] for edge in edges] simple_g = networkx.DiGraph() simple_g.add_edges_from(edges) write_dot(simple_g, filename)
def gvgraph(self, pngfile=None): """Return networkx DiGraph. Maybe write to PNG file.""" G = nx.DiGraph(self.graph) if pngfile is not None: dotfile = pngfile + ".dot" write_dot(G, dotfile) cmd = (f'dot -Tpng -o{pngfile} {dotfile} ') with open(pngfile, 'w') as f: subprocess.check_output(cmd, shell=True) return G
def coloured_network(network, setup, filename): """ Writes a coloured (hyper-)graph to a dot file Parameters ---------- network : object An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured. Typically, it will be an instance of either :class:`caspo.core.graph.Graph`, :class:`caspo.core.logicalnetwork.LogicalNetwork` or :class:`caspo.core.logicalnetwork.LogicalNetworkList` setup : :class:`caspo.core.setup.Setup` Experimental setup to be coloured .. _networkx.MultiDiGraph: https://networkx.readthedocs.io/en/stable/reference/classes.multidigraph.html#networkx.MultiDiGraph """ graph = network.__plot__() for node in graph.nodes(): _type = 'DEFAULT' for attr, value in settings.NODES_ATTR[_type].items(): graph.node[node][attr] = value if 'gate' in graph.node[node]: _type = 'GATE' elif node in setup.stimuli: _type = 'STIMULI' elif node in setup.readouts and node in setup.inhibitors: _type = 'INHOUT' elif node in setup.readouts: _type = 'READOUT' elif node in setup.inhibitors: _type = 'INHIBITOR' if _type != 'DEFAULT': for attr, value in settings.NODES_ATTR[_type].items(): graph.node[node][attr] = value for source, target in graph.edges(): for k in graph.edge[source][target]: for attr, value in settings.EDGES_ATTR['DEFAULT'].items(): graph.edge[source][target][k][attr] = value for attr, value in settings.EDGES_ATTR[graph.edge[source][target][k]['sign']].items(): graph.edge[source][target][k][attr] = value if 'weight' in graph.edge[source][target][k]: graph.edge[source][target][k]['penwidth'] = 5 * graph.edge[source][target][k]['weight'] write_dot(graph, filename)
def ftrace_callgraph_dot(ftracefile): callgraph=nx.DiGraph() ftracef=open(ftracefile) for l in ftracef: ltok=l.split(":") callgraphedge=ltok[1] callgraphedgetok=callgraphedge.split("<-") callgraph.add_edge(callgraphedgetok[1], callgraphedgetok[0]) write_dot(callgraph,"Spark_USBWWANLogMapReduceParser.ftrace_callgraph.dot") sorted_pagerank_nxg=sorted(nx.pagerank(callgraph).items(),key=operator.itemgetter(1), reverse=True) print "Most active kernel code - PageRank of call graph:",sorted_pagerank_nxg sorted_degreecentral_nxg=sorted(nx.degree_centrality(callgraph).items(),key=operator.itemgetter(1), reverse=True) print "Most active kernel code - Degree centrality of call graph:",sorted_degreecentral_nxg
def dump_graph(self) -> str: """Dumps both as a dot file and as a svg. Returns: Name of the file with a displayable graph. """ graph_dot_file = f'{self._name}.dot' graph_diagram_file = f'{self._name}.svg' write_dot(self._graph, graph_dot_file) subprocess.check_output( shlex.split(f'dot -Tsvg {graph_dot_file} -o {graph_diagram_file}') ) return graph_diagram_file
def write_dot(self, path): """ Build the dot file. The .ps can be built from the dot file with the command line: "dot -Tps {filename}.dot - o {filename}.ps" """ # To build .ps : dot -Tps {filename}.dot - o {filename}.ps nx.draw(self.dot_digraph) write_dot(self.dot_digraph, path) # building the openable file: list_popen = ["dot", "-Tps", path, "-o", path.rsplit("/", 1)[0] + "/" + path.rsplit("/", 1)[1].split(".")[-2] + ".ps"] Logger.instance().debug("SubProcess command line for .ps file: " + str(list_popen)) p = subprocess.Popen(list_popen) p.wait()
def cli(ek, draw, input_file): g, source, sink = parse_dicaps_graph(input_file) if draw: write_dot(g, 'graph.dot') return if ek: print('Using Edmonds Karp') flow_func = edmonds_karp else: print('Using Preflow Push') flow_func = None t0 = time.time() flow = nx.maximum_flow_value(g, source, sink, flow_func=flow_func) t1 = time.time() print("Max Flow Solution: {0}".format(flow)) print("Runtime: {0}s".format(t1 - t0))
def ftrace_callgraph_dot(ftracefile): callgraph=nx.DiGraph() ftracef=open(ftracefile) for l in ftracef: ltok=l.split(":") callgraphedge=ltok[1] callgraphedgetok=callgraphedge.split("<-") callgraph.add_edge(callgraphedgetok[1], callgraphedgetok[0]) write_dot(callgraph,"CyclomaticComplexitySparkMapReducer.ftrace_callgraph.dot") sorted_pagerank_nxg=sorted(nx.pagerank(callgraph).items(),key=operator.itemgetter(1), reverse=True) print "Most active kernel code - PageRank of call graph:",sorted_pagerank_nxg sorted_degreecentral_nxg=sorted(nx.degree_centrality(callgraph).items(),key=operator.itemgetter(1), reverse=True) print "Most active kernel code - Degree centrality of call graph:",sorted_degreecentral_nxg print "Simple Cycles in call graph:" for cycle in nx.simple_cycles(callgraph): print "Cycle:",cycle print "Longest Path (callstack) in call graph:",nx.dag_longest_path(callgraph)
def output(self, options, args, dependencies): """Output result """ if options.reverse: dependencies = map(lambda x: x[::-1], dependencies) if options.json_file: self._output_json(options.json_file, dependencies) logger.notify("Dependencies relationships result is in %s now", options.json_file) if options.display_graph or options.py_dot or options.py_graphviz: import networkx as nx # extract name and version def convert(pair): return ( pretty_project_name(pair[0]), pretty_project_name(pair[1]), ) plain_dependencies = map(convert, dependencies) dg = nx.DiGraph() dg.add_edges_from(plain_dependencies) if options.py_dot: logger.notify("Writing dot to %s with Pydot ...", options.py_dot) from networkx.drawing.nx_pydot import write_dot write_dot(dg, options.py_dot) if options.py_graphviz: logger.notify("Writing dot to %s with PyGraphviz ...", options.py_graphviz) from networkx.drawing.nx_agraph import write_dot write_dot(dg, options.py_graphviz) if options.display_graph: import matplotlib.pyplot as plt logger.notify("Drawing graph ...") if not plain_dependencies: logger.notify("There is no dependency to draw.") else: nx.draw(dg) plt.show()
def print_tree(self, file_name): write_dot(self.tree, "tree.dot") graph = pydot.graph_from_dot_file("tree.dot")[0] graph.obj_dict['attributes']["size"] = '"10,10!"' graph.obj_dict['attributes']["dpi"] = "720" for k, v in self.get_labels().items(): node = graph.get_node(str(k))[0] node.set('label', v) node.set('fontsize', '32') colors_list = ['blue', 'green', 'red', 'yellow', 'brown', 'purple'] for way in self.ways: # color = colors_list.pop(0) color = 'red' for i in range(len(way) - 1): edge = graph.get_edge(str(way[i]), str(way[i + 1]))[0] if not edge.get('color'): edge.set('color', color) else: graph.add_edge(pydot.Edge(way[i], way[i + 1], color=color)) graph.write_png(file_name)
def gen_dot_file(graph): """ Writes to file the NetworkX graph """ from networkx.drawing.nx_pydot import write_dot write_dot(graph, 'graph.dot')
def main(args, help=''): if args.debug: logging.basicConfig(level=logging.DEBUG) if args.version: print(__version__) sys.exit() if args.examples: print(examples) sys.exit() # if no stdin and no input file if args.input_file == '-' and sys.stdin.isatty(): sys.stdout.write(help) sys.exit() elif args.input_file == '-': input_file = sys.stdin elif args.input_file != '-': input_file = io.open(args.input_file, 'r', encoding='utf-8') else: sys.exit('malformed input') # pre-process markdown by using knitr on it if args.knit: knitr = Knitr() input_file = knitr.knit(input_file, opts_chunk=args.knit) if args.rmagic: args.precode.append(r"%load_ext rpy2.ipython") if args.render: template_file = markdown_figure_template else: template_file = markdown_template template_file = args.template or template_file # reader and writer classes with args and kwargs to # instantiate with readers = {'notebook': nbformat, 'markdown': MarkdownReader(precode='\n'.join(args.precode), magic=args.magic, match=args.match, caption_comments=args.render) } writers = {'notebook': nbformat, 'markdown': MarkdownWriter(template_file, strip_outputs=args.strip_outputs) } informat = args.informat or ftdetect(input_file.name) or 'markdown' outformat = args.outformat or ftdetect(args.output) or 'notebook' if args.render: outformat = 'markdown' reader = readers[informat] writer = writers[outformat] # TODO: If args.include then read the notebook and get a new input file if args.includes: if informat != 'markdown': sys.exit('Can only use includes with markdown files') if args.document_tree: import networkx as nx doc_tree = nx.DiGraph() else: doc_tree = None input_file = recursive_include(input_file, doc_tree) if args.document_tree: import pydot from networkx.drawing.nx_pydot import write_dot write_dot(doc_tree, args.document_tree) with input_file as ip: notebook = reader.read(ip, as_version=4) if args.run: run(notebook, timeout=args.timeout) if args.strip_outputs: strip(notebook) output_ext = {'markdown': '.md', 'notebook': '.ipynb'} if not args.output and args.input_file != '-': # overwrite fout = os.path.splitext(args.input_file)[0] + output_ext[outformat] # grab the output here so we don't obliterate the file if # there is an error output = writer.writes(notebook) with io.open(fout, 'w', encoding='utf-8') as op: op.write(output) elif not args.output and args.input_file == '-': # overwrite error (input is stdin) sys.exit('Cannot overwrite with no input file given.') elif args.output == '-': # write stdout writer.write(notebook, unicode_std_stream('stdout')) elif args.output != '-': # write to filename with io.open(args.output, 'w', encoding='utf-8') as op: writer.write(notebook, op)
#mainGraph=open("/home/hduser1/AttackGraph.xml") #doc=xmltodict.parse(mainGraph.read()) #G1=nx.Graph() #for i in range(0,len(doc['attack_graph']['arcs']['arc'])): # G1.add_edge(int(doc['attack_graph']['arcs']['arc'][i]['src']),int(doc['attack_graph']['arcs']['arc'][i]['dst'])) Gr=nx.Graph() redfile = open("/home/hduser1/red/part-00000", "r") for i in redfile.readlines(): Gr.add_edge(int(i.split(",")[0].strip()),int(i.split(",")[1].strip())) for i in Gr.nodes(): Gr.node[i]['color']=str('red') write_dot(Gr, 'redGraph.dot') redfile.close() Gn=nx.Graph() greenfile = open("/home/hduser1/green/part-00000", "r") for i in greenfile.readlines(): Gn.add_edge(int(i.split(",")[0].strip()),int(i.split(",")[1].strip())) for i in Gn.nodes(): Gn.node[i]['color']=str('green') write_dot(Gn, 'greenGraph.dot') greenfile.close() Gb=nx.Graph() bluefile = open("/home/hduser1/blue/part-00000", "r")
# Read options & provide with defaults defaults_opts={} defaults_opts['win_out'] = False defaults_opts['infile'] = 'test.gen' defaults_opts['dotfile'] = None defaults_opts['pngfile'] = None (options, args) = read_options(defaults_opts) # Create the graph object of the genome g = process_graph(options.infile) # dot ? png ? window ? if options.dotfile != None : #nx. write_dot(g, options.dotfile) #gPydot = nx.nx_pydot.to_pydot(g) if options.pngfile != None : dot2png(options.dotfile, options.pngfile) # If we draw things ... prepare if options.win_out: pylab.ion() fig = pylab.figure(num=None, figsize=(5, 5), dpi=100) pylab.show() pylab.clf() p=nx.circular_layout(g) nx.draw(g) pylab.draw() print 'Press enter to exit'
# print G.edges() # print G.nodes() (edgecuts, parts) = metis.part_graph(G, 3) # print G.edge[1] print G.edge[2] print G.edges()[1] # for i, p in enumerate(parts): # print G.edge[i+1] colors = ['red','blue','green'] # for i, p in enumerate(parts): # G.node[i+1]['color'] = colors[1] # write_dot(G, 'before.dot') for i, p in enumerate(parts): G.node[i+1]['color'] = colors[p] write_dot(G, 'before.dot') m={} for i in G.edges(): # count=count+1 if str(G.node[i[1]]['color']) == str(G.node[i[0]]['color']): m[i]=G.node[i[0]]['color'] else: m[i]='black' #print m bb = nx.edge_betweenness_centrality(G, normalized=False) #print bb #print m nx.edge_betweenness_centrality(G, normalized=False) nx.set_edge_attributes(G, 'color', m)
def export_to_dot(self,fname): write_dot(self.G,fname)
def coloured_network(network, setup, filename): """ Plots a coloured (hyper-)graph to a dot file Parameters ---------- network : object An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured. Typically, it will be an instance of either :class:`caspo.core.graph.Graph`, :class:`caspo.core.logicalnetwork.LogicalNetwork` or :class:`caspo.core.logicalnetwork.LogicalNetworkList` setup : :class:`caspo.core.setup.Setup` Experimental setup to be coloured in the network .. _networkx.MultiDiGraph: https://networkx.readthedocs.io/en/stable/reference/classes.multidigraph.html#networkx.MultiDiGraph """ NODES_ATTR = { 'DEFAULT': {'color': 'black', 'fillcolor': 'white', 'style': 'filled, bold', 'fontname': 'Helvetica', 'fontsize': 18, 'shape': 'ellipse'}, 'STIMULI': {'color': 'olivedrab3', 'fillcolor': 'olivedrab3'}, 'INHIBITOR': {'color': 'orangered', 'fillcolor': 'orangered'}, 'READOUT': {'color': 'lightblue', 'fillcolor': 'lightblue'}, 'INHOUT': {'color': 'orangered', 'fillcolor': 'SkyBlue2', 'style': 'filled, bold, diagonals'}, 'GATE' : {'fillcolor': 'black', 'fixedsize': True, 'width': 0.2, 'height': 0.2, 'label': '.'} } EDGES_ATTR = { 'DEFAULT': {'dir': 'forward', 'penwidth': 2.5}, 1 : {'color': 'forestgreen', 'arrowhead': 'normal'}, -1 : {'color': 'red', 'arrowhead': 'tee'} } graph = network.__plot__() for node in graph.nodes(): _type = 'DEFAULT' for attr, value in NODES_ATTR[_type].items(): graph.node[node][attr] = value if 'gate' in graph.node[node]: _type = 'GATE' elif node in setup.stimuli: _type = 'STIMULI' elif node in setup.readouts and node in setup.inhibitors: _type = 'INHOUT' elif node in setup.readouts: _type = 'READOUT' elif node in setup.inhibitors: _type = 'INHIBITOR' if _type != 'DEFAULT': for attr, value in NODES_ATTR[_type].items(): graph.node[node][attr] = value for source, target in graph.edges(): for k in graph.edge[source][target]: for attr, value in EDGES_ATTR['DEFAULT'].items(): graph.edge[source][target][k][attr] = value for attr, value in EDGES_ATTR[graph.edge[source][target][k]['sign']].items(): graph.edge[source][target][k][attr] = value if 'weight' in graph.edge[source][target][k]: graph.edge[source][target][k]['penwidth'] = 5 * graph.edge[source][target][k]['weight'] write_dot(graph, filename)
def grow_lambda_function3(self,text,level=3): stpairs=[] maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit=("",0.0) definitiongraph_merit=RecursiveGlossOverlap_Classifier.RecursiveGlossOverlapGraph(text,level) definitiongraph=definitiongraph_merit[0] sentiment=SentimentAnalyzer.SentimentAnalysis_RGO_Belief_Propagation_MarkovRandomFields(definitiongraph) apsp=nx.all_pairs_shortest_path(definitiongraph) for a in definitiongraph.nodes(): for b in definitiongraph.nodes(): stpairs.append((a,b)) rw_ct="" if self.ClosedPaths==False: for k,v in stpairs: try: print "===================================================================" print "Random Walk between :",k," and ",v,":",apsp[k][v] instrumented_apspkv=self.instrument_relations(apsp[k][v]) rw_ct=self.randomwalk_lambda_function_composition_tree(instrumented_apspkv) print "Random Walk Composition Tree for walk between :",k," and ",v,":",rw_ct print "maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit=",maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit print "===================================================================" if rw_ct[1] > maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit[1]: maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit=rw_ct except KeyError: pass rw_ct="" if self.ClosedPaths==True: allsimplecycles=nx.simple_cycles(definitiongraph) #allsimplecycles=nx.cycle_basis(definitiongraph) number_of_cycles=0 for cycle in allsimplecycles: number_of_cycles += 1 if number_of_cycles > 500: break try: print "===================================================================" print "Cycle :",cycle instrumented_cycle=self.instrument_relations(cycle) print "instrumented_cycle:",instrumented_cycle rw_ct=self.randomwalk_lambda_function_composition_tree(instrumented_cycle) print "Cycle Composition Tree for this cycle :",rw_ct print "maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit=",maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit print "===================================================================" if rw_ct[1] > maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit[1]: maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit=rw_ct except KeyError: pass rw_ct="" intrinsic_merit_dict={} print "grow_lambda_function3(): Graph Tensor Neuron Network Intrinsic Merit for this text:",self.graph_tensor_neuron_network_intrinsic_merit print "grow_lambda_function3(): Machine Translation Example - English to Kannada:" self.machine_translation(definitiongraph, "kn") self.korner_entropy(definitiongraph) print "grow_lambda_function3(): Korner Entropy Intrinsic Merit for this text:",self.entropy density = self.density(definitiongraph) print "grow_lambda_function3(): Graph Density (Regularity Lemma):",density bose_einstein_intrinsic_fitness=self.bose_einstein_intrinsic_fitness(definitiongraph) print "grow_lambda_function3(): Bose-Einstein Intrinsic Fitness:",bose_einstein_intrinsic_fitness print "grow_lambda_function3(): Maximum Per Random Walk Graph Tensor Neuron Network Intrinsic Merit :",maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit print "grow_lambda_function3(): Recursive Gloss Overlap Classifier classes for text:",RecursiveGlossOverlap_Classifier.RecursiveGlossOverlap_Classify(text) intrinsic_merit_dict["graph_tensor_neuron_network_intrinsic_merit"]=self.graph_tensor_neuron_network_intrinsic_merit intrinsic_merit_dict["maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit"]=maximum_per_random_walk_graph_tensor_neuron_network_intrinsic_merit intrinsic_merit_dict["korner_entropy"]=self.entropy intrinsic_merit_dict["density"]=density intrinsic_merit_dict["bose_einstein_intrinsic_fitness"]=bose_einstein_intrinsic_fitness intrinsic_merit_dict["recursive_gloss_overlap_intrinsic_merit"]=definitiongraph_merit[1] intrinsic_merit_dict["empath_sentiment"]=sentiment write_dot(definitiongraph,"RecursiveLambdaFunctionGrowth.dot") self.graph_tensor_neuron_network_intrinsic_merit=1.0 print "intrinsic_merit_dict:",intrinsic_merit_dict return intrinsic_merit_dict
def graphPrinter(self,DG): for n,nbrs in DG.adjacency_iter(): for nbr,eattr in nbrs.items(): data=eattr['path'] print('(%s, %s, %s)' % (n,nbr,data)) write_dot(DG,'file.dot')
def export_to_dot(self, filename): write_dot(self.graph, filename)
#! /usr/bin/env python import networkx as nx from networkx.drawing.nx_pydot import write_dot import metis import xmltodict with open('/home/sanchit/mulval/AttackGraph.xml') as fd: doc=xmltodict.parse(fd.read()) G=nx.Graph() for i in range(0,200): G.add_edge(int(doc['attack_graph']['arcs']['arc'][i]['src']),int(doc['attack_graph']['arcs']['arc'][i]['dst'])) # print G.edges() # print G.nodes() (edgecuts, parts) = metis.part_graph(G, 3) colors = ['red','blue','green'] # for i, p in enumerate(parts): # G.node[i+1]['color'] = colors[1] # write_dot(G, 'before.dot') for i, p in enumerate(parts): G.node[i+1]['color'] = colors[p] # print G.node[i+1] # print G2.edges() # print G.node[0] write_dot(G, 'clusteredGraph.dot')
import networkx as nx import networkx.drawing.nx_pydot as nxdot name = [] G = nx.MultiGraph() with open('name.in') as fname: tmp = fname.read().splitlines() name = tmp for n in name: G.add_node(n) print name; p = 0; with open('graph.in') as fgraph: for line in fgraph: array = [int(x) for x in line.split()] for x in array: G.add_edge(name[p], name[x]) p += 1 print(G.edges()) nx.readwrite.gml.write_gml(G, 'graph.gml') nxdot.write_dot(G, 'graph.dot')
ax.scatter(0,0, c='red', marker='o') ax.scatter(0,0, c='yellow', marker='o') ax.scatter(0,0, c='green', marker='o') ax.scatter(0,0, c='cyan', marker='o') ax.scatter(0,0, c='violet', marker='o') ax.scatter(0,0, c='pink', marker='o') ax.scatter(0,0, c='grey', marker='o') ax.scatter(0,0, c='white', marker='o') leg = ['status<20', 'status=21', 'status=22', 'status=23', '30<status<40', '40<status<50', '50<status<60', '60<status<70', '70<status'] ax.legend(leg, loc=2, scatterpoints=1, markerscale=2) if(not os.path.exists("dot")): print "please make dir dot/ here" quit() write_dot(G,'dot/multi.'+label+'.dot') nx.draw(G,pos,labels=nlabels,with_labels=True, node_color=colors, node_size=100, font_size=5, arrows=True) if(not os.path.exists("pdf")): print "please make dir pdf/ here" quit() plt.savefig("pdf/path."+label+".pdf") plt.close() print "counters=",counters cnv = TCanvas("cnv "+label, "", 500,500) hStatuses.Draw("col") cnv.SaveAs("pdf/status."+label+".pdf") cnv = TCanvas("cnv", "", 500,500) cnv.Draw()
# END if not nice modd # END for each file in file list # use copy after first iteration filelist = listcopy # END for each direction to search # ALL INVALID FILES OUTPUT ########################### if not queried_files and return_invalid: invalidFiles = graph.invalidFiles() sys.stdout.writelines( ( iv + "\n" for iv in invalidFiles ) ) # DOT OUTPUT ################### if dotOutputFile: if verbose: sys.stdout.write("Saving dot file to %s\n" % dotOutputFile) try: import networkx.drawing.nx_pydot as pydot except ImportError: sys.stderr.write( "Required pydot module not installed" ) else: if queried_files and dotgraph is not None: pydot.write_dot( dotgraph, dotOutputFile ) else: pydot.write_dot( graph, dotOutputFile ) # END dot writing
def gen_dot(graph, out): from networkx.drawing.nx_pydot import write_dot write_dot(graph, out)
def get_linkage(self, selection, molid): """ Checks if the selection corresponds to a residue that is covalently bonded to some other residue other than the normal + or - peptide bonds. Sets the patch line (bond line for leap) appropriately and matches atom names using a maximal subgraph isomorphism to the normal residue. Args: selection (VMD atomsel): Selection to check molid (int): VMD molecule ID to look for other bonded residue in Returns: resnames (dict int -> str) Residue name translation dictionary atomnames (dict int -> str) Atom name translation dictionary conect (str) Leap patch line to apply for this linkage """ # Sanity check selection corresponds to one resid resids = set(selection.get("resid")) if len(resids) > 1: raise ValueError("Multiple resids in selection: %s" % resids) # Get externally bonded atoms externs = self.get_extraresidue_atoms(selection) # Create a subgraph with no externally bonded atoms for matching # Otherwise, extra bonded atom will prevent matches from happening noext,_ = self.parse_vmd_graph(selection) noext.remove_nodes_from([i for i in noext.nodes() if noext.node[i].get("residue") != "self"]) # Find all possible subgraph matches, only amino acids for now, otherwise # weird terminal versions like NLYS instead of LYS could be chosen matches = {} for names in self.known_res: graph = self.known_res.get(names).copy() graph.remove_nodes_from([i for i in graph.nodes() if graph.node[i].get("residue") != "self"]) matcher = isomorphism.GraphMatcher(noext, graph, \ node_match=super(AmberMatcher, self)._check_atom_match) if matcher.is_isomorphic(): matches[names] = matcher.match() if not matches: write_dot(noext, "noext.dot") return (None, None, None) # Want minimumally different thing, ie fewest _join atoms different def difference(res): return len(self.known_res[res]) - len(noext) minscore = min(difference(_) for _ in matches) possible_matches = [_ for _ in matches if difference(_) == minscore] # Prefer canonical amino acids here over weird other types if len(possible_matches) > 1: canonicals = [_ for _ in possible_matches if _ in self._acids] if len(canonicals) == 1: print("\tPreferring canonical acid %s" % canonicals[0]) matchname = canonicals.pop() else: raise ValueError("Ambiguous bonded residue %s" % selection.get("resname")[0]) else: matchname = possible_matches.pop() # Invert mapping so it's idx-> name. It's backwards b/c of subgraph mapping = next(matches[matchname]) graph = self.known_res.get(matchname) # Generate naming dictionaries to return nammatch = dict((i, graph.node[mapping[i]].get("atomname")) \ for i in mapping.keys() if \ graph.node[mapping[i]].get("residue") == "self") resmatch = dict((i, graph.node[mapping[i]].get("resname")) \ for i in mapping.keys() if \ graph.node[mapping[i]].get("residue") == "self") # Find resid and fragment for other molecule partners = [] resid = selection.get("resid")[0] chain = selection.get("chain")[0] for num in externs: rid = atomsel("index %d" % num, molid=molid).get("resid")[0] ch = atomsel("index %d" % num, molid=molid).get("chain")[0] if ch != chain: partners.append(num) elif rid != resid+1 and rid != resid-1: partners.append(num) if len(partners) != 1: return (None, None, None) return (resmatch, nammatch, partners[0])