Python networkx.write_gml() Examples
The following are 20
code examples of networkx.write_gml().
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: test_gml.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_unicode_node(self): node = 'node' + unichr(169) G = nx.Graph() G.add_node(node) fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ node [ id 0 label "node©" ] ]""" assert_equal(data, answer)
Example #2
Source File: test_gml.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_quotes(self): # https://github.com/networkx/networkx/issues/1061 # Encoding quotes as HTML entities. G = nx.path_graph(1) G.name = "path_graph(1)" attr = 'This is "quoted" and this is a copyright: ' + unichr(169) G.nodes[0]['demo'] = attr fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ name "path_graph(1)" node [ id 0 label "0" demo "This is "quoted" and this is a copyright: ©" ] ]""" assert_equal(data, answer)
Example #3
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 #4
Source File: test_gml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_float_label(self): node = 1.0 G = nx.Graph() G.add_node(node) fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ node [ id 0 label "1.0" ] ]""" assert_equal(data, answer)
Example #5
Source File: reports_to_gml.py From arguman.org with GNU Affero General Public License v3.0 | 6 votes |
def create_report_graph(self): for (fallacy_type, localized) in get_fallacy_types(): node = unidecode(self.normalize(localized)) graph.add_node(node, type="fallacy", Weight=10) for premise in Premise.objects.filter( reports__fallacy_type=fallacy_type): #graph.add_node(premise.argument.pk, type="argument") #graph.add_edge(premise.argument.pk, node, type="reported") if premise.argument.channel: channel_node = unidecode(premise.argument.channel.title) graph.add_node(channel_node, type="channel", Weight=premise.argument.channel.contentions.count() * 30) graph.add_edge(channel_node, node, type="reported") nx.write_gml(graph, 'reports.gml')
Example #6
Source File: test_gml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_unicode_node(self): node = 'node' + unichr(169) G = nx.Graph() G.add_node(node) fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ node [ id 0 label "node©" ] ]""" assert_equal(data, answer)
Example #7
Source File: test_gml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_quotes(self): # https://github.com/networkx/networkx/issues/1061 # Encoding quotes as HTML entities. G = nx.path_graph(1) G.name = "path_graph(1)" attr = 'This is "quoted" and this is a copyright: ' + unichr(169) G.nodes[0]['demo'] = attr fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ name "path_graph(1)" node [ id 0 label "0" demo "This is "quoted" and this is a copyright: ©" ] ]""" assert_equal(data, answer)
Example #8
Source File: test_gml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_quotes(self): # https://github.com/networkx/networkx/issues/1061 # Encoding quotes as HTML entities. G = nx.path_graph(1) attr = 'This is "quoted" and this is a copyright: ' + unichr(169) G.node[0]['demo'] = attr fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ name "path_graph(1)" node [ id 0 label 0 demo "This is "quoted" and this is a copyright: ©" ] ]""" assert_equal(data, answer)
Example #9
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 #10
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 #11
Source File: main.py From dcc with Apache License 2.0 | 5 votes |
def _write_gml(G, path): """ Wrapper around nx.write_gml """ import networkx as nx return nx.write_gml(G, path, stringizer=str)
Example #12
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 #13
Source File: graphs.py From textplot with MIT License | 5 votes |
def write_gml(self, path): """ Write a GML file. Args: path (str): The file path. """ nx.write_gml(self.graph, path)
Example #14
Source File: integrate.py From panaroo with MIT License | 5 votes |
def reformat_network(single_gml, output_dir, isolateName): """Reformats the output of generate_network() for linear graphs to allow input into merge_graphs()""" for adj in single_gml._adj: for x in single_gml._adj[adj]: y = single_gml._adj[adj][x] y.pop('members') zero = {'members': 0} y.update(zero) genomes = {'genomeIDs': '0'} y.update(genomes) for node in single_gml._node: y = single_gml._node[node] y.pop('members') zero = { 'members': 0 } #members are assigned intbitset[0]. needs to be 0 y.update(zero) to_replace = {"[": "", "]": "", "'": ""} y['centroid'] = replace_all(str(y['centroid']), to_replace) y['dna'] = replace_all(str(y['dna']), to_replace) y['protein'] = replace_all(str(y['protein']), to_replace) y['hasEnd'] = int(y['hasEnd']) y['mergedDNA'] = int(y['mergedDNA']) y['paralog'] = int(y['paralog']) y['longCentroidID'] = list(y['longCentroidID']) y['seqIDs'] = list(y['seqIDs']) single_gml.graph.update({'isolateNames': 'x'}) # isolateName from gff filename nx.write_gml(single_gml, output_dir + "final_graph.gml") return single_gml
Example #15
Source File: reports_to_gml.py From arguman.org with GNU Affero General Public License v3.0 | 5 votes |
def create_conjunction_graph(self): fallacy_map = { unidecode(key): value for (key, value) in get_fallacy_types() } for contention in Contention.objects.all(): for premise in contention.premises.all(): fallacies = filter(None, premise.reports.values_list( 'fallacy_type', flat=True)) fallacies = [ fallacy_map[unidecode(_f)] for _f in fallacies ] fallacies_set = set(fallacies) for fallacy in fallacies_set: graph.add_edges_from( [ (unidecode(self.normalize(fallacy)), unidecode(self.normalize(_f))) for _f in fallacies_set if _f != fallacy ] ) nx.write_gml(graph, 'conjunction.gml')
Example #16
Source File: cli.py From bioconda-utils with MIT License | 5 votes |
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')
Example #17
Source File: __init__.py From kevlar with MIT License | 5 votes |
def to_gml(graph, outfilename, logfile=sys.stderr): """Write the given read graph to a GML file.""" if not outfilename.endswith('.gml'): print('[kevlar] WARNING: GML files usually need extension .gml', file=logfile) networkx.write_gml(graph, outfilename, stringizer=str) message = '[kevlar] graph written to {}'.format(outfilename) print(message, file=logfile)
Example #18
Source File: gml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def read_gml(path, label='label', destringizer=None): """Read graph in GML format from path. Parameters ---------- path : filename or filehandle The filename or filehandle to read from. label : string, optional If not None, the parsed nodes will be renamed according to node attributes indicated by ``label``. Default value: ``'label'``. destringizer : callable, optional A destringizer that recovers values stored as strings in GML. If it cannot convert a string to a value, a ``ValueError`` is raised. Default value : ``None``. Returns ------- G : NetworkX graph The parsed graph. Raises ------ NetworkXError If the input cannot be parsed. See Also -------- write_gml, parse_gml Notes ----- The GML specification says that files should be ASCII encoded, with any extended ASCII characters (iso8859-1) appearing as HTML character entities. References ---------- GML specification: http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html Examples -------- >>> G = nx.path_graph(4) >>> nx.write_gml(G, 'test.gml') >>> H = nx.read_gml('test.gml') """ def filter_lines(lines): for line in lines: try: line = line.decode('ascii') except UnicodeDecodeError: raise NetworkXError('input is not ASCII-encoded') if not isinstance(line, str): lines = str(lines) if line and line[-1] == '\n': line = line[:-1] yield line G = parse_gml_lines(filter_lines(path), label, destringizer) return G
Example #19
Source File: gml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def write_gml(G, path, stringizer=None): """Write a graph ``G`` in GML format to the file or file handle ``path``. Parameters ---------- G : NetworkX graph The graph to be converted to GML. path : filename or filehandle The filename or filehandle to write. Files whose names end with .gz or .bz2 will be compressed. stringizer : callable, optional A stringizer which converts non-int/non-float/non-dict values into strings. If it cannot convert a value into a string, it should raise a ``ValueError`` to indicate that. Default value: ``None``. Raises ------ NetworkXError If ``stringizer`` cannot convert a value into a string, or the value to convert is not a string while ``stringizer`` is ``None``. See Also -------- read_gml, generate_gml Notes ----- Graph attributes named ``'directed'``, ``'multigraph'``, ``'node'`` or ``'edge'``,node attributes named ``'id'`` or ``'label'``, edge attributes named ``'source'`` or ``'target'`` (or ``'key'`` if ``G`` is a multigraph) are ignored because these attribute names are used to encode the graph structure. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_gml(G, "test.gml") Filenames ending in .gz or .bz2 will be compressed. >>> nx.write_gml(G, "test.gml.gz") """ for line in generate_gml(G, stringizer): path.write((line + '\n').encode('ascii')) # fixture for nose
Example #20
Source File: gml.py From aws-kube-codesuite with Apache License 2.0 | 4 votes |
def write_gml(G, path, stringizer=None): """Write a graph `G` in GML format to the file or file handle `path`. Parameters ---------- G : NetworkX graph The graph to be converted to GML. path : filename or filehandle The filename or filehandle to write. Files whose names end with .gz or .bz2 will be compressed. stringizer : callable, optional A `stringizer` which converts non-int/non-float/non-dict values into strings. If it cannot convert a value into a string, it should raise a `ValueError` to indicate that. Default value: None. Raises ------ NetworkXError If `stringizer` cannot convert a value into a string, or the value to convert is not a string while `stringizer` is None. See Also -------- read_gml, generate_gml, literal_stringizer Notes ----- Graph attributes named 'directed', 'multigraph', 'node' or 'edge', node attributes named 'id' or 'label', edge attributes named 'source' or 'target' (or 'key' if `G` is a multigraph) are ignored because these attribute names are used to encode the graph structure. GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of handling `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For other data types, you need to explicitly supply a `stringizer`/`destringizer`. For additional documentation on the GML file format, please see the `GML website <http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html>`_. See the module docstring :mod:`networkx.readwrite.gml` for additional details. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_gml(G, "test.gml") Filenames ending in .gz or .bz2 will be compressed. >>> nx.write_gml(G, "test.gml.gz") """ for line in generate_gml(G, stringizer): path.write((line + '\n').encode('ascii')) # fixture for nose