Python networkx.write_graphml() Examples
The following are 30
code examples of networkx.write_graphml().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: pagerank_iterative.py From complex_network with GNU General Public License v2.0 | 6 votes |
def main(): # Step 1: Build up a graph ''' G = buildupgraph.build_graph_wikipedia_pagerank_example() out_file = 'wikipedia_pagerank_example.graphml' nx.write_graphml(G, out_file) ''' in_file = 'wikipedia_pagerank_example_layout.graphml' # Visualize the graph with the help of Graphviz G = buildupgraph.read_graphml_with_position(in_file) # Step 2: PageRank calculation node_and_pr = pagerank_iterative(G) # Normalized PageRank total_pr = sum(node_and_pr.values()) # 0.843339703286 node_and_pr = {node : pr/total_pr for node, pr in node_and_pr.items()} # Plot the graph node_size = [pr*30000 for node, pr in node_and_pr.items()] node_and_labels = {node : node+'\n'+str(round(pr, 3)) for node, pr in node_and_pr.items()} plotnxgraph.plot_graph(G, node_size=node_size, node_and_labels=node_and_labels)
Example #2
Source File: ABPUtils.py From SDA with MIT License | 6 votes |
def WriteAdjList(adjList, graphName, colorLabels=None): g = nx.Graph() for i in range(0,len(adjList)): if (colorLabels is not None): g.add_node(i, color=colorLabels[i], id=str(i)) else: g.add_node(i) idx = 0 for i in range(0,len(adjList)): for j in range(0,len(adjList[i])): g.add_edge(i, adjList[i][j][0], capacity=adjList[i][j][1]) if (graphName.find("gml") >= 0): nx.write_gml(g, graphName) elif (graphName.find("gexf") >= 0): nx.write_gexf(g, graphName) elif (graphName.find("graphml") >= 0): nx.write_graphml(g, graphName)
Example #3
Source File: nx_transformer.py From kgx with BSD 3-Clause "New" or "Revised" License | 6 votes |
def save(self, path, **kwargs): # self.graph contains python lists in its meta obj, but write_graphml function does not know # how to serialize python lists, i.e. graphml does not support lists as a valid type for serialization. # As a workaround, we converts lists into comma-separated strings. # We use deepcopy to avoid modifying original self.graph object. dgraph = copy.deepcopy(self.graph) for n, nbrs in dgraph.adjacency(): for nbr, eattr in nbrs.items(): for entry, adjitem in eattr.items(): for prop_uri, obj_curies in adjitem.items(): if obj_curies is None: adjitem[prop_uri] = "" else: if isinstance(obj_curies, list): adjitem[prop_uri] = ','.join(obj_curies) else: adjitem[prop_uri] = str(obj_curies) nx.write_graphml(dgraph, path)
Example #4
Source File: test_graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_default_attribute(self): G=nx.Graph() G.add_node(1,label=1,color='green') G.add_path([0,1,2,3]) G.add_edge(1,2,weight=3) G.graph['node_default']={'color':'yellow'} G.graph['edge_default']={'weight':7} fh = io.BytesIO() nx.write_graphml(G,fh) fh.seek(0) H=nx.read_graphml(fh,node_type=int) assert_equal(sorted(G.nodes()),sorted(H.nodes())) assert_equal( sorted(sorted(e) for e in G.edges()), sorted(sorted(e) for e in H.edges())) assert_equal(G.graph,H.graph)
Example #5
Source File: unitTest_GG.py From GenGraph with GNU General Public License v3.0 | 6 votes |
def test_create_genome_alignment_graph(self): """Is the correct block graph created?""" test_bbone_file = './unitTestFiles/globalAlignment_phyloTest.backbone' parsed_input_dict = parse_seq_file('./unitTestFiles/multiGenome.txt') created_test_graph = create_genome_alignment_graph(test_bbone_file, parsed_input_dict[0], parsed_input_dict[1]) #nx.write_graphml(created_test_graph, './test_files/unit_tests/bbone_to_graph_test_out.xml') test_pass = True #print test_pass self.assertTrue(test_pass)
Example #6
Source File: test_graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_unicode(self): G = nx.Graph() try: # Python 3.x name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) node_type=str except ValueError: # Python 2.6+ name1 = unichr(2344) + unichr(123) + unichr(6543) name2 = unichr(5543) + unichr(1543) + unichr(324) node_type=unicode G.add_edge(name1, 'Radiohead', attr_dict={'foo': name2}) fd, fname = tempfile.mkstemp() nx.write_graphml(G, fname) H = nx.read_graphml(fname,node_type=node_type) assert_equal(G.adj, H.adj) os.close(fd) os.unlink(fname)
Example #7
Source File: gengraph.py From GenGraph with GNU General Public License v3.0 | 6 votes |
def realign_all_nodes(inGraph, input_dict): logging.info('Running realign_all_nodes') realign_node_list = [] iso_list = inGraph.graph['isolates'].split(',') # Load genomes into memory # Only need to realign nodes with more than one isolate in them for node, data in inGraph.nodes(data=True): # print(data) if len(data['ids'].split(',')) > 1: realign_node_list.append(node) # Realign the nodes. This is where multiprocessing will come in. for a_node in realign_node_list: inGraph = local_node_realign_new(inGraph, a_node, input_dict[1]) nx.write_graphml(inGraph, 'intermediate_split_unlinked.xml') return inGraph
Example #8
Source File: networkx.py From Verum with Apache License 2.0 | 6 votes |
def write_graph(self, G=None, subgraph_file=None): if G is None: G = self.context_graph if subgraph_file is None: subgraph_file = self.context_graph_file logging.info("Writing graph.") # write the graph out file_format = subgraph_file.split(".")[-1] if file_format == "graphml": nx.write_graphml(G, subgraph_file) elif file_format == "gml": nx.write_gml(G, subgraph_file) elif file_format == "gexf": nx.write_gexf(G, subgraph_file) elif file_format == "net": nx.write_pajek(G, subgraph_file) elif file_format == "yaml": nx.write_yaml(G, subgraph_file) elif file_format == "gpickle": nx.write_gpickle(G, subgraph_file) else: print "File format not found, writing graphml." nx.write_graphml(G, subgraph_file)
Example #9
Source File: graphml.py From pybel with MIT License | 6 votes |
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO], schema: Optional[str] = None) -> None: """Write a graph to a GraphML XML file using :func:`networkx.write_graphml`. :param graph: BEL Graph :param path: Path to the new exported file :param schema: Type of export. Currently supported: "simple" and "umbrella". The .graphml file extension is suggested so Cytoscape can recognize it. By default, this function exports using the PyBEL schema of including modifier information into the edges. As an alternative, this function can also distinguish between """ if schema is None or schema == 'simple': rv = _to_graphml_simple(graph) elif schema == 'umbrella': rv = _to_graphml_umbrella(graph) else: raise ValueError('Unhandled schema: {}'.format(schema)) nx.write_graphml(rv, path)
Example #10
Source File: test_graphml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_write_interface(self): try: import lxml.etree assert_equal(nx.write_graphml, nx.write_graphml_lxml) except ImportError: assert_equal(nx.write_graphml, nx.write_graphml_xml)
Example #11
Source File: test_graphml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_preserve_multi_edge_data(self): """ Test that data and keys of edges are preserved on consequent write and reads """ G = nx.MultiGraph() G.add_node(1) G.add_node(2) G.add_edges_from([ # edges with no data, no keys: (1, 2), # edges with only data: (1, 2, dict(key='data_key1')), (1, 2, dict(id='data_id2')), (1, 2, dict(key='data_key3', id='data_id3')), # edges with both data and keys: (1, 2, 103, dict(key='data_key4')), (1, 2, 104, dict(id='data_id5')), (1, 2, 105, dict(key='data_key6', id='data_id7')), ]) fh = io.BytesIO() nx.write_graphml(G, fh) fh.seek(0) H = nx.read_graphml(fh, node_type=int) assert_edges_equal( G.edges(data=True, keys=True), H.edges(data=True, keys=True) ) assert_equal(G._adj, H._adj)
Example #12
Source File: graph_builder.py From MicroTokenizer with MIT License | 5 votes |
def write_graphml(self, graphml_file): nx.write_graphml( self.G, graphml_file, # Determine if numeric types should be generalized. For example, # if edges have both int and float 'weight' attributes, # we infer in GraphML that both are floats. infer_numeric_types=True )
Example #13
Source File: graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def write_graphml(G, path, encoding='utf-8',prettyprint=True): """Write G in GraphML XML format to path Parameters ---------- G : graph A networkx graph path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. encoding : string (optional) Encoding for text data. prettyprint : bool (optional) If True use line breaks and indenting in output XML. Examples -------- >>> G=nx.path_graph(4) >>> nx.write_graphml(G, "test.graphml") Notes ----- This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges, nested graphs, or ports. """ writer = GraphMLWriter(encoding=encoding,prettyprint=prettyprint) writer.add_graph_element(G) writer.dump(path)
Example #14
Source File: graphml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def write_graphml_xml(G, path, encoding='utf-8', prettyprint=True, infer_numeric_types=False): """Write G in GraphML XML format to path Parameters ---------- G : graph A networkx graph path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. encoding : string (optional) Encoding for text data. prettyprint : bool (optional) If True use line breaks and indenting in output XML. infer_numeric_types : boolean Determine if numeric types should be generalized. For example, if edges have both int and float 'weight' attributes, we infer in GraphML that both are floats. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_graphml(G, "test.graphml") Notes ----- It may be a good idea in Python2 to convert strings to unicode before giving the graph to write_gml. At least the strings with either many characters to escape. This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges, nested graphs, or ports. """ writer = GraphMLWriter(encoding=encoding, prettyprint=prettyprint, infer_numeric_types=infer_numeric_types) writer.add_graph_element(G) writer.dump(path)
Example #15
Source File: test_graphml.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_preserve_multi_edge_data(self): """ Test that data and keys of edges are preserved on consequent write and reads """ G = nx.MultiGraph() G.add_node(1) G.add_node(2) G.add_edges_from([ # edges with no data, no keys: (1, 2), # edges with only data: (1, 2, dict(key='data_key1')), (1, 2, dict(id='data_id2')), (1, 2, dict(key='data_key3', id='data_id3')), # edges with both data and keys: (1, 2, 103, dict(key='data_key4')), (1, 2, 104, dict(id='data_id5')), (1, 2, 105, dict(key='data_key6', id='data_id7')), ]) fh = io.BytesIO() nx.write_graphml(G, fh) fh.seek(0) H = nx.read_graphml(fh, node_type=int) assert_edges_equal( G.edges(data=True, keys=True), H.edges(data=True, keys=True) ) assert_equal(G._adj, H._adj)
Example #16
Source File: test_graphml.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_write_interface(self): try: import lxml.etree assert_equal(nx.write_graphml, nx.write_graphml_lxml) except ImportError: assert_equal(nx.write_graphml, nx.write_graphml_xml)
Example #17
Source File: graphml.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def write_graphml_xml(G, path, encoding='utf-8', prettyprint=True, infer_numeric_types=False): """Write G in GraphML XML format to path Parameters ---------- G : graph A networkx graph path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. encoding : string (optional) Encoding for text data. prettyprint : bool (optional) If True use line breaks and indenting in output XML. infer_numeric_types : boolean Determine if numeric types should be generalized. For example, if edges have both int and float 'weight' attributes, we infer in GraphML that both are floats. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_graphml(G, "test.graphml") Notes ----- It may be a good idea in Python2 to convert strings to unicode before giving the graph to write_gml. At least the strings with either many characters to escape. This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges, nested graphs, or ports. """ writer = GraphMLWriter(encoding=encoding, prettyprint=prettyprint, infer_numeric_types=infer_numeric_types) writer.add_graph_element(G) writer.dump(path)
Example #18
Source File: test_graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_write_read_simple_directed_graphml(self): G=self.simple_directed_graph fh=io.BytesIO() nx.write_graphml(G,fh) fh.seek(0) H=nx.read_graphml(fh) assert_equal(sorted(G.nodes()),sorted(H.nodes())) assert_equal(sorted(G.edges()),sorted(H.edges())) assert_equal(sorted(G.edges(data=True)), sorted(H.edges(data=True))) self.simple_directed_fh.seek(0)
Example #19
Source File: ABPUtils.py From SDA with MIT License | 5 votes |
def WriteGraph(g, graphName, colorLabels=None): if (graphName.find("gml") >= 0): nx.write_gml(g, graphName) elif (graphName.find("gexf") >= 0): nx.write_gexf(g, graphName) elif (graphName.find("graphml") >= 0): nx.write_graphml(g, graphName)
Example #20
Source File: merge_token.py From MicroTokenizer with MIT License | 5 votes |
def write_graph(self, graph_path): nx.write_graphml(self.G, graph_path)
Example #21
Source File: calc_network.py From MD-TASK with GNU General Public License v3.0 | 5 votes |
def construct_graph(frame, ligands=None, prefix="frame", threshold=6.7, save_graph=True): atom_filter = "(name CB and protein) or (name CA and resname GLY)" if ligands: ligands = ligands.split(",") for ligand in ligands: arr = ligand.split(":") atom_filter += " or (name %s and resname %s)" % (arr[1], arr[0]) atoms = frame.topology.select(atom_filter) nodes_range = len(atoms) nodes = range(0, len(atoms)) edges = [] for i in range(nodes_range - 1): for j in range(i + 1, nodes_range): dist = calc_distance(frame, atoms[i], atoms[j]) * 10 if dist < threshold: edges.append((i, j)) protein_graph = nx.Graph() protein_graph.add_nodes_from(nodes) protein_graph.add_edges_from(edges) if save_graph: nx.write_gml(protein_graph, "%s_graph.gml" % prefix) nx.write_graphml(protein_graph, "%s_graph.graphml" % prefix) return protein_graph
Example #22
Source File: unitTest_GG.py From GenGraph with GNU General Public License v3.0 | 5 votes |
def test_alignment_to_graph_conversion(self): """Are fasta alignment files correctly converted to graphs?""" test_fasta_aln = './unitTestFiles/alignedSeq.fa' test_start_dict = {'seq1':1,'seq2':-50,'seq3':1} fasta_object = input_parser(test_fasta_aln) new_graph = fasta_alignment_to_subnet(test_fasta_aln, true_start=test_start_dict, node_prefix='X', orientation={}, re_link_nodes=True, add_seq=True) nx.write_graphml(new_graph, './unitTestFiles/alignedSeq.xml') seq1_seq = extract_original_seq(new_graph, 'seq1') seq2_seq = extract_original_seq(new_graph, 'seq2') seq3_seq = extract_original_seq(new_graph, 'seq3') does_pass = True print seq1_seq print 'GAGATTAGGAGTAGATAGATAGATATTTAGAGCCCGGAAAATTTATATTATTTAAT' print seq2_seq print reverse_compliment('GATTAGGAGTAGATAGATAGATATTTAGAGAGAGAAAATTTATATTATTT') print seq3_seq print 'GAGATTAGGAGTAGATAGATAGTATTTAGAGAGAGAAAATTTATATTATTTAAT' if seq1_seq != 'GAGATTAGGAGTAGATAGATAGATATTTAGAGCCCGGAAAATTTATATTATTTAAT': does_pass = False print 'seq1 fails' if seq2_seq != reverse_compliment('GATTAGGAGTAGATAGATAGATATTTAGAGAGAGAAAATTTATATTATTT'): does_pass = False print 'seq2 fails' if seq3_seq != 'GAGATTAGGAGTAGATAGATAGTATTTAGAGAGAGAAAATTTATATTATTTAAT': does_pass = False print 'seq3 fails' self.assertTrue(does_pass)
Example #23
Source File: graphs.py From textplot with MIT License | 5 votes |
def write_graphml(self, path): """ Write a GraphML file. Args: path (str): The file path. """ nx.write_graphml(self.graph, path)
Example #24
Source File: buildupgraph.py From complex_network with GNU General Public License v2.0 | 5 votes |
def main(): # Step 1: Build up a graph G = build_graph_wikipedia_pagerank_example() out_file = 'wikipedia_pagerank_example.graphml' nx.write_graphml(G, out_file) ''' in_file = 'wikipedia_pagerank_example_layout.graphml' G = read_graphml_with_position(in_file) '''
Example #25
Source File: build_follower_network.py From smappPy with GNU General Public License v2.0 | 5 votes |
def generate_output_file(users_collection, edges_collection, keep_empty_nodes): graph = nx.DiGraph() nonempty_user_ids = set() for user in users_collection.find(): nonempty_user_ids.add(user['id']) attrs_to_keep = [ 'name', 'id', 'geo_enabled', 'followers_count', 'protected', 'lang', 'utc_offset', 'statuses_count', 'friends_count', 'screen_name', 'url', 'location', ] user_attrs = { key : user[key] or '' for key in attrs_to_keep } graph.add_node(user['id'], attr_dict=user_attrs) for edge in edges_collection.find(): if keep_empty_nodes or edge['from'] in nonempty_user_ids and edge['to'] in nonempty_user_ids: graph.add_edge(edge['from'], edge['to']) nx.write_graphml(graph, sys.stdout)
Example #26
Source File: decompiler_utils.py From FIDL with MIT License | 5 votes |
def dump_i_cfg(self): """Dump interim CFG for debugging purposes """ print("[DEBUG] Dumping CFG") for u, v in self.i_cfg.edges(): print("{} -> {}".format(u, v)) print("[DEBUG] Writing GraphML...") # Labeling the nodes for node in self.i_cfg.nodes(): self.i_cfg.node[node]['label'] = "{}".format(node) nx.write_graphml(self.i_cfg, r"D:\graphs\di.graphml")
Example #27
Source File: graph.py From open-syllabus-project with Apache License 2.0 | 5 votes |
def write_graphml(self, path): """ Serialize the graph as .graphml. Args: path (str) """ nx.write_graphml(self.graph, path)
Example #28
Source File: rede_cnpj.py From CNPJ-full with GNU General Public License v3.0 | 5 votes |
def gera_graphml_G(self, G, path): nx.write_graphml(G, path)
Example #29
Source File: main.py From dcc with Apache License 2.0 | 4 votes |
def androcg_main(verbose, APK, classname, methodname, descriptor, accessflag, no_isolated, show, output): from androguard.core.androconf import show_logging from androguard.core.bytecode import FormatClassToJava from androguard.misc import AnalyzeAPK import networkx as nx import logging log = logging.getLogger("androcfg") if verbose: show_logging(logging.INFO) a, d, dx = AnalyzeAPK(APK) entry_points = map(FormatClassToJava, a.get_activities() + a.get_providers() + a.get_services() + a.get_receivers()) entry_points = list(entry_points) log.info("Found The following entry points by search AndroidManifest.xml: " "{}".format(entry_points)) CG = dx.get_call_graph(classname, methodname, descriptor, accessflag, no_isolated, entry_points, ) write_methods = dict(gml=_write_gml, gexf=nx.write_gexf, gpickle=nx.write_gpickle, graphml=nx.write_graphml, yaml=nx.write_yaml, net=nx.write_pajek, ) if show: plot(CG) else: writer = output.rsplit(".", 1)[1] if writer in ["bz2", "gz"]: writer = output.rsplit(".", 2)[1] if writer not in write_methods: print("Could not find a method to export files to {}!" .format(writer)) sys.exit(1) write_methods[writer](CG, output)
Example #30
Source File: metaknowledgeCLI.py From metaknowledge with GNU General Public License v2.0 | 4 votes |
def outputNetwork(clargs, grph): outDict = collections.OrderedDict([ ('1', "edge list and node attribute list"), ('2', "edge list"), ('3', "node attribute list"), ('4', "graphml (SLOW)"), ]) try: import metaknowledge.contour except ImportError: import metaknowledge else: outDict['0'] = "view graph" outDict.move_to_end('0', last = False) print("The network contains {} nodes and {} edges.".format(len(grph.nodes()), len(grph.edges()))) outID = int(inputMenu(outDict, header = "What type of output to you want? ")) if outID == 0: metaknowledge.contour.quickVisual(grph) outputNetwork(clargs, grph) elif outID == 1: while True: try: outName = getOutputName(clargs, '', checking = False) metaknowledge.writeGraph(grph, outName, overwrite = False) except OSError: if clargs.name: metaknowledge.writeGraph(grph, outName, overwrite = True) break else: overWrite = yesorNo("{}, overwrite (y/n)? ") if overWrite: metaknowledge.writeGraph(grph, outName, overwrite = True) break else: pass else: break elif outID == 2: outName = getOutputName(clargs, '.csv') metaknowledge.writeEdgeList(grph, outName) elif outID == 3: outName = getOutputName(clargs, '.csv') metaknowledge.writeNodeAttributeFile(grph, outName) else: outName = getOutputName(clargs, '.graphml') nx.write_graphml(grph, outName)