def unload_graph(g, fname): if fname.endswith('.g6'): nx.write_graph6(g, fname, header=False) return s = serialize_graph(g) with open(fname, 'w') as f: json.dump(s, f)
def test_length(self): for i in list(range(13)) + [31, 47, 62, 63, 64, 72]: g = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i) gstr = BytesIO() nx.write_graph6(g, gstr, header=False) # Strip the trailing newline. gstr = gstr.getvalue().rstrip() assert_equal(len(gstr), ((i-1) * i // 2 + 5) // 6 + (1 if i < 63 else 4))
def test_roundtrip(self): for i in list(range(13)) + [31, 47, 62, 63, 64, 72]: G = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i) f = BytesIO() nx.write_graph6(G, f) f.seek(0) H = nx.read_graph6(f) assert_nodes_equal(G.nodes(), H.nodes()) assert_edges_equal(G.edges(), H.edges())
def test_roundtrip(self): for i in list(range(13)) + [31, 47, 62, 63, 64, 72]: G = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i) f = BytesIO() nx.write_graph6(G, f) f.seek(0) H = nx.read_graph6(f) assert nodes_equal(G.nodes(), H.nodes()) assert edges_equal(G.edges(), H.edges())
def test_length(self): for i in list(range(13)) + [31, 47, 62, 63, 64, 72]: g = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i) gstr = BytesIO() nx.write_graph6(g, gstr, header=False) # Strip the trailing newline. gstr = gstr.getvalue().rstrip() assert len(gstr) == ( (i - 1) * i // 2 + 5) // 6 + (1 if i < 63 else 4)
def record_graphs(graphs, path): '''writes graphs in g6 format to the designated filename''' for graph in graphs: with open('temp', 'w') as temp: nx.write_graph6(graph, 'temp', header=False) with open('temp', 'r') as temp: with open(path, 'a') as out: out.write(''.join(temp.readlines())) with open(path, 'r') as f: log('Recorded %d graphs' % len(f.readlines())) os.remove('temp')
def generateRandomNetworks(randomSeed=622527): seed(randomSeed) # Network size will be 10^1, 10 ^2, 10^3, 10^4 for exponent in range(1, 4): # 1 .. 4 n = 10 ** exponent for p in [0.1, 0.3, 0.5, 0.7, 0.9]: m = round(n * p) # Generate erdos Renyi networks graph = nx.erdos_renyi_graph(n, p, randomNum()) graphName = "erdos_renyi_n{}_p{}.graph6".format(n, p) nx.write_graph6(graph, directory + graphName) # Generate Barabasi Albert networks graph = nx.barabasi_albert_graph(n, m, randomNum()) graphName = "barabasi_albert_n{}_m{}.graph6".format(n, m) nx.write_graph6(graph, directory + graphName) for k in [0.1, 0.3, 0.5, 0.7, 0.9]: k = round(n * k) # Generate Watts Strogatz networks graph = nx.watts_strogatz_graph(n, k, p, randomNum()) graphName = "watts_strogatz_n{}_k{}_p{}.graph6".format(n, k, p) nx.write_graph6(graph, directory + graphName)
def generateRandomNetworks(randomSeed=622527): seed(randomSeed) # Network size will be 10^1, 10 ^2, 10^3, 10^4 for exponent in range(1, 4): # 1 .. 4 n = 10**exponent for p in [0.1, 0.3, 0.5, 0.7, 0.9]: m = round(n * p) # Generate erdos Renyi networks graph = nx.erdos_renyi_graph(n, p, randomNum()) graphName = "erdos_renyi_n{}_p{}.graph6".format(n, p) nx.write_graph6(graph, directory + graphName) # Generate Barabasi Albert networks graph = nx.barabasi_albert_graph(n, m, randomNum()) graphName = "barabasi_albert_n{}_m{}.graph6".format(n, m) nx.write_graph6(graph, directory + graphName) for k in [0.1, 0.3, 0.5, 0.7, 0.9]: k = round(n * k) # Generate Watts Strogatz networks graph = nx.watts_strogatz_graph(n, k, p, randomNum()) graphName = "watts_strogatz_n{}_k{}_p{}.graph6".format(n, k, p) nx.write_graph6(graph, directory + graphName)
def test_complete_bipartite_graph(self): result = BytesIO() G = nx.complete_bipartite_graph(6, 9) nx.write_graph6(G, result, header=False) # The expected encoding here was verified by Sage. assert result.getvalue() == b"N??F~z{~Fw^_~?~?^_?\n"
def test_no_header(self): result = BytesIO() nx.write_graph6(nx.complete_graph(4), result, header=False) assert result.getvalue() == b"C~\n"
def test_large_complete_graph(self): result = BytesIO() nx.write_graph6(nx.complete_graph(67), result, header=False) assert result.getvalue() == b"~?@B" + b"~" * 368 + b"w\n"
def test_complete_graph(self): result = BytesIO() nx.write_graph6(nx.complete_graph(4), result) assert result.getvalue() == b">>graph6<<C~\n"
def test_trivial_graph(self): result = BytesIO() nx.write_graph6(nx.trivial_graph(), result) assert result.getvalue() == b">>graph6<<@\n"
def test_null_graph(self): result = BytesIO() nx.write_graph6(nx.null_graph(), result) assert result.getvalue() == b">>graph6<<?\n"
def test_complete_graph(self): result = BytesIO() nx.write_graph6(nx.complete_graph(4), result) self.assertEqual(result.getvalue(), b'>>graph6<<C~\n')
import json if __name__ == '__main__': graph = nx.read_edgelist('input/example_graph.edgelist', nodetype=int, data=(('weight', float),)) assert isinstance(graph, nx.Graph) print 'edges:', graph.edges() # raw nx.write_adjlist(graph, 'output_raw/example_graph.adjlist') nx.write_multiline_adjlist(graph, 'output_raw/example_graph.multiline_adjlist') nx.write_edgelist(graph, 'output_raw/example_graph.edgelist') # better serialization nx.write_gpickle(graph, 'output_serialization/example_graph.pickle') nx.write_yaml(graph, 'output_serialization/example_graph.yaml') nx.write_graph6(graph, 'output_serialization/example_graph.graph6') # xml nx.write_gexf(graph, 'output_xml/example_graph.gexf') nx.write_graphml(graph, 'output_xml/example_graph.graphml') # json with open('output_json/node_link.json', 'w') as outfile: json.dump(json_graph.node_link_data(graph), outfile, indent=2) with open('output_json/adjacency.json', 'w') as outfile: json.dump(json_graph.adjacency_data(graph), outfile, indent=2) # other nx.write_gml(graph, 'output_other/example_graph.gml') nx.write_pajek(graph, 'output_other/example_graph.pajek')
def test_write_graph6(self): fh = StringIO() nx.write_graph6(nx.complete_bipartite_graph(6,9), fh) fh.seek(0) assert_equal(fh.read(), '>>graph6<<N??F~z{~Fw^_~?~?^_?\n')
def test_null_graph(self): result = BytesIO() nx.write_graph6(nx.null_graph(), result) self.assertEqual(result.getvalue(), b'>>graph6<<?\n')
def no_directed_graphs(self): with self.assertRaises(nx.NetworkXNotImplemented): nx.write_graph6(nx.DiGraph(), BytesIO())
def test_complete_bipartite_graph(self): result = BytesIO() G = nx.complete_bipartite_graph(6, 9) nx.write_graph6(G, result, header=False) # The expected encoding here was verified by Sage. self.assertEqual(result.getvalue(), b'N??F~z{~Fw^_~?~?^_?\n')
def test_no_header(self): result = BytesIO() nx.write_graph6(nx.complete_graph(4), result, header=False) self.assertEqual(result.getvalue(), b'C~\n')
def test_large_complete_graph(self): result = BytesIO() nx.write_graph6(nx.complete_graph(67), result, header=False) self.assertEqual(result.getvalue(), b'~?@B' + b'~' * 368 + b'w\n')
def test_no_directed_graphs(self): with pytest.raises(nx.NetworkXNotImplemented): nx.write_graph6(nx.DiGraph(), BytesIO())
def to_graph(self, tokenizer, counter, variant='gexf', **preprocessing): """Converst the corpus into a graph. In mathematics, and more specifically in graph theory, a graph is a structure amounting to a set of objects in which some pairs of the objects are in some sense *related*. This method creates nodes (*objects*) for each document (basically the filename), as well as for each type in the corpus. Each document node has one or more attributes based on the metadata extracted from the filenames. If a type appears in a document, there will be an directed edge between document node and type node. Each edge has an attribute with type frequency within the document. You can convert the graph to various graph-specific XML formats: * `GEXF <https://gephi.org/gexf/format/>`_ * `GML <https://gephi.org/users/supported-graph-formats/gml-\ format/>`_ * `GraphML <http://graphml.graphdrawing.org/>`_ * `Pajek <http://vlado.fmf.uni-lj.si/pub/networks/pajek/>`_ * `SparseGraph6 <https://networkx.github.io/documentation/networkx\ -1.10/reference/readwrite.sparsegraph6.html>`_ * `YAML <http://yaml.org/>`_ Args: tokenizer (:obj:`function`): This must be a function for tokenization. You could use a simple regex function or from `NLTK <http://www.nltk.org>`_. counter (:obj:`function`): This must be a function which counts elements of an iterable. There are various schemes for determining the value that each entry in the matrix should take. One such scheme is `tf-idf <https://en.wikipedia.org/wiki/Tf-idf>`_. But you can simply use the :class:`Counter` provided in the Python standard library. variant (:obj:`str`): This must be the kind of XML foramt you want to convert the graph to. Possible values are ``gexf``, ``gml``, ``graphml``, ``pajek``, ``graph6``, and ``yaml``. \*\*preprocessing (:obj:`function`, optional): This can be one or even more functions which take the output of your tokenizer function as input. So, you could write a function which counts the terms in your corpus and removes the 100 most frequent words. Returns: None, but writes the formatted corpus to disk. """ G = nx.DiGraph() for meta, text in self.corpus: stem = Path(meta.index[0]).stem G.add_node(stem, **meta.to_dict('record')[0]) tokens = tokenizer(text) frequencies = counter(tokens) if preprocessing: for func in preprocessing.values(): tokens = func(tokens) for token in tokens: G.add_edge(token, stem, frequency=frequencies[token]) if variant == 'gexf': nx.write_gexf(G, Path(self.target, 'corpus.gexf')) elif variant == 'gml': nx.write_gml(G, Path(self.target, 'corpus.gml')) elif variant == 'graphml': nx.write_graphml(G, Path(self.target, 'corpus.graphml')) elif variant == 'pajek': nx.write_pajek(G, Path(self.target, 'corpus.pajek')) elif variant == 'graph6': nx.write_graph6(G, Path(self.target, 'corpus.graph6')) elif variant == 'yaml': nx.write_yaml(G, Path(self.target, 'corpus.yaml')) else: raise ValueError("The variant '{0}' is not supported." "Use 'gexf', 'gml', 'graphml', 'pajek'," "'graph6' or 'yaml'.".format(variant))
def test_trivial_graph(self): result = BytesIO() nx.write_graph6(nx.trivial_graph(), result) self.assertEqual(result.getvalue(), b'>>graph6<<@\n')
def test_write_graph6(self): fh = StringIO() nx.write_graph6(nx.complete_bipartite_graph(6, 9), fh) fh.seek(0) assert_equal(fh.read(), '>>graph6<<N??F~z{~Fw^_~?~?^_?\n')
elif(output_file_type=='SparseGraph6'): a=input("enter 1.for Sparse6 \n2.for graph6 format\n") if(a==1): try: G = nx.write_sparse6(G,output_file_path) #if the file format isin ---sparse6--- write graph G break except IOError: print("The out put type:"+output_file_type+"please select another output file path\n") else : try: G=nx.write_graph6(G,output_file_path) #if the file format isin ---graph6---- write graph G break except IOError: print("The out put type:"+output_file_type+"please select another output file path\n") #if the file format isin ---SparseGraph6---- write graph G elif(output_file_type=='GISShapefile'): try: G = nx.write_shp(G,output_file_path) #if the file format isin ---Gisshapefile--- write graph G+ break except IOError: print("The out put type:"+output_file_type+"please select another output file path\n") output_file_type=raw_input("Now enter file type again other than-> " +output_file_type+" \nE to exit")